<commit_before>#include "InputMesh.h"

#include <maya/MFnMesh.h>
#include <maya/MFnSingleIndexedComponent.h>
#include <maya/MDagPath.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>

#include "hapiutil.h"
#include "types.h"
#include "util.h"

InputMesh::InputMesh() :
    Input()
{
    Util::PythonInterpreterLock pythonInterpreterLock;

    HAPI_NodeId nodeId;
    CHECK_HAPI(HAPI_CreateInputNode(
        Util::theHAPISession.get(),
        &nodeId,
        NULL
        ));
    if(!Util::statusCheckLoop())
    {
        DISPLAY_ERROR(MString("Unexpected error when creating input asset."));
    }

    HAPI_NodeInfo nodeInfo;
    HAPI_GetNodeInfo(
        Util::theHAPISession.get(),
        nodeId,
        &nodeInfo
        );

    setTransformNodeId(nodeInfo.parentId);
    setGeometryNodeId(nodeId);
}

InputMesh::~InputMesh()
{
    CHECK_HAPI(HAPI_DeleteNode(
                Util::theHAPISession.get(),
                geometryNodeId()
                ));
}

Input::AssetInputType
InputMesh::assetInputType() const
{
    return Input::AssetInputType_Mesh;
}

void
InputMesh::setInputGeo(
        MDataBlock &dataBlock,
        const MPlug &plug
        )
{
    MDataHandle dataHandle = dataBlock.inputValue(plug);

    // extract mesh data from Maya
    MObject meshObj = dataHandle.asMesh();

    MFnMesh meshFn(meshObj);

    // get face data
    std::vector<int> vertexCount;
    std::vector<int> vertexList;
    {
        MIntArray mayaVertexCount;
        MIntArray mayaVertexList;
        meshFn.getVertices(mayaVertexCount, mayaVertexList);

        vertexCount.resize(mayaVertexCount.length());
        mayaVertexCount.get(&vertexCount[0]);

        vertexList.resize(mayaVertexList.length());
        mayaVertexList.get(&vertexList[0]);
    }
    Util::reverseWindingOrder(vertexList, vertexCount);

    // set up part info
    HAPI_PartInfo partInfo;
    HAPI_PartInfo_Init(&partInfo);
    partInfo.id = 0;
    partInfo.faceCount        = vertexCount.size();
    partInfo.vertexCount      = vertexList.size();
    partInfo.pointCount       = meshFn.numVertices();

    // Set the data
    HAPI_SetPartInfo(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &partInfo
            );
    HAPI_SetFaceCounts(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &vertexCount[0],
            0, partInfo.faceCount
            );
    HAPI_SetVertexList(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &vertexList[0],
            0, partInfo.vertexCount
            );

    // Set position attributes.
    processPoints(meshFn);

    // normals
    processNormals(meshFn, vertexCount);

    // UVs
    processUVs(meshFn, vertexCount, vertexList);

    // Colors and Alphas
    processColorSets(meshFn, vertexCount, vertexList);

    processSets(plug, meshFn);

    Input::setInputName(
            geometryNodeId(), 0,
            HAPI_ATTROWNER_PRIM, partInfo.faceCount,
            plug
            );

    // Commit it
    HAPI_CommitGeo(
            Util::theHAPISession.get(),
            geometryNodeId()
            );
}

bool
InputMesh::processPoints(
        const MFnMesh &meshFn
        )
{
    CHECK_HAPI(hapiSetPointAttribute(
            geometryNodeId(), 0,
            3,
            "P",
            rawArray(
                meshFn.getRawPoints(NULL),
                meshFn.numVertices() * 3
                )
            ));

    return true;
}

bool
InputMesh::processNormals(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount
        )
{
    // get normal IDs
    MIntArray normalCounts;
    MIntArray normalIds;
    meshFn.getNormalIds(normalCounts, normalIds);

    if(!normalIds.length())
    {
        return false;
    }

    // reverse winding order
    Util::reverseWindingOrder(normalIds, vertexCount);

    // get normal values
    const float* rawNormals = meshFn.getRawNormals(NULL);

    // build the per-vertex normals
    std::vector<float> vertexNormals;
    vertexNormals.reserve(normalIds.length() * 3);
    for(unsigned int i = 0; i < normalIds.length(); ++i)
    {
        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
    }

    // add and set it to HAPI
    CHECK_HAPI(hapiSetVertexAttribute(
            geometryNodeId(), 0,
            3,
            "N",
            vertexNormals
            ));

    return true;
}

bool
InputMesh::processUVs(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount,
        std::vector<int> vertexList
        )
{
    MString currentUVSetName = meshFn.currentUVSetName();

    MStringArray uvSetNames;
    meshFn.getUVSetNames(uvSetNames);

    MStringArray mappedUVAttributeNames;
    mappedUVAttributeNames.setLength(uvSetNames.length());

    for(unsigned int uvSetIndex = 0;
            uvSetIndex < uvSetNames.length(); uvSetIndex++)
    {
        const MString uvSetName = uvSetNames[uvSetIndex];

        const MString uvAttributeName
            = Util::getAttrLayerName("uv", uvSetIndex);
        const MString uvNumberAttributeName
            = Util::getAttrLayerName("uvNumber", uvSetIndex);

        mappedUVAttributeNames[uvSetIndex] = uvAttributeName;

        // get UV IDs
        MIntArray uvCounts;
        MIntArray uvIds;
        meshFn.getAssignedUVs(uvCounts, uvIds, &uvSetName);

        // reverse winding order
        Util::reverseWindingOrder(uvIds, uvCounts);

        // get UV values
        MFloatArray uArray;
        MFloatArray vArray;
        meshFn.getUVs(uArray, vArray, &uvSetName);

        // build the per-vertex UVs
        std::vector<float> vertexUVs;
        std::vector<int> vertexUVNumbers;
        vertexUVs.reserve(vertexList.size() * 3);
        unsigned int uvIdIndex = 0;
        for(unsigned int i = 0; i < uvCounts.length(); ++i)
        {
            if(uvCounts[i] == vertexCount[i])
            {
                // has UVs assigned
                for(int j = 0; j < uvCounts[i]; ++j)
                {
                    vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
                    vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
                    vertexUVs.push_back(0);
                    vertexUVNumbers.push_back(uvIds[uvIdIndex]);

                    uvIdIndex++;
                }
            }
            else
            {
                // no UVs assigned
                for(int j = 0; j < vertexCount[i]; ++j)
                {
                    vertexUVs.push_back(0);
                    vertexUVs.push_back(0);
                    vertexUVs.push_back(0);
                    vertexUVNumbers.push_back(0);
                }
            }
        }

        // add and set it to HAPI
        CHECK_HAPI(hapiSetVertexAttribute(
                geometryNodeId(), 0,
                3,
                uvAttributeName.asChar(),
                vertexUVs
                ));
        CHECK_HAPI(hapiSetVertexAttribute(
                geometryNodeId(), 0,
                1,
                uvNumberAttributeName.asChar(),
                vertexUVNumbers
                ));
    }

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_current",
            currentUVSetName
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_name",
            uvSetNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_mapped_uv",
            mappedUVAttributeNames
            ));

    return true;
}

bool
InputMesh::processColorSets(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount,
        std::vector<int> vertexList
        )
{
    MStringArray currentColorSetName(1, meshFn.currentColorSetName());

    MStringArray colorSetNames;
    meshFn.getColorSetNames(colorSetNames);

    MStringArray mappedCdNames;
    MStringArray mappedAlphaNames;
    mappedCdNames.setLength(colorSetNames.length());
    mappedAlphaNames.setLength(colorSetNames.length());

    MColor defaultUnsetColor;
    MColorArray colors;
    std::vector<float> buffer;
    for(unsigned int i = 0; i < colorSetNames.length(); i++)
    {
        const MString colorSetName = colorSetNames[i];

        bool hasColor = false;
        bool hasAlpha = false;
        {
            MFnMesh::MColorRepresentation colorSetRepresentation =
                meshFn.getColorRepresentation(colorSetName);

            switch(colorSetRepresentation)
            {
                case MFnMesh::kAlpha:
                    hasAlpha = true;
                    break;
                case MFnMesh::kRGB:
                    hasColor = true;
                    break;
                case MFnMesh::kRGBA:
                    hasColor = true;
                    hasAlpha = true;
                    break;
            }
        }

        CHECK_MSTATUS(const_cast<MFnMesh&>(meshFn).getFaceVertexColors(
                    colors,
                    &colorSetName,
                    &defaultUnsetColor
                    ));

        // reverse winding order
        Util::reverseWindingOrder(colors, vertexCount);

        if(hasColor)
        {
            const MString colorAttributeName
                = Util::getAttrLayerName("Cd", i);

            mappedCdNames[i] = colorAttributeName;

            buffer = Util::reshapeArray<
                3,
                0, 3,
                0, 4,
                std::vector<float>
                >(colors);

            // add and set Cd
            CHECK_HAPI(hapiSetVertexAttribute(
                    geometryNodeId(), 0,
                    3,
                    colorAttributeName.asChar(),
                    buffer
                    ));
        }

        if(hasAlpha)
        {
            const MString alphaAttributeName
                = Util::getAttrLayerName("Alpha", i);

            mappedAlphaNames[i] = alphaAttributeName;

            buffer = Util::reshapeArray<
                1,
                0, 1,
                3, 4,
                std::vector<float>
                >(colors);

            // add and set Alpha
            CHECK_HAPI(hapiSetVertexAttribute(
                    geometryNodeId(), 0,
                    1,
                    alphaAttributeName.asChar(),
                    buffer
                    ));
        }
    }

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_current",
            currentColorSetName
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_name",
            colorSetNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_mapped_Cd",
            mappedCdNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_mapped_Alpha",
            mappedAlphaNames
            ));

    return true;
}

bool
InputMesh::processSets(
        const MPlug &plug,
        const MFnMesh &meshFn
        )
{
    MStatus status;

    // The source node may not be actually mesh node.
    MPlug srcPlug = Util::plugSource(plug);
    if(srcPlug.isNull())
    {
        return false;
    }

    // XXX: instance number
    MDagPath srcDagPath = MDagPath::getAPathTo(srcPlug.node());

    // Sets and Members
    MFnMesh srcNodeFn(srcDagPath, &status);
    CHECK_MSTATUS_AND_RETURN_IT(status);

    MObjectArray sets;
    MObjectArray comps;
    // XXX: instance number
    srcNodeFn.getConnectedSetsAndMembers(0, sets, comps, false);

    MStringArray sgNames;
    MObjectArray sgCompObjs;

    std::vector<int> groupMembership;
    for(int setIndex = 0; setIndex < (int) sets.length(); setIndex++)
    {
        const MObject &setObj = sets[setIndex];
        const MObject &compObj = comps[setIndex];

        MFnDependencyNode setFn(setObj, &status);
        CHECK_MSTATUS(status);

        // Filter out unwanted sets. This mimics setFilterScript().
        MString setType = setFn.typeName();
        if(setType == "shadingEngine")
        {
            sgNames.append(setFn.name());
            sgCompObjs.append(compObj);
            continue;
        }

        if(!(setType == "objectSet" ||
                    setType == "textureBakeSet" ||
                    setType == "vertexBakeSet" ||
                    setType == "creaseSet" ||
                    setType == "character"))
        {
            continue;
        }

        if(setFn.findPlug("verticesOnlySet").asBool()
                || setFn.findPlug("edgesOnlySet").asBool()
                || setFn.findPlug("facetsOnlySet").asBool()
                || setFn.findPlug("editPointsOnlySet").asBool()
                || setFn.findPlug("renderableOnlySet").asBool()
          )
        {
            continue;
        }

        HAPI_GroupType groupType;

        if(compObj.isNull())
        {
            groupType = HAPI_GROUPTYPE_PRIM;
            groupMembership.resize(meshFn.numPolygons());

            std::fill(groupMembership.begin(), groupMembership.end(), 1);
        }
        else
        {
            MFnSingleIndexedComponent componentFn(compObj, &status);
            CHECK_MSTATUS(status);

            switch(componentFn.componentType())
            {
                case MFn::kMeshPolygonComponent:
                    groupType = HAPI_GROUPTYPE_PRIM;
                    groupMembership.resize(meshFn.numPolygons());
                    break;
                case MFn::kMeshVertComponent:
                    groupType = HAPI_GROUPTYPE_POINT;
                    groupMembership.resize(meshFn.numVertices());
                    break;
                default:
                    continue;
                    break;
            }

            std::fill(groupMembership.begin(), groupMembership.end(), 0);
            for(int i = 0; i < componentFn.elementCount(); i++)
            {
                groupMembership[componentFn.element(i)] = 1;
            }
        }

        MString setName = setFn.name();
        // If the set is in a namespace, the name will contain a colon.
        setName = Util::sanitizeStringForNodeName(setName);

        CHECK_HAPI(HAPI_AddGroup(
                    Util::theHAPISession.get(),
                    geometryNodeId(), 0,
                    groupType,
                    setName.asChar()
                    ));

        CHECK_HAPI(HAPI_SetGroupMembership(
                    Util::theHAPISession.get(),
                    geometryNodeId(), 0,
                    groupType,
                    setName.asChar(),
                    &groupMembership[0],
                    0, groupMembership.size()
                    ));
    }

    processShadingGroups(meshFn, sgNames, sgCompObjs);

    return true;
}

bool
InputMesh::processShadingGroups(
        const MFnMesh &meshFn,
        const MStringArray &sgNames,
        const MObjectArray &sgCompObjs
        )
{
    MStatus status;

    if(sgCompObjs.length() == 1 && sgCompObjs[0].isNull())
    {
        CHECK_HAPI(hapiSetDetailAttribute(
                    geometryNodeId(), 0,
                    "maya_shading_group",
                    const_cast<MStringArray&>(sgNames)[0]
                    ));
    }
    else
    {
        MString defaultShader;

        std::vector<const char*> sgNamePerComp;
        sgNamePerComp.resize(meshFn.numPolygons(), defaultShader.asChar());

        for(int i = 0; i < (int) sgNames.length(); i++)
        {
            const char* sgName = sgNames[i].asChar();
            const MObject &sgCompObj = sgCompObjs[i];

            assert(!sgCompObj.isNull());

            MFnSingleIndexedComponent componentFn(sgCompObj, &status);
            CHECK_MSTATUS(status);

            assert(componentFn.componentType()
                    == MFn::kMeshPolygonComponent);

            for(int j = 0; j < componentFn.elementCount(); j++)
            {
                sgNamePerComp[componentFn.element(j)] = sgName;
            }
        }

        CHECK_HAPI(hapiSetPrimAttribute(
                    geometryNodeId(), 0,
                    1,
                    "maya_shading_group",
                    sgNamePerComp
                    ));
    }

    return true;
}
<commit_msg>Add support for locked normals when inputting mesh<commit_after>#include "InputMesh.h"

#include <maya/MFnMesh.h>
#include <maya/MFnSingleIndexedComponent.h>
#include <maya/MDagPath.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>

#include "hapiutil.h"
#include "types.h"
#include "util.h"

InputMesh::InputMesh() :
    Input()
{
    Util::PythonInterpreterLock pythonInterpreterLock;

    HAPI_NodeId nodeId;
    CHECK_HAPI(HAPI_CreateInputNode(
        Util::theHAPISession.get(),
        &nodeId,
        NULL
        ));
    if(!Util::statusCheckLoop())
    {
        DISPLAY_ERROR(MString("Unexpected error when creating input asset."));
    }

    HAPI_NodeInfo nodeInfo;
    HAPI_GetNodeInfo(
        Util::theHAPISession.get(),
        nodeId,
        &nodeInfo
        );

    setTransformNodeId(nodeInfo.parentId);
    setGeometryNodeId(nodeId);
}

InputMesh::~InputMesh()
{
    CHECK_HAPI(HAPI_DeleteNode(
                Util::theHAPISession.get(),
                geometryNodeId()
                ));
}

Input::AssetInputType
InputMesh::assetInputType() const
{
    return Input::AssetInputType_Mesh;
}

void
InputMesh::setInputGeo(
        MDataBlock &dataBlock,
        const MPlug &plug
        )
{
    MDataHandle dataHandle = dataBlock.inputValue(plug);

    // extract mesh data from Maya
    MObject meshObj = dataHandle.asMesh();

    MFnMesh meshFn(meshObj);

    // get face data
    std::vector<int> vertexCount;
    std::vector<int> vertexList;
    {
        MIntArray mayaVertexCount;
        MIntArray mayaVertexList;
        meshFn.getVertices(mayaVertexCount, mayaVertexList);

        vertexCount.resize(mayaVertexCount.length());
        mayaVertexCount.get(&vertexCount[0]);

        vertexList.resize(mayaVertexList.length());
        mayaVertexList.get(&vertexList[0]);
    }
    Util::reverseWindingOrder(vertexList, vertexCount);

    // set up part info
    HAPI_PartInfo partInfo;
    HAPI_PartInfo_Init(&partInfo);
    partInfo.id = 0;
    partInfo.faceCount        = vertexCount.size();
    partInfo.vertexCount      = vertexList.size();
    partInfo.pointCount       = meshFn.numVertices();

    // Set the data
    HAPI_SetPartInfo(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &partInfo
            );
    HAPI_SetFaceCounts(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &vertexCount[0],
            0, partInfo.faceCount
            );
    HAPI_SetVertexList(
            Util::theHAPISession.get(),
            geometryNodeId(), 0,
            &vertexList[0],
            0, partInfo.vertexCount
            );

    // Set position attributes.
    processPoints(meshFn);

    // normals
    processNormals(meshFn, vertexCount);

    // UVs
    processUVs(meshFn, vertexCount, vertexList);

    // Colors and Alphas
    processColorSets(meshFn, vertexCount, vertexList);

    processSets(plug, meshFn);

    Input::setInputName(
            geometryNodeId(), 0,
            HAPI_ATTROWNER_PRIM, partInfo.faceCount,
            plug
            );

    // Commit it
    HAPI_CommitGeo(
            Util::theHAPISession.get(),
            geometryNodeId()
            );
}

bool
InputMesh::processPoints(
        const MFnMesh &meshFn
        )
{
    CHECK_HAPI(hapiSetPointAttribute(
            geometryNodeId(), 0,
            3,
            "P",
            rawArray(
                meshFn.getRawPoints(NULL),
                meshFn.numVertices() * 3
                )
            ));

    return true;
}

bool
InputMesh::processNormals(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount
        )
{
    // get normal IDs
    MIntArray normalCounts;
    MIntArray normalIds;
    meshFn.getNormalIds(normalCounts, normalIds);

    if(!normalIds.length())
    {
        return false;
    }

    // reverse winding order
    Util::reverseWindingOrder(normalIds, vertexCount);

    // get normal values
    const float* rawNormals = meshFn.getRawNormals(NULL);

    // build the per-vertex normals
    std::vector<int> lockedNormals(normalIds.length());
    std::vector<float> vertexNormals;
    vertexNormals.reserve(normalIds.length() * 3);
    for(unsigned int i = 0; i < normalIds.length(); ++i)
    {
        if(meshFn.isNormalLocked(normalIds[i]))
        {
            lockedNormals[i] = 1;
        }

        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
        vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
    }

    // add and set it to HAPI
    CHECK_HAPI(hapiSetVertexAttribute(
                geometryNodeId(), 0,
                1,
                "maya_locked_normal",
                lockedNormals
                ));
    CHECK_HAPI(hapiSetVertexAttribute(
            geometryNodeId(), 0,
            3,
            "N",
            vertexNormals
            ));

    return true;
}

bool
InputMesh::processUVs(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount,
        std::vector<int> vertexList
        )
{
    MString currentUVSetName = meshFn.currentUVSetName();

    MStringArray uvSetNames;
    meshFn.getUVSetNames(uvSetNames);

    MStringArray mappedUVAttributeNames;
    mappedUVAttributeNames.setLength(uvSetNames.length());

    for(unsigned int uvSetIndex = 0;
            uvSetIndex < uvSetNames.length(); uvSetIndex++)
    {
        const MString uvSetName = uvSetNames[uvSetIndex];

        const MString uvAttributeName
            = Util::getAttrLayerName("uv", uvSetIndex);
        const MString uvNumberAttributeName
            = Util::getAttrLayerName("uvNumber", uvSetIndex);

        mappedUVAttributeNames[uvSetIndex] = uvAttributeName;

        // get UV IDs
        MIntArray uvCounts;
        MIntArray uvIds;
        meshFn.getAssignedUVs(uvCounts, uvIds, &uvSetName);

        // reverse winding order
        Util::reverseWindingOrder(uvIds, uvCounts);

        // get UV values
        MFloatArray uArray;
        MFloatArray vArray;
        meshFn.getUVs(uArray, vArray, &uvSetName);

        // build the per-vertex UVs
        std::vector<float> vertexUVs;
        std::vector<int> vertexUVNumbers;
        vertexUVs.reserve(vertexList.size() * 3);
        unsigned int uvIdIndex = 0;
        for(unsigned int i = 0; i < uvCounts.length(); ++i)
        {
            if(uvCounts[i] == vertexCount[i])
            {
                // has UVs assigned
                for(int j = 0; j < uvCounts[i]; ++j)
                {
                    vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
                    vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
                    vertexUVs.push_back(0);
                    vertexUVNumbers.push_back(uvIds[uvIdIndex]);

                    uvIdIndex++;
                }
            }
            else
            {
                // no UVs assigned
                for(int j = 0; j < vertexCount[i]; ++j)
                {
                    vertexUVs.push_back(0);
                    vertexUVs.push_back(0);
                    vertexUVs.push_back(0);
                    vertexUVNumbers.push_back(0);
                }
            }
        }

        // add and set it to HAPI
        CHECK_HAPI(hapiSetVertexAttribute(
                geometryNodeId(), 0,
                3,
                uvAttributeName.asChar(),
                vertexUVs
                ));
        CHECK_HAPI(hapiSetVertexAttribute(
                geometryNodeId(), 0,
                1,
                uvNumberAttributeName.asChar(),
                vertexUVNumbers
                ));
    }

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_current",
            currentUVSetName
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_name",
            uvSetNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_uv_mapped_uv",
            mappedUVAttributeNames
            ));

    return true;
}

bool
InputMesh::processColorSets(
        const MFnMesh &meshFn,
        std::vector<int> vertexCount,
        std::vector<int> vertexList
        )
{
    MStringArray currentColorSetName(1, meshFn.currentColorSetName());

    MStringArray colorSetNames;
    meshFn.getColorSetNames(colorSetNames);

    MStringArray mappedCdNames;
    MStringArray mappedAlphaNames;
    mappedCdNames.setLength(colorSetNames.length());
    mappedAlphaNames.setLength(colorSetNames.length());

    MColor defaultUnsetColor;
    MColorArray colors;
    std::vector<float> buffer;
    for(unsigned int i = 0; i < colorSetNames.length(); i++)
    {
        const MString colorSetName = colorSetNames[i];

        bool hasColor = false;
        bool hasAlpha = false;
        {
            MFnMesh::MColorRepresentation colorSetRepresentation =
                meshFn.getColorRepresentation(colorSetName);

            switch(colorSetRepresentation)
            {
                case MFnMesh::kAlpha:
                    hasAlpha = true;
                    break;
                case MFnMesh::kRGB:
                    hasColor = true;
                    break;
                case MFnMesh::kRGBA:
                    hasColor = true;
                    hasAlpha = true;
                    break;
            }
        }

        CHECK_MSTATUS(const_cast<MFnMesh&>(meshFn).getFaceVertexColors(
                    colors,
                    &colorSetName,
                    &defaultUnsetColor
                    ));

        // reverse winding order
        Util::reverseWindingOrder(colors, vertexCount);

        if(hasColor)
        {
            const MString colorAttributeName
                = Util::getAttrLayerName("Cd", i);

            mappedCdNames[i] = colorAttributeName;

            buffer = Util::reshapeArray<
                3,
                0, 3,
                0, 4,
                std::vector<float>
                >(colors);

            // add and set Cd
            CHECK_HAPI(hapiSetVertexAttribute(
                    geometryNodeId(), 0,
                    3,
                    colorAttributeName.asChar(),
                    buffer
                    ));
        }

        if(hasAlpha)
        {
            const MString alphaAttributeName
                = Util::getAttrLayerName("Alpha", i);

            mappedAlphaNames[i] = alphaAttributeName;

            buffer = Util::reshapeArray<
                1,
                0, 1,
                3, 4,
                std::vector<float>
                >(colors);

            // add and set Alpha
            CHECK_HAPI(hapiSetVertexAttribute(
                    geometryNodeId(), 0,
                    1,
                    alphaAttributeName.asChar(),
                    buffer
                    ));
        }
    }

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_current",
            currentColorSetName
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_name",
            colorSetNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_mapped_Cd",
            mappedCdNames
            ));

    CHECK_HAPI(hapiSetDetailAttribute(
            geometryNodeId(), 0,
            "maya_colorset_mapped_Alpha",
            mappedAlphaNames
            ));

    return true;
}

bool
InputMesh::processSets(
        const MPlug &plug,
        const MFnMesh &meshFn
        )
{
    MStatus status;

    // The source node may not be actually mesh node.
    MPlug srcPlug = Util::plugSource(plug);
    if(srcPlug.isNull())
    {
        return false;
    }

    // XXX: instance number
    MDagPath srcDagPath = MDagPath::getAPathTo(srcPlug.node());

    // Sets and Members
    MFnMesh srcNodeFn(srcDagPath, &status);
    CHECK_MSTATUS_AND_RETURN_IT(status);

    MObjectArray sets;
    MObjectArray comps;
    // XXX: instance number
    srcNodeFn.getConnectedSetsAndMembers(0, sets, comps, false);

    MStringArray sgNames;
    MObjectArray sgCompObjs;

    std::vector<int> groupMembership;
    for(int setIndex = 0; setIndex < (int) sets.length(); setIndex++)
    {
        const MObject &setObj = sets[setIndex];
        const MObject &compObj = comps[setIndex];

        MFnDependencyNode setFn(setObj, &status);
        CHECK_MSTATUS(status);

        // Filter out unwanted sets. This mimics setFilterScript().
        MString setType = setFn.typeName();
        if(setType == "shadingEngine")
        {
            sgNames.append(setFn.name());
            sgCompObjs.append(compObj);
            continue;
        }

        if(!(setType == "objectSet" ||
                    setType == "textureBakeSet" ||
                    setType == "vertexBakeSet" ||
                    setType == "creaseSet" ||
                    setType == "character"))
        {
            continue;
        }

        if(setFn.findPlug("verticesOnlySet").asBool()
                || setFn.findPlug("edgesOnlySet").asBool()
                || setFn.findPlug("facetsOnlySet").asBool()
                || setFn.findPlug("editPointsOnlySet").asBool()
                || setFn.findPlug("renderableOnlySet").asBool()
          )
        {
            continue;
        }

        HAPI_GroupType groupType;

        if(compObj.isNull())
        {
            groupType = HAPI_GROUPTYPE_PRIM;
            groupMembership.resize(meshFn.numPolygons());

            std::fill(groupMembership.begin(), groupMembership.end(), 1);
        }
        else
        {
            MFnSingleIndexedComponent componentFn(compObj, &status);
            CHECK_MSTATUS(status);

            switch(componentFn.componentType())
            {
                case MFn::kMeshPolygonComponent:
                    groupType = HAPI_GROUPTYPE_PRIM;
                    groupMembership.resize(meshFn.numPolygons());
                    break;
                case MFn::kMeshVertComponent:
                    groupType = HAPI_GROUPTYPE_POINT;
                    groupMembership.resize(meshFn.numVertices());
                    break;
                default:
                    continue;
                    break;
            }

            std::fill(groupMembership.begin(), groupMembership.end(), 0);
            for(int i = 0; i < componentFn.elementCount(); i++)
            {
                groupMembership[componentFn.element(i)] = 1;
            }
        }

        MString setName = setFn.name();
        // If the set is in a namespace, the name will contain a colon.
        setName = Util::sanitizeStringForNodeName(setName);

        CHECK_HAPI(HAPI_AddGroup(
                    Util::theHAPISession.get(),
                    geometryNodeId(), 0,
                    groupType,
                    setName.asChar()
                    ));

        CHECK_HAPI(HAPI_SetGroupMembership(
                    Util::theHAPISession.get(),
                    geometryNodeId(), 0,
                    groupType,
                    setName.asChar(),
                    &groupMembership[0],
                    0, groupMembership.size()
                    ));
    }

    processShadingGroups(meshFn, sgNames, sgCompObjs);

    return true;
}

bool
InputMesh::processShadingGroups(
        const MFnMesh &meshFn,
        const MStringArray &sgNames,
        const MObjectArray &sgCompObjs
        )
{
    MStatus status;

    if(sgCompObjs.length() == 1 && sgCompObjs[0].isNull())
    {
        CHECK_HAPI(hapiSetDetailAttribute(
                    geometryNodeId(), 0,
                    "maya_shading_group",
                    const_cast<MStringArray&>(sgNames)[0]
                    ));
    }
    else
    {
        MString defaultShader;

        std::vector<const char*> sgNamePerComp;
        sgNamePerComp.resize(meshFn.numPolygons(), defaultShader.asChar());

        for(int i = 0; i < (int) sgNames.length(); i++)
        {
            const char* sgName = sgNames[i].asChar();
            const MObject &sgCompObj = sgCompObjs[i];

            assert(!sgCompObj.isNull());

            MFnSingleIndexedComponent componentFn(sgCompObj, &status);
            CHECK_MSTATUS(status);

            assert(componentFn.componentType()
                    == MFn::kMeshPolygonComponent);

            for(int j = 0; j < componentFn.elementCount(); j++)
            {
                sgNamePerComp[componentFn.element(j)] = sgName;
            }
        }

        CHECK_HAPI(hapiSetPrimAttribute(
                    geometryNodeId(), 0,
                    1,
                    "maya_shading_group",
                    sgNamePerComp
                    ));
    }

    return true;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------

Copyright (c) 2010 Nigel Atkinson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include <scriptingsystem.h>
#include <OgreLogManager.h>
#include <inputeventdata.h>
#include <windoweventdata.h>
#include <animationeventdata.h>
#include <luaresource.h>
#include <gameentity.h>
#include <version.h>
#include <LuaBridge.h>

void bindOgre( lua_State* L ); // From ogrebind.cpp
/*
void bindAnimation( lua_State* L ); // From animationbind.cpp
void bindNavigationMesh( lua_State* L); // From navmeshbind.cpp
*/
void bindGorilla( lua_State *L ); // From gorillabind.cpp

template<class D, class B>
D* downcast( B* ptr )
{
    return dynamic_cast<D*>( ptr );
}

int ScriptingSystem::GUID = 0;

void queueEventThunk( Event& event, lua_State *L )
{
    lua_pushlightuserdata( L, (void *)&ScriptingSystem::GUID );
    lua_gettable( L, LUA_REGISTRYINDEX );

    ScriptingSystem* scriptingSystem = static_cast<ScriptingSystem*>(lua_touserdata( L, -1 ));

    if( scriptingSystem )
    {
        scriptingSystem->queueEvent( EventPtr( new Event(event) ) );
    }
    else
    {
        Ogre::LogManager::getSingleton().stream() << "Error queuing event from Lua; could not retrieve scripting system instance";
    }
}

int luaLibraryLoader( lua_State *L )
{
    if( ! lua_isstring( L, 1 ) )
    {
        luaL_error( L, "luaLibraryLoader: Expected string for first parameter" );
    }

    std::string libraryFile = lua_tostring( L, 1 );
    // In order to be compatible with the normal Lua file loader,
    // translate '.' to the file system seperator character.
    // In this case (An ogre resource) '/'
    while( libraryFile.find('.') != std::string::npos )
        libraryFile.replace( libraryFile.find('.'), 1, "/" );

    libraryFile += ".lua";

    if( ! Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup( libraryFile ) )
    {
        // Could not find the file.
        std::string errMessage = "\n  no file '" + libraryFile + "' found in Ogre resource archives.";
        lua_pushstring( L, errMessage.c_str() );
    }
    else
    {
        LuaResourcePtr library = LuaResourceManager::getSingleton().load( libraryFile, "General" );

        if( luaL_loadbuffer( L, library->getScriptSource().c_str(), library->calculateSize(), libraryFile.c_str() ) )
        {
            luaL_error( L, "Error loading library '%s' from resource archive.\n%s", libraryFile.c_str(), lua_tostring( L, -1 ) );
        }
    }
    return 1;
}

void installLibraryLoader( lua_State *L )
{
    // Insert the c++ func 'luaLibraryLoader' into package.loaders.
    // Inserted at the start of the table in order to take precedence.
    lua_getglobal( L, "table" );
    lua_getfield( L, -1, "insert" );
    lua_remove( L, -2 );    // table
    lua_getglobal( L, "package" );
    lua_getfield( L, -1, "searchers" );
    lua_remove( L, -2 );    // package
    lua_pushnumber( L, 1 ); // index where to insert into loaders table
    lua_pushcfunction( L, luaLibraryLoader );
    if( lua_pcall( L, 3, 0, 0 ) )
        Ogre::LogManager::getSingleton().stream() << lua_tostring( L, 1);
}

void getClassMembers( lua_State* L, luabridge::LuaRef ret )
{

    // List keys where they don't start with underscore.
    lua_pushnil( L );
    while( lua_next( L, -2 ) )
    {
        lua_pushvalue( L, -2 ); // Push copy of key.
        const char *key = lua_tostring( L, -1 );

        if( key )
        {
            if( key[0] != '_' )
            {
                ret.append( key );
            }
        }

        lua_pop( L, 2 ); // Key copy and value
    }
    // List properties
    lua_pushstring( L, "__propget" );
    lua_rawget( L, -2 );
    if( lua_istable( L, -1 ) )
    {
        lua_pushnil( L );
        while( lua_next( L, -2 ) )
        {
            lua_pushvalue( L, -2 ); // Push copy of key.
            const char *key = lua_tostring( L, -1 );

            if( key )
            {
                ret.append( key );
            }

            lua_pop( L, 2 ); // Key copy and value
        }
    }
    lua_pop( L, 1 ); // __propget table

    return;
}

int getClassInfo( lua_State* L )
{
    luabridge::LuaRef ret = luabridge::newTable( L );

    if( lua_istable( L, 1 ) )
    {
        // Class Type
        lua_getmetatable( L, 1 );
        lua_pushstring( L, "__class" );
        lua_rawget( L, -2 );

        if( lua_istable( L, -1 ) )
        {
            getClassMembers( L, ret );
        }
    }
    else if( lua_isuserdata( L, 1 ) )
    {
        // Class instance
        lua_getmetatable( L, 1 );

        getClassMembers( L, ret );
    }

    // Just return an empty table if not a class.
    ret.push( L );

    return 1;
}

void ScriptingSystem::shutdown()
{
    if( mL )
        lua_close( mL );
    mL = 0;
}

void ScriptingSystem::initialise()
{
    mL = luaL_newstate();

    luaL_openlibs( mL );

    lua_pushlightuserdata( mL, (void *)&GUID );
    lua_pushlightuserdata( mL, this );
    lua_settable( mL, LUA_REGISTRYINDEX );

    bind();
    bindOgre( mL );
    /*
    bindGameEntityClasses( mL );
    bindAnimation( mL );
    bindNavigationMesh( mL );
    */
    bindGorilla( mL );

    using namespace luabridge;

    LuaResourcePtr mainlua = LuaResourceManager::getSingleton().load( "main.lua" );

    if( luaL_loadbuffer( mL,
                mainlua->getScriptSource().c_str(),
                mainlua->calculateSize(), "main.lua" ) || lua_pcall( mL, 0, LUA_MULTRET, 0) )
    {
        Ogre::LogManager::getSingleton().stream() << " ****************************** ";
        Ogre::LogManager::getSingleton().stream() << " *** main.lua failed to run     ";
        Ogre::LogManager::getSingleton().stream() << " *** " << lua_tostring( mL, -1 );
        Ogre::LogManager::getSingleton().stream() << " ****************************** ";
    }
}

void ScriptingSystem::bind()
{
    using namespace luabridge;

    installLibraryLoader( mL );

    getGlobalNamespace( mL )
        .addCFunction( "getClassInfo", &getClassInfo )
        .beginNamespace( "Engine" )
        .beginClass<Event>( "Event" )
            .addConstructor<void (*) (const char*)>()
            .addData( "type", &Event::type )
            .addData( "data", &Event::data )
            .addStaticFunction( "hash", &Event::hash )
        .endClass()
        .addFunction( "queueEvent", &queueEventThunk )
        .beginClass<EventData>( "EventData" )
        .endClass()
        .deriveClass<InputEventData, EventData>( "InputEventData" )
            .addConstructor<void (*) (void)>()
            .addStaticFunction( "downcast", &downcast<InputEventData, EventData> )
            .addData( "x", &InputEventData::x )
            .addData( "y", &InputEventData::y )
            .addData( "buttons", &InputEventData::parm )
            .addProperty( "text", &InputEventDataBindingHelper::getText, &InputEventDataBindingHelper::setText )
            .addProperty( "key",  &InputEventDataBindingHelper::getKey,  &InputEventDataBindingHelper::setKey  )
        .endClass()
        .deriveClass<WindowEventData, EventData>( "WindowEventData" )
            .addStaticFunction( "downcast", &downcast<WindowEventData, EventData> )
            .addData( "width", &WindowEventData::width )
            .addData( "height", &WindowEventData::height )
        .endClass()
        /*
        .deriveClass<AnimationEventData, EventData>( "AnimationEventData" )
            .addData( "animation", &AnimationEventData::animation )
        .endClass()
        */
        .addFunction( "versionString", versionString )
    .endNamespace();
}

bool ScriptingSystem::EventNotification( EventPtr event )
{
    luabridge::LuaRef notify = luabridge::getGlobal( mL, "EventNotification");
    luabridge::LuaRef ret( mL );

    if( notify )
    {
        try
        {
            ret = notify( *event );
            if( ret == true )
                return true;
        }
        catch( luabridge::LuaException& e )
        {
            Ogre::LogManager::getSingleton().stream() << e.what();
        }
    }

    return false;
}

bool ScriptingSystem::frameStarted(const Ogre::FrameEvent& evt)
{
    luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameStarted" );

    try
    {
        // If the function is not defined, don't worry about it.
        if( func )
            func( evt.timeSinceLastFrame );
    }
    catch( luabridge::LuaException& e )
    {
        Ogre::LogManager::getSingleton().stream() << e.what();
    }

    return true;
}

bool ScriptingSystem::frameEnded(const Ogre::FrameEvent& evt)
{
    luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameEnded" );

    try
    {
        // If the function is not defined, don't worry about it.
        if( func )
            func( evt.timeSinceLastFrame );
    }
    catch( luabridge::LuaException& e )
    {
        Ogre::LogManager::getSingleton().stream() << e.what();
    }

    // Do a Lua garbage collection.
    lua_gc( mL, LUA_GCSTEP, 1 );

    return true;
}
<commit_msg>Add static members to class info list<commit_after>/*
-----------------------------------------------------------------------------

Copyright (c) 2010 Nigel Atkinson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include <scriptingsystem.h>
#include <OgreLogManager.h>
#include <inputeventdata.h>
#include <windoweventdata.h>
#include <animationeventdata.h>
#include <luaresource.h>
#include <gameentity.h>
#include <version.h>
#include <LuaBridge.h>

void bindOgre( lua_State* L ); // From ogrebind.cpp
/*
void bindAnimation( lua_State* L ); // From animationbind.cpp
void bindNavigationMesh( lua_State* L); // From navmeshbind.cpp
*/
void bindGorilla( lua_State *L ); // From gorillabind.cpp

template<class D, class B>
D* downcast( B* ptr )
{
    return dynamic_cast<D*>( ptr );
}

int ScriptingSystem::GUID = 0;

void queueEventThunk( Event& event, lua_State *L )
{
    lua_pushlightuserdata( L, (void *)&ScriptingSystem::GUID );
    lua_gettable( L, LUA_REGISTRYINDEX );

    ScriptingSystem* scriptingSystem = static_cast<ScriptingSystem*>(lua_touserdata( L, -1 ));

    if( scriptingSystem )
    {
        scriptingSystem->queueEvent( EventPtr( new Event(event) ) );
    }
    else
    {
        Ogre::LogManager::getSingleton().stream() << "Error queuing event from Lua; could not retrieve scripting system instance";
    }
}

int luaLibraryLoader( lua_State *L )
{
    if( ! lua_isstring( L, 1 ) )
    {
        luaL_error( L, "luaLibraryLoader: Expected string for first parameter" );
    }

    std::string libraryFile = lua_tostring( L, 1 );
    // In order to be compatible with the normal Lua file loader,
    // translate '.' to the file system seperator character.
    // In this case (An ogre resource) '/'
    while( libraryFile.find('.') != std::string::npos )
        libraryFile.replace( libraryFile.find('.'), 1, "/" );

    libraryFile += ".lua";

    if( ! Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup( libraryFile ) )
    {
        // Could not find the file.
        std::string errMessage = "\n  no file '" + libraryFile + "' found in Ogre resource archives.";
        lua_pushstring( L, errMessage.c_str() );
    }
    else
    {
        LuaResourcePtr library = LuaResourceManager::getSingleton().load( libraryFile, "General" );

        if( luaL_loadbuffer( L, library->getScriptSource().c_str(), library->calculateSize(), libraryFile.c_str() ) )
        {
            luaL_error( L, "Error loading library '%s' from resource archive.\n%s", libraryFile.c_str(), lua_tostring( L, -1 ) );
        }
    }
    return 1;
}

void installLibraryLoader( lua_State *L )
{
    // Insert the c++ func 'luaLibraryLoader' into package.loaders.
    // Inserted at the start of the table in order to take precedence.
    lua_getglobal( L, "table" );
    lua_getfield( L, -1, "insert" );
    lua_remove( L, -2 );    // table
    lua_getglobal( L, "package" );
    lua_getfield( L, -1, "searchers" );
    lua_remove( L, -2 );    // package
    lua_pushnumber( L, 1 ); // index where to insert into loaders table
    lua_pushcfunction( L, luaLibraryLoader );
    if( lua_pcall( L, 3, 0, 0 ) )
        Ogre::LogManager::getSingleton().stream() << lua_tostring( L, 1);
}

void getClassMembers( lua_State* L, luabridge::LuaRef ret )
{

    // List keys where they don't start with underscore.
    lua_pushnil( L );
    while( lua_next( L, -2 ) )
    {
        lua_pushvalue( L, -2 ); // Push copy of key.
        const char *key = lua_tostring( L, -1 );

        if( key )
        {
            if( key[0] != '_' )
            {
                ret.append( key );
            }
        }

        lua_pop( L, 2 ); // Key copy and value
    }
    // List properties
    lua_pushstring( L, "__propget" );
    lua_rawget( L, -2 );
    if( lua_istable( L, -1 ) )
    {
        lua_pushnil( L );
        while( lua_next( L, -2 ) )
        {
            lua_pushvalue( L, -2 ); // Push copy of key.
            const char *key = lua_tostring( L, -1 );

            if( key )
            {
                ret.append( key );
            }

            lua_pop( L, 2 ); // Key copy and value
        }
    }
    lua_pop( L, 1 ); // __propget table

    return;
}

int getClassInfo( lua_State* L )
{
    luabridge::LuaRef ret = luabridge::newTable( L );

    if( lua_istable( L, 1 ) )
    {
        // Class Type
        lua_getmetatable( L, 1 );

        // Static members.
        getClassMembers( L, ret );

        // Regular members.
        lua_pushstring( L, "__class" );
        lua_rawget( L, -2 );

        if( lua_istable( L, -1 ) )
        {
            getClassMembers( L, ret );
        }
    }
    else if( lua_isuserdata( L, 1 ) )
    {
        // Class instance
        lua_getmetatable( L, 1 );

        getClassMembers( L, ret );
    }

    // Just return an empty table if not a class.
    ret.push( L );

    return 1;
}

void ScriptingSystem::shutdown()
{
    if( mL )
        lua_close( mL );
    mL = 0;
}

void ScriptingSystem::initialise()
{
    mL = luaL_newstate();

    luaL_openlibs( mL );

    lua_pushlightuserdata( mL, (void *)&GUID );
    lua_pushlightuserdata( mL, this );
    lua_settable( mL, LUA_REGISTRYINDEX );

    bind();
    bindOgre( mL );
    /*
    bindGameEntityClasses( mL );
    bindAnimation( mL );
    bindNavigationMesh( mL );
    */
    bindGorilla( mL );

    using namespace luabridge;

    LuaResourcePtr mainlua = LuaResourceManager::getSingleton().load( "main.lua" );

    if( luaL_loadbuffer( mL,
                mainlua->getScriptSource().c_str(),
                mainlua->calculateSize(), "main.lua" ) || lua_pcall( mL, 0, LUA_MULTRET, 0) )
    {
        Ogre::LogManager::getSingleton().stream() << " ****************************** ";
        Ogre::LogManager::getSingleton().stream() << " *** main.lua failed to run     ";
        Ogre::LogManager::getSingleton().stream() << " *** " << lua_tostring( mL, -1 );
        Ogre::LogManager::getSingleton().stream() << " ****************************** ";
    }
}

void ScriptingSystem::bind()
{
    using namespace luabridge;

    installLibraryLoader( mL );

    getGlobalNamespace( mL )
        .addCFunction( "getClassInfo", &getClassInfo )
        .beginNamespace( "Engine" )
        .beginClass<Event>( "Event" )
            .addConstructor<void (*) (const char*)>()
            .addData( "type", &Event::type )
            .addData( "data", &Event::data )
            .addStaticFunction( "hash", &Event::hash )
        .endClass()
        .addFunction( "queueEvent", &queueEventThunk )
        .beginClass<EventData>( "EventData" )
        .endClass()
        .deriveClass<InputEventData, EventData>( "InputEventData" )
            .addConstructor<void (*) (void)>()
            .addStaticFunction( "downcast", &downcast<InputEventData, EventData> )
            .addData( "x", &InputEventData::x )
            .addData( "y", &InputEventData::y )
            .addData( "buttons", &InputEventData::parm )
            .addProperty( "text", &InputEventDataBindingHelper::getText, &InputEventDataBindingHelper::setText )
            .addProperty( "key",  &InputEventDataBindingHelper::getKey,  &InputEventDataBindingHelper::setKey  )
        .endClass()
        .deriveClass<WindowEventData, EventData>( "WindowEventData" )
            .addStaticFunction( "downcast", &downcast<WindowEventData, EventData> )
            .addData( "width", &WindowEventData::width )
            .addData( "height", &WindowEventData::height )
        .endClass()
        /*
        .deriveClass<AnimationEventData, EventData>( "AnimationEventData" )
            .addData( "animation", &AnimationEventData::animation )
        .endClass()
        */
        .addFunction( "versionString", versionString )
    .endNamespace();
}

bool ScriptingSystem::EventNotification( EventPtr event )
{
    luabridge::LuaRef notify = luabridge::getGlobal( mL, "EventNotification");
    luabridge::LuaRef ret( mL );

    if( notify )
    {
        try
        {
            ret = notify( *event );
            if( ret == true )
                return true;
        }
        catch( luabridge::LuaException& e )
        {
            Ogre::LogManager::getSingleton().stream() << e.what();
        }
    }

    return false;
}

bool ScriptingSystem::frameStarted(const Ogre::FrameEvent& evt)
{
    luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameStarted" );

    try
    {
        // If the function is not defined, don't worry about it.
        if( func )
            func( evt.timeSinceLastFrame );
    }
    catch( luabridge::LuaException& e )
    {
        Ogre::LogManager::getSingleton().stream() << e.what();
    }

    return true;
}

bool ScriptingSystem::frameEnded(const Ogre::FrameEvent& evt)
{
    luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameEnded" );

    try
    {
        // If the function is not defined, don't worry about it.
        if( func )
            func( evt.timeSinceLastFrame );
    }
    catch( luabridge::LuaException& e )
    {
        Ogre::LogManager::getSingleton().stream() << e.what();
    }

    // Do a Lua garbage collection.
    lua_gc( mL, LUA_GCSTEP, 1 );

    return true;
}
<|endoftext|>


<commit_before>/*
   Copyright (C) 2006-2009
   by Marco Gulino <marco.gulino@gmail.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2.1 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "constants.h"
#include "servicesfactory.h"
#include "previewingfile.h"
#include "videobackendiface.h"
#include "mplayervideobackend.h"
#include "mplayerthumbs.h"
#include "mplayerthumbs-config.h"

#ifdef PHONON_API
	#include "phononbackend.h"
#endif

PreviewingFile* ServicesFactory::previewingFile(const QString& filePath, unsigned int scalingWidth, unsigned int scalingHeight, QObject* parent) {
  return new PreviewingFile(filePath, scalingWidth, scalingHeight, parent);
}

VideoBackendIFace *ServicesFactory::videoBackend(PreviewingFile* previewingFile, MPlayerThumbsCfg* cfg) {
  kDebug(DBG_AREA) << "videopreview: backend: " << cfg->backend() << endl;
  switch(cfg->backend() ) {
#ifdef PHONON_API
    case VideoBackendIFace::Phonon:
      kDebug(DBG_AREA) << "videopreview: Selected phonon backend\n";
      return new PhononBackend(previewingFile, cfg);
	  break;
    case VideoBackendIFace::MPlayer:
#else
    #warning using mplayer as only backend
    default:
#endif
      kDebug(DBG_AREA) << "videopreview: Selected mplayer backend\n";
      return new MPlayerVideoBackend(previewingFile, cfg);
      break;
  }
  // Well, we should never be here...
  return NULL;
}

MPlayerThumbsCfg* ServicesFactory::config() {
  return MPlayerThumbsCfg::self();
}

ServicesFactory::~ServicesFactory() {

}

<commit_msg>compile on windows<commit_after>/*
   Copyright (C) 2006-2009
   by Marco Gulino <marco.gulino@gmail.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2.1 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "constants.h"
#include "servicesfactory.h"
#include "previewingfile.h"
#include "videobackendiface.h"
#include "mplayervideobackend.h"
#include "mplayerthumbs.h"
#include "mplayerthumbs-config.h"

#ifdef PHONON_API
	#include "phononbackend.h"
#endif

PreviewingFile* ServicesFactory::previewingFile(const QString& filePath, unsigned int scalingWidth, unsigned int scalingHeight, QObject* parent) {
  return new PreviewingFile(filePath, scalingWidth, scalingHeight, parent);
}

VideoBackendIFace *ServicesFactory::videoBackend(PreviewingFile* previewingFile, MPlayerThumbsCfg* cfg) {
  kDebug(DBG_AREA) << "videopreview: backend: " << cfg->backend() << endl;
  switch(cfg->backend() ) {
#ifdef PHONON_API
    case VideoBackendIFace::Phonon:
      kDebug(DBG_AREA) << "videopreview: Selected phonon backend\n";
      return new PhononBackend(previewingFile, cfg);
	  break;
    case VideoBackendIFace::MPlayer:
#else
#ifdef __GNUC__
    #warning using mplayer as only backend
#endif
    default:
#endif
      kDebug(DBG_AREA) << "videopreview: Selected mplayer backend\n";
      return new MPlayerVideoBackend(previewingFile, cfg);
      break;
  }
  // Well, we should never be here...
  return NULL;
}

MPlayerThumbsCfg* ServicesFactory::config() {
  return MPlayerThumbsCfg::self();
}

ServicesFactory::~ServicesFactory() {

}

<|endoftext|>


<commit_before>#include "shared_handlers.h"
#include "canwrite.h"
#include "log.h"

float rotationsSinceRestart = 0;
float odometerSinceRestart = 0;
float fuelConsumedSinceRestartLiters = 0;

void sendDoorStatus(const char* doorId, uint64_t data, CanSignal* signal,
        CanSignal* signals, int signalCount, Listener* listener) {
    if(signal == NULL) {
        debug("Specific door signal for ID %s is NULL, vehicle may not support",
                doorId);
        return;
    }

    float rawAjarStatus = decodeCanSignal(signal, data);
    bool send = true;
    bool ajarStatus = booleanHandler(NULL, signals, signalCount, rawAjarStatus,
            &send);

    if(send && (signal->sendSame || !signal->received ||
                rawAjarStatus != signal->lastValue)) {
        signal->received = true;
        sendEventedBooleanMessage(DOOR_STATUS_GENERIC_NAME, doorId, ajarStatus,
                listener);
    }
    signal->lastValue = rawAjarStatus;
}

void handleDoorStatusMessage(int messageId, uint64_t data, CanSignal* signals,
        int signalCount, Listener* listener) {
    sendDoorStatus("driver", data,
            lookupSignal("driver_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("passenger", data,
            lookupSignal("passenger_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("rear_right", data,
            lookupSignal("rear_right_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("rear_left", data,
            lookupSignal("rear_left_door", signals, signalCount),
            signals, signalCount, listener);
}

float handleRollingOdometer(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    if(value < signal->lastValue) {
        odometerSinceRestart +=
                signal->maxValue - signal->lastValue + value;
    } else {
        odometerSinceRestart += value - signal->lastValue;
    }
    return odometerSinceRestart;
}

float handleRollingOdometerMiles(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    return KM_PER_MILE * handleRollingOdometer(signal, signals, signalCount,
            value, send);
}

float handleRollingOdometerMeters(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    return KM_PER_M * handleRollingOdometer(signal, signals, signalCount, value,
            send);
}

bool handleStrictBoolean(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send) {
    if(value != 0) {
        return true;
    }
    return false;
}

float handleFuelFlow(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send, float multiplier) {
    if(value < signal->lastValue) {
        value += signal->maxValue - signal->lastValue + value;
    } else {
        value += value - signal->lastValue;
    }
    fuelConsumedSinceRestartLiters += multiplier * value;
    return fuelConsumedSinceRestartLiters;
}

float handleFuelFlowGallons(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send) {
    return handleFuelFlow(signal, signals, signalCount, value, send,
            LITERS_PER_GALLON);
}

float handleFuelFlowMicroliters(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send) {
    return handleFuelFlow(signal, signals, signalCount, value, send,
            LITERS_PER_UL);
}

float handleInverted(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send) {
    return value * -1;
}

void handleGpsMessage(int messageId, uint64_t data, CanSignal* signals,
        int signalCount, Listener* listener) {
    float latitudeDegrees = decodeCanSignal(
            lookupSignal("latitude_degrees", signals, signalCount), data);
    float latitudeMinutes = decodeCanSignal(
            lookupSignal("latitude_minutes", signals, signalCount), data);
    float latitudeMinuteFraction = decodeCanSignal(
            lookupSignal("latitude_minute_fraction", signals, signalCount),
            data);
    float longitudeDegrees = decodeCanSignal(
            lookupSignal("longitude_degrees", signals, signalCount), data);
    float longitudeMinutes = decodeCanSignal(
            lookupSignal("longitude_minutes", signals, signalCount), data);
    float longitudeMinuteFraction = decodeCanSignal(
            lookupSignal("longitude_minute_fraction", signals, signalCount),
            data);

    latitudeMinutes = (latitudeMinutes + latitudeMinuteFraction) / 60.0;
    if(latitudeDegrees < 0) {
        latitudeMinutes *= -1;
    }
    latitudeDegrees += latitudeMinutes;

    longitudeMinutes = (longitudeMinutes + longitudeMinuteFraction) / 60.0;
    if(longitudeDegrees < 0) {
        longitudeMinutes *= -1;
    }
    longitudeDegrees += longitudeMinutes;

    sendNumericalMessage("latitude", latitudeDegrees, listener);
    sendNumericalMessage("longitude", longitudeDegrees, listener);
}

bool handleExteriorLightSwitch(CanSignal* signal, CanSignal* signals,
            int signalCount, float value, bool* send) {
    return value == 2 || value == 3;
}

float handleUnsignedSteeringWheelAngle(CanSignal* signal,
        CanSignal* signals, int signalCount, float value, bool* send) {
    CanSignal* steeringAngleSign = lookupSignal("steering_wheel_angle_sign",
            signals, signalCount);

    if(steeringAngleSign == NULL) {
        debug("Unable to find stering wheel angle sign signal\r\n");
        *send = false;
    } else {
        if(steeringAngleSign->lastValue == 0) {
            // left turn
            value *= -1;
        }
    }
    return value;
}

float handleMultisizeWheelRotationCount(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send, float wheelRadius) {
    if(value < signal->lastValue) {
        rotationsSinceRestart += signal->maxValue - signal->lastValue + value;
    } else {
        rotationsSinceRestart += value - signal->lastValue;
    }
    return 2 * PI * wheelRadius * rotationsSinceRestart;
}

void handleButtonEventMessage(int messageId, uint64_t data,
        CanSignal* signals, int signalCount, Listener* listener) {
    CanSignal* buttonTypeSignal = lookupSignal("button_type", signals,
            signalCount);
    CanSignal* buttonStateSignal = lookupSignal("button_state", signals,
            signalCount);

    if(buttonTypeSignal == NULL || buttonStateSignal == NULL) {
        debug("Unable to find button type and state signals\r\n");
        return;
    }

    float rawButtonType = decodeCanSignal(buttonTypeSignal, data);
    float rawButtonState = decodeCanSignal(buttonStateSignal, data);

    bool send = true;
    const char* buttonType = stateHandler(buttonTypeSignal, signals,
            signalCount, rawButtonType, &send);
    if(!send || buttonType == NULL) {
        debug("Unable to find button type corresponding to %f\r\n",
                rawButtonType);
        return;
    }

    const char* buttonState = stateHandler(buttonStateSignal, signals,
            signalCount, rawButtonState, &send);
    if(!send || buttonState == NULL) {
        debug("Unable to find button state corresponding to %f\r\n",
                rawButtonState);
        return;
    }

    sendEventedBooleanMessage(BUTTON_EVENT_GENERIC_NAME, buttonType,
            buttonState, listener);
}

bool handleTurnSignalCommand(const char* name, cJSON* value, cJSON* event,
        CanSignal* signals, int signalCount) {
    const char* direction = value->valuestring;
    CanSignal* signal = NULL;
    if(!strcmp("left", direction)) {
        signal = lookupSignal("turn_signal_left", signals, signalCount);
    } else if(!strcmp("right", direction)) {
        signal = lookupSignal("turn_signal_right", signals, signalCount);
    }

    if(signal != NULL) {
        return sendCanSignal(signal, cJSON_CreateBool(true), booleanWriter,
                signals, signalCount, true);
    } else {
        debug("Unable to find signal for %s turn signal\r\n", direction);
    }
    return false;
}
<commit_msg>Send proper event type from button event handler.<commit_after>#include "shared_handlers.h"
#include "canwrite.h"
#include "log.h"

float rotationsSinceRestart = 0;
float odometerSinceRestart = 0;
float fuelConsumedSinceRestartLiters = 0;

void sendDoorStatus(const char* doorId, uint64_t data, CanSignal* signal,
        CanSignal* signals, int signalCount, Listener* listener) {
    if(signal == NULL) {
        debug("Specific door signal for ID %s is NULL, vehicle may not support",
                doorId);
        return;
    }

    float rawAjarStatus = decodeCanSignal(signal, data);
    bool send = true;
    bool ajarStatus = booleanHandler(NULL, signals, signalCount, rawAjarStatus,
            &send);

    if(send && (signal->sendSame || !signal->received ||
                rawAjarStatus != signal->lastValue)) {
        signal->received = true;
        sendEventedBooleanMessage(DOOR_STATUS_GENERIC_NAME, doorId, ajarStatus,
                listener);
    }
    signal->lastValue = rawAjarStatus;
}

void handleDoorStatusMessage(int messageId, uint64_t data, CanSignal* signals,
        int signalCount, Listener* listener) {
    sendDoorStatus("driver", data,
            lookupSignal("driver_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("passenger", data,
            lookupSignal("passenger_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("rear_right", data,
            lookupSignal("rear_right_door", signals, signalCount),
            signals, signalCount, listener);
    sendDoorStatus("rear_left", data,
            lookupSignal("rear_left_door", signals, signalCount),
            signals, signalCount, listener);
}

float handleRollingOdometer(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    if(value < signal->lastValue) {
        odometerSinceRestart +=
                signal->maxValue - signal->lastValue + value;
    } else {
        odometerSinceRestart += value - signal->lastValue;
    }
    return odometerSinceRestart;
}

float handleRollingOdometerMiles(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    return KM_PER_MILE * handleRollingOdometer(signal, signals, signalCount,
            value, send);
}

float handleRollingOdometerMeters(CanSignal* signal, CanSignal* signals,
       int signalCount, float value, bool* send) {
    return KM_PER_M * handleRollingOdometer(signal, signals, signalCount, value,
            send);
}

bool handleStrictBoolean(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send) {
    if(value != 0) {
        return true;
    }
    return false;
}

float handleFuelFlow(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send, float multiplier) {
    if(value < signal->lastValue) {
        value += signal->maxValue - signal->lastValue + value;
    } else {
        value += value - signal->lastValue;
    }
    fuelConsumedSinceRestartLiters += multiplier * value;
    return fuelConsumedSinceRestartLiters;
}

float handleFuelFlowGallons(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send) {
    return handleFuelFlow(signal, signals, signalCount, value, send,
            LITERS_PER_GALLON);
}

float handleFuelFlowMicroliters(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send) {
    return handleFuelFlow(signal, signals, signalCount, value, send,
            LITERS_PER_UL);
}

float handleInverted(CanSignal* signal, CanSignal* signals, int signalCount,
        float value, bool* send) {
    return value * -1;
}

void handleGpsMessage(int messageId, uint64_t data, CanSignal* signals,
        int signalCount, Listener* listener) {
    float latitudeDegrees = decodeCanSignal(
            lookupSignal("latitude_degrees", signals, signalCount), data);
    float latitudeMinutes = decodeCanSignal(
            lookupSignal("latitude_minutes", signals, signalCount), data);
    float latitudeMinuteFraction = decodeCanSignal(
            lookupSignal("latitude_minute_fraction", signals, signalCount),
            data);
    float longitudeDegrees = decodeCanSignal(
            lookupSignal("longitude_degrees", signals, signalCount), data);
    float longitudeMinutes = decodeCanSignal(
            lookupSignal("longitude_minutes", signals, signalCount), data);
    float longitudeMinuteFraction = decodeCanSignal(
            lookupSignal("longitude_minute_fraction", signals, signalCount),
            data);

    latitudeMinutes = (latitudeMinutes + latitudeMinuteFraction) / 60.0;
    if(latitudeDegrees < 0) {
        latitudeMinutes *= -1;
    }
    latitudeDegrees += latitudeMinutes;

    longitudeMinutes = (longitudeMinutes + longitudeMinuteFraction) / 60.0;
    if(longitudeDegrees < 0) {
        longitudeMinutes *= -1;
    }
    longitudeDegrees += longitudeMinutes;

    sendNumericalMessage("latitude", latitudeDegrees, listener);
    sendNumericalMessage("longitude", longitudeDegrees, listener);
}

bool handleExteriorLightSwitch(CanSignal* signal, CanSignal* signals,
            int signalCount, float value, bool* send) {
    return value == 2 || value == 3;
}

float handleUnsignedSteeringWheelAngle(CanSignal* signal,
        CanSignal* signals, int signalCount, float value, bool* send) {
    CanSignal* steeringAngleSign = lookupSignal("steering_wheel_angle_sign",
            signals, signalCount);

    if(steeringAngleSign == NULL) {
        debug("Unable to find stering wheel angle sign signal\r\n");
        *send = false;
    } else {
        if(steeringAngleSign->lastValue == 0) {
            // left turn
            value *= -1;
        }
    }
    return value;
}

float handleMultisizeWheelRotationCount(CanSignal* signal, CanSignal* signals,
        int signalCount, float value, bool* send, float wheelRadius) {
    if(value < signal->lastValue) {
        rotationsSinceRestart += signal->maxValue - signal->lastValue + value;
    } else {
        rotationsSinceRestart += value - signal->lastValue;
    }
    return 2 * PI * wheelRadius * rotationsSinceRestart;
}

void handleButtonEventMessage(int messageId, uint64_t data,
        CanSignal* signals, int signalCount, Listener* listener) {
    CanSignal* buttonTypeSignal = lookupSignal("button_type", signals,
            signalCount);
    CanSignal* buttonStateSignal = lookupSignal("button_state", signals,
            signalCount);

    if(buttonTypeSignal == NULL || buttonStateSignal == NULL) {
        debug("Unable to find button type and state signals\r\n");
        return;
    }

    float rawButtonType = decodeCanSignal(buttonTypeSignal, data);
    float rawButtonState = decodeCanSignal(buttonStateSignal, data);

    bool send = true;
    const char* buttonType = stateHandler(buttonTypeSignal, signals,
            signalCount, rawButtonType, &send);
    if(!send || buttonType == NULL) {
        debug("Unable to find button type corresponding to %f\r\n",
                rawButtonType);
        return;
    }

    const char* buttonState = stateHandler(buttonStateSignal, signals,
            signalCount, rawButtonState, &send);
    if(!send || buttonState == NULL) {
        debug("Unable to find button state corresponding to %f\r\n",
                rawButtonState);
        return;
    }

    sendEventedStringMessage(BUTTON_EVENT_GENERIC_NAME, buttonType,
            buttonState, listener);
}

bool handleTurnSignalCommand(const char* name, cJSON* value, cJSON* event,
        CanSignal* signals, int signalCount) {
    const char* direction = value->valuestring;
    CanSignal* signal = NULL;
    if(!strcmp("left", direction)) {
        signal = lookupSignal("turn_signal_left", signals, signalCount);
    } else if(!strcmp("right", direction)) {
        signal = lookupSignal("turn_signal_right", signals, signalCount);
    }

    if(signal != NULL) {
        return sendCanSignal(signal, cJSON_CreateBool(true), booleanWriter,
                signals, signalCount, true);
    } else {
        debug("Unable to find signal for %s turn signal\r\n", direction);
    }
    return false;
}
<|endoftext|>


<commit_before>/*
 *  SnapFind
 *  An interactive image search application
 *  Version 1
 *
 *  Copyright (c) 2002-2005 Intel Corporation
 *  Copyright (c) 2006 Larry Huston <larry@thehustons.net>
 *  All Rights Reserved.
 *
 *  This software is distributed under the terms of the Eclipse Public
 *  License, Version 1.0 which can be found in the file named LICENSE.
 *  ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
 *  RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
 */

#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <sys/queue.h>
#include "lib_results.h"
#include "img_search.h"
#include "search_support.h"
#include "search_set.h"
#include "read_config.h"
#include "factory.h"

static factory_map_t * fmap = NULL;
static factory_map_t * codec_fmap = NULL;

void add_new_search_type(img_factory *fact);
void add_new_codec(img_factory *fact);

void
factory_register_codec(img_factory *factory)
{
	factory_map_t *new_map;

	new_map = (factory_map_t *)malloc(sizeof(*new_map));
	assert(new_map != NULL);

	new_map->fm_factory = factory;
	new_map->fm_next = codec_fmap;
	codec_fmap = new_map;

	add_new_codec(factory);
}

void
factory_register(img_factory *factory)
{

	factory_map_t *new_map;

	new_map = (factory_map_t *)malloc(sizeof(*new_map));
	assert(new_map != NULL);

	new_map->fm_factory = factory;

	/* XXX find dups ?? */

	new_map->fm_next = fmap;
	fmap = new_map;

	add_new_search_type(factory);
}

img_factory *
find_codec_factory(const char *name)
{
	factory_map_t *cur_map;

	printf("**** find_codec_factory\n");

	for (cur_map = codec_fmap; cur_map != NULL;
	    cur_map = cur_map->fm_next) {
		if (strcmp(name, cur_map->fm_factory->get_description()) == 0) {
			return(cur_map->fm_factory);
		}
	}

	fprintf(stderr, "Could not find a codec factory for %s.\n", name);
	fprintf(stderr, "Is the PLUGIN_DIR configuration setting correct\n");
	fprintf(stderr, "in your snapfindrc file?\n");

	return(NULL);
}

img_factory *
find_factory(const char *name)
{
	factory_map_t *cur_map;

	for (cur_map = fmap; cur_map != NULL; cur_map = cur_map->fm_next) {
		if (strcmp(name, cur_map->fm_factory->get_description()) == 0) {
			return(cur_map->fm_factory);
		}
	}
	return(NULL);
}

img_factory *
get_first_factory(void **cookie)
{
	factory_map_t *cur_map;

	cur_map = fmap;
	if (cur_map == NULL) {
		*cookie = NULL;
		return(NULL);
	} else {
		*cookie = (void *)cur_map;
		return(cur_map->fm_factory);
	}
}

img_factory *
get_next_factory(void **cookie)
{
	factory_map_t *cur_map = (factory_map_t *)*cookie;

	if (cur_map == NULL) {
		*cookie = NULL;
		return(NULL);
	} else {
		cur_map = cur_map->fm_next;
		*cookie = (void *)cur_map;
		if (cur_map == NULL) {
			return(NULL);
		} else {
			return(cur_map->fm_factory);
		}
	}
}
<commit_msg>Remove old debug printf<commit_after>/*
 *  SnapFind
 *  An interactive image search application
 *  Version 1
 *
 *  Copyright (c) 2002-2005 Intel Corporation
 *  Copyright (c) 2006 Larry Huston <larry@thehustons.net>
 *  All Rights Reserved.
 *
 *  This software is distributed under the terms of the Eclipse Public
 *  License, Version 1.0 which can be found in the file named LICENSE.
 *  ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
 *  RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
 */

#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <sys/queue.h>
#include "lib_results.h"
#include "img_search.h"
#include "search_support.h"
#include "search_set.h"
#include "read_config.h"
#include "factory.h"

static factory_map_t * fmap = NULL;
static factory_map_t * codec_fmap = NULL;

void add_new_search_type(img_factory *fact);
void add_new_codec(img_factory *fact);

void
factory_register_codec(img_factory *factory)
{
	factory_map_t *new_map;

	new_map = (factory_map_t *)malloc(sizeof(*new_map));
	assert(new_map != NULL);

	new_map->fm_factory = factory;
	new_map->fm_next = codec_fmap;
	codec_fmap = new_map;

	add_new_codec(factory);
}

void
factory_register(img_factory *factory)
{

	factory_map_t *new_map;

	new_map = (factory_map_t *)malloc(sizeof(*new_map));
	assert(new_map != NULL);

	new_map->fm_factory = factory;

	/* XXX find dups ?? */

	new_map->fm_next = fmap;
	fmap = new_map;

	add_new_search_type(factory);
}

img_factory *
find_codec_factory(const char *name)
{
	factory_map_t *cur_map;

	//printf("**** find_codec_factory\n");

	for (cur_map = codec_fmap; cur_map != NULL;
	    cur_map = cur_map->fm_next) {
		if (strcmp(name, cur_map->fm_factory->get_description()) == 0) {
			return(cur_map->fm_factory);
		}
	}

	fprintf(stderr, "Could not find a codec factory for %s.\n", name);
	fprintf(stderr, "Is the PLUGIN_DIR configuration setting correct\n");
	fprintf(stderr, "in your snapfindrc file?\n");

	return(NULL);
}

img_factory *
find_factory(const char *name)
{
	factory_map_t *cur_map;

	for (cur_map = fmap; cur_map != NULL; cur_map = cur_map->fm_next) {
		if (strcmp(name, cur_map->fm_factory->get_description()) == 0) {
			return(cur_map->fm_factory);
		}
	}
	return(NULL);
}

img_factory *
get_first_factory(void **cookie)
{
	factory_map_t *cur_map;

	cur_map = fmap;
	if (cur_map == NULL) {
		*cookie = NULL;
		return(NULL);
	} else {
		*cookie = (void *)cur_map;
		return(cur_map->fm_factory);
	}
}

img_factory *
get_next_factory(void **cookie)
{
	factory_map_t *cur_map = (factory_map_t *)*cookie;

	if (cur_map == NULL) {
		*cookie = NULL;
		return(NULL);
	} else {
		cur_map = cur_map->fm_next;
		*cookie = (void *)cur_map;
		if (cur_map == NULL) {
			return(NULL);
		} else {
			return(cur_map->fm_factory);
		}
	}
}
<|endoftext|>


<commit_before>/**
 * \file stereoCalibPrep.cpp
 *
 *  \date Aug 6, 2013
 *  \author Michał Orynicz
 */

#include <boost/program_options.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <string>
#include <iostream>

#include "ConvenienceFunctions.hpp"

const int USER_TRIGGERED_EXIT = 0;

void parseCommandline(const int &argc, char **argv,
        std::string &target, int &leftCapture, int &rightCapture) {

    boost::program_options::options_description desc;

    desc.add_options()("help,h", "this help message")("left,l",
            boost::program_options::value<int>(),
            "number of /dev/videoX device used as left camera")(
            "right,r", boost::program_options::value<int>(),
            "number of /dev/videoX device used as left camera")(
            "output,o", boost::program_options::value<std::string>(),
            "output file for list of pictures");
    boost::program_options::variables_map vm;
    boost::program_options::store(
            boost::program_options::parse_command_line(argc, argv,
                    desc), vm);
    boost::program_options::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        throw USER_TRIGGERED_EXIT;
    }

    if (vm.count("left")) {
        leftCapture = vm["left"].as<int>();
    }

    if (vm.count("right")) {
        rightCapture = vm["right"].as<int>();
    }

    if (vm.count("output")) {
        target = vm["output"].as<std::string>();
    }
}

int main(int argc, char **argv) {
    std::string target;
    int leftDevice;
    int rightDevice;

    cv::VideoCapture leftCapture;
    cv::VideoCapture rightCapture;

    parseCommandline(argc, argv, target, leftDevice, rightDevice);

    leftCapture.open(leftDevice);
    if (!leftCapture.isOpened()) {
        cv::Exception ex(0, "Didn't open device left", __func__, __FILE__,
        __LINE__);
        throw ex;
    }
    rightCapture.open(rightDevice);
    if (!rightCapture.isOpened()) {
        cv::Exception ex(0, "Didn't open device rightCapture", __func__, __FILE__,
        __LINE__);
        throw ex;
    }
    cv::Size imageSize(leftCapture.get(CV_CAP_PROP_FRAME_WIDTH),
            leftCapture.get(CV_CAP_PROP_FRAME_HEIGHT));

    cv::Mat display(imageSize.height, imageSize.width * 2, CV_8UC3);

    char c = ' ';

    cv::Rect leftRoi(cv::Point(imageSize.width, 0), imageSize);
    cv::Rect rightRoi(cv::Point(0, 0), imageSize);
    std::cerr << imageSize << std::endl;
    std::cerr << display.size() << std::endl;
    std::cerr << leftRoi << std::endl;
    std::cerr << rightRoi << std::endl;
    cv::namedWindow("main", cv::WINDOW_NORMAL);

    cv::FileStorage fs(target + "/imageList.xml",
            cv::FileStorage::WRITE);
    if (!fs.isOpened()) {
        cv::Exception ex(-1, "Could not open FileStorage", __func__,
                __FILE__, __LINE__);
    }

    fs << "images" << "[";
    int counter = 0;
    int delay = 300;
    int dc = 0;
    cv::waitKey(1000);
    do {
        std::vector<cv::Mat> tmp(2);
        cv::Mat l = display(leftRoi);
        cv::Mat r = display(rightRoi);
        leftCapture.grab();
        rightCapture.grab();
        leftCapture.retrieve(tmp[0]);
        rightCapture.retrieve(tmp[1]);
        tmp[0].copyTo(l);
        tmp[1].copyTo(r);
        cv::imshow("main", display);
        c = cv::waitKey(1);
        if (dc >= delay) {
            std::string leftPath = target + "/left"
                    + std::to_string(counter) + ".png";
            std::string rightPath = target + "/right"
                    + std::to_string(counter) + ".png";
            cv::imwrite(leftPath, l);
            cv::imwrite(rightPath, r);
            fs << leftPath;
            fs << rightPath;
            dc = 0;
        }
        ++dc;
    } while ('q' != c);
    fs << "]";
    fs.release();
}
<commit_msg>Fix broken include paths<commit_after>/**
 * \file stereoCalibPrep.cpp
 *
 *  \date Aug 6, 2013
 *  \author Michał Orynicz
 */

#include <boost/program_options.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <string>
#include <iostream>

#include "ConvenienceFunctions.hpp"

const int USER_TRIGGERED_EXIT = 0;

void parseCommandline(const int &argc, char **argv,
        std::string &target, int &leftCapture, int &rightCapture) {

    boost::program_options::options_description desc;

    desc.add_options()("help,h", "this help message")("left,l",
            boost::program_options::value<int>(),
            "number of /dev/videoX device used as left camera")(
            "right,r", boost::program_options::value<int>(),
            "number of /dev/videoX device used as left camera")(
            "output,o", boost::program_options::value<std::string>(),
            "output file for list of pictures");
    boost::program_options::variables_map vm;
    boost::program_options::store(
            boost::program_options::parse_command_line(argc, argv,
                    desc), vm);
    boost::program_options::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        throw USER_TRIGGERED_EXIT;
    }

    if (vm.count("left")) {
        leftCapture = vm["left"].as<int>();
    }

    if (vm.count("right")) {
        rightCapture = vm["right"].as<int>();
    }

    if (vm.count("output")) {
        target = vm["output"].as<std::string>();
    }
}

int main(int argc, char **argv) {
    std::string target;
    int leftDevice;
    int rightDevice;

    cv::VideoCapture leftCapture;
    cv::VideoCapture rightCapture;

    parseCommandline(argc, argv, target, leftDevice, rightDevice);

    leftCapture.open(leftDevice);
    if (!leftCapture.isOpened()) {
        cv::Exception ex(0, "Didn't open device left", __func__, __FILE__,
        __LINE__);
        throw ex;
    }
    rightCapture.open(rightDevice);
    if (!rightCapture.isOpened()) {
        cv::Exception ex(0, "Didn't open device rightCapture", __func__, __FILE__,
        __LINE__);
        throw ex;
    }
    cv::Size imageSize(leftCapture.get(CV_CAP_PROP_FRAME_WIDTH),
            leftCapture.get(CV_CAP_PROP_FRAME_HEIGHT));

    cv::Mat display(imageSize.height, imageSize.width * 2, CV_8UC3);

    char c = ' ';

    cv::Rect leftRoi(cv::Point(imageSize.width, 0), imageSize);
    cv::Rect rightRoi(cv::Point(0, 0), imageSize);
    std::cerr << imageSize << std::endl;
    std::cerr << display.size() << std::endl;
    std::cerr << leftRoi << std::endl;
    std::cerr << rightRoi << std::endl;
    cv::namedWindow("main", cv::WINDOW_NORMAL);

    cv::FileStorage fs(target + "/imageList.xml",
            cv::FileStorage::WRITE);
    if (!fs.isOpened()) {
        cv::Exception ex(-1, "Could not open FileStorage", __func__,
                __FILE__, __LINE__);
    }

    fs << "images" << "[";
    int counter = 0;
    int delay = 300;
    int dc = 0;
    cv::waitKey(1000);
    do {
        std::vector<cv::Mat> tmp(2);
        cv::Mat l = display(leftRoi);
        cv::Mat r = display(rightRoi);
        leftCapture.grab();
        rightCapture.grab();
        leftCapture.retrieve(tmp[0]);
        rightCapture.retrieve(tmp[1]);
        tmp[0].copyTo(l);
        tmp[1].copyTo(r);
        cv::imshow("main", display);
        c = cv::waitKey(1);
        if (dc >= delay) {
            std::string leftPath = target + "/left"
                    + std::to_string(counter) + ".png";
            std::string rightPath = target + "/right"
                    + std::to_string(counter) + ".png";
            cv::imwrite(leftPath, l);
            cv::imwrite(rightPath, r);
            fs << leftPath;
            fs << rightPath;
            dc = 0;
        }
        ++dc;
    } while ('q' != c);
    fs << "]";
    fs.release();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: svgcom.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-09 09:08:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVGCOM_HXX
#define _SVGCOM_HXX

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#ifndef _SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GDIMTF_HXX
#include <vcl/gdimtf.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metaact.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#include <com/sun/star/svg/XSVGWriter.hpp>
#include <com/sun/star/svg/XSVGPrinter.hpp>

#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

// -----------------------------------------------------------------------------

#define NMSP_CPPU       cppu
#define NMSP_RTL        rtl
#define NMSP_UNO        com::sun::star::uno
#define NMSP_LANG       com::sun::star::lang
#define NMSP_SAX        com::sun::star::xml::sax
#define NMSP_SVG        com::sun::star::svg
#define NMSP_REGISTRY   com::sun::star::registry

#define REF( _def_Obj )                     NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )                     NMSP_UNO::Sequence< _def_Obj >
#define ANY                                 NMSP_UNO::Any
#define B2UCONST( _def_pChar )              (NMSP_RTL::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
#define SVG_DTD_STRING                      B2UCONST( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" )

#endif // _SYNCCOM_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.214); FILE MERGED 2005/09/05 13:01:12 rt 1.4.214.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svgcom.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:41:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVGCOM_HXX
#define _SVGCOM_HXX

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#ifndef _SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GDIMTF_HXX
#include <vcl/gdimtf.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metaact.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#include <com/sun/star/svg/XSVGWriter.hpp>
#include <com/sun/star/svg/XSVGPrinter.hpp>

#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

// -----------------------------------------------------------------------------

#define NMSP_CPPU       cppu
#define NMSP_RTL        rtl
#define NMSP_UNO        com::sun::star::uno
#define NMSP_LANG       com::sun::star::lang
#define NMSP_SAX        com::sun::star::xml::sax
#define NMSP_SVG        com::sun::star::svg
#define NMSP_REGISTRY   com::sun::star::registry

#define REF( _def_Obj )                     NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )                     NMSP_UNO::Sequence< _def_Obj >
#define ANY                                 NMSP_UNO::Any
#define B2UCONST( _def_pChar )              (NMSP_RTL::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
#define SVG_DTD_STRING                      B2UCONST( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" )

#endif // _SYNCCOM_HXX
<|endoftext|>