<commit_before>//
//  GameScene.cpp
//  ItoToshi
//
//  Created by Mihyaeru on H27/05/23.
//
//

#include "GameScene.h"

USING_NS_CC;

Scene* GameScene::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = GameScene::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool GameScene::init()
{
    if (!Layer::init()) {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    this->player = std::shared_ptr<Player>(new Player(this));

    // タッチイベントをplayerに通知する
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [=](Touch *t, Event *e) -> bool {
        this->player->onTouchBegan();
        return true;
    };
    listener->onTouchEnded     = [=](Touch *t, Event *e) { this->player->onTouchEnded(); };
    listener->onTouchCancelled = [=](Touch *t, Event *e) { this->player->onTouchEnded(); };
    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

    // ゲームオーバーを表示するためのラベル
    this->gameOverLabel = Label::createWithTTF("GameOver!!!", "fonts/Marker Felt.ttf", 24);
    gameOverLabel->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
    gameOverLabel->setVisible(false);  // 隠しておく
    this->addChild(gameOverLabel);

    this->scheduleUpdate();
    return true;
}

void GameScene::update(float delta)
{
    this->player->update(delta);

    if (!this->isInScreen(this->player->getPoint())) {
        this->gameOverLabel->setVisible(true);
    }
}

bool GameScene::isInScreen(cocos2d::Vec2 p)
{
    Size s = Director::getInstance()->getVisibleSize();

    if (p.x < 0 || p.x > s.width)  return false;
    if (p.y < 0 || p.y > s.height) return false;
    return true;
}
<commit_msg>ゲームオーバー時は動作を止めておく<commit_after>//
//  GameScene.cpp
//  ItoToshi
//
//  Created by Mihyaeru on H27/05/23.
//
//

#include "GameScene.h"

USING_NS_CC;

Scene* GameScene::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = GameScene::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool GameScene::init()
{
    if (!Layer::init()) {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    this->player = std::shared_ptr<Player>(new Player(this));

    // タッチイベントをplayerに通知する
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [=](Touch *t, Event *e) -> bool {
        this->player->onTouchBegan();
        return true;
    };
    listener->onTouchEnded     = [=](Touch *t, Event *e) { this->player->onTouchEnded(); };
    listener->onTouchCancelled = [=](Touch *t, Event *e) { this->player->onTouchEnded(); };
    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

    // ゲームオーバーを表示するためのラベル
    this->gameOverLabel = Label::createWithTTF("GameOver!!!", "fonts/Marker Felt.ttf", 24);
    gameOverLabel->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
    gameOverLabel->setVisible(false);  // 隠しておく
    this->addChild(gameOverLabel);

    this->scheduleUpdate();
    return true;
}

void GameScene::update(float delta)
{
    this->player->update(delta);

    if (!this->isInScreen(this->player->getPoint())) {
        this->gameOverLabel->setVisible(true);
        this->unscheduleUpdate();
    }
}

bool GameScene::isInScreen(cocos2d::Vec2 p)
{
    Size s = Director::getInstance()->getVisibleSize();

    if (p.x < 0 || p.x > s.width)  return false;
    if (p.y < 0 || p.y > s.height) return false;
    return true;
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include <OSGConfig.h>

#include "OSGNodeCore.h"

OSG_BEGIN_NAMESPACE

// Documentation for this class is emitted in the
// OSGNodeCoreBase.cpp file.
// To modify it, please change the .fcd file (OSGNodeCore.fcd) and
// regenerate the base file.

/***************************************************************************\
 *                           Class variables                               *
\***************************************************************************/

/***************************************************************************\
 *                           Class methods                                 *
\***************************************************************************/

void NodeCore::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

    if(ePhase == TypeObject::SystemPost)
    {
    }
}

/***************************************************************************\
 *                           Instance methods                              *
\***************************************************************************/

/*-------------------------------------------------------------------------*\
 -  private                                                                 -
\*-------------------------------------------------------------------------*/

/*----------------------- constructors & destructors ----------------------*/

NodeCore::NodeCore(void) :
    Inherited()
{
}

NodeCore::NodeCore(const NodeCore &source) :
    Inherited(source)
{
}

NodeCore::~NodeCore(void)
{
}

/*----------------------------- class specific ----------------------------*/

void NodeCore::accumulateMatrix(Matrixr &result)
{
}

void NodeCore::adjustVolume(Volume &volume)
{
}

void NodeCore::invalidateVolume(void)
{
    MFParentsType::const_iterator pIt  = _mfParents.begin();
    MFParentsType::const_iterator pEnd = _mfParents.end  ();

    for(; pIt != pEnd; ++pIt)
        (*pIt)->invalidateVolume();
}

void NodeCore::changed(ConstFieldMaskArg whichField,
                            UInt32            origin,
                            BitVector         details)
{
    Inherited::changed(whichField, origin, details);
}

void NodeCore::dump(      UInt32    uiIndent,
                    const BitVector bvFlags  ) const
{
    indentLog(uiIndent, PLOG);

    PLOG << "Core"
         << "("
         << std::dec
         << this->getId()
         << ") : "
         << getType().getName()
         << " "
         << this
         << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "[" << std::endl;

    indentLog(uiIndent + 4, PLOG);
    PLOG << "Parents : " << std::endl;

    for(UInt32 i = 0; i < _mfParents.size(); i++)
    {
        indentLog(uiIndent + 4, PLOG);
        PLOG << "           " << i << ") " << &(*(_mfParents[i])) << std::endl;
    }

    Inherited::dump(uiIndent + 4, bvFlags);

    indentLog(uiIndent, PLOG);
    PLOG << "]" << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "{" << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "}" << std::endl;
}

OSG_END_NAMESPACE
<commit_msg>changed: use iters in NodeCore::dump()<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include <OSGConfig.h>

#include "OSGNodeCore.h"

OSG_BEGIN_NAMESPACE

// Documentation for this class is emitted in the
// OSGNodeCoreBase.cpp file.
// To modify it, please change the .fcd file (OSGNodeCore.fcd) and
// regenerate the base file.

/***************************************************************************\
 *                           Class variables                               *
\***************************************************************************/

/***************************************************************************\
 *                           Class methods                                 *
\***************************************************************************/

void NodeCore::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

    if(ePhase == TypeObject::SystemPost)
    {
    }
}

/***************************************************************************\
 *                           Instance methods                              *
\***************************************************************************/

/*-------------------------------------------------------------------------*\
 -  private                                                                 -
\*-------------------------------------------------------------------------*/

/*----------------------- constructors & destructors ----------------------*/

NodeCore::NodeCore(void) :
    Inherited()
{
}

NodeCore::NodeCore(const NodeCore &source) :
    Inherited(source)
{
}

NodeCore::~NodeCore(void)
{
}

/*----------------------------- class specific ----------------------------*/

void NodeCore::accumulateMatrix(Matrixr &result)
{
}

void NodeCore::adjustVolume(Volume &volume)
{
}

void NodeCore::invalidateVolume(void)
{
    MFParentsType::const_iterator pIt  = _mfParents.begin();
    MFParentsType::const_iterator pEnd = _mfParents.end  ();

    for(; pIt != pEnd; ++pIt)
        (*pIt)->invalidateVolume();
}

void NodeCore::changed(ConstFieldMaskArg whichField,
                            UInt32            origin,
                            BitVector         details)
{
    Inherited::changed(whichField, origin, details);
}

void NodeCore::dump(      UInt32    uiIndent,
                    const BitVector bvFlags  ) const
{
    indentLog(uiIndent, PLOG);

    PLOG << "Core"
         << "("
         << std::dec
         << this->getId()
         << ") : "
         << getType().getName()
         << " "
         << this
         << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "[" << std::endl;

    indentLog(uiIndent + 4, PLOG);
    PLOG << "Parents : " << std::endl;

    MFParentsType::const_iterator pIt  = _mfParents.begin();
    MFParentsType::const_iterator pEnd = _mfParents.end  ();

    for(UInt32 i = 0; pIt != pEnd; ++pIt)
    {
        indentLog(uiIndent + 4, PLOG);
        PLOG << "           " << i << ") " << *pIt << std::endl;
    }

    Inherited::dump(uiIndent + 4, bvFlags);

    indentLog(uiIndent, PLOG);
    PLOG << "]" << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "{" << std::endl;

    indentLog(uiIndent, PLOG);
    PLOG << "}" << std::endl;
}

OSG_END_NAMESPACE
<|endoftext|>


<commit_before>//
// Created by fred.nicolson on 01/10/18.
//

#include <frnetlib/TcpListener.h>
#include <iostream>
#include <frnetlib/SocketSelector.h>
#include <frnetlib/Http.h>
#include <frnetlib/HttpRequest.h>
#include <frnetlib/HttpResponse.h>
#include <thread>

int main()
{
    //Bind to port
    auto listener = std::make_shared<fr::TcpListener>();
    if(listener->listen("8080") != fr::Socket::Success)
    {
        std::cerr << "Failed to bind to port" << std::endl;
        return EXIT_FAILURE;
    }

    for(size_t a = 0; a < std::thread::hardware_concurrency(); ++a)
    {
        if(fork() <= 0)
            break;
    }

    //Setup our socket selector and add the listener to it
    fr::SocketSelector selector;
    selector.add(listener, nullptr);

    //Enter main server loop
    volatile bool running = true;
    while(running)
    {
        //Wait for a socket to be ready with no timeout
        auto ready_sockets = selector.wait();

        //Process each socket
        for(auto &ready_socket : ready_sockets)
        {
            //If this is the listener, then accept a new connection
            if(ready_socket.first->get_socket_descriptor() == listener->get_socket_descriptor())
            {
                auto client = std::make_shared<fr::TcpSocket>();
                if(listener->accept(*client) == fr::Socket::Success)
                {
                    //We've accepted the connection, so add it to the selector, associating a new fr::HttpRequest
                    //Object which will slowly be filled with the client's request. You could also pass a struct
                    //associated with the connection for easier state management.
                    selector.add(client, new fr::HttpRequest());
                    client->set_blocking(false);
                }
                break;
            }

            //Else, a socket is sending data/has disconnected, accept it
            auto client = std::static_pointer_cast<fr::Socket>(ready_socket.first); //fr::TcpSocket -> fr::Socket -> fr::SocketDescriptor
            auto partial_request = static_cast<fr::HttpRequest*>(ready_socket.second);

            char data[0x1000];
            size_t received = 0;
            auto recv_status = client->receive_raw(data, sizeof(data), received);
            if(recv_status == fr::Socket::Success)
            {
                //We receied data, so parse it using the partial HTTP request associated with this connection
                auto parse_status = partial_request->parse(data, received);
                if(parse_status == fr::Socket::Success)
                {
                    //The client has sent a full request, send them something back
                    //This could alternatively pass this connection/request off to a handler in another
                    //thread for further processing.
                    fr::HttpResponse response;
                    response.set_body("
Hello World!
");
                    client->send(response);
                }
                else if(parse_status == fr::Socket::NotEnoughData)
                {
                    //More data needed, wait for it
                }
                else
                {
                    //HTTP error, disconnect the client
                    delete partial_request;
                    selector.remove(client);
                    client->disconnect();
                }
            }
            else if(recv_status == fr::Socket::Disconnected)
            {
                //Free the allocated fr::HttpRequest. The socket is auto-removed from the selector as it notified us.
                delete partial_request;
            }
        }
    }
}<commit_msg>Better Concurrent HTTP Server example<commit_after>//
// Created by fred.nicolson on 01/10/18.
//

#include <frnetlib/TcpListener.h>
#include <iostream>
#include <frnetlib/SocketSelector.h>
#include <frnetlib/Http.h>
#include <frnetlib/HttpRequest.h>
#include <frnetlib/HttpResponse.h>
#include <thread>

class SessionState
{
public:
    fr::HttpRequest partial_request;
};

void process_complete_request(const std::shared_ptr<fr::Socket> &client, fr::HttpRequest request)
{
    //Note: *NEVER* disconnect the client in the handler. Or it will never be removed from
    //the socket selector, and its opaque data will never be free'd. You're better off having a
    //disconnection queue which is processed by the listening thread, and added to here.
    fr::HttpResponse response;
    response.set_body("
Hello World!
");
    client->send(response);
}

int main()
{
    //Bind to port. Note that it is possible to fork/create new threads and then bind to the same
    //port multiple times. Each thread should have its own fr::SocketSelector, this will
    //spread connections over multiple workers.
    auto listener = std::make_shared<fr::TcpListener>();
    if(listener->listen("8080") != fr::Socket::Success)
    {
        std::cerr << "Failed to bind to port" << std::endl;
        return EXIT_FAILURE;
    }

    //Create a socket selector, and add the listener so we get notified on connection requests
    fr::SocketSelector listen_loop_selector;
    listen_loop_selector.add(listener, nullptr);

    bool running = true;
    while(running)
    {
        //Pass a timeout here, so that we can periodically check 'running' to see if we should exit
        auto ready_sockets = listen_loop_selector.wait(std::chrono::milliseconds(100));
        for(auto &ready_socket : ready_sockets)
        {
            //If it's the listener, accept a new connection
            if(ready_socket.first->get_socket_descriptor() == listener->get_socket_descriptor())
            {
                auto client = std::make_shared<fr::TcpSocket>(); //Or fr::SSLSocket
                if(listener->accept(*client) == fr::Socket::Success)
                {
                    client->set_blocking(false); //This is important
                    listen_loop_selector.add(client, new SessionState()); //We assign a 'SessionState' object for each connection as opaque data
                }
                continue;
            }

            //Else, we have new activity on a client socket
            auto client = std::static_pointer_cast<fr::Socket>(ready_socket.first);
            auto session = static_cast<SessionState*>(ready_socket.second);

            //Try and receive data
            char data[0x1000];
            size_t received = 0;
            auto recv_status = client->receive_raw(data, sizeof(data), received);
            if(recv_status == fr::Socket::Success)
            {
                //We received data, so parse it using the partial HTTP request associated with this connection
                auto parse_status = session->partial_request.parse(data, received);
                if(parse_status == fr::Socket::Success)
                {
                    //The client has sent a full request, queue it for processing
                    process_complete_request(client, std::move(session->partial_request));
                    session->partial_request = fr::HttpRequest();
                }
                else if(parse_status != fr::Socket::NotEnoughData)
                {
                    //HTTP error, disconnect the client. Remove from socket selector, and delete opaque data.
                    delete (SessionState*)listen_loop_selector.remove(client);
                }
            }
            else if(recv_status != fr::Socket::WouldBlock)
            {
                //Error, disconnect it. Remove from socket selector, and delete opaque data.
                delete (SessionState*)listen_loop_selector.remove(client);
            }
        }
    }
}<|endoftext|>


<commit_before>#include "JavascriptFunction.h"
#include "JavascriptInterop.h"
#include "JavascriptContext.h"
#include "JavascriptException.h"

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

namespace Noesis { namespace Javascript {

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

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

JavascriptFunction::JavascriptFunction(v8::Local<v8::Object> iFunction, JavascriptContext^ context)
{
	if (!iFunction->IsFunction())
		throw gcnew System::ArgumentException("Trying to use non-function as function");

	if(!context)
		throw gcnew System::ArgumentException("Must provide a JavascriptContext");

	mFuncHandle = new Persistent<Function>(context->GetCurrentIsolate(), Local<Function>::Cast(iFunction));
    mContextHandle = gcnew System::WeakReference(context);
}

JavascriptFunction::~JavascriptFunction()
{
	if(mFuncHandle)
	{
		if (IsAlive())
		{
            JavascriptScope scope(GetContext());
			mFuncHandle->Reset();
		}
		delete mFuncHandle;
		mFuncHandle = nullptr;
	}
}

JavascriptFunction::!JavascriptFunction()
{
    delete this;
}

System::Object^ JavascriptFunction::Call(... cli::array<System::Object^>^ args)
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");
    if (!args)
        throw gcnew System::ArgumentNullException("args");

    auto context = GetContext();
    JavascriptScope scope(context);
	v8::Isolate* isolate = context->GetCurrentIsolate();
	HandleScope handleScope(isolate);

	Local<v8::Object> global = context->GetGlobal();

	int argc = args->Length;
	Local<v8::Value> *argv = new Local<v8::Value>[argc];
	for (int i = 0; i < argc; i++)
	{
		argv[i] = JavascriptInterop::ConvertToV8(args[i]);
	}

	TryCatch tryCatch(isolate);
	MaybeLocal<Value> retVal = mFuncHandle->Get(isolate)->Call(isolate->GetCurrentContext(), global, argc, argv);
	if (retVal.IsEmpty())
		throw gcnew JavascriptException(tryCatch);

	delete [] argv;
	return JavascriptInterop::ConvertFromV8(retVal.ToLocalChecked());
}

bool JavascriptFunction::operator==(JavascriptFunction^ func1, JavascriptFunction^ func2)
{
    bool func1_null = ReferenceEquals(func1, nullptr),
        func2_null = ReferenceEquals(func2, nullptr);
    if (func1_null != func2_null)
        return false;
    if (func1_null && func2_null)
        return true;
    if (!func1->IsAlive())
        throw gcnew JavascriptException(L"'func1's owning JavascriptContext has been disposed");
    if (!func2->IsAlive())
        throw gcnew JavascriptException(L"'func2's owning JavascriptContext has been disposed");

    auto context = func1->GetContext();
    if (func2->GetContext() != context)
        return false;

    JavascriptScope scope(context);
    auto isolate = context->GetCurrentIsolate();
    HandleScope handleScope(isolate);

    auto jsFuncPtr1 = func1->mFuncHandle->Get(isolate);
    auto jsFuncPtr2 = func2->mFuncHandle->Get(isolate);

    return jsFuncPtr1->Equals(isolate->GetCurrentContext(), jsFuncPtr2).ToChecked();
}

bool JavascriptFunction::Equals(JavascriptFunction^ other)
{
	return this == other;
}

bool JavascriptFunction::Equals(Object^ other)
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");
    JavascriptFunction^ otherFunc = dynamic_cast<JavascriptFunction^>(other);
    if (otherFunc != nullptr && !otherFunc->IsAlive())
        throw gcnew JavascriptException(L"The other function's owning JavascriptContext has been disposed");

	return (otherFunc && this->Equals(otherFunc));
}

System::String^ JavascriptFunction::ToString()
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");

    auto context = GetContext();
    JavascriptScope scope(context);
    auto isolate = context->GetCurrentIsolate();
    HandleScope handleScope(isolate);
    auto asString = mFuncHandle->Get(isolate)->ToString(isolate->GetCurrentContext());
    return safe_cast<System::String^>(JavascriptInterop::ConvertFromV8(asString.ToLocalChecked()));
}

} } // namespace Noesis::Javascript

////////////////////////////////////////////////////////////////////////////////////////////////////<commit_msg>Return early if the function references are the same<commit_after>#include "JavascriptFunction.h"
#include "JavascriptInterop.h"
#include "JavascriptContext.h"
#include "JavascriptException.h"

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

namespace Noesis { namespace Javascript {

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

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

JavascriptFunction::JavascriptFunction(v8::Local<v8::Object> iFunction, JavascriptContext^ context)
{
	if (!iFunction->IsFunction())
		throw gcnew System::ArgumentException("Trying to use non-function as function");

	if(!context)
		throw gcnew System::ArgumentException("Must provide a JavascriptContext");

	mFuncHandle = new Persistent<Function>(context->GetCurrentIsolate(), Local<Function>::Cast(iFunction));
    mContextHandle = gcnew System::WeakReference(context);
}

JavascriptFunction::~JavascriptFunction()
{
	if(mFuncHandle)
	{
		if (IsAlive())
		{
            JavascriptScope scope(GetContext());
			mFuncHandle->Reset();
		}
		delete mFuncHandle;
		mFuncHandle = nullptr;
	}
}

JavascriptFunction::!JavascriptFunction()
{
    delete this;
}

System::Object^ JavascriptFunction::Call(... cli::array<System::Object^>^ args)
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");
    if (!args)
        throw gcnew System::ArgumentNullException("args");

    auto context = GetContext();
    JavascriptScope scope(context);
	v8::Isolate* isolate = context->GetCurrentIsolate();
	HandleScope handleScope(isolate);

	Local<v8::Object> global = context->GetGlobal();

	int argc = args->Length;
	Local<v8::Value> *argv = new Local<v8::Value>[argc];
	for (int i = 0; i < argc; i++)
	{
		argv[i] = JavascriptInterop::ConvertToV8(args[i]);
	}

	TryCatch tryCatch(isolate);
	MaybeLocal<Value> retVal = mFuncHandle->Get(isolate)->Call(isolate->GetCurrentContext(), global, argc, argv);
	if (retVal.IsEmpty())
		throw gcnew JavascriptException(tryCatch);

	delete [] argv;
	return JavascriptInterop::ConvertFromV8(retVal.ToLocalChecked());
}

bool JavascriptFunction::operator==(JavascriptFunction^ func1, JavascriptFunction^ func2)
{
    if (ReferenceEquals(func1, func2))
        return true;
    if (ReferenceEquals(func1, nullptr) != ReferenceEquals(func2, nullptr))
        return false;

    if (!func1->IsAlive())
        throw gcnew JavascriptException(L"'func1's owning JavascriptContext has been disposed");
    if (!func2->IsAlive())
        throw gcnew JavascriptException(L"'func2's owning JavascriptContext has been disposed");

    auto context = func1->GetContext();
    if (func2->GetContext() != context)
        return false;

    JavascriptScope scope(context);
    auto isolate = context->GetCurrentIsolate();
    HandleScope handleScope(isolate);

    auto jsFuncPtr1 = func1->mFuncHandle->Get(isolate);
    auto jsFuncPtr2 = func2->mFuncHandle->Get(isolate);

    return jsFuncPtr1->Equals(isolate->GetCurrentContext(), jsFuncPtr2).ToChecked();
}

bool JavascriptFunction::Equals(JavascriptFunction^ other)
{
	return this == other;
}

bool JavascriptFunction::Equals(Object^ other)
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");
    JavascriptFunction^ otherFunc = dynamic_cast<JavascriptFunction^>(other);
    if (otherFunc != nullptr && !otherFunc->IsAlive())
        throw gcnew JavascriptException(L"The other function's owning JavascriptContext has been disposed");

	return (otherFunc && this->Equals(otherFunc));
}

System::String^ JavascriptFunction::ToString()
{
    if (!IsAlive())
        throw gcnew JavascriptException(L"This function's owning JavascriptContext has been disposed");

    auto context = GetContext();
    JavascriptScope scope(context);
    auto isolate = context->GetCurrentIsolate();
    HandleScope handleScope(isolate);
    auto asString = mFuncHandle->Get(isolate)->ToString(isolate->GetCurrentContext());
    return safe_cast<System::String^>(JavascriptInterop::ConvertFromV8(asString.ToLocalChecked()));
}

} } // namespace Noesis::Javascript

////////////////////////////////////////////////////////////////////////////////////////////////////<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *                Copyright (C) 2009 by the OpenSG Forum                     *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

#if __GNUC__ >= 4 || __GNUC_MINOR__ >=3
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

#include "OSGColladaNode.h"

#ifdef OSG_WITH_COLLADA

#include "OSGColladaLog.h"
#include "OSGColladaGlobal.h"
#include "OSGColladaInstanceNode.h"
#include "OSGColladaInstanceGeometry.h"
#include "OSGTransform.h"
#include "OSGNameAttachment.h"

#include <dom/domLookat.h>
#include <dom/domMatrix.h>
#include <dom/domRotate.h>
#include <dom/domScale.h>
#include <dom/domSkew.h>
#include <dom/domTranslate.h>
#include <dom/domInstance_node.h>
#include <dom/domNode.h>

OSG_BEGIN_NAMESPACE

ColladaElementRegistrationHelper ColladaNode::_regHelper(
    &ColladaNode::create, "node");

ColladaElementTransitPtr
ColladaNode::create(daeElement *elem, ColladaGlobal *global)
{
    return ColladaElementTransitPtr(new ColladaNode(elem, global));
}

void
ColladaNode::read(void)
{
    OSG_COLLADA_LOG(("ColladaNode::read\n"));

    domNodeRef                node     = getDOMElementAs<domNode>();
    const daeElementRefArray &contents = node->getContents();

    // handle "transform" child elements in the order
    // they occur in the document

    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]));
            break;

        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]));
        break;

        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]));
        break;

        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]));
        break;

        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]));
        break;

        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]));
        break;
        }
    }

    // handle <node> child elements
    const domNode_Array &nodes = node->getNode_array();

    for(UInt32 i = 0; i < nodes.getCount(); ++i)
    {
        handleNode(nodes[i]);
    }

    // handle <instance_node> child elements
    const domInstance_node_Array &instNodes = node->getInstance_node_array();

    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
    {
        handleInstanceNode(instNodes[i]);
    }

    // handle <instance_geometry> child elements
    const domInstance_geometry_Array &instGeos =
        node->getInstance_geometry_array();

    for(UInt32 i = 0; i < instGeos.getCount(); ++i)
    {
        handleInstanceGeometry(instGeos[i]);
    }

    // handle <instance_controller> child elemnts
    const domInstance_controller_Array &instControllers =
        node->getInstance_controller_array();

    for(UInt32 i = 0; i < instControllers.getCount(); ++i)
    {
        handleInstanceController(instControllers[i]);
    }

    // nothing created? build a dummy node
    if(_topN == NULL)
    {
        _topN = makeCoredNode<Group>();

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(_topN, node->getName());
        }
    }

    if(_bottomN == NULL)
    {
        _bottomN = _topN;
    }
}

Node *
ColladaNode::createInstance(ColladaInstanceElement *colInstElem)
{
    OSG_COLLADA_LOG(("ColladaNode::createInstance\n"));

    NodeUnrecPtr retVal = NULL;

    if(getInstStore().empty() == true)
    {
        retVal = _topN;
    }
    else
    {
        retVal = cloneTree(_topN);
    }

    editInstStore().push_back(retVal);

    return retVal;
}

Node *
ColladaNode::getTopNode(void) const
{
    return _topN;
}

Node *
ColladaNode::getBottomNode(void) const
{
    return _bottomN;
}

ColladaNode::ColladaNode(daeElement *elem, ColladaGlobal *global)
    : Inherited(elem, global)
    , _topN    (NULL)
    , _bottomN (NULL)
{
}

ColladaNode::~ColladaNode(void)
{
}

void
ColladaNode::handleLookAt(domLookat *lookat)
{
    if(lookat == NULL)
        return;

    SWARNING << "ColladaNode::handleLookAt: NIY" << std::endl;
}

void
ColladaNode::handleMatrix(domMatrix *matrix)
{
    if(matrix == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    Matrix m(matrix->getValue()[0],      // rVal00
             matrix->getValue()[1],      // rVal10
             matrix->getValue()[2],      // rVal20
             matrix->getValue()[3],      // rVal30
             matrix->getValue()[4],      // rVal01
             matrix->getValue()[5],      // rVal11
             matrix->getValue()[6],      // rVal21
             matrix->getValue()[7],      // rVal31
             matrix->getValue()[8],      // rVal02
             matrix->getValue()[9],      // rVal12
             matrix->getValue()[10],     // rVal22
             matrix->getValue()[11],     // rVal32
             matrix->getValue()[12],     // rVal03
             matrix->getValue()[13],     // rVal13
             matrix->getValue()[14],     // rVal23
             matrix->getValue()[15] );   // rVal33

    xform->setMatrix(m);

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(matrix->getSid() != NULL)
        {
            nodeName.append("."             );
            nodeName.append(matrix->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleRotate(domRotate *rotate)
{
    if(rotate == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    Quaternion q;
    q.setValueAsAxisDeg(rotate->getValue()[0],
                        rotate->getValue()[1],
                        rotate->getValue()[2],
                        rotate->getValue()[3] );

    xform->editMatrix().setRotate(q);

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(rotate->getSid() != NULL)
        {
            nodeName.append("."             );
            nodeName.append(rotate->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleScale(domScale *scale)
{
    if(scale == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    xform->editMatrix().setScale(scale->getValue()[0],
                                 scale->getValue()[1],
                                 scale->getValue()[2] );

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(scale->getSid() != NULL)
        {
            nodeName.append("."            );
            nodeName.append(scale->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleSkew(domSkew *skew)
{
    if(skew == NULL)
        return;

    SWARNING << "ColladaNode::handleSkew: NIY" << std::endl;
}

void
ColladaNode::handleTranslate(domTranslate *translate)
{
    if(translate == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    xform->editMatrix().setTranslate(translate->getValue()[0],
                                     translate->getValue()[1],
                                     translate->getValue()[2] );

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(translate->getSid() != NULL)
        {
            nodeName.append("."                );
            nodeName.append(translate->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleNode(domNode *node)
{
    ColladaNodeRefPtr colNode = getUserDataAs<ColladaNode>(node);

    if(colNode == NULL)
    {
        colNode = dynamic_pointer_cast<ColladaNode>(
            ColladaElementFactory::the()->create(node, getGlobal()));

        colNode->read();
    }

    Node *childN = colNode->getTopNode();

    if(childN->getParent() != NULL)
    {
        SWARNING << "ColladaNode::handleNode: Node already has a parent."
                 << std::endl;
    }

    appendChild(childN);
}

void
ColladaNode::handleInstanceNode(domInstance_node *instNode)
{
    ColladaInstanceNodeRefPtr colInstNode =
        getUserDataAs<ColladaInstanceNode>(instNode);

    if(colInstNode == NULL)
    {
        colInstNode = dynamic_pointer_cast<ColladaInstanceNode>(
            ColladaElementFactory::the()->create(instNode, getGlobal()));

        colInstNode->read();
    }

    NodeUnrecPtr childN = colInstNode->process(this);

    appendChild(childN);
}

void
ColladaNode::handleInstanceGeometry(domInstance_geometry *instGeo)
{
    ColladaInstanceGeometryRefPtr colInstGeo =
        getUserDataAs<ColladaInstanceGeometry>(instGeo);

    if(colInstGeo == NULL)
    {
        colInstGeo = dynamic_pointer_cast<ColladaInstanceGeometry>(
            ColladaElementFactory::the()->create(instGeo, getGlobal()));

        colInstGeo->read();
    }

    NodeUnrecPtr geoN = colInstGeo->process(this);

    appendChild(geoN);
}

void
ColladaNode::handleInstanceController(domInstance_controller *instController)
{
    SWARNING << "ColladaNode::handleInstanceController: NIY"
             << std::endl;
}

/*! Add a transform node to the OpenSG tree representing
    this <node>.
 */
void
ColladaNode::appendXForm(Node *xformN)
{
    if(_topN == NULL)
    {
        _topN = xformN;
    }

    if(_bottomN != NULL)
    {
        _bottomN->addChild(xformN);
    }

    _bottomN = xformN;
}

/*! Add a child node to the OpenSG tree representing
    this <node>.
 */
void
ColladaNode::appendChild(Node *childN)
{
    if(_bottomN == NULL)
    {
        _bottomN = makeCoredNode<Group>();

        domNodeRef node = getDOMElementAs<domNode>();

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(_bottomN, node->getName());
        }
    }

    if(_topN == NULL)
    {
        _topN = _bottomN;
    }

    _bottomN->addChild(childN);
}

OSG_END_NAMESPACE

#endif // OSG_WITH_COLLADA
<commit_msg>fixed: avoid reparenting node when creating instances.<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *                Copyright (C) 2009 by the OpenSG Forum                     *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

#if __GNUC__ >= 4 || __GNUC_MINOR__ >=3
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

#include "OSGColladaNode.h"

#ifdef OSG_WITH_COLLADA

#include "OSGColladaLog.h"
#include "OSGColladaGlobal.h"
#include "OSGColladaInstanceNode.h"
#include "OSGColladaInstanceGeometry.h"
#include "OSGTransform.h"
#include "OSGNameAttachment.h"

#include <dom/domLookat.h>
#include <dom/domMatrix.h>
#include <dom/domRotate.h>
#include <dom/domScale.h>
#include <dom/domSkew.h>
#include <dom/domTranslate.h>
#include <dom/domInstance_node.h>
#include <dom/domNode.h>

OSG_BEGIN_NAMESPACE

ColladaElementRegistrationHelper ColladaNode::_regHelper(
    &ColladaNode::create, "node");

ColladaElementTransitPtr
ColladaNode::create(daeElement *elem, ColladaGlobal *global)
{
    return ColladaElementTransitPtr(new ColladaNode(elem, global));
}

void
ColladaNode::read(void)
{
    OSG_COLLADA_LOG(("ColladaNode::read\n"));

    domNodeRef                node     = getDOMElementAs<domNode>();
    const daeElementRefArray &contents = node->getContents();

    // handle "transform" child elements in the order
    // they occur in the document

    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]));
            break;

        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]));
        break;

        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]));
        break;

        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]));
        break;

        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]));
        break;

        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]));
        break;
        }
    }

    // handle <node> child elements
    const domNode_Array &nodes = node->getNode_array();

    for(UInt32 i = 0; i < nodes.getCount(); ++i)
    {
        handleNode(nodes[i]);
    }

    // handle <instance_node> child elements
    const domInstance_node_Array &instNodes = node->getInstance_node_array();

    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
    {
        handleInstanceNode(instNodes[i]);
    }

    // handle <instance_geometry> child elements
    const domInstance_geometry_Array &instGeos =
        node->getInstance_geometry_array();

    for(UInt32 i = 0; i < instGeos.getCount(); ++i)
    {
        handleInstanceGeometry(instGeos[i]);
    }

    // handle <instance_controller> child elemnts
    const domInstance_controller_Array &instControllers =
        node->getInstance_controller_array();

    for(UInt32 i = 0; i < instControllers.getCount(); ++i)
    {
        handleInstanceController(instControllers[i]);
    }

    // nothing created? build a dummy node
    if(_topN == NULL)
    {
        _topN = makeCoredNode<Group>();

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(_topN, node->getName());
        }
    }

    if(_bottomN == NULL)
    {
        _bottomN = _topN;
    }
}

Node *
ColladaNode::createInstance(ColladaInstanceElement *colInstElem)
{
    OSG_COLLADA_LOG(("ColladaNode::createInstance\n"));

    NodeUnrecPtr retVal = NULL;

    if(_topN->getParent() != NULL)
    {
        retVal = cloneTree(_topN);
    }
    else
    {
        retVal = cloneTree(_topN);
    }

    editInstStore().push_back(retVal);

    return retVal;
}

Node *
ColladaNode::getTopNode(void) const
{
    return _topN;
}

Node *
ColladaNode::getBottomNode(void) const
{
    return _bottomN;
}

ColladaNode::ColladaNode(daeElement *elem, ColladaGlobal *global)
    : Inherited(elem, global)
    , _topN    (NULL)
    , _bottomN (NULL)
{
}

ColladaNode::~ColladaNode(void)
{
}

void
ColladaNode::handleLookAt(domLookat *lookat)
{
    if(lookat == NULL)
        return;

    SWARNING << "ColladaNode::handleLookAt: NIY" << std::endl;
}

void
ColladaNode::handleMatrix(domMatrix *matrix)
{
    if(matrix == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    Matrix m(matrix->getValue()[0],      // rVal00
             matrix->getValue()[1],      // rVal10
             matrix->getValue()[2],      // rVal20
             matrix->getValue()[3],      // rVal30
             matrix->getValue()[4],      // rVal01
             matrix->getValue()[5],      // rVal11
             matrix->getValue()[6],      // rVal21
             matrix->getValue()[7],      // rVal31
             matrix->getValue()[8],      // rVal02
             matrix->getValue()[9],      // rVal12
             matrix->getValue()[10],     // rVal22
             matrix->getValue()[11],     // rVal32
             matrix->getValue()[12],     // rVal03
             matrix->getValue()[13],     // rVal13
             matrix->getValue()[14],     // rVal23
             matrix->getValue()[15] );   // rVal33

    xform->setMatrix(m);

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(matrix->getSid() != NULL)
        {
            nodeName.append("."             );
            nodeName.append(matrix->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleRotate(domRotate *rotate)
{
    if(rotate == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    Quaternion q;
    q.setValueAsAxisDeg(rotate->getValue()[0],
                        rotate->getValue()[1],
                        rotate->getValue()[2],
                        rotate->getValue()[3] );

    xform->editMatrix().setRotate(q);

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(rotate->getSid() != NULL)
        {
            nodeName.append("."             );
            nodeName.append(rotate->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleScale(domScale *scale)
{
    if(scale == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    xform->editMatrix().setScale(scale->getValue()[0],
                                 scale->getValue()[1],
                                 scale->getValue()[2] );

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(scale->getSid() != NULL)
        {
            nodeName.append("."            );
            nodeName.append(scale->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleSkew(domSkew *skew)
{
    if(skew == NULL)
        return;

    SWARNING << "ColladaNode::handleSkew: NIY" << std::endl;
}

void
ColladaNode::handleTranslate(domTranslate *translate)
{
    if(translate == NULL)
        return;

    domNodeRef        node   = getDOMElementAs<domNode>();

    TransformUnrecPtr xform  = Transform::create();
    NodeUnrecPtr      xformN = makeNodeFor(xform);

    xform->editMatrix().setTranslate(translate->getValue()[0],
                                     translate->getValue()[1],
                                     translate->getValue()[2] );

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
       node->getName()                                       != NULL   )
    {
        std::string nodeName = node->getName();

        if(translate->getSid() != NULL)
        {
            nodeName.append("."                );
            nodeName.append(translate->getSid());
        }

        setName(xformN, nodeName);
    }

    appendXForm(xformN);
}

void
ColladaNode::handleNode(domNode *node)
{
    ColladaNodeRefPtr colNode = getUserDataAs<ColladaNode>(node);

    if(colNode == NULL)
    {
        colNode = dynamic_pointer_cast<ColladaNode>(
            ColladaElementFactory::the()->create(node, getGlobal()));

        colNode->read();
    }

    Node *childN = colNode->getTopNode();

    if(childN->getParent() != NULL)
    {
        SWARNING << "ColladaNode::handleNode: Node already has a parent."
                 << std::endl;
    }

    appendChild(childN);
}

void
ColladaNode::handleInstanceNode(domInstance_node *instNode)
{
    ColladaInstanceNodeRefPtr colInstNode =
        getUserDataAs<ColladaInstanceNode>(instNode);

    if(colInstNode == NULL)
    {
        colInstNode = dynamic_pointer_cast<ColladaInstanceNode>(
            ColladaElementFactory::the()->create(instNode, getGlobal()));

        colInstNode->read();
    }

    NodeUnrecPtr childN = colInstNode->process(this);

    appendChild(childN);
}

void
ColladaNode::handleInstanceGeometry(domInstance_geometry *instGeo)
{
    ColladaInstanceGeometryRefPtr colInstGeo =
        getUserDataAs<ColladaInstanceGeometry>(instGeo);

    if(colInstGeo == NULL)
    {
        colInstGeo = dynamic_pointer_cast<ColladaInstanceGeometry>(
            ColladaElementFactory::the()->create(instGeo, getGlobal()));

        colInstGeo->read();
    }

    NodeUnrecPtr geoN = colInstGeo->process(this);

    appendChild(geoN);
}

void
ColladaNode::handleInstanceController(domInstance_controller *instController)
{
    SWARNING << "ColladaNode::handleInstanceController: NIY"
             << std::endl;
}

/*! Add a transform node to the OpenSG tree representing
    this <node>.
 */
void
ColladaNode::appendXForm(Node *xformN)
{
    if(_topN == NULL)
    {
        _topN = xformN;
    }

    if(_bottomN != NULL)
    {
        _bottomN->addChild(xformN);
    }

    _bottomN = xformN;
}

/*! Add a child node to the OpenSG tree representing
    this <node>.
 */
void
ColladaNode::appendChild(Node *childN)
{
    if(_bottomN == NULL)
    {
        _bottomN = makeCoredNode<Group>();

        domNodeRef node = getDOMElementAs<domNode>();

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(_bottomN, node->getName());
        }
    }

    if(_topN == NULL)
    {
        _topN = _bottomN;
    }

    _bottomN->addChild(childN);
}

OSG_END_NAMESPACE

#endif // OSG_WITH_COLLADA
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/DIALOGS/pythonHotkeys.h>

#include <qtable.h>
#include <qpushbutton.h>

namespace BALL
{
	namespace VIEW
	{

PythonHotkeys::PythonHotkeys( QWidget* parent,  const char* name, WFlags fl )
    : PythonHotkeysData( parent, name, fl )
{
  table->horizontalHeader()->setLabel(0, "Modifier");
  table->horizontalHeader()->setLabel(1, "Key");
  table->horizontalHeader()->setLabel(2, "Command");

  table->setNumRows(0);
	table->setColumnWidth(2, 240);

	modifier_ << "None" << "Shift" << "Ctrl" << "Alt";
	for (Position p = 1; p < 13; p++)
	{
		keys_ << String("F") + String(p).c_str();
	}

	setDefaults();
}

List<Hotkey> PythonHotkeys::getContent() const
	throw()
{
	List<Hotkey> result;
	for (Index p = 0; p < table->numRows(); p++)
	{
		if (table->item(p, 2)->text().isEmpty() ||
				table->item(p, 0) == 0  						||
				!RTTI::isKindOf<QComboTableItem>(*table->item(p, 0)))
		{
			continue;
		}

		Hotkey hotkey;

Log.error() << "#~~#   14 "    << __FILE__ << "  " << __LINE__<< std::endl;
		Index p = ((QComboTableItem*) table->item(p, 0))->currentItem();
Log.error() << "#~~#   16 "    << __FILE__ << "  " << __LINE__<< std::endl;
		if (p == 0)
		{
			hotkey.button_state = Qt::NoButton;
		}
		else
		{
			hotkey.button_state = (Qt::ButtonState) (Qt::ShiftButton + p - 1);
		}

Log.error() << "#~~#   15 "    << __FILE__ << "  " << __LINE__<< std::endl;
		p = ((QComboTableItem*) table->item(p, 1))->currentItem();
		hotkey.key = (Qt::Key) (Qt::Key_F1 + p);

		result.push_back(hotkey);
	}

	return result;
}

void PythonHotkeys::setContent(const List<Hotkey>& hotkeys)
	throw()
{
  table->setNumRows(hotkeys.size());
	table->setColumnWidth(2, 230);

	List<Hotkey>::ConstIterator it = hotkeys.begin();
	Position p = 0;
	for (; it != hotkeys.end(); it++)
	{
		QComboTableItem * item = new QComboTableItem(table, modifier_, FALSE );
		if ((*it).button_state == Qt::NoButton ||
				(*it).button_state == 0)
		{
			item->setCurrentItem(0);
		}
		else
		{
			if ((*it).button_state < Qt::ShiftButton)
			{
				Log.error() << "Invalid button state for Hotkey" << std::endl;
			}
			else
			{
				item->setCurrentItem((*it).button_state - Qt::ShiftButton + 1);
			}
		}
    table->setItem(p, 0,  item) ;

		QComboTableItem * item2 = new QComboTableItem(table, keys_, FALSE );
		item2->setCurrentItem((*it).key - Qt::Key_F1);
    table->setItem(p, 1,  item2) ;

    table->setText(p, 2,  (*it).action.c_str());

		p++;
	}
}

void PythonHotkeys::setDefaults(bool all)
	throw()
{
}

void PythonHotkeys::addEmtpyLine_()
	throw()
{
	table->setNumRows(table->numRows() + 1);
	QComboTableItem * item = new QComboTableItem(table, modifier_, FALSE );
	item->setCurrentItem(0);
  table->setItem(table->numRows() -1, 0,  item) ;
	item = new QComboTableItem(table, keys_, FALSE );
	item->setCurrentItem(0);
  table->setItem(table->numRows() -1, 1,  item) ;
  table->setText(table->numRows() -1, 2, "");
	table->update();
}

void PythonHotkeys::removePressed()
{
	for (Index p = 0; p < table->numRows(); p++)
	{
		if (table->isRowSelected(p))
		{
			table->removeRow(p);
			return;
		}
	}
}

void PythonHotkeys::newPressed()
{
	addEmtpyLine_();
}

void PythonHotkeys::rowSelected()
{
	remove_button->setEnabled(table->currentSelection() == -1);
}

} } // NAMESPACE
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/DIALOGS/pythonHotkeys.h>

#include <qtable.h>
#include <qpushbutton.h>

namespace BALL
{
	namespace VIEW
	{

PythonHotkeys::PythonHotkeys( QWidget* parent,  const char* name, WFlags fl )
    : PythonHotkeysData( parent, name, fl )
{
  table->horizontalHeader()->setLabel(0, "Modifier");
  table->horizontalHeader()->setLabel(1, "Key");
  table->horizontalHeader()->setLabel(2, "Command");

  table->setNumRows(0);
	table->setColumnWidth(2, 240);

	modifier_ << "None" << "Shift" << "Ctrl" << "Alt";
	for (Position p = 1; p < 13; p++)
	{
		keys_ << String("F") + String(p).c_str();
	}

	setDefaults();
}

List<Hotkey> PythonHotkeys::getContent() const
	throw()
{
	List<Hotkey> result;
	for (Index pos = 0; pos < table->numRows(); pos++)
	{
		if (table->item(pos, 2)->text().isEmpty() ||
				!RTTI::isKindOf<QComboTableItem>(*table->item(pos, 0)))
		{
			continue;
		}

		Hotkey hotkey;

		table->item(pos, 0);
		Index p = (dynamic_cast<QComboTableItem*>( table->item(pos, 0)))->currentItem();
		if (p == 0)
		{
			hotkey.button_state = Qt::NoButton;
		}
		else
		{
			hotkey.button_state = (Qt::ButtonState) (Qt::ShiftButton + p - 1);
		}

		p = ((QComboTableItem*) table->item(p, 1))->currentItem();
		hotkey.key = (Qt::Key) (Qt::Key_F1 + p);

		hotkey.action = table->item(pos, 2)->text().ascii();

		result.push_back(hotkey);
	}

	return result;
}

void PythonHotkeys::setContent(const List<Hotkey>& hotkeys)
	throw()
{
  table->setNumRows(hotkeys.size());
	table->setColumnWidth(2, 230);

	List<Hotkey>::ConstIterator it = hotkeys.begin();
	Position p = 0;
	for (; it != hotkeys.end(); it++)
	{
		QComboTableItem * item = new QComboTableItem(table, modifier_, FALSE );
		if ((*it).button_state == Qt::NoButton ||
				(*it).button_state == 0)
		{
			item->setCurrentItem(0);
		}
		else
		{
			if ((*it).button_state < Qt::ShiftButton)
			{
				Log.error() << "Invalid button state for Hotkey" << std::endl;
			}
			else
			{
				item->setCurrentItem((*it).button_state - Qt::ShiftButton + 1);
			}
		}
    table->setItem(p, 0,  item) ;

		QComboTableItem * item2 = new QComboTableItem(table, keys_, FALSE );
		item2->setCurrentItem((*it).key - Qt::Key_F1);
    table->setItem(p, 1,  item2) ;

    table->setText(p, 2,  (*it).action.c_str());

		p++;
	}
}

void PythonHotkeys::setDefaults(bool all)
	throw()
{
}

void PythonHotkeys::addEmtpyLine_()
	throw()
{
	table->setNumRows(table->numRows() + 1);
	QComboTableItem * item = new QComboTableItem(table, modifier_, FALSE );
	item->setCurrentItem(0);
  table->setItem(table->numRows() -1, 0,  item) ;
	item = new QComboTableItem(table, keys_, FALSE );
	item->setCurrentItem(0);
  table->setItem(table->numRows() -1, 1,  item) ;
  table->setText(table->numRows() -1, 2, "");
	table->update();
}

void PythonHotkeys::removePressed()
{
	for (Index p = 0; p < table->numRows(); p++)
	{
		if (table->isRowSelected(p))
		{
			table->removeRow(p);
			return;
		}
	}
}

void PythonHotkeys::newPressed()
{
	addEmtpyLine_();
}

void PythonHotkeys::rowSelected()
{
	remove_button->setEnabled(table->currentSelection() == -1);
}

} } // NAMESPACE
<|endoftext|>


<commit_before>#include <iostream>
#include <regex>
#include <ctime>
#include <Ice/Ice.h>
#include <vlc/libvlc.h>
#include <vlc/vlc.h>
#include "server.h"

class MusicServer : public Player::IMusicServer
{
	public:
		enum FindBy { Artist, Title, Everything };

		MusicServer(const std::string& port);
		~MusicServer();

		virtual void add(const Player::Song& s, const Ice::Current& c) override;
		virtual void remove(const std::string& path, const Ice::Current& c) override;
		virtual Player::SongSeq find(const std::string& s, const Ice::Current& c) override;
		Player::SongSeq find(const std::string& s, const FindBy fb);
		virtual Player::SongSeq findByArtist(const std::string& s, const Ice::Current& c) override;
		virtual Player::SongSeq findByTitle(const std::string& s, const Ice::Current& c) override;
		virtual Player::SongSeq listSongs(const Ice::Current& c) override;

		virtual Player::StreamToken setupStreaming(const std::string& path, const std::string& ip, const std::string& port, const Ice::Current& c) override;
		virtual void play(const Player::StreamToken& token, const Ice::Current& c) override;
		virtual void stop(const Player::StreamToken& token, const Ice::Current& c) override;

	private:
		std::string streamingPort;
		std::map<std::string, Player::Song> db;
		libvlc_instance_t* vlc;

};

MusicServer::MusicServer(const std::string& port) : streamingPort(port)
{
	vlc = libvlc_new(0, nullptr);
	if (!vlc)
		throw std::runtime_error("Could not create libvlc instance");
}

MusicServer::~MusicServer()
{
	libvlc_vlm_release(vlc);
}

void MusicServer::add(const Player::Song& s, const Ice::Current& c)
{
	std::cout << "Adding to db: " << s.artist << " - " << s.title << " - " << s.path << '\n';
	if (!db.emplace(s.path, s).second)
		throw Player::Error("Another song has the same path");
}

void MusicServer::remove(const std::string& path, const Ice::Current& c)
{
	std::cout << "Removing: " << path << '\n';
	db.erase(path);
}

Player::SongSeq MusicServer::find(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for: " << s << '\n';
	return find(s, FindBy::Everything);
}

Player::SongSeq MusicServer::findByArtist(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for artist: " << s << '\n';
	return find(s, FindBy::Artist);
}

Player::SongSeq MusicServer::findByTitle(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for title: " << s << '\n';
	return find(s, FindBy::Title);
}

Player::SongSeq MusicServer::find(const std::string& s, const FindBy fb)
{
	Player::SongSeq songs;
	std::string str(s);
	std::transform(str.begin(), str.end(), str.begin(), tolower);

	for (const auto& it : db) {
		std::string artist(it.second.artist);
		std::string title(it.second.title);
		std::transform(artist.begin(), artist.end(), artist.begin(), tolower);
		std::transform(title.begin(), title.end(), title.begin(), tolower);

		if ((fb == FindBy::Everything && (artist.find(str) != std::string::npos || title.find(str) != std::string::npos))
				|| (fb == FindBy::Artist && artist.find(str) != std::string::npos)
				|| (fb == FindBy::Title && title.find(str) != std::string::npos))
			songs.push_back(it.second);
	}

	return songs;
}

Player::SongSeq MusicServer::listSongs(const Ice::Current& c)
{
	Player::SongSeq songs;
	songs.reserve(db.size());

	for (const auto& it : db)
		songs.push_back(it.second);

	return songs;
}

Player::StreamToken MusicServer::setupStreaming(const std::string& path, const std::string& clientIP, const std::string& clientPort, const Ice::Current& c)
{
	std::cout << "Setup stream " << path << '\n';
	Player::StreamToken token;
	std::string::size_type pos = path.find_last_of("/");
	std::string file(path, (pos == std::string::npos) ? 0 : pos);
	std::string cleanClientIP = std::regex_replace(clientIP, std::regex(":"), "");
	std::string mediaName = cleanClientIP + '_' + clientPort + '_' + std::to_string(time(nullptr)) + file;

	std::string sout = "#transcode{acodec=mp3,ab=128,channels=2,"
		"samplerate=44100}:http{dst=:"+ streamingPort + "/" + mediaName + ".mp3}";

	if (libvlc_vlm_add_broadcast(vlc, mediaName.c_str(), path.c_str(), sout.c_str(), 0, nullptr, true, false) == 0) {
		token.libvlcMediaName = mediaName;
		token.streamingURL = mediaName + ".mp3";
	}

	return token;
}

void MusicServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
	std::cout << "Play " << token.streamingURL << '\n';
	libvlc_vlm_play_media(vlc, token.libvlcMediaName.c_str());
}

void MusicServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
	std::cout << "Stop " << token.streamingURL << '\n';
	libvlc_vlm_stop_media(vlc, token.libvlcMediaName.c_str());
}

void setPort(std::string& port, const char* arg)
{
	try {
		std::stoul(arg);
	}
	catch (const std::exception& e) {
		std::cerr << "Invalid port number: " << arg << '\n';
		exit(1);
	}

	port = arg;
}

int main(int argc, char **argv)
{
	int status = 0;
	Ice::CommunicatorPtr ic;
	std::string port("10001");
	std::string streamPort("8090");
	int opt;

	while ((opt = getopt(argc, argv, "p:s:")) != -1) {
		if (opt == 'p') {
			setPort(port, optarg);
		}
		else if (opt == 's') {
			setPort(streamPort, optarg);
		}
		else {
			std::cerr << "Usage: " << argv[0] << " [-p listeningPort] [-d streamingPort]\n";
			return 1;
		}
	}

	try {
		ic = Ice::initialize(argc, argv);
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MusicServerAdapter", "default -p " + port);
		Ice::ObjectPtr object = new MusicServer(streamPort);
		adapter->add(object, ic->stringToIdentity("MusicServer"));
		adapter->activate();
		ic->waitForShutdown();
	}
	catch (const Ice::Exception& e) {
		std::cerr << e << std::endl;
		status = 1;
	}
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		status = 1;
	}
	catch (...) {
		status = 1;
	}

	if (ic) {
		try {
			ic->destroy();
		}
		catch (const Ice::Exception& e) {
			std::cerr << e << std::endl;
			status = 1;
		}
	}

	return status;
}
<commit_msg>remove blank line<commit_after>#include <iostream>
#include <regex>
#include <ctime>
#include <Ice/Ice.h>
#include <vlc/libvlc.h>
#include <vlc/vlc.h>
#include "server.h"

class MusicServer : public Player::IMusicServer
{
	public:
		enum FindBy { Artist, Title, Everything };

		MusicServer(const std::string& port);
		~MusicServer();

		virtual void add(const Player::Song& s, const Ice::Current& c) override;
		virtual void remove(const std::string& path, const Ice::Current& c) override;
		virtual Player::SongSeq find(const std::string& s, const Ice::Current& c) override;
		Player::SongSeq find(const std::string& s, const FindBy fb);
		virtual Player::SongSeq findByArtist(const std::string& s, const Ice::Current& c) override;
		virtual Player::SongSeq findByTitle(const std::string& s, const Ice::Current& c) override;
		virtual Player::SongSeq listSongs(const Ice::Current& c) override;

		virtual Player::StreamToken setupStreaming(const std::string& path, const std::string& ip, const std::string& port, const Ice::Current& c) override;
		virtual void play(const Player::StreamToken& token, const Ice::Current& c) override;
		virtual void stop(const Player::StreamToken& token, const Ice::Current& c) override;

	private:
		std::string streamingPort;
		std::map<std::string, Player::Song> db;
		libvlc_instance_t* vlc;
};

MusicServer::MusicServer(const std::string& port) : streamingPort(port)
{
	vlc = libvlc_new(0, nullptr);
	if (!vlc)
		throw std::runtime_error("Could not create libvlc instance");
}

MusicServer::~MusicServer()
{
	libvlc_vlm_release(vlc);
}

void MusicServer::add(const Player::Song& s, const Ice::Current& c)
{
	std::cout << "Adding to db: " << s.artist << " - " << s.title << " - " << s.path << '\n';
	if (!db.emplace(s.path, s).second)
		throw Player::Error("Another song has the same path");
}

void MusicServer::remove(const std::string& path, const Ice::Current& c)
{
	std::cout << "Removing: " << path << '\n';
	db.erase(path);
}

Player::SongSeq MusicServer::find(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for: " << s << '\n';
	return find(s, FindBy::Everything);
}

Player::SongSeq MusicServer::findByArtist(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for artist: " << s << '\n';
	return find(s, FindBy::Artist);
}

Player::SongSeq MusicServer::findByTitle(const std::string& s, const Ice::Current& c)
{
	std::cout << "Searching for title: " << s << '\n';
	return find(s, FindBy::Title);
}

Player::SongSeq MusicServer::find(const std::string& s, const FindBy fb)
{
	Player::SongSeq songs;
	std::string str(s);
	std::transform(str.begin(), str.end(), str.begin(), tolower);

	for (const auto& it : db) {
		std::string artist(it.second.artist);
		std::string title(it.second.title);
		std::transform(artist.begin(), artist.end(), artist.begin(), tolower);
		std::transform(title.begin(), title.end(), title.begin(), tolower);

		if ((fb == FindBy::Everything && (artist.find(str) != std::string::npos || title.find(str) != std::string::npos))
				|| (fb == FindBy::Artist && artist.find(str) != std::string::npos)
				|| (fb == FindBy::Title && title.find(str) != std::string::npos))
			songs.push_back(it.second);
	}

	return songs;
}

Player::SongSeq MusicServer::listSongs(const Ice::Current& c)
{
	Player::SongSeq songs;
	songs.reserve(db.size());

	for (const auto& it : db)
		songs.push_back(it.second);

	return songs;
}

Player::StreamToken MusicServer::setupStreaming(const std::string& path, const std::string& clientIP, const std::string& clientPort, const Ice::Current& c)
{
	std::cout << "Setup stream " << path << '\n';
	Player::StreamToken token;
	std::string::size_type pos = path.find_last_of("/");
	std::string file(path, (pos == std::string::npos) ? 0 : pos);
	std::string cleanClientIP = std::regex_replace(clientIP, std::regex(":"), "");
	std::string mediaName = cleanClientIP + '_' + clientPort + '_' + std::to_string(time(nullptr)) + file;

	std::string sout = "#transcode{acodec=mp3,ab=128,channels=2,"
		"samplerate=44100}:http{dst=:"+ streamingPort + "/" + mediaName + ".mp3}";

	if (libvlc_vlm_add_broadcast(vlc, mediaName.c_str(), path.c_str(), sout.c_str(), 0, nullptr, true, false) == 0) {
		token.libvlcMediaName = mediaName;
		token.streamingURL = mediaName + ".mp3";
	}

	return token;
}

void MusicServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
	std::cout << "Play " << token.streamingURL << '\n';
	libvlc_vlm_play_media(vlc, token.libvlcMediaName.c_str());
}

void MusicServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
	std::cout << "Stop " << token.streamingURL << '\n';
	libvlc_vlm_stop_media(vlc, token.libvlcMediaName.c_str());
}

void setPort(std::string& port, const char* arg)
{
	try {
		std::stoul(arg);
	}
	catch (const std::exception& e) {
		std::cerr << "Invalid port number: " << arg << '\n';
		exit(1);
	}

	port = arg;
}

int main(int argc, char **argv)
{
	int status = 0;
	Ice::CommunicatorPtr ic;
	std::string port("10001");
	std::string streamPort("8090");
	int opt;

	while ((opt = getopt(argc, argv, "p:s:")) != -1) {
		if (opt == 'p') {
			setPort(port, optarg);
		}
		else if (opt == 's') {
			setPort(streamPort, optarg);
		}
		else {
			std::cerr << "Usage: " << argv[0] << " [-p listeningPort] [-d streamingPort]\n";
			return 1;
		}
	}

	try {
		ic = Ice::initialize(argc, argv);
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MusicServerAdapter", "default -p " + port);
		Ice::ObjectPtr object = new MusicServer(streamPort);
		adapter->add(object, ic->stringToIdentity("MusicServer"));
		adapter->activate();
		ic->waitForShutdown();
	}
	catch (const Ice::Exception& e) {
		std::cerr << e << std::endl;
		status = 1;
	}
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		status = 1;
	}
	catch (...) {
		status = 1;
	}

	if (ic) {
		try {
			ic->destroy();
		}
		catch (const Ice::Exception& e) {
			std::cerr << e << std::endl;
			status = 1;
		}
	}

	return status;
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageMomentsTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

#include "itkAffineTransform.h"
#include "itkImage.h"
#include "itkImageMomentsCalculator.h"
#include "itkIndex.h"
#include "itkSize.h"

typedef itk::Vector<double,3>  VectorType;
typedef itk::Matrix<double,3>  MatrixType;

int
main(
    int argc,
    char *argv[])
{
    /* Define acceptable (absolute) error in computed results.
       All the calculations are done in double and are well-conditioned,
       so we should be able to get within a few epsilon of the right
       values.  So choose maxerr to be 10*epsilon for IEEE 754 double. */
    double maxerr = 1.0e-15;

    /* Define the image size and physical coordinates */
    itk::Size<3> size = {{20, 40, 80}};
    double origin [3] = { 0.5,   0.5,   0.5};
    double spacing[3] = { 0.1,   0.05 , 0.025};

    /* Define positions of the test masses in index coordinates */
    unsigned short mass = 1;           // Test mass
    unsigned long point[8][3] = {
	{ 10+8, 20+12, 40+0},
	{ 10-8, 20-12, 40-0},
	{ 10+3, 20-8,  40+0},
	{ 10-3, 20+8,  40-0},
	{ 10+0, 20+0,  40+10},
	{ 10-0, 20-0,  40-10},
    };

    /* Define the expected (true) results for comparison */
    double ttm = 6.0;                      // Total mass
    double pad[3][3] = {                   // Principal axes
      { 0.0,  0.0, 1.0},
      { 0.6, -0.8, 0.0},
      { 0.8,  0.6, 0.0},
    };

    VectorType tcg;
    tcg = 1.5,   1.5, 1.5;    // Center of gravity

    VectorType tpm;
    tpm = 0.125, 0.5, 2.0;    // Principal moments

    MatrixType tpa;
    tpa.set((double *)pad);

    /* Allocate a simple test image */
    itk::Image<unsigned short, 3>::Pointer
      image = itk::Image<unsigned short,3>::New();
    itk::Image<unsigned short, 3>::RegionType region;
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetBufferedRegion(region);

    /* Set origin and spacing of physical coordinates */
    image->SetOrigin(origin);
    image->SetSpacing(spacing);
    image->Allocate();

    /* Set a few mass points within the image */
    /* FIXME: The method used here to set the points is klutzy,
       but appears to be the only method currently supported. */
    itk::Index<3> index;          /* Index over pixels */
    for ( int i = 0; i < 6; i++) {
	index.SetIndex(point[i]);
	image->SetPixel(index, mass);
    }

    /* Compute the moments */
    itk::ImageMomentsCalculator<unsigned short, 3>
	moments(image);
    double ctm = moments.GetTotalMass();
    VectorType ccg = moments.GetCenterOfGravity();
    VectorType cpm = moments.GetPrincipalMoments();
    MatrixType cpa = moments.GetPrincipalAxes();

    /* Report the various non-central moments */
    // FIXME:  Indentation is not handled correctly in matrix output
    std::cout << "\nTotal mass = " << ctm << std::endl;
    std::cout << "True total mass = " << ttm << std::endl;
    std::cout << "\nFirst moments about index origin =\n";
    std::cout << "   " <<  moments.GetFirstMoments() << std::endl;
    std::cout << "\nSecond moments about index origin =\n";
    std::cout << "   " << moments.GetSecondMoments() << std::endl;

    /* Report the center of gravity and central moments */
    std::cout << "\nCenter of gravity =\n";
    std::cout << "   " << ccg << "\n";
    std::cout << "True center of gravity =\n";
    std::cout << "   " << tcg << "\n";
    std::cout << "\nSecond central moments =\n";
    std::cout << "   " << moments.GetCentralMoments() << "\n";

    /* Report principal moments and axes */
    std::cout << "\nPrincipal moments = \n";
    std::cout << "   " << cpm << "\n";
    std::cout << "True principal moments = \n";
    std::cout << "   " << tpm << "\n";
    std::cout << "\nPrincipal axes = \n";
    std::cout << "   " << cpa << "\n";
    std::cout << "True principal axes = \n";
    std::cout << "   " << tpa << "\n";

    /* Compute transforms between principal and physical axes */
    /* FIXME: Automatically check correctness of these results? */
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        pa2p = moments.GetPrincipalAxesToPhysicalAxesTransform();
    std::cout << "\nPrincipal axes to physical axes transform:\n";
    std::cout << pa2p << std::endl;
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        p2pa = moments.GetPhysicalAxesToPrincipalAxesTransform();
    std::cout << "\nPhysical axes to principal axes transform:\n";
    std::cout << p2pa << std::endl;

    /* Do some error checking on the transforms */
    double dist = pa2p.Metric(pa2p);
    std::cout << "Distance from self to self = " << dist << std::endl;
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        p2pa2p;
    p2pa2p.Compose(p2pa);
    p2pa2p.Compose(pa2p);
    double trerr = p2pa2p.Metric();
    std::cout << "Distance from composition to identity = ";
    std::cout << trerr << std::endl;

    /* Compute and report max abs error in computed */
    double tmerr = abs(ttm - ctm);  // Error in total mass
    double cgerr = 0.0;             // Error in center of gravity
    double pmerr = 0.0;             // Error in moments
    double paerr = 0.0;             // Error in axes
    for ( int i = 0; i < 3; ++i) {
        if ( abs(ccg[i] - tcg[i]) > cgerr )
            cgerr = abs(ccg[i] - tcg[i]);
        if ( abs(cpm[i] - tpm[i]) > pmerr )
            pmerr = abs(cpm[i] - tpm[i]);
        for (int j = 0; j < 3; ++j) {
            if (abs(cpa[i][j] - tpa[i][j]) > paerr)
                paerr = abs(cpa[i][j] - tpa[i][j]);
        }
    }
    std::cout << "\nErrors found in:\n";
    std::cout << "   Total mass        = " << tmerr << std::endl;
    std::cout << "   Center of gravity = " << cgerr << std::endl;
    std::cout << "   Principal moments = " << pmerr << std::endl;
    std::cout << "   Principal axes    = " << paerr << std::endl;
    std::cout << "   Transformations   = " << trerr << std::endl;

    /* Return error if differences are too large */
    int stat =
        tmerr > maxerr || cgerr > maxerr ||
        pmerr > maxerr || paerr > maxerr ||
        trerr > maxerr;
    if (stat)
        std::cout << "\n*** Errors are larger than defined maximum value.\n";
    else
        std::cout << "\n*** Errors are acceptable.\n";
    return stat;
}
<commit_msg><commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageMomentsTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

#include "itkAffineTransform.h"
#include "itkPhysicalImage.h"
#include "itkImageMomentsCalculator.h"
#include "itkIndex.h"
#include "itkSize.h"

typedef itk::Vector<double,3>  VectorType;
typedef itk::Matrix<double,3>  MatrixType;

int
main(
    int argc,
    char *argv[])
{
    /* Define acceptable (absolute) error in computed results.
       All the calculations are done in double and are well-conditioned,
       so we should be able to get within a few epsilon of the right
       values.  So choose maxerr to be 10*epsilon for IEEE 754 double. */
    double maxerr = 1.0e-15;

    /* Define the image size and physical coordinates */
    itk::Size<3> size = {{20, 40, 80}};
    double origin [3] = { 0.5,   0.5,   0.5};
    double spacing[3] = { 0.1,   0.05 , 0.025};

    /* Define positions of the test masses in index coordinates */
    unsigned short mass = 1;           // Test mass
    unsigned long point[8][3] = {
	{ 10+8, 20+12, 40+0},
	{ 10-8, 20-12, 40-0},
	{ 10+3, 20-8,  40+0},
	{ 10-3, 20+8,  40-0},
	{ 10+0, 20+0,  40+10},
	{ 10-0, 20-0,  40-10},
    };

    /* Define the expected (true) results for comparison */
    double ttm = 6.0;                      // Total mass
    double pad[3][3] = {                   // Principal axes
      { 0.0,  0.0, 1.0},
      { 0.6, -0.8, 0.0},
      { 0.8,  0.6, 0.0},
    };

    VectorType tcg;
    tcg = 1.5,   1.5, 1.5;    // Center of gravity

    VectorType tpm;
    tpm = 0.125, 0.5, 2.0;    // Principal moments

    MatrixType tpa;
    tpa.set((double *)pad);

    /* Allocate a simple test image */
    itk::PhysicalImage<unsigned short, 3>::Pointer
      image = itk::PhysicalImage<unsigned short,3>::New();
    itk::PhysicalImage<unsigned short, 3>::RegionType region;
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetBufferedRegion(region);

    /* Set origin and spacing of physical coordinates */
    image->SetOrigin(origin);
    image->SetSpacing(spacing);
    image->Allocate();

    /* Set a few mass points within the image */
    /* FIXME: The method used here to set the points is klutzy,
       but appears to be the only method currently supported. */
    itk::Index<3> index;          /* Index over pixels */
    for ( int i = 0; i < 6; i++) {
	index.SetIndex(point[i]);
	image->SetPixel(index, mass);
    }

    /* Compute the moments */
    itk::ImageMomentsCalculator<unsigned short, 3>
	moments(image);
    double ctm = moments.GetTotalMass();
    VectorType ccg = moments.GetCenterOfGravity();
    VectorType cpm = moments.GetPrincipalMoments();
    MatrixType cpa = moments.GetPrincipalAxes();

    /* Report the various non-central moments */
    // FIXME:  Indentation is not handled correctly in matrix output
    std::cout << "\nTotal mass = " << ctm << std::endl;
    std::cout << "True total mass = " << ttm << std::endl;
    std::cout << "\nFirst moments about index origin =\n";
    std::cout << "   " <<  moments.GetFirstMoments() << std::endl;
    std::cout << "\nSecond moments about index origin =\n";
    std::cout << "   " << moments.GetSecondMoments() << std::endl;

    /* Report the center of gravity and central moments */
    std::cout << "\nCenter of gravity =\n";
    std::cout << "   " << ccg << "\n";
    std::cout << "True center of gravity =\n";
    std::cout << "   " << tcg << "\n";
    std::cout << "\nSecond central moments =\n";
    std::cout << "   " << moments.GetCentralMoments() << "\n";

    /* Report principal moments and axes */
    std::cout << "\nPrincipal moments = \n";
    std::cout << "   " << cpm << "\n";
    std::cout << "True principal moments = \n";
    std::cout << "   " << tpm << "\n";
    std::cout << "\nPrincipal axes = \n";
    std::cout << "   " << cpa << "\n";
    std::cout << "True principal axes = \n";
    std::cout << "   " << tpa << "\n";

    /* Compute transforms between principal and physical axes */
    /* FIXME: Automatically check correctness of these results? */
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        pa2p = moments.GetPrincipalAxesToPhysicalAxesTransform();
    std::cout << "\nPrincipal axes to physical axes transform:\n";
    std::cout << pa2p << std::endl;
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        p2pa = moments.GetPhysicalAxesToPrincipalAxesTransform();
    std::cout << "\nPhysical axes to principal axes transform:\n";
    std::cout << p2pa << std::endl;

    /* Do some error checking on the transforms */
    double dist = pa2p.Metric(pa2p);
    std::cout << "Distance from self to self = " << dist << std::endl;
    itk::ImageMomentsCalculator<unsigned short, 3>::AffineTransformType
        p2pa2p;
    p2pa2p.Compose(p2pa);
    p2pa2p.Compose(pa2p);
    double trerr = p2pa2p.Metric();
    std::cout << "Distance from composition to identity = ";
    std::cout << trerr << std::endl;

    /* Compute and report max abs error in computed */
    double tmerr = abs(ttm - ctm);  // Error in total mass
    double cgerr = 0.0;             // Error in center of gravity
    double pmerr = 0.0;             // Error in moments
    double paerr = 0.0;             // Error in axes
    for ( int i = 0; i < 3; ++i) {
        if ( abs(ccg[i] - tcg[i]) > cgerr )
            cgerr = abs(ccg[i] - tcg[i]);
        if ( abs(cpm[i] - tpm[i]) > pmerr )
            pmerr = abs(cpm[i] - tpm[i]);
        for (int j = 0; j < 3; ++j) {
            if (abs(cpa[i][j] - tpa[i][j]) > paerr)
                paerr = abs(cpa[i][j] - tpa[i][j]);
        }
    }
    std::cout << "\nErrors found in:\n";
    std::cout << "   Total mass        = " << tmerr << std::endl;
    std::cout << "   Center of gravity = " << cgerr << std::endl;
    std::cout << "   Principal moments = " << pmerr << std::endl;
    std::cout << "   Principal axes    = " << paerr << std::endl;
    std::cout << "   Transformations   = " << trerr << std::endl;

    /* Return error if differences are too large */
    int stat =
        tmerr > maxerr || cgerr > maxerr ||
        pmerr > maxerr || paerr > maxerr ||
        trerr > maxerr;
    if (stat)
        std::cout << "\n*** Errors are larger than defined maximum value.\n";
    else
        std::cout << "\n*** Errors are acceptable.\n";
    return stat;
}
<|endoftext|>


<commit_before>// $Id$
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//#define MAIN

#include "itkExceptionObject.h"
#include <iostream>

#include "itkImage.h"
#include "itkStreamingImageFilter.h"
#include "itkMeanImageFilter.h"

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

int otbStreamingImageFilterTest (int argc, char* argv[])
{
  try
  {
        // Verify the number of parameters in the command line
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        typedef unsigned char  	                                InputPixelType;
        typedef unsigned char  	                                OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef itk::MeanImageFilter<InputImageType,OutputImageType> MeanImageFilterType;
        typedef itk::StreamingImageFilter<InputImageType,OutputImageType> StreamingImageFilterType;

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

//        StreamingImageFilterType::Pointer streamer = StreamingImageFilterType::New();
//        MeanImageFilterType::Pointer filter1 = MeanImageFilterType::New();

//        filter1->SetInput( reader->GetOutput() );
//        streamer->SetInput( filter1->GetOutput() );

//        streamer->SetInput( reader->GetOutput() );
//        streamer->SetNumberOfStreamDivisions( 5 );
//        streamer->Update();

        writer->SetInput( reader->GetOutput() );
//        writer->SetInput( filter1->GetOutput() );
        writer->Update();

  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cerr << "Exception OTB non attrappee !" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<commit_msg>nomsg<commit_after>// $Id$
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkExceptionObject.h"
#include <iostream>

#include "itkImage.h"
#include "itkStreamingImageFilter.h"
//#include "itkMeanImageFilter.h"

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

int otbStreamingImageFilterTest (int argc, char* argv[])
{
  try
  {
        // Verify the number of parameters in the command line
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        typedef unsigned char  	                                InputPixelType;
        typedef unsigned char  	                                OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

//        typedef itk::MeanImageFilter<InputImageType,OutputImageType> MeanImageFilterType;
        typedef itk::StreamingImageFilter<InputImageType,OutputImageType> StreamingImageFilterType;

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

        StreamingImageFilterType::Pointer streamer = StreamingImageFilterType::New();
//        MeanImageFilterType::Pointer filter1 = MeanImageFilterType::New();

//        filter1->SetInput( reader->GetOutput() );
//        streamer->SetInput( filter1->GetOutput() );

        streamer->SetInput( reader->GetOutput() );
        streamer->SetNumberOfStreamDivisions( 10 );
        streamer->Update();

        writer->SetInput( streamer->GetOutput() );
//        writer->SetInput( reader->GetOutput() );
//        writer->SetInput( filter1->GetOutput() );
        writer->Update();

  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cerr << "Exception OTB non attrappee !" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>