<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  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
//
//  Current versions can be found at www.libavg.de
//

void export_bitmap();
void export_raster();
void export_event();
#ifndef WIN32
void export_devices();
#endif

#include "WrapHelper.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../player/Player.h"
#include "../player/AVGNode.h"
#include "../player/DivNode.h"
#include "../player/PanoImage.h"
#include "../player/Sound.h"

#include <boost/version.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost::python;
using namespace avg;

void export_node()
{
    class_<Node, boost::shared_ptr<Node>, boost::noncopyable>("Node",
            "Base class for all elements in the avg tree.",
            no_init)
        .def(self == self)
        .def(self != self)
        .def("__hash__", &Node::getHash)
        .def("getParent", &Node::getParent,
                "getParent() -> node\n"
                "Returns the container (AVGNode or DivNode) the node is in. For\n"
                "the root node, returns None.\n")
        .def("unlink", &Node::unlink,
                "unlink() -> None\n"
                "Removes a node from it's parent container. Equivalent to\n"
                "node.getParent().removeChild(node.getParent().indexOf(node)).")
        .def("setEventCapture", &Node::setMouseEventCapture,
                "setEventCapture(cursorid)\n"
                "Sets up event capturing so that cursor events are sent to this node\n"
                "regardless of the cursor position. cursorid is optional; if left out,\n"
                "the mouse cursor is captured. If not, events from a specific tracker\n"
                "cursor are captured. If the node doesn't handle the event, it\n"
                "propagates to its parent normally. This function is useful for the\n"
                "implementation of user interface elements such as scroll bars. Only one\n"
                "node can capture a cursor at any one time. Normal operation can\n"
                "be restored by calling releaseEventCapture().\n"
                "@param cursorid: The id of the tracker cursor to capture (optional).\n")
        .def("setEventCapture", &Node::setEventCapture)
        .def("releaseEventCapture", &Node::releaseMouseEventCapture,
                "releaseEventCapture(cursorid)\n"
                "Restores normal mouse operation after a call to setEventCapture().\n"
                "@param cursorid: The id of the tracker cursor to release (optional).\n")
        .def("releaseEventCapture", &Node::releaseEventCapture)
        .def("setEventHandler", &Node::setEventHandler,
                "setEventHandler(type, source, pyfunc)\n"
                "Sets a callback function that is invoked whenever an event of the\n"
                "specified type from the specified source occurs. This function is\n"
                "similar to the event handler node attributes (e.g. oncursordown).\n"
                "It is more specific since it takes the event source as a parameter\n"
                "and allows the use of any python callable as callback function.\n"
                "@param type: One of the event types KEYUP, KEYDOWN, CURSORMOTION,\n"
                "CURSORUP, CURSORDOWN, CURSOROVER, CURSOROUT, RESIZE or QUIT.\n"
                "@param source: MOUSE for mouse events, TOUCH for multitouch touch\n"
                "events, TRACK for multitouch track events or other tracking, \n"
                "NONE for keyboard events. Sources can be or'ed together to set a\n"
                "handler for several sources at once.\n"
                "@param pyfunc: The python callable to invoke.\n")
        .def("getAbsPos", &Node::getAbsPos,
                "getAbsPos(relpos) -> abspos\n"
                "Transforms a position in coordinates relative to the node to a\n"
                "position in window coordinates.\n"
                "@param relpos: Relative coordinate to transform.")
        .def("getRelPos", &Node::getRelPos,
                "getRelPos(abspos) -> relpos\n"
                "Transforms a position in window coordinates to a position\n"
                "in coordinates relative to the node.\n"
                "@param abspos: Absolute coordinate to transform.")
        .def("getMediaSize", &Node::getMediaSize,
                "getMediaSize() -> mediasize\n"
                "Returns the size in pixels of the media in the node. Image nodes\n"
                "return the bitmap size, Camera nodes\n"
                "the size of a camera frame and Words nodes the amount of space\n"
                "the text takes. Video nodes the video size if decoding has started\n"
                "or (0,0) if not.")
        .add_property("id", make_function(&Node::getID,
                return_value_policy<copy_const_reference>()), &Node::setID,
                "A unique identifier that can be used to reference the node.\n")
        .add_property("x", &Node::getX, &Node::setX,
                "The position of the node's left edge relative to it's parent node.\n")
        .add_property("y", &Node::getY, &Node::setY,
                "The position of the node's top edge relative to it's parent node.\n")
        .add_property("pos", make_function(&Node::getPos,
                return_value_policy<copy_const_reference>()), &Node::setPos,
                "The position of the node's top left corner relative to it's parent node.\n")
        .add_property("width", &Node::getWidth, &Node::setWidth)
        .add_property("height", &Node::getHeight, &Node::setHeight)
        .add_property("size", &Node::getSize, &Node::setSize)
        .add_property("angle", &Node::getAngle, &Node::setAngle,
                "The angle that the node is rotated to in radians. 0 is\n"
                "unchanged, 3.14 is upside-down.\n")
        .add_property("pivotx", &Node::getPivotX, &Node::setPivotX,
                "x coordinate of the point that the node is rotated around.\n"
                "Default is the center of the node.\n")
        .add_property("pivoty", &Node::getPivotY, &Node::setPivotY,
                "y coordinate of the point that the node is rotated around.\n"
                "Default is the center of the node.\n")
        .add_property("opacity", &Node::getOpacity, &Node::setOpacity,
                      "A measure of the node's transparency. 0.0 is completely\n"
                      "transparent, 1.0 is completely opaque. Opacity is relative to\n"
                      "the parent node's opacity.\n")
        .add_property("active", &Node::getActive, &Node::setActive,
                      "If this attribute is true, the node behaves as usual. If not, it\n"
                      "is neither drawn nor does it react to events. Videos are paused.\n")
        .add_property("sensitive", &Node::getSensitive, &Node::setSensitive,
                      "A node only reacts to events if sensitive is true.")
    ;

    export_bitmap();
    export_raster();

    class_<DivNode, bases<Node>, boost::noncopyable>("DivNode",
            "A div node is a node that groups other nodes logically and visually.\n"
            "Its upper left corner is used as point of origin for the coordinates\n"
            "of its child nodes. Its extents are used to clip the children. Its\n"
            "opacity is used as base opacity for the child nodes' opacities.\n"
            "The children of a div node are drawn in the order they are found\n"
            "in the avg file.",
            no_init)
        .add_property("mediadir", make_function(&DivNode::getMediaDir,
                return_value_policy<copy_const_reference>()), &DivNode::setMediaDir,
                "The directory that the media files for the children of this node are in.\n")
        .add_property("crop", &DivNode::getCrop, &DivNode::setCrop,
                "Turns clipping on or off. Default is True.\n")
        .def("getNumChildren", &DivNode::getNumChildren,
                "getNumChildren() -> numchildren\n"
                "Returns the number of immediate children that this div contains.")
        .def("getChild", &DivNode::getChild,
                "getChild(pos) -> node\n"
                "Returns the child at position pos.")
        .def("appendChild", &DivNode::appendChild,
                "appendChild(node)\n"
                "Adds a new child to the container behind the last existing child.")
        .def("insertChildBefore", &DivNode::insertChildBefore,
                "insertChildBefore(newNode, oldChild)\n"
                "Adds a new child to the container in front of the existing node oldChild.")
        .def("insertChild", &DivNode::insertChild,
                "insertChild(node, pos)\n"
                "Adds a new child to the container at position pos.")
        .def("removeChild", (void (DivNode::*)(NodePtr))(&DivNode::removeChild),
                "removeChild(node)\n"
                "Removes the child given by pNode.")
        .def("removeChild", (void (DivNode::*)(unsigned))(&DivNode::removeChild),
                "removeChild(pos)\n"
                "Removes the child at index pos.")
        .def("reorderChild", (void (DivNode::*)(unsigned, unsigned))(&DivNode::reorderChild),
                "reorderChild(oldPos, newPos)\n"
                "Moves the child at index pos so it's at index newPos. This function\n"
                "can be used to change the order in which the children are drawn.")
        .def("reorderChild", (void (DivNode::*)(NodePtr, unsigned))(&DivNode::reorderChild),
                "reorderChild(node, newPos)\n"
                "Moves the child node so it's at index newPos. This function\n"
                "can be used to change the order in which the children are drawn.")
        .def("indexOf", &DivNode::indexOf,
                "indexOf(childnode)\n"
                "Returns the index of the child given or -1 if childnode isn't a\n"
                "child of the container. This function does a linear search through\n"
                "the list of children until the child is found.")
    ;

    class_<AVGNode, bases<DivNode> >("AVGNode",
            "Root node of any avg tree. Defines the properties of the display and\n"
            "handles key press events. The AVGNode's width and height define the\n"
            "coordinate system for the display and are the default for the window\n"
            "size used (i.e. by default, the coordinate system is pixel-based.)\n",
            no_init)
        .def("getCropSetting", &AVGNode::getCropSetting,
                "getCropSetting() -> isCropActive\n\n"
                "Returns true if cropping is active. Cropping can be turned off globally\n"
                "in the avg file. (Deprecated. This attribute is only nessesary because\n"
                "of certain buggy display drivers that don't work with cropping.)")
    ;

    class_<Sound, bases<Node> >("Sound",
            "A sound played from a file.\n",
            no_init)
        .def("play", &Sound::play,
                "play()\n"
                "Starts audio playback.")
        .def("stop", &Sound::stop,
                "stop()\n"
                "Stops audio playback. Closes the object and 'rewinds' the playback\n"
                "cursor.")
        .def("pause", &Sound::pause,
                "pause()\n"
                "Stops audio playback but doesn't close the object. The playback\n"
                "cursor stays at the same position.")
        .def("setEOFCallback", &Sound::setEOFCallback,
                "setEOFCallback(pyfunc)\n"
                "Sets a python callable to be invoked when the video reaches end of file.")
        .add_property("href", make_function(&Sound::getHRef,
                return_value_policy<copy_const_reference>()), &Sound::setHRef,
                "The source filename of the sound.\n")
        .add_property("loop", &Sound::getLoop,
                "Whether to start the sound again when it has ended (ro).\n")
    ;
    class_<PanoImage, bases<Node> >("PanoImage",
            "A panorama image displayed in cylindrical projection.\n",
            no_init)
        .def("getScreenPosFromPanoPos", &PanoImage::getScreenPosFromPanoPos,
                "getScreenPosFromPanoPos(panoPos) -> pos\n"
                "Converts a position in panorama image pixels to pixels in coordinates\n"
                "relative to the node, taking into account the current rotation angle.\n")
        .def("getScreenPosFromAngle", &PanoImage::getScreenPosFromAngle,
                "getScreenPosFromAngle(angle) -> pos\n"
                "Converts panorama angle to pixels in coordinates\n"
                "relative to the node, taking into account the current rotation angle.\n")
        .add_property("href", make_function(&PanoImage::getHRef,
                return_value_policy<copy_const_reference>()), &PanoImage::setHRef,
                "The source filename of the image.\n")
        .add_property("sensorwidth", &PanoImage::getSensorWidth,
                &PanoImage::setSensorWidth,
                "The width of the sensor used to make the image. This value\n"
                "is used together with sensorheight and focallength to\n"
                "determine the projection to use.\n")
        .add_property("sensorheight", &PanoImage::getSensorHeight,
                &PanoImage::setSensorHeight,
                "The height of the sensor used to make the image.\n")
        .add_property("focallength", &PanoImage::getFocalLength,
                &PanoImage::setFocalLength,
                "The focal length of the lens in millimeters.\n")
        .add_property("hue", &PanoImage::getHue,
                "A hue to color the image in. (ro, deprecated)\n")
        .add_property("saturation", &PanoImage::getSaturation,
                "The saturation the image should have. (ro, deprecated)\n")
        .add_property("rotation", &PanoImage::getRotation, &PanoImage::setRotation,
                "The current angle the viewer is looking at in radians.\n")
        .add_property("maxrotation", &PanoImage::getMaxRotation,
                "The maximum angle the viewer can look at.\n")
    ;

}
<commit_msg>Added duration property to Sound nodes.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  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
//
//  Current versions can be found at www.libavg.de
//

void export_bitmap();
void export_raster();
void export_event();
#ifndef WIN32
void export_devices();
#endif

#include "WrapHelper.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../player/Player.h"
#include "../player/AVGNode.h"
#include "../player/DivNode.h"
#include "../player/PanoImage.h"
#include "../player/Sound.h"

#include <boost/version.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost::python;
using namespace avg;

void export_node()
{
    class_<Node, boost::shared_ptr<Node>, boost::noncopyable>("Node",
            "Base class for all elements in the avg tree.",
            no_init)
        .def(self == self)
        .def(self != self)
        .def("__hash__", &Node::getHash)
        .def("getParent", &Node::getParent,
                "getParent() -> node\n"
                "Returns the container (AVGNode or DivNode) the node is in. For\n"
                "the root node, returns None.\n")
        .def("unlink", &Node::unlink,
                "unlink() -> None\n"
                "Removes a node from it's parent container. Equivalent to\n"
                "node.getParent().removeChild(node.getParent().indexOf(node)).")
        .def("setEventCapture", &Node::setMouseEventCapture,
                "setEventCapture(cursorid)\n"
                "Sets up event capturing so that cursor events are sent to this node\n"
                "regardless of the cursor position. cursorid is optional; if left out,\n"
                "the mouse cursor is captured. If not, events from a specific tracker\n"
                "cursor are captured. If the node doesn't handle the event, it\n"
                "propagates to its parent normally. This function is useful for the\n"
                "implementation of user interface elements such as scroll bars. Only one\n"
                "node can capture a cursor at any one time. Normal operation can\n"
                "be restored by calling releaseEventCapture().\n"
                "@param cursorid: The id of the tracker cursor to capture (optional).\n")
        .def("setEventCapture", &Node::setEventCapture)
        .def("releaseEventCapture", &Node::releaseMouseEventCapture,
                "releaseEventCapture(cursorid)\n"
                "Restores normal mouse operation after a call to setEventCapture().\n"
                "@param cursorid: The id of the tracker cursor to release (optional).\n")
        .def("releaseEventCapture", &Node::releaseEventCapture)
        .def("setEventHandler", &Node::setEventHandler,
                "setEventHandler(type, source, pyfunc)\n"
                "Sets a callback function that is invoked whenever an event of the\n"
                "specified type from the specified source occurs. This function is\n"
                "similar to the event handler node attributes (e.g. oncursordown).\n"
                "It is more specific since it takes the event source as a parameter\n"
                "and allows the use of any python callable as callback function.\n"
                "@param type: One of the event types KEYUP, KEYDOWN, CURSORMOTION,\n"
                "CURSORUP, CURSORDOWN, CURSOROVER, CURSOROUT, RESIZE or QUIT.\n"
                "@param source: MOUSE for mouse events, TOUCH for multitouch touch\n"
                "events, TRACK for multitouch track events or other tracking, \n"
                "NONE for keyboard events. Sources can be or'ed together to set a\n"
                "handler for several sources at once.\n"
                "@param pyfunc: The python callable to invoke.\n")
        .def("getAbsPos", &Node::getAbsPos,
                "getAbsPos(relpos) -> abspos\n"
                "Transforms a position in coordinates relative to the node to a\n"
                "position in window coordinates.\n"
                "@param relpos: Relative coordinate to transform.")
        .def("getRelPos", &Node::getRelPos,
                "getRelPos(abspos) -> relpos\n"
                "Transforms a position in window coordinates to a position\n"
                "in coordinates relative to the node.\n"
                "@param abspos: Absolute coordinate to transform.")
        .def("getMediaSize", &Node::getMediaSize,
                "getMediaSize() -> mediasize\n"
                "Returns the size in pixels of the media in the node. Image nodes\n"
                "return the bitmap size, Camera nodes\n"
                "the size of a camera frame and Words nodes the amount of space\n"
                "the text takes. Video nodes the video size if decoding has started\n"
                "or (0,0) if not.")
        .add_property("id", make_function(&Node::getID,
                return_value_policy<copy_const_reference>()), &Node::setID,
                "A unique identifier that can be used to reference the node.\n")
        .add_property("x", &Node::getX, &Node::setX,
                "The position of the node's left edge relative to it's parent node.\n")
        .add_property("y", &Node::getY, &Node::setY,
                "The position of the node's top edge relative to it's parent node.\n")
        .add_property("pos", make_function(&Node::getPos,
                return_value_policy<copy_const_reference>()), &Node::setPos,
                "The position of the node's top left corner relative to it's parent node.\n")
        .add_property("width", &Node::getWidth, &Node::setWidth)
        .add_property("height", &Node::getHeight, &Node::setHeight)
        .add_property("size", &Node::getSize, &Node::setSize)
        .add_property("angle", &Node::getAngle, &Node::setAngle,
                "The angle that the node is rotated to in radians. 0 is\n"
                "unchanged, 3.14 is upside-down.\n")
        .add_property("pivotx", &Node::getPivotX, &Node::setPivotX,
                "x coordinate of the point that the node is rotated around.\n"
                "Default is the center of the node.\n")
        .add_property("pivoty", &Node::getPivotY, &Node::setPivotY,
                "y coordinate of the point that the node is rotated around.\n"
                "Default is the center of the node.\n")
        .add_property("opacity", &Node::getOpacity, &Node::setOpacity,
                      "A measure of the node's transparency. 0.0 is completely\n"
                      "transparent, 1.0 is completely opaque. Opacity is relative to\n"
                      "the parent node's opacity.\n")
        .add_property("active", &Node::getActive, &Node::setActive,
                      "If this attribute is true, the node behaves as usual. If not, it\n"
                      "is neither drawn nor does it react to events. Videos are paused.\n")
        .add_property("sensitive", &Node::getSensitive, &Node::setSensitive,
                      "A node only reacts to events if sensitive is true.")
    ;

    export_bitmap();
    export_raster();

    class_<DivNode, bases<Node>, boost::noncopyable>("DivNode",
            "A div node is a node that groups other nodes logically and visually.\n"
            "Its upper left corner is used as point of origin for the coordinates\n"
            "of its child nodes. Its extents are used to clip the children. Its\n"
            "opacity is used as base opacity for the child nodes' opacities.\n"
            "The children of a div node are drawn in the order they are found\n"
            "in the avg file.",
            no_init)
        .add_property("mediadir", make_function(&DivNode::getMediaDir,
                return_value_policy<copy_const_reference>()), &DivNode::setMediaDir,
                "The directory that the media files for the children of this node are in.\n")
        .add_property("crop", &DivNode::getCrop, &DivNode::setCrop,
                "Turns clipping on or off. Default is True.\n")
        .def("getNumChildren", &DivNode::getNumChildren,
                "getNumChildren() -> numchildren\n"
                "Returns the number of immediate children that this div contains.")
        .def("getChild", &DivNode::getChild,
                "getChild(pos) -> node\n"
                "Returns the child at position pos.")
        .def("appendChild", &DivNode::appendChild,
                "appendChild(node)\n"
                "Adds a new child to the container behind the last existing child.")
        .def("insertChildBefore", &DivNode::insertChildBefore,
                "insertChildBefore(newNode, oldChild)\n"
                "Adds a new child to the container in front of the existing node oldChild.")
        .def("insertChild", &DivNode::insertChild,
                "insertChild(node, pos)\n"
                "Adds a new child to the container at position pos.")
        .def("removeChild", (void (DivNode::*)(NodePtr))(&DivNode::removeChild),
                "removeChild(node)\n"
                "Removes the child given by pNode.")
        .def("removeChild", (void (DivNode::*)(unsigned))(&DivNode::removeChild),
                "removeChild(pos)\n"
                "Removes the child at index pos.")
        .def("reorderChild", (void (DivNode::*)(unsigned, unsigned))(&DivNode::reorderChild),
                "reorderChild(oldPos, newPos)\n"
                "Moves the child at index pos so it's at index newPos. This function\n"
                "can be used to change the order in which the children are drawn.")
        .def("reorderChild", (void (DivNode::*)(NodePtr, unsigned))(&DivNode::reorderChild),
                "reorderChild(node, newPos)\n"
                "Moves the child node so it's at index newPos. This function\n"
                "can be used to change the order in which the children are drawn.")
        .def("indexOf", &DivNode::indexOf,
                "indexOf(childnode)\n"
                "Returns the index of the child given or -1 if childnode isn't a\n"
                "child of the container. This function does a linear search through\n"
                "the list of children until the child is found.")
    ;

    class_<AVGNode, bases<DivNode> >("AVGNode",
            "Root node of any avg tree. Defines the properties of the display and\n"
            "handles key press events. The AVGNode's width and height define the\n"
            "coordinate system for the display and are the default for the window\n"
            "size used (i.e. by default, the coordinate system is pixel-based.)\n",
            no_init)
        .def("getCropSetting", &AVGNode::getCropSetting,
                "getCropSetting() -> isCropActive\n\n"
                "Returns true if cropping is active. Cropping can be turned off globally\n"
                "in the avg file. (Deprecated. This attribute is only nessesary because\n"
                "of certain buggy display drivers that don't work with cropping.)")
    ;

    class_<Sound, bases<Node> >("Sound",
            "A sound played from a file.\n",
            no_init)
        .def("play", &Sound::play,
                "play()\n"
                "Starts audio playback.")
        .def("stop", &Sound::stop,
                "stop()\n"
                "Stops audio playback. Closes the object and 'rewinds' the playback\n"
                "cursor.")
        .def("pause", &Sound::pause,
                "pause()\n"
                "Stops audio playback but doesn't close the object. The playback\n"
                "cursor stays at the same position.")
        .def("setEOFCallback", &Sound::setEOFCallback,
                "setEOFCallback(pyfunc)\n"
                "Sets a python callable to be invoked when the video reaches end of file.")
        .add_property("href", make_function(&Sound::getHRef,
                return_value_policy<copy_const_reference>()), &Sound::setHRef,
                "The source filename of the sound.\n")
        .add_property("loop", &Sound::getLoop,
                "Whether to start the sound again when it has ended (ro).\n")
        .add_property("duration", &Sound::getDuration,
                "The duration of the sound file in milliseconds (ro).\n")
    ;

    class_<PanoImage, bases<Node> >("PanoImage",
            "A panorama image displayed in cylindrical projection.\n",
            no_init)
        .def("getScreenPosFromPanoPos", &PanoImage::getScreenPosFromPanoPos,
                "getScreenPosFromPanoPos(panoPos) -> pos\n"
                "Converts a position in panorama image pixels to pixels in coordinates\n"
                "relative to the node, taking into account the current rotation angle.\n")
        .def("getScreenPosFromAngle", &PanoImage::getScreenPosFromAngle,
                "getScreenPosFromAngle(angle) -> pos\n"
                "Converts panorama angle to pixels in coordinates\n"
                "relative to the node, taking into account the current rotation angle.\n")
        .add_property("href", make_function(&PanoImage::getHRef,
                return_value_policy<copy_const_reference>()), &PanoImage::setHRef,
                "The source filename of the image.\n")
        .add_property("sensorwidth", &PanoImage::getSensorWidth,
                &PanoImage::setSensorWidth,
                "The width of the sensor used to make the image. This value\n"
                "is used together with sensorheight and focallength to\n"
                "determine the projection to use.\n")
        .add_property("sensorheight", &PanoImage::getSensorHeight,
                &PanoImage::setSensorHeight,
                "The height of the sensor used to make the image.\n")
        .add_property("focallength", &PanoImage::getFocalLength,
                &PanoImage::setFocalLength,
                "The focal length of the lens in millimeters.\n")
        .add_property("hue", &PanoImage::getHue,
                "A hue to color the image in. (ro, deprecated)\n")
        .add_property("saturation", &PanoImage::getSaturation,
                "The saturation the image should have. (ro, deprecated)\n")
        .add_property("rotation", &PanoImage::getRotation, &PanoImage::setRotation,
                "The current angle the viewer is looking at in radians.\n")
        .add_property("maxrotation", &PanoImage::getMaxRotation,
                "The maximum angle the viewer can look at.\n")
    ;

}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdio>
#include <stack>

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/raw_ostream.h>

using namespace llvm;

static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";

struct Loop {
  BasicBlock *Entry, *Body, *Exit;
  PHINode *DataPtrBody, *DataPtrExit;
};

int main() {
  // LLVM context.
  LLVMContext &Context = getGlobalContext();
  Module MainModule("brainfuck program", Context);
  IRBuilder<> Builder(Context);

  // Some useful constants.
  Type *CellType = Type::getInt8Ty(Context);
  Constant *One = ConstantInt::get(CellType, 1);

  // Function prototypes for the shim.
  FunctionType *PutFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>(1, CellType) /* argument types */,
      false /* var args */);
  Function *PutFunction = Function::Create(PutFunctionType,
      Function::ExternalLinkage, "brainfuck_put", &MainModule);
  FunctionType *GetFunctionType = FunctionType::get(
      CellType /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *GetFunction = Function::Create(GetFunctionType,
      Function::ExternalLinkage, "brainfuck_get", &MainModule);

  // Global data for a brainfuck program.
  ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
  GlobalVariable *Data = new GlobalVariable(
      MainModule, DataType, false /* constant */,
      GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
      DATA_NAME);
  Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);

  // Main function definition.
  FunctionType *MainFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *MainFunction = Function::Create(MainFunctionType,
      Function::ExternalLinkage, "brainfuck_main", &MainModule);
  BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
  Builder.SetInsertPoint(MainBlock);

  // Code generation.
  int c;
  Value *Value;
  std::stack<Loop> Loops;
  Loop ThisLoop;
  while ((c = getchar()) != EOF) {
    switch (c) {
      case '>':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
        break;
      case '<':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
        break;
      case '+':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateAdd(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '-':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateSub(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '.':
        Value = Builder.CreateLoad(DataPtr);
        Builder.CreateCall(PutFunction, Value);
        break;
      case ',':
        Value = Builder.CreateCall(GetFunction);
        Builder.CreateStore(Value, DataPtr);
        break;

      case '[':
        // Prepare data for the stack.
        ThisLoop.Entry = Builder.GetInsertBlock();
        ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
        ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);

        // Emit the beginning conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Define the pointer after the loop.
        Builder.SetInsertPoint(ThisLoop.Exit);
        ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);

        // Define the pointer within the loop.
        Builder.SetInsertPoint(ThisLoop.Body);
        ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);

        // Continue generating code within the loop.
        DataPtr = ThisLoop.DataPtrBody;
        Loops.push(ThisLoop);
        break;

      case ']':
        // Pop data off the stack.
        if (Loops.empty()) {
          fputs("] requires matching [\n", stderr);
          abort();
        }
        ThisLoop = Loops.top();
        Loops.pop();

        // Finish off the phi nodes.
        ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
        ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());

        // Emit the ending conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Move insertion after the loop.
        ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
        DataPtr = ThisLoop.DataPtrExit;
        Builder.SetInsertPoint(ThisLoop.Exit);
        break;
    }
  }

  // Ensure all loops have been closed.
  if (!Loops.empty()) {
    fputs("[ requires matching ]\n", stderr);
    abort();
  }

  // Finish off brainfuck_main and dump.
  Builder.CreateRetVoid();
  MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<commit_msg>Alphabetize the llvm headers.<commit_after>#include <cassert>
#include <cstdio>
#include <stack>

#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/raw_ostream.h>

using namespace llvm;

static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";

struct Loop {
  BasicBlock *Entry, *Body, *Exit;
  PHINode *DataPtrBody, *DataPtrExit;
};

int main() {
  // LLVM context.
  LLVMContext &Context = getGlobalContext();
  Module MainModule("brainfuck program", Context);
  IRBuilder<> Builder(Context);

  // Some useful constants.
  Type *CellType = Type::getInt8Ty(Context);
  Constant *One = ConstantInt::get(CellType, 1);

  // Function prototypes for the shim.
  FunctionType *PutFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>(1, CellType) /* argument types */,
      false /* var args */);
  Function *PutFunction = Function::Create(PutFunctionType,
      Function::ExternalLinkage, "brainfuck_put", &MainModule);
  FunctionType *GetFunctionType = FunctionType::get(
      CellType /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *GetFunction = Function::Create(GetFunctionType,
      Function::ExternalLinkage, "brainfuck_get", &MainModule);

  // Global data for a brainfuck program.
  ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
  GlobalVariable *Data = new GlobalVariable(
      MainModule, DataType, false /* constant */,
      GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
      DATA_NAME);
  Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);

  // Main function definition.
  FunctionType *MainFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *MainFunction = Function::Create(MainFunctionType,
      Function::ExternalLinkage, "brainfuck_main", &MainModule);
  BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
  Builder.SetInsertPoint(MainBlock);

  // Code generation.
  int c;
  Value *Value;
  std::stack<Loop> Loops;
  Loop ThisLoop;
  while ((c = getchar()) != EOF) {
    switch (c) {
      case '>':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
        break;
      case '<':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
        break;
      case '+':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateAdd(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '-':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateSub(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '.':
        Value = Builder.CreateLoad(DataPtr);
        Builder.CreateCall(PutFunction, Value);
        break;
      case ',':
        Value = Builder.CreateCall(GetFunction);
        Builder.CreateStore(Value, DataPtr);
        break;

      case '[':
        // Prepare data for the stack.
        ThisLoop.Entry = Builder.GetInsertBlock();
        ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
        ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);

        // Emit the beginning conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Define the pointer after the loop.
        Builder.SetInsertPoint(ThisLoop.Exit);
        ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);

        // Define the pointer within the loop.
        Builder.SetInsertPoint(ThisLoop.Body);
        ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);

        // Continue generating code within the loop.
        DataPtr = ThisLoop.DataPtrBody;
        Loops.push(ThisLoop);
        break;

      case ']':
        // Pop data off the stack.
        if (Loops.empty()) {
          fputs("] requires matching [\n", stderr);
          abort();
        }
        ThisLoop = Loops.top();
        Loops.pop();

        // Finish off the phi nodes.
        ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
        ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());

        // Emit the ending conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Move insertion after the loop.
        ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
        DataPtr = ThisLoop.DataPtrExit;
        Builder.SetInsertPoint(ThisLoop.Exit);
        break;
    }
  }

  // Ensure all loops have been closed.
  if (!Loops.empty()) {
    fputs("[ requires matching ]\n", stderr);
    abort();
  }

  // Finish off brainfuck_main and dump.
  Builder.CreateRetVoid();
  MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkTestingMacros.h"

#include "mitkDataNodeFactory.h"
#include "mitkStandaloneDataStorage.h"

#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkPNGWriter.h>
#include <vtkRegressionTestImage.h> // nice one

#include <vector>
#include <algorithm>

#include "mitkRenderingTestHelper.h"
#include <mitkLevelWindow.h>

class mitkRenderingTestHelperClass
{

public:

    static mitk::BaseData::Pointer AddToStorage(const std::string& filename)
    {
        mitk::DataNodeFactory::Pointer reader = mitk::DataNodeFactory::New();
        try
        {
            reader->SetFileName( filename );
            reader->Update();

            if(reader->GetNumberOfOutputs()<1)
            {
                MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'");
            }

            mitk::DataNode::Pointer node = reader->GetOutput( 0 );
            mitkRenderingTestHelperClass::s_DataStorage->Add(node);
            return node->GetData();
        }
        catch ( itk::ExceptionObject & e )
        {
            MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what());
        }
    }

    static mitk::DataStorage::Pointer s_DataStorage;

}; // end test helper class

mitk::DataStorage::Pointer mitkRenderingTestHelperClass::s_DataStorage;

int mitkRenderingTest(int argc, char* argv[])
{
    // load all arguments into a datastorage, take last argument as reference rendering
    // setup a renderwindow of fixed size X*Y
    // render the datastorage
    // compare rendering to reference image
    MITK_TEST_BEGIN("RenderingTest")

            // enough parameters?
            if ( argc < 2 )
    {
        MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" )
                MITK_TEST_OUTPUT( << "Will render a central transversal slice of all given files into outputfile" )
                exit( EXIT_SUCCESS );
    }

    // parse parameters
    std::vector<std::string> inputFileNames;
    for (int i = 1; i < argc-1; ++i)
    {
        //add everything to a list but -T and -V
        std::string tmp = argv[i];
        if((tmp.compare("-T")) && (tmp.compare("-V")))
        {
            inputFileNames.push_back( tmp );
        }
    }
    //    std::string outputFileName( argv[argc-1] );

    // load all input into a data storage
    mitkRenderingTestHelperClass::s_DataStorage = mitk::StandaloneDataStorage::New().GetPointer();
    MITK_TEST_CONDITION_REQUIRED(mitkRenderingTestHelperClass::s_DataStorage.IsNotNull(),"StandaloneDataStorage instantiation");

    std::for_each( inputFileNames.begin(), inputFileNames.end(), mitkRenderingTestHelperClass::AddToStorage );

    // create a QmitkRenderWindow, let it render the scene and get the vtkRenderWindow
    mitkRenderingTestHelper renderingHelper( 640, 480, mitkRenderingTestHelperClass::s_DataStorage );
    //use this to generate a reference screenshot or save the file:
    renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png");
    int retVal = vtkRegressionTestImage( renderingHelper.GetVtkRenderWindow() );

    //retVal meanings: (see VTK/Rendering/vtkTesting.h)
    //0 = test failed
    //1 = test passed
    //2 = test not run
    //3 = something with vtkInteraction
    MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" );

    MITK_TEST_END();
}

<commit_msg>Added boolean variable to save the reference screenshot<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkTestingMacros.h"

#include "mitkDataNodeFactory.h"
#include "mitkStandaloneDataStorage.h"

#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkPNGWriter.h>
#include <vtkRegressionTestImage.h> // nice one

#include <vector>
#include <algorithm>

#include "mitkRenderingTestHelper.h"
#include <mitkLevelWindow.h>

class mitkRenderingTestHelperClass
{

public:

    static mitk::BaseData::Pointer AddToStorage(const std::string& filename)
    {
        mitk::DataNodeFactory::Pointer reader = mitk::DataNodeFactory::New();
        try
        {
            reader->SetFileName( filename );
            reader->Update();

            if(reader->GetNumberOfOutputs()<1)
            {
                MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'");
            }

            mitk::DataNode::Pointer node = reader->GetOutput( 0 );
            mitkRenderingTestHelperClass::s_DataStorage->Add(node);
            return node->GetData();
        }
        catch ( itk::ExceptionObject & e )
        {
            MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what());
        }
    }

    static mitk::DataStorage::Pointer s_DataStorage;

}; // end test helper class

mitk::DataStorage::Pointer mitkRenderingTestHelperClass::s_DataStorage;

int mitkRenderingTest(int argc, char* argv[])
{
    // load all arguments into a datastorage, take last argument as reference rendering
    // setup a renderwindow of fixed size X*Y
    // render the datastorage
    // compare rendering to reference image
    MITK_TEST_BEGIN("RenderingTest")

            // enough parameters?
            if ( argc < 2 )
    {
        MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" )
                MITK_TEST_OUTPUT( << "Will render a central transversal slice of all given files into outputfile" )
                exit( EXIT_SUCCESS );
    }

    // parse parameters
    std::vector<std::string> inputFileNames;
    for (int i = 1; i < argc-1; ++i)
    {
        //add everything to a list but -T and -V
        std::string tmp = argv[i];
        if((tmp.compare("-T")) && (tmp.compare("-V")))
        {
            inputFileNames.push_back( tmp );
        }
    }
    //    std::string outputFileName( argv[argc-1] );

    // load all input into a data storage
    mitkRenderingTestHelperClass::s_DataStorage = mitk::StandaloneDataStorage::New().GetPointer();
    MITK_TEST_CONDITION_REQUIRED(mitkRenderingTestHelperClass::s_DataStorage.IsNotNull(),"StandaloneDataStorage instantiation");

    std::for_each( inputFileNames.begin(), inputFileNames.end(), mitkRenderingTestHelperClass::AddToStorage );

    // create a mitkRenderWindow, let it render the scene and get the vtkRenderWindow
    mitkRenderingTestHelper renderingHelper( 640, 480, mitkRenderingTestHelperClass::s_DataStorage );

    //use this to generate a reference screenshot or save the file:
    bool generateReferenceScreenshot = false;
    if(generateReferenceScreenshot)
    {
        renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png");
    }
    int retVal = vtkRegressionTestImage( renderingHelper.GetVtkRenderWindow() );

    //retVal meanings: (see VTK/Rendering/vtkTesting.h)
    //0 = test failed
    //1 = test passed
    //2 = test not run
    //3 = something with vtkInteraction
    MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" );

    MITK_TEST_END();
}

<|endoftext|>


<commit_before>#include<cstdio>
#include<cstring>
#include"serv.h"
int main(int argc, char **argv) {
  unsigned int i, port = 65637, id = 257;
  bool topo = false;
  Server serv;
  for (i = 1; i + 1 < argc; ++i) {
    if (!strcmp(argv[i], "-p"))
      sscanf(argv[++i], "%u", &port);
    else if (!strcmp(argv[i], "-t"))
      topo |= serv.Load(argv[++i]);
    else if (!strcmp(argv[i], "-d"))
      sscanf(argv[++i], "%u", &id);
  }
  if (!topo || !serv.Init(id, port))
    return 0;
  while (1) {
    printf("> ");
    serv.Wait();
    char cmd[64];
    if (!strcmp(cmd, "send"))
      serv.Send();
    else if (!strcmp(cmd, "update")) {
      unsigned id, cost;
      scanf("%u %u", &id, &cost);
      serv.Update(id, cost);
    }
    else if (!strcmp(cmd, "display"))
      serv.Display();
  }
}
<commit_msg>忘了scanf指令<commit_after>#include<cstdio>
#include<cstring>
#include"serv.h"
int main(int argc, char **argv) {
  unsigned int i, port = 65637, id = 257;
  bool topo = false;
  Server serv;
  for (i = 1; i + 1 < argc; ++i) {
    if (!strcmp(argv[i], "-p"))
      sscanf(argv[++i], "%u", &port);
    else if (!strcmp(argv[i], "-t"))
      topo |= serv.Load(argv[++i]);
    else if (!strcmp(argv[i], "-d"))
      sscanf(argv[++i], "%u", &id);
  }
  if (!topo || !serv.Init(id, port)){
	  fprintf(stderr, "Usage: DV_routing -p <port> -t <topo-file> -d <server-id>\n");
    return 0;
  }
  while (1) {
    printf("> ");
	fflush(stdout);
    serv.Wait();
    char cmd[64];
	scanf("%s", cmd);
    if (!strcmp(cmd, "send"))
      serv.Send();
    else if (!strcmp(cmd, "update")) {
      unsigned id, cost;
      scanf("%u %u", &id, &cost);
      serv.Update(id, cost);
    }
    else if (!strcmp(cmd, "display"))
      serv.Display();
  }
}
<|endoftext|>


<commit_before>d1f303cc-2747-11e6-8c37-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>d2007066-2747-11e6-b40a-e0f84713e7b8<|endoftext|>


<commit_before>// Platform Specific Code
#include "Standard.h"

// Sub-System Components
#include "component/entities/entities.h"
#include "component/gameai/gameai.h"
#include "component/enemyai/enemyai.h"
#include "component/rendering/rendering.h"
#include "component/physics/physics.h"
#include "component/input/input.h"
#ifdef _WIN32
#include "component/audio/audio.h"
#endif

#define PLAYAUDIO 0

int main( int argc, char** argv )
{
	// -- Platfor Specific Init -----------------------------------------------
	INIT_PLATFORM();

	// -- Init components -----------------------------------------------------
	// Register Events
	Renderer *renderer = new Renderer();
	init_inventory();
	Physics::Simulation *simulation = new Physics::Simulation();
	Input *input = new Input();
#if (PLAYAUDIO)
	Audio *audio = new Audio();
#endif

	GameAi *gameai = new GameAi();
	EnemyAi *enemyai = new EnemyAi();

	// Act on events
	gameai->setup();
	renderer->setup();
	simulation->loadWorld();
	input->setup();
	enemyai->setup();
#if (PLAYAUDIO)
	audio->setup();
#endif

	// -- Main Loop -----------------------------------------------------------
	while (gameai->planFrame())
	{
		Real elapsed_time = gameai->getElapsedTime();

		input->HandleEvents();
		enemyai->update(elapsed_time);

		simulation->step(elapsed_time);

#if (PLAYAUDIO)
		audio->update(elapsed_time);
#endif
		renderer->render(elapsed_time);
	}

	// -- Cleanup & Exit ------------------------------------------------------
	delete enemyai;
	delete input;
	delete simulation;
	delete gameai;
#if (PLAYAUDIO)
	delete audio;
#endif
	delete renderer;
	shutdown_inventory();

	return 0;
}
<commit_msg>turned sound on<commit_after>// Platform Specific Code
#include "Standard.h"

// Sub-System Components
#include "component/entities/entities.h"
#include "component/gameai/gameai.h"
#include "component/enemyai/enemyai.h"
#include "component/rendering/rendering.h"
#include "component/physics/physics.h"
#include "component/input/input.h"
#ifdef _WIN32
#include "component/audio/audio.h"
#endif

#define PLAYAUDIO 1

int main( int argc, char** argv )
{
	// -- Platfor Specific Init -----------------------------------------------
	INIT_PLATFORM();

	// -- Init components -----------------------------------------------------
	// Register Events
	Renderer *renderer = new Renderer();
	init_inventory();
	Physics::Simulation *simulation = new Physics::Simulation();
	Input *input = new Input();
#if (PLAYAUDIO)
	Audio *audio = new Audio();
#endif

	GameAi *gameai = new GameAi();
	EnemyAi *enemyai = new EnemyAi();

	// Act on events
	gameai->setup();
	renderer->setup();
	simulation->loadWorld();
	input->setup();
	enemyai->setup();
#if (PLAYAUDIO)
	audio->setup();
#endif

	// -- Main Loop -----------------------------------------------------------
	while (gameai->planFrame())
	{
		Real elapsed_time = gameai->getElapsedTime();

		input->HandleEvents();
		enemyai->update(elapsed_time);

		simulation->step(elapsed_time);

#if (PLAYAUDIO)
		audio->update(elapsed_time);
#endif
		renderer->render(elapsed_time);
	}

	// -- Cleanup & Exit ------------------------------------------------------
	delete enemyai;
	delete input;
	delete simulation;
	delete gameai;
#if (PLAYAUDIO)
	delete audio;
#endif
	delete renderer;
	shutdown_inventory();

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: document.hxx,v $
 *
 *  $Revision: 1.32 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 12:39:43 $
 *
 *  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 DOCUMENT_HXX
#define DOCUMENT_HXX

#define SMDLL   1

#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif

#include <vcl/jobset.hxx>

class SmNode;
class SfxMenuBarManager;
class SfxPrinter;
class Printer;

#define HINT_DATACHANGED    1004

#define SM30BIDENT   ((ULONG)0x534D3033L)
#define SM30IDENT    ((ULONG)0x30334d53L)
#define SM304AIDENT  ((ULONG)0x34303330L)
#define SM30VERSION  ((ULONG)0x00010000L)
#define SM50VERSION  ((ULONG)0x00010001L)   //Unterschied zur SM30VERSION ist
                                            //der neue Border im Format.

#define FRMIDENT    ((ULONG)0x03031963L)
#define FRMVERSION  ((ULONG)0x00010001L)

#define STAROFFICE_XML  "StarOffice XML (Math)"
#define MATHML_XML      "MathML XML (Math)"

/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
 * ==========================================================================
 *
 * Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
 * das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
 * grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
 * einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
 * im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
 * Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
 * (etwa waehrend des Paints).
 * Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
 * oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
 * fuer die der Access auch Friend der DocShell ist.
*/

class SmDocShell;
class EditEngine;

class SmPrinterAccess
{
    Printer* pPrinter;
    OutputDevice* pRefDev;
public:
    SmPrinterAccess( SmDocShell &rDocShell );
    ~SmPrinterAccess();
    Printer* GetPrinter()  { return pPrinter; }
    OutputDevice* GetRefDev()  { return pRefDev; }
};

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

void SetEditEngineDefaultFonts(
        EditEngine &rEditEngine,
        SfxItemPool &rEditEngineItemPool );

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

class SmDocShell : public SfxObjectShell, public SfxListener
{
    friend class SmPrinterAccess;
    friend class SmModel;

    String              aText;
    SmFormat            aFormat;
    SmParser            aInterpreter;
    String              aAccText;
    SmNode             *pTree;
    SfxMenuBarManager  *pMenuMgr;
    SfxItemPool        *pEditEngineItemPool;
    EditEngine         *pEditEngine;
    SfxPrinter         *pPrinter;       //Siehe Kommentar zum SmPrinter Access!
    Printer            *pTmpPrinter;    //ebenfalls
    long                nLeftBorder,
                        nRightBorder,
                        nTopBorder,
                        nBottomBorder;
    USHORT              nModifyCount;
    BOOL                bIsFormulaArranged;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
                        const SfxHint& rHint, const TypeId& rHintType);

    BOOL        WriteAsMathType3( SfxMedium& );

    virtual void        Draw(OutputDevice *pDevice,
                             const JobSetup & rSetup,
                             USHORT nAspect = ASPECT_CONTENT);

    virtual void        FillClass(SvGlobalName* pClassName,
                                  sal_uInt32*  pFormat,
                                  String* pAppName,
                                  String* pFullTypeName,
                                  String* pShortTypeName,
                                  sal_Int32 nFileFormat ) const;

    virtual BOOL        SetData( const String& rData );
    virtual ULONG       GetMiscStatus() const;
    virtual void        OnDocumentPrinterChanged( Printer * );
    virtual sal_Bool    InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL        Load( SfxMedium& rMedium );
            void        ImplSave(  SvStorageStreamRef xStrm  );
    virtual BOOL        Save();
    virtual BOOL        SaveAs( SfxMedium& rMedium );
    virtual BOOL        ConvertTo( SfxMedium &rMedium );
    virtual BOOL        SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    Printer             *GetPrt();
    OutputDevice*       GetRefDev();

    BOOL                IsFormulaArranged() const { return bIsFormulaArranged; }
    void                SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }

    virtual BOOL        ConvertFrom(SfxMedium &rMedium);

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1)
    using SotObject::GetInterface;
    SFX_DECL_OBJECTFACTORY();

                SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    virtual     ~SmDocShell();

    void        LoadSymbols();
    void        SaveSymbols();

    void        ArrangeFormula();

    //Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
    //und fuer die Kommunikation mit dem SFX!
    //Alle internen Verwendungen des Printers sollten ausschlieslich uber
    //den SmPrinterAccess funktionieren.
    BOOL        HasPrinter()    { return 0 != pPrinter; }
    SfxPrinter *GetPrinter()    { GetPrt(); return pPrinter; }
    void        SetPrinter( SfxPrinter * );

    const String &GetComment() const;

    // to replace chars that can not be saved with the document...
    sal_Bool    ReplaceBadChars();

    void        UpdateText();
    void        SetText(const String& rBuffer);
    String&     GetText() { return (aText); }
    void        SetFormat(SmFormat& rFormat);
    const SmFormat&  GetFormat() { return (aFormat); }

    void            Parse();
    SmParser &      GetParser() { return aInterpreter; }
    const SmNode *  GetFormulaTree() const  { return pTree; }
    void            SetFormulaTree(SmNode *&rTree) { pTree = rTree; }

    String          GetAccessibleText();

    EditEngine &    GetEditEngine();
    SfxItemPool &   GetEditEngineItemPool();

    void        Draw(OutputDevice &rDev, Point &rPosition);
    Size        GetSize();

    void        Repaint();

    virtual     SfxUndoManager *GetUndoManager ();

    virtual     SfxItemPool& GetPool() const;

    void        Execute( SfxRequest& rReq );
    void        GetState(SfxItemSet &);

    virtual void SetVisArea (const Rectangle & rVisArea);
    virtual void SetModified(BOOL bModified);
};

#endif

<commit_msg>INTEGRATION: CWS custommeta (1.32.54); FILE MERGED 2008/01/23 17:11:39 mst 1.32.54.1: - starmath/inc/document.hxx, starmath/source/document.cxx:   + use XDocumentProperties instead of SfxDocumentInfo   + SmDocShell::GetComment returns String instead of String&   + fix bug: GetComment used a static variable to store document-specific data<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: document.hxx,v $
 *
 *  $Revision: 1.33 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-26 14:43:27 $
 *
 *  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 DOCUMENT_HXX
#define DOCUMENT_HXX

#define SMDLL   1

#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif

#include <vcl/jobset.hxx>

class SmNode;
class SfxMenuBarManager;
class SfxPrinter;
class Printer;

#define HINT_DATACHANGED    1004

#define SM30BIDENT   ((ULONG)0x534D3033L)
#define SM30IDENT    ((ULONG)0x30334d53L)
#define SM304AIDENT  ((ULONG)0x34303330L)
#define SM30VERSION  ((ULONG)0x00010000L)
#define SM50VERSION  ((ULONG)0x00010001L)   //Unterschied zur SM30VERSION ist
                                            //der neue Border im Format.

#define FRMIDENT    ((ULONG)0x03031963L)
#define FRMVERSION  ((ULONG)0x00010001L)

#define STAROFFICE_XML  "StarOffice XML (Math)"
#define MATHML_XML      "MathML XML (Math)"

/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
 * ==========================================================================
 *
 * Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
 * das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
 * grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
 * einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
 * im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
 * Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
 * (etwa waehrend des Paints).
 * Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
 * oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
 * fuer die der Access auch Friend der DocShell ist.
*/

class SmDocShell;
class EditEngine;

class SmPrinterAccess
{
    Printer* pPrinter;
    OutputDevice* pRefDev;
public:
    SmPrinterAccess( SmDocShell &rDocShell );
    ~SmPrinterAccess();
    Printer* GetPrinter()  { return pPrinter; }
    OutputDevice* GetRefDev()  { return pRefDev; }
};

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

void SetEditEngineDefaultFonts(
        EditEngine &rEditEngine,
        SfxItemPool &rEditEngineItemPool );

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

class SmDocShell : public SfxObjectShell, public SfxListener
{
    friend class SmPrinterAccess;
    friend class SmModel;

    String              aText;
    SmFormat            aFormat;
    SmParser            aInterpreter;
    String              aAccText;
    SmNode             *pTree;
    SfxMenuBarManager  *pMenuMgr;
    SfxItemPool        *pEditEngineItemPool;
    EditEngine         *pEditEngine;
    SfxPrinter         *pPrinter;       //Siehe Kommentar zum SmPrinter Access!
    Printer            *pTmpPrinter;    //ebenfalls
    long                nLeftBorder,
                        nRightBorder,
                        nTopBorder,
                        nBottomBorder;
    USHORT              nModifyCount;
    BOOL                bIsFormulaArranged;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
                        const SfxHint& rHint, const TypeId& rHintType);

    BOOL        WriteAsMathType3( SfxMedium& );

    virtual void        Draw(OutputDevice *pDevice,
                             const JobSetup & rSetup,
                             USHORT nAspect = ASPECT_CONTENT);

    virtual void        FillClass(SvGlobalName* pClassName,
                                  sal_uInt32*  pFormat,
                                  String* pAppName,
                                  String* pFullTypeName,
                                  String* pShortTypeName,
                                  sal_Int32 nFileFormat ) const;

    virtual BOOL        SetData( const String& rData );
    virtual ULONG       GetMiscStatus() const;
    virtual void        OnDocumentPrinterChanged( Printer * );
    virtual sal_Bool    InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL        Load( SfxMedium& rMedium );
            void        ImplSave(  SvStorageStreamRef xStrm  );
    virtual BOOL        Save();
    virtual BOOL        SaveAs( SfxMedium& rMedium );
    virtual BOOL        ConvertTo( SfxMedium &rMedium );
    virtual BOOL        SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    Printer             *GetPrt();
    OutputDevice*       GetRefDev();

    BOOL                IsFormulaArranged() const { return bIsFormulaArranged; }
    void                SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }

    virtual BOOL        ConvertFrom(SfxMedium &rMedium);

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1)
    using SotObject::GetInterface;
    SFX_DECL_OBJECTFACTORY();

                SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    virtual     ~SmDocShell();

    void        LoadSymbols();
    void        SaveSymbols();

    void        ArrangeFormula();

    //Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
    //und fuer die Kommunikation mit dem SFX!
    //Alle internen Verwendungen des Printers sollten ausschlieslich uber
    //den SmPrinterAccess funktionieren.
    BOOL        HasPrinter()    { return 0 != pPrinter; }
    SfxPrinter *GetPrinter()    { GetPrt(); return pPrinter; }
    void        SetPrinter( SfxPrinter * );

    const String GetComment() const;

    // to replace chars that can not be saved with the document...
    sal_Bool    ReplaceBadChars();

    void        UpdateText();
    void        SetText(const String& rBuffer);
    String&     GetText() { return (aText); }
    void        SetFormat(SmFormat& rFormat);
    const SmFormat&  GetFormat() { return (aFormat); }

    void            Parse();
    SmParser &      GetParser() { return aInterpreter; }
    const SmNode *  GetFormulaTree() const  { return pTree; }
    void            SetFormulaTree(SmNode *&rTree) { pTree = rTree; }

    String          GetAccessibleText();

    EditEngine &    GetEditEngine();
    SfxItemPool &   GetEditEngineItemPool();

    void        Draw(OutputDevice &rDev, Point &rPosition);
    Size        GetSize();

    void        Repaint();

    virtual     SfxUndoManager *GetUndoManager ();

    virtual     SfxItemPool& GetPool() const;

    void        Execute( SfxRequest& rReq );
    void        GetState(SfxItemSet &);

    virtual void SetVisArea (const Rectangle & rVisArea);
    virtual void SetModified(BOOL bModified);
};

#endif

<|endoftext|>


<commit_before>//===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the C bindings for the ExecutionEngine library.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "jit"
#include "llvm-c/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include <cstring>

using namespace llvm;

/*===-- Operations on generic values --------------------------------------===*/

LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
                                                unsigned long long N,
                                                int IsSigned) {
  GenericValue *GenVal = new GenericValue();
  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
  return wrap(GenVal);
}

LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
  GenericValue *GenVal = new GenericValue();
  GenVal->PointerVal = P;
  return wrap(GenVal);
}

LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
  GenericValue *GenVal = new GenericValue();
  switch (unwrap(TyRef)->getTypeID()) {
  case Type::FloatTyID:
    GenVal->FloatVal = N;
    break;
  case Type::DoubleTyID:
    GenVal->DoubleVal = N;
    break;
  default:
    assert(0 && "LLVMGenericValueToFloat supports only float and double.");
    break;
  }
  return wrap(GenVal);
}

unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
  return unwrap(GenValRef)->IntVal.getBitWidth();
}

unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
                                         int IsSigned) {
  GenericValue *GenVal = unwrap(GenValRef);
  if (IsSigned)
    return GenVal->IntVal.getSExtValue();
  else
    return GenVal->IntVal.getZExtValue();
}

void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
  return unwrap(GenVal)->PointerVal;
}

double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
  switch (unwrap(TyRef)->getTypeID()) {
  case Type::FloatTyID:
    return unwrap(GenVal)->FloatVal;
  case Type::DoubleTyID:
    return unwrap(GenVal)->DoubleVal;
  default:
    assert(0 && "LLVMGenericValueToFloat supports only float and double.");
    break;
  }
  return 0; // Not reached
}

void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
  delete unwrap(GenVal);
}

/*===-- Operations on execution engines -----------------------------------===*/

int LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
                              LLVMModuleProviderRef MP,
                              char **OutError) {
  std::string Error;
  if (ExecutionEngine *EE = ExecutionEngine::create(unwrap(MP), false, &Error)){
    *OutEE = wrap(EE);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
                          LLVMModuleProviderRef MP,
                          char **OutError) {
  std::string Error;
  if (ExecutionEngine *Interp =
      ExecutionEngine::create(unwrap(MP), true, &Error)) {
    *OutInterp = wrap(Interp);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
                          LLVMModuleProviderRef MP,
                          unsigned OptLevel,
                          char **OutError) {
  std::string Error;
  if (ExecutionEngine *JIT =
      ExecutionEngine::createJIT(unwrap(MP), &Error, 0,
                                 (CodeGenOpt::Level)OptLevel)) {
    *OutJIT = wrap(JIT);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
  delete unwrap(EE);
}

void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
  unwrap(EE)->runStaticConstructorsDestructors(false);
}

void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
  unwrap(EE)->runStaticConstructorsDestructors(true);
}

int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
                          unsigned ArgC, const char * const *ArgV,
                          const char * const *EnvP) {
  std::vector<std::string> ArgVec;
  for (unsigned I = 0; I != ArgC; ++I)
    ArgVec.push_back(ArgV[I]);

  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
}

LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
                                    unsigned NumArgs,
                                    LLVMGenericValueRef *Args) {
  std::vector<GenericValue> ArgVec;
  ArgVec.reserve(NumArgs);
  for (unsigned I = 0; I != NumArgs; ++I)
    ArgVec.push_back(*unwrap(Args[I]));

  GenericValue *Result = new GenericValue();
  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
  return wrap(Result);
}

void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
  unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
}

void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
  unwrap(EE)->addModuleProvider(unwrap(MP));
}

int LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
                             LLVMModuleProviderRef MP,
                             LLVMModuleRef *OutMod, char **OutError) {
  std::string Error;
  if (Module *Gone = unwrap(EE)->removeModuleProvider(unwrap(MP), &Error)) {
    *OutMod = wrap(Gone);
    return 0;
  }
  if (OutError)
    *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
                     LLVMValueRef *OutFn) {
  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
    *OutFn = wrap(F);
    return 0;
  }
  return 1;
}

LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
  return wrap(unwrap(EE)->getTargetData());
}

void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
                          void* Addr) {
  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
}

void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
}
<commit_msg>Fix the EE bindings to use the proper EE interfaces for creating a JIT. Calling into createJIT directly creates a circular dependency between libjit and lib ee.<commit_after>//===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the C bindings for the ExecutionEngine library.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "jit"
#include "llvm-c/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include <cstring>

using namespace llvm;

/*===-- Operations on generic values --------------------------------------===*/

LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
                                                unsigned long long N,
                                                int IsSigned) {
  GenericValue *GenVal = new GenericValue();
  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
  return wrap(GenVal);
}

LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
  GenericValue *GenVal = new GenericValue();
  GenVal->PointerVal = P;
  return wrap(GenVal);
}

LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
  GenericValue *GenVal = new GenericValue();
  switch (unwrap(TyRef)->getTypeID()) {
  case Type::FloatTyID:
    GenVal->FloatVal = N;
    break;
  case Type::DoubleTyID:
    GenVal->DoubleVal = N;
    break;
  default:
    assert(0 && "LLVMGenericValueToFloat supports only float and double.");
    break;
  }
  return wrap(GenVal);
}

unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
  return unwrap(GenValRef)->IntVal.getBitWidth();
}

unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
                                         int IsSigned) {
  GenericValue *GenVal = unwrap(GenValRef);
  if (IsSigned)
    return GenVal->IntVal.getSExtValue();
  else
    return GenVal->IntVal.getZExtValue();
}

void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
  return unwrap(GenVal)->PointerVal;
}

double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
  switch (unwrap(TyRef)->getTypeID()) {
  case Type::FloatTyID:
    return unwrap(GenVal)->FloatVal;
  case Type::DoubleTyID:
    return unwrap(GenVal)->DoubleVal;
  default:
    assert(0 && "LLVMGenericValueToFloat supports only float and double.");
    break;
  }
  return 0; // Not reached
}

void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
  delete unwrap(GenVal);
}

/*===-- Operations on execution engines -----------------------------------===*/

int LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
                              LLVMModuleProviderRef MP,
                              char **OutError) {
  std::string Error;
  if (ExecutionEngine *EE = ExecutionEngine::create(unwrap(MP), false, &Error)){
    *OutEE = wrap(EE);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
                          LLVMModuleProviderRef MP,
                          char **OutError) {
  std::string Error;
  if (ExecutionEngine *Interp =
      ExecutionEngine::create(unwrap(MP), true, &Error)) {
    *OutInterp = wrap(Interp);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
                          LLVMModuleProviderRef MP,
                          unsigned OptLevel,
                          char **OutError) {
  std::string Error;
  if (ExecutionEngine *JIT =
      ExecutionEngine::create(unwrap(MP), false, &Error,
                                 (CodeGenOpt::Level)OptLevel)) {
    *OutJIT = wrap(JIT);
    return 0;
  }
  *OutError = strdup(Error.c_str());
  return 1;
}

void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
  delete unwrap(EE);
}

void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
  unwrap(EE)->runStaticConstructorsDestructors(false);
}

void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
  unwrap(EE)->runStaticConstructorsDestructors(true);
}

int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
                          unsigned ArgC, const char * const *ArgV,
                          const char * const *EnvP) {
  std::vector<std::string> ArgVec;
  for (unsigned I = 0; I != ArgC; ++I)
    ArgVec.push_back(ArgV[I]);

  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
}

LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
                                    unsigned NumArgs,
                                    LLVMGenericValueRef *Args) {
  std::vector<GenericValue> ArgVec;
  ArgVec.reserve(NumArgs);
  for (unsigned I = 0; I != NumArgs; ++I)
    ArgVec.push_back(*unwrap(Args[I]));

  GenericValue *Result = new GenericValue();
  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
  return wrap(Result);
}

void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
  unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
}

void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
  unwrap(EE)->addModuleProvider(unwrap(MP));
}

int LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
                             LLVMModuleProviderRef MP,
                             LLVMModuleRef *OutMod, char **OutError) {
  std::string Error;
  if (Module *Gone = unwrap(EE)->removeModuleProvider(unwrap(MP), &Error)) {
    *OutMod = wrap(Gone);
    return 0;
  }
  if (OutError)
    *OutError = strdup(Error.c_str());
  return 1;
}

int LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
                     LLVMValueRef *OutFn) {
  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
    *OutFn = wrap(F);
    return 0;
  }
  return 1;
}

LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
  return wrap(unwrap(EE)->getTargetData());
}

void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
                          void* Addr) {
  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
}

void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
}
<|endoftext|>


<commit_before>#include "marketMaker.h"
int main(int argc, char** argv)
{
	MarketMaker marketMaker(argc, argv);
	cout << "Succefully Initiated!" << endl << endl;
	marketMaker.start();
}<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>

using namespace std;

char const * const SERVER_PORT = "2000";
size_t const MAX_BUF_LEN = 250;
int const TIMEOUT_DURATION = 1;

int
main()
{
    addrinfo hints, *server_addrinfo;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    int status = getaddrinfo("localhost", SERVER_PORT, &hints, &server_addrinfo);
    if (status < 0)
    {
        cerr << "getaddrinfo() failed, " << gai_strerror(status) << endl;
        return EXIT_FAILURE;
    }

    int server_socket = -1;
    for (addrinfo *p = server_addrinfo; p != NULL; p = p->ai_next)
    {
        server_socket = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (server_socket < 0)
        {
            cerr << "Couldn't create socket, continuing..." << endl;
            continue;
        }
        timeval duration;
        duration.tv_sec = TIMEOUT_DURATION;
        duration.tv_usec = 0;
        if (setsockopt(server_socket, SOL_SOCKET, SO_RCVTIMEO, &duration, sizeof(duration)) < 0)
        {
            close(server_socket);
            server_socket = -1;
            cerr << "setsockout() failed to set SO_RCVTIMEO, continuing..." << endl;
            continue;
        }
        if (bind(server_socket, p->ai_addr, p->ai_addrlen) < 0)
        {
            close(server_socket);
            server_socket = -1;
            cerr << "bind() failed, continuing..." << endl;
            continue;
        }
        sockaddr_in * server_sockaddr = reinterpret_cast< sockaddr_in *> (p->ai_addr);
        char server_name[INET_ADDRSTRLEN];
        inet_ntop(p->ai_family, &(server_sockaddr->sin_addr), server_name, INET_ADDRSTRLEN);
        cout << "Bound to socket at " << server_name << ":" << ntohs(server_sockaddr->sin_port) << endl;
        break;
    }

    freeaddrinfo(server_addrinfo);
    if (server_socket == -1)
    {
        cerr << "bind() failed" << endl;
    }

    char buffer[MAX_BUF_LEN];
    sockaddr client_addr;
    socklen_t client_addrlen;
    ssize_t num_bytes = recvfrom(server_socket, buffer, sizeof(buffer), 0, &client_addr, &client_addrlen);
    if (num_bytes < 0)
    {
        int err_no = errno;
        if (err_no == EAGAIN || errno == EWOULDBLOCK)
        {
            cerr << "No data recieved in " << TIMEOUT_DURATION << " seconds." << endl;
        }
        else
        {
            cerr << "recvfrom() failed." << endl;
        }
    }

    close(server_socket);
    return 0;
}<commit_msg>Added poll(2) to wait<commit_after>#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <sys/poll.h>

using namespace std;

char const *const SERVER_PORT = "2000";

size_t const MAX_BUF_LEN = 250;

int const TIMEOUT_DURATION = 5; /* Seconds */

int
main()
{
    addrinfo hints, *server_addrinfo;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    int status = getaddrinfo("localhost", SERVER_PORT, &hints, &server_addrinfo);
    if (status < 0)
    {
        cerr << "getaddrinfo() failed, " << gai_strerror(status) << endl;
        return EXIT_FAILURE;
    }

    int server_socket = -1;
    for (addrinfo *p = server_addrinfo; p != NULL; p = p->ai_next)
    {
        server_socket = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (server_socket < 0)
        {
            cerr << "Couldn't create socket, continuing..." << endl;
            continue;
        }

        int yes = 1;
        if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
        {
            close(server_socket);
            server_socket = -1;
            cerr << "setsockopt() failed to set SO_REUSEADDR, continuing..." << endl;
            continue;
        }

//        timeval duration;
//        duration.tv_sec = TIMEOUT_DURATION;
//        duration.tv_usec = 0;
//        if (setsockopt(server_socket, SOL_SOCKET, SO_RCVTIMEO, &duration, sizeof(duration)) < 0)
//        {
//            close(server_socket);
//            server_socket = -1;
//            cerr << "setsockopt() failed to set SO_RCVTIMEO, continuing..." << endl;
//            continue;
//        }

        if (bind(server_socket, p->ai_addr, p->ai_addrlen) < 0)
        {
            close(server_socket);
            server_socket = -1;
            cerr << "bind() failed, continuing..." << endl;
            continue;
        }
        sockaddr_in *server_sockaddr = reinterpret_cast< sockaddr_in *> (p->ai_addr);
        char server_name[INET_ADDRSTRLEN];
        inet_ntop(p->ai_family, &(server_sockaddr->sin_addr), server_name, INET_ADDRSTRLEN);
        cout << "Bound to socket at " << server_name << ":" << ntohs(server_sockaddr->sin_port) << endl;
        break;
    }

    freeaddrinfo(server_addrinfo);
    if (server_socket == -1)
    {
        cerr << "bind() failed" << endl;
        return EXIT_FAILURE;
    }

    /* Now poll for already existing server on the network */
    pollfd server_pollfds[1];
    memset(&server_pollfds[0], 0, sizeof(pollfd));
    server_pollfds[0].fd = server_socket;
    server_pollfds[0].events = POLLIN | POLLPRI | POLLHUP;
    status = poll(server_pollfds, sizeof(server_pollfds) / sizeof(server_pollfds[0]), TIMEOUT_DURATION * 1000);

    /* Read data from server, if available */
    char buffer[MAX_BUF_LEN];
    sockaddr client_addr;
    socklen_t client_addrlen;
    ssize_t num_bytes = -1;
    switch (status)
    {
        case -1:cerr << "poll() failed, " << status << endl;
            return EXIT_FAILURE;
        case 0:cerr << "No data received in " << TIMEOUT_DURATION << " seconds." << endl;
        default:
            if (server_pollfds[0].revents & POLLIN)
            {
                num_bytes = recvfrom(server_socket, buffer, sizeof(buffer), 0, &client_addr, &client_addrlen);
            }
            else if (server_pollfds[0].revents & POLLPRI)
            {
                num_bytes = recvfrom(server_socket, buffer, sizeof(buffer), MSG_OOB, &client_addr, &client_addrlen);
            }
            else if (server_pollfds[0].revents & POLLHUP)
            {
                cerr << "Remote server ended, continuing..." << endl;
            }
    }

    if (num_bytes > 0)
    {
        cout << "Data received: <" << buffer << ">" << endl;
    }
    else
    {
        cout << "No data received." << endl;
    }

    close(server_socket);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * meego-handset-pin
 * Copyright © 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

/* Qt includes */
#include <QtGui/QApplication>
#include <QDBusConnection>
#include <QtDebug>

/* oFono DBus interfaces */
#include "mgrif.h"
#include "simif.h"

/* oFono utilities*/
#include "ofonoutils.h"

/* oFono DBus types */
#include "ofonodbustypes.h"

/* PinApplication */
#include "pinapplication.h"

int main(int argc, char *argv[])
{
    int mainErr = -1;
    PinApplication a(argc, argv);

    // Register meta types defined in ofonodbustypes.h"
    registerOfonoDbusTypes();

    // DBus Connection systemBus
    QDBusConnection systemBus = QDBusConnection::systemBus();
    if( !systemBus.isConnected() ) {
        QDBusError dbusError = systemBus.lastError();
        qDebug() << "Error:" << dbusError.name() << ":" << dbusError.message();
        return mainErr;
    }

    // Instanciate proxy for org.ofono.Manager interface
    MgrIf mgrIf("org.ofono","/",systemBus,NULL);

    // find org.ofono.SimManager interfaces for all modems
    QList<SimIf*> simIfs = OfonoUtils::findSimInterfaces(systemBus,&mgrIf);
    if (simIfs.isEmpty()) {
        qDebug() << "No  org.ofono.SimManager interface found, exiting";
        return mainErr;
    }

    // use just the first element of SimManager interfaces list
    SimIf *firstSimIf = simIfs.first();

    // Run SimToolkit application
    mainErr = a.exec();

    // delete all org.ofono.SimManager interfaces
    while (!simIfs.isEmpty()) {
        delete simIfs.first();
        simIfs.removeFirst();
    }

    return mainErr;
}

<commit_msg>meego-handset-pin: fix property changes registration<commit_after>/*
 * meego-handset-pin
 * Copyright © 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

/* Qt includes */
#include <QtGui/QApplication>
#include <QDBusConnection>
#include <QtDebug>

/* oFono DBus interfaces */
#include "mgrif.h"
#include "simif.h"

/* oFono utilities*/
#include "ofonoutils.h"

/* oFono DBus types */
#include "ofonodbustypes.h"

/* PinApplication */
#include "pinapplication.h"

int main(int argc, char *argv[])
{
    int mainErr = -1;
    PinApplication a(argc, argv);

    // Register meta types defined in ofonodbustypes.h"
    registerOfonoDbusTypes();

    // DBus Connection systemBus
    QDBusConnection systemBus = QDBusConnection::systemBus();
    if( !systemBus.isConnected() ) {
        QDBusError dbusError = systemBus.lastError();
        qDebug() << "Error:" << dbusError.name() << ":" << dbusError.message();
        return mainErr;
    }

    // Instanciate proxy for org.ofono.Manager interface
    MgrIf mgrIf("org.ofono","/",systemBus,NULL);

    // find org.ofono.SimManager interfaces for all modems
    QList<SimIf*> simIfs = OfonoUtils::findSimInterfaces(systemBus,&mgrIf);
    if (simIfs.isEmpty()) {
        qDebug() << "No  org.ofono.SimManager interface found, exiting";
        return mainErr;
    }

    // use just the first element of SimManager interfaces list
    SimIf *firstSimIf = simIfs.first();

    // register app to track changes on "PinRequired" property
    a.registerPinPropertyChanged(firstSimIf);

    // Run SimToolkit application
    mainErr = a.exec();

    // delete all org.ofono.SimManager interfaces
    while (!simIfs.isEmpty()) {
        delete simIfs.first();
        simIfs.removeFirst();
    }

    return mainErr;
}

<|endoftext|>


<commit_before>84e585de-4b02-11e5-833f-28cfe9171a43<commit_msg>update testing<commit_after>84f29bf3-4b02-11e5-a751-28cfe9171a43<|endoftext|>


<commit_before>#ifdef QT_QML_DEBUG
#include <QtQuick>
#endif

#include <QQuickView>
#include <QQmlContext>
#include <sailfishapp.h>
#include "servercomm.h"

int main(int argc, char *argv[])
{
    QScopedPointer<QQuickView> view(SailfishApp::createView());
    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);
    view->setSource(SailfishApp::pathTo("main.qml"));
    view->show();
}
<commit_msg>More fixes to main.cpp<commit_after>#ifdef QT_QML_DEBUG
#include <QtQuick>
#endif

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <sailfishapp.h>
#include "servercomm.h"

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());
    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);
    view->setSource(SailfishApp::pathTo("main.qml"));
    view->showFullScreen();
    return app->exec();
}
<|endoftext|>


<commit_before>25bdb717-ad5c-11e7-8655-ac87a332f658<commit_msg>bug fix<commit_after>263e9585-ad5c-11e7-989d-ac87a332f658<|endoftext|>