Esempio n. 1
0
 bool is_root() const noexcept
 {
     if (node.expired()) {
         return false;
     }
     return bool{std::dynamic_pointer_cast<node::inu>(node.lock())};
 }
Esempio n. 2
0
Listener::Listener(const std::weak_ptr<Manager>& manager){
    LOG_ENTER_FUNC("");

    std::string host;
    if(manager.expired()){
        //todo: notify main thread to eventHandler error.
        exit(1);
    }
    this->manager = manager.lock();
    log("3333333333333 this->manager.use_count:",this->manager.use_count());
    std::string tmp;
    int port;
    if(this->manager->getConfig("port", tmp)){
        port = boost::lexical_cast<int>(tmp);
    }
    int backlog;
    if(this->manager->getConfig("backlog", tmp)){
        backlog = boost::lexical_cast<int>(tmp);
    }
    if(this->manager->getConfig("host", tmp)){
        host = tmp;
    }
    this->serverSocket = std::make_shared<ServerSocket>(port, host, backlog);
    LOG_LEAVE_FUNC("");
}
Esempio n. 3
0
void EventDispatcher::vRemoveListener(const EventType & eType, const std::weak_ptr<void> & eListener)
{
	//If the eListener is dead or there is no eType in the listener list, simply return.
	if (eListener.expired() || pimpl->m_ListenerCallbackLists.find(eType) == pimpl->m_ListenerCallbackLists.end())
		return;

	//If it's dispatching, we should cache this operation and call it after the dispatch.
	if (pimpl->m_IsDispatchingQueue){
		pimpl->m_CachedOperations.emplace_back([this, eType, eListener](){vRemoveListener(eType, eListener); });
		return;
	}

	//Prepare for traversing the listener list.
	const auto strongListener = eListener.lock();
	auto & listenerListOfType = pimpl->m_ListenerCallbackLists[eType];

	//Traverse the listener list to see if there is an listener to be removed.
	//Don't use for(xx:yy) because there is at most one listener to remove from the list. Once we find it, we can simply remove it and return.
	for (auto listenerIter = listenerListOfType.begin(); listenerIter != listenerListOfType.end(); ++listenerIter){
		//If the current listener is dead, ignore it.
		if (listenerIter->first.expired())
			continue;

		//If the current listener "equals" eListener, remove it from the list.
		if (listenerIter->first.lock() == strongListener){
			listenerListOfType.erase(listenerIter);
			return;
		}
	}
}
Esempio n. 4
0
void touchmind::model::node::NodeModel::RemoveLink(const std::weak_ptr<touchmind::model::link::LinkModel> &link)
{
    m_links.erase(std::remove_if(std::begin(m_links), std::end(m_links),
    [&](std::weak_ptr<touchmind::model::link::LinkModel> e) {
        return !link.expired() && !e.expired() && link.lock()->GetLinkId() == e.lock()->GetLinkId();
    }), std::end(m_links));
}
 /** Creates either a client or server lobby protocol as a singleton. */
 template<typename singleton> static std::shared_ptr<singleton> create()
 {
     assert(m_lobby.expired());
     auto ret = std::make_shared<singleton>();
     m_lobby = ret;
     return std::dynamic_pointer_cast<singleton>(ret);
 }   // create
	// STATIC:
	float PhysicsEntityContainer::getSquaredDistance(std::weak_ptr<PhysicsEntity> e1, 
													 std::weak_ptr<PhysicsEntity> e2)
	{
		// Abort if null pointers
		if(e1.expired() || e2.expired()) return 0;

		// Set the difference between positions in each dimension
		float deltaX = e1._Get()->GetTransform()._Get()->GetPosition().x
			- e2._Get()->GetTransform()._Get()->GetPosition().x;
		float deltaY = e1._Get()->GetTransform()._Get()->GetPosition().y
			- e2._Get()->GetTransform()._Get()->GetPosition().y;
		float deltaZ = e1._Get()->GetTransform()._Get()->GetPosition().z
			- e2._Get()->GetTransform()._Get()->GetPosition().z;

		// Squared distance formula (doesn't use square root)
		return deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ;
	}
Esempio n. 7
0
	void GameObject::Destroy(std::weak_ptr<GameObject> &obj)
	{
		if(!obj.expired())
		{
			obj.lock()->Delete();
			obj.reset();
		}
	}
Esempio n. 8
0
Dispatcher::Dispatcher(const std::weak_ptr<Manager>& manager){
    LOG_ENTER_FUNC("constructor");
    if(manager.expired()){
        exit(1);
    }
    this->manager = manager.lock();
    log("manager.use_count()", this->manager.use_count());
    LOG_LEAVE_FUNC("constructor");
}
Esempio n. 9
0
void Benchmark::addBenchmark(std::weak_ptr<Benchmark> benchmark)
{
    std::lock_guard<std::recursive_mutex> lock(_benchmarkLock);
    if(benchmark.expired())
        return;

    benchmark.lock()->_parent = this;
    _benchmarks.push_back(benchmark);
}
Esempio n. 10
0
void SavePlayer2DB(std::weak_ptr<CPlayer> player)
{
    if (!player.expired()&&player.lock()->GetPlayerID()!=0)
    {
        DBPlayer oldPlayerData;
        player.lock()->Player2DB(oldPlayerData);
        DBServer::GetInstance().SavePlayerData(oldPlayerData);
    }
}
Esempio n. 11
0
void Connection::handleWriteTimeout(std::weak_ptr<Connection> weak, const boost::system::error_code& error)
{
	if(error == boost::asio::error::operation_aborted || weak.expired())
		return;

	if(std::shared_ptr<Connection> connection = weak.lock())
	{
		connection->onWriteTimeout();
	}
}
Esempio n. 12
0
void LibUSB::DeviceImpl::setParentDevice( std::weak_ptr<Device> pParentDevice )
{

	if (pParentDevice.expired())
	{
		throw std::logic_error("LibUSB::DeviceImpl::setParentDevice() - new parent device pointer is expired.");
	}

	m_ParentDevice = pParentDevice;
}
Esempio n. 13
0
int CreateUser(const Data& data, std::weak_ptr<CPlayer> player)
{
    if(player.expired())
    {
        return -1;
    }
    std::shared_ptr<CPlayer> playerPtr = player.lock();
    if (playerPtr->GetSocket().expired())
    {
        return -1;
    }
    if (!playerPtr->GetSocket().lock()->GetPlayer().expired())
    {
        PBS2CCreateUserRes res;
        res.set_createuserresult(-1);
        player.lock()->GetSocket().lock()->SendBuff((int)TypeS2CCreateUserRes, res);
        return 0;
    }

    PBC2SCreateUserReq req;
    req.ParseFromArray(data.buffer, data.bufferLength);

    PBS2CCreateUserRes res;
    if (DBServer::GetInstance().CreateUser(player.lock()->GetSocket().lock()->GetLoginID(), req.playername().c_str(), res) != 0)
    {
        return -1;
    }
    DBPlayer playerData;
    if (DBServer::GetInstance().GetPlayerData(playerPtr->GetSocket().lock()->GetLoginID(), playerData) == 0)
    {
        std::weak_ptr<CTCPClientSocket> socket = player.lock()->GetSocket();
        std::weak_ptr<CPlayer> newPlayer = socket.lock()->GetPlayer();
        if (newPlayer.expired())
        {
            newPlayer = PlayerManager::GetInstance().CreatePlayer(playerData.playerid(), socket);
            if (newPlayer.expired())
            {
                return -1;
            }
            newPlayer.lock()->DB2Player(playerData);
            newPlayer.lock()->SetSocket(socket);
            socket.lock()->SetPlayer(newPlayer);
        }
        else
        {
            return -1;
        }
    }
    else
    {
        return -1;
    }
    player.lock()->GetSocket().lock()->SendBuff((int)TypeS2CCreateUserRes, res);
    return 0;
}
Esempio n. 14
0
int LoginCheck(const Data& data, std::weak_ptr<CPlayer> player)
{
    if(player.expired())
    {
        return -1;
    }
    std::shared_ptr<CPlayer> playerPtr = player.lock();
    if (playerPtr->GetSocket().expired())
    {
        return -1;
    }

    PBC2SLoginCheckReq req;
    req.ParseFromArray(data.buffer, data.bufferLength);

    PBS2CLoginCheckRes res;
    if (DBServer::GetInstance().LoginCheck(req.username().c_str(), req.password().c_str(), res) != 0)
    {
        return -1;
    }
    if (res.logincheckresult() > 0)
    {
        player.lock()->GetSocket().lock()->SetLoginID(res.logincheckresult());
        DBPlayer playerData;
        if (DBServer::GetInstance().GetPlayerData(res.logincheckresult(), playerData) == 0)
        {
            std::weak_ptr<CTCPClientSocket> socket = player.lock()->GetSocket();
            std::weak_ptr<CPlayer> newPlayer = socket.lock()->GetPlayer();
            if (!newPlayer.expired())
            {
                DBPlayer oldPlayerData;
                player.lock()->Player2DB(oldPlayerData);
                DBServer::GetInstance().SavePlayerData(oldPlayerData);
                socket.lock()->SetPlayer(std::weak_ptr<CPlayer>());
                PlayerManager::GetInstance().RemovePlayer(player.lock()->GetPlayerID());
            }
            newPlayer = PlayerManager::GetInstance().CreatePlayer(playerData.playerid(), socket);
            if (newPlayer.expired())
            {
                return -1;
            }
            newPlayer.lock()->DB2Player(playerData);
            newPlayer.lock()->SetSocket(socket);
            socket.lock()->SetPlayer(newPlayer);
        }

    }
    else
    {
        player.lock()->GetSocket().lock()->SetPlayer(std::weak_ptr<CPlayer>());
    }
    player.lock()->GetSocket().lock()->SendBuff((int)TypeS2CLoginCheckRes, res);

    return 0;
}
Esempio n. 15
0
/* Notes *
    * std::weak_ptr *
    expired - checks whether the referenced object was already deleted
    lock    - creates a shared_ptr that manages the referenced object 

    * std::unique_ptr * ,using this instead of auto_ptr considering:
    1 - operators supported(==, !=, < ...),so they can be used/stored in STL
        which uses/relies on a lot of these operations
    2 - array supported, can point to an array
*/
void f()
{
    if ( !wp.expired()) {
        auto spt = wp.lock();
        std::cout << *spt << "\n";
        std::cout << wp.use_count() << "\n";
    }
    else {
        std::cout << "wp is expired\n";
    }
}
	// STATIC:
	void PhysicsEntityContainer::Add(std::weak_ptr<PhysicsEntity> newObject)
	{
		// Was this initalized
		if(!PhysicsEntityContainer::verifyInstantiation()) return;
		
		// Check if the pointer is empty
		if(newObject.expired()) return;

		// Add it
		PhysicsEntityContainer::_instance->_listOfContainedObjects.push_front(newObject);
	}
Esempio n. 17
0
std::shared_ptr<ScriptEngine> ScriptEngine::instance()
{
	static std::weak_ptr<ScriptEngine> ptr;
	if (ptr.expired())
	{
		auto engine = std::shared_ptr<ScriptEngine>(new ScriptEngine());
		ptr = engine;
		return engine;
	}
	else
		return ptr.lock();
}
Esempio n. 18
0
std::shared_ptr<ImGui_Wrapper> ImGui_Wrapper::instance(PandaDocument* doc)
{
	static std::weak_ptr<ImGui_Wrapper> ptr;
	if (ptr.expired())
	{
		auto wrapper = std::shared_ptr<ImGui_Wrapper>(new ImGui_Wrapper(doc));
		ptr = wrapper;
		return wrapper;
	}
	else
		return ptr.lock();
}
Esempio n. 19
0
bool visot_ff_weak(std::weak_ptr<ff> pWeakFF)
{
	if (pWeakFF.expired() == false)
	{
		std::shared_ptr<ff> pFF = pWeakFF.lock();
		if (pFF)
		{
			return true;
		}
	}
	return false;
}
Esempio n. 20
0
void SHContainer::insert(std::weak_ptr<lif::Collider> obj) {
	if (obj.expired()) return;

	const auto cld = obj.lock();
	if (!cld->isActive()) return;

	const auto ids = _getIdFor(*cld);
	for (auto id : ids) {
		buckets[id].emplace_back(obj);
	}
	all.emplace_back(obj);
}
Esempio n. 21
0
void ServicePort::onOpen(std::weak_ptr<ServicePort> weakService, uint16_t port)
{
	LOGt("ServicePort::onOpen()");

	if(weakService.expired())
		return;

	if(ServicePort_ptr service = weakService.lock())
	{
		service->open(port);
	}
}
Esempio n. 22
0
 void transform(const Transform& trans) {
 
     //to access the right primitive type and transform it we use the visitors
     symbolic::Geometry* prop;
     if(!m_parent.expired()) 
         prop = std::static_pointer_cast<typename Final::Graph>(m_parent.lock()->m_cluster)->template getProperty<symbolic::GeometryProperty>(Base::getVertexProperty());
     else {
         auto cluster = std::static_pointer_cast<typename Final::Graph>(Base::m_system->getGraph());
         prop = cluster->template getProperty<symbolic::GeometryProperty>(Base::getVertexProperty());
     }
     PropTransformer functor(prop, trans);
     Base::apply(functor);
 };
Esempio n. 23
0
void Connection::handleWriteTimeout(std::weak_ptr<Connection> weak_conn, const boost::system::error_code& error)
{
	if (error == boost::asio::error::operation_aborted) {
		return;
	}

	if (weak_conn.expired()) {
		return;
	}

	if (Connection_ptr connection = weak_conn.lock()) {
		connection->onWriteTimeout();
	}
}
Esempio n. 24
0
LibUSB::InterfaceImpl::InterfaceImpl( const libusb_interface* pInterface, std::weak_ptr<DeviceImpl> pDeviceImpl )
	: m_pInterface(pInterface), m_alternateSetting(0), m_bClaimed(false)
{

	if (!pDeviceImpl.expired())
	{
		m_pDeviceImpl = pDeviceImpl;
	}
	else
	{
		throw std::logic_error("LibUSB::InterfaceImpl::InterfaceImpl(): Constructed with expired DeviceImpl.");
	}

}
Esempio n. 25
0
void Observable<ObserverType>::removeObserver(std::weak_ptr<ObserverType> observerToRemove)
{
    if (observerToRemove.expired())
    {
        return;
    }

    observers.erase(
        std::remove_if(
            observers.begin(), observers.end(),
            [=](std::weak_ptr<ObserverType> observer)
            {
                return observer.lock() == observerToRemove.lock();
            }),
        observers.end());
}
bool AnimationSaver::saveAnimation(std::string path, std::weak_ptr<IFrameController> container)
{
	if (!path.length() != 0)
	{
		return false;
	}
	FileManager writer;
	if (!writer.openFileForWriting(path))
	{
		return false;
	}
	std::shared_ptr<IFrameController> currentContainer;
	if(container.expired())
	{
		return false;
	}
	currentContainer = container.lock();
	int total = currentContainer->totalNumberOfFrames();
	if (!writer.writeToFile<int>(total))
	{
		return false;
	}

	//Fake-zero frame for algorithnm to be more consistent
	std::shared_ptr<Frame> fakeZeroShared = std::make_shared<Frame>(total);
	std::weak_ptr<Frame>fakezero = std::weak_ptr<Frame>(fakeZeroShared);
	std::weak_ptr<Frame> currentFrame = currentContainer->getFirstFrame();
	
	//save difference between first and empty frame
	if(!saveDifference(currentFrame.lock()->getDifference(fakezero), writer))
	{
		return false;
	}
	fakeZeroShared.reset();
	for (int i = 1; i < total; ++i)
	{
		auto tmpFrame = currentContainer->getNextFrame().lock();
		std::unique_ptr<Frame::Diff> diff = tmpFrame->getDifference(currentFrame);
		if (!saveDifference(diff, writer))
		{	
			return false;
		}
		currentFrame = currentContainer->getCurrentFrame();
	}
	writer.closeOutputFile();
	return true;
}
Esempio n. 27
0
void Application::registerDestroyable(std::weak_ptr<Destroyable> ptr)
{
	if (!ptr.expired())
	{
		auto sptr = ptr.lock();
		auto fptr = std::find_if(m_destroyableList.begin(), m_destroyableList.end(), [=](std::weak_ptr<Destroyable> ptr2)
		{
			if (ptr2.expired()) return false;
			return sptr == ptr2.lock();
		});

		if (fptr == m_destroyableList.end())
		{
			m_destroyableList.push_back(ptr);
		}
	}
}
Esempio n. 28
0
void Observable<ObserverType>::addObserver(std::weak_ptr<ObserverType> observerToAdd)
{
    if (observerToAdd.expired())
    {
        return;
    }

    if (!std::any_of(
            observers.begin(), observers.end(),
            [=](std::weak_ptr<ObserverType> observer)
            {
                return observer.lock() == observerToAdd.lock();
            }))
    {
        observers.push_back(observerToAdd);
    }
}
Esempio n. 29
0
  void transfair(std::weak_ptr<this_handle>& wp, handle_container<T>& other)
  {
    if (wp.expired()) {
      return;
    }
    const std::size_t last_index = get_last_index();
    const std::size_t last_index_other = other.get_last_index();
    auto sp = wp.lock();
    swap(sp->index, last_index);
    other.container.push_back(std::move(container[last_index]));
    container.erase(std::next(container.begin(), last_index));
    handle_map.erase(last_index);

    sp->hc = &other;
    sp->index = last_index_other;
    other.handle_map.insert({ last_index_other, std::move(sp) });
  }
Esempio n. 30
0
void Core::Dispatch(const std::string& request, std::weak_ptr<User> caller) {
	Command cmd = XML::ParseCommand(request);

	Ensure<SocketException>(!caller.expired());
	auto userPtr = caller.lock();

	switch (cmd) {
	case Command::Auth:
		throw std::exception{}; // catched in Tick() and disconnect

	case Command::GetLobbies: {
		auto vec = LobbyFacade::Get()->GetData();
		auto xml = XML::GetLobbies::Build(vec);
		userPtr->Send(xml);
	} break;
	case Command::JoinLobby: {
		//std::string id = XML::JoinLobby::Parse(request);
		//LobbyFacade::Join(id, caller);
	} break;

	case Command::CreateLobby:
		break;
	case Command::LeaveLobby:
		break;
	case Command::StartCreatingLobby: {
		auto vec = SharedLibraryFacade::Get()->GetLoadedDlls();
		auto xml = XML::StartCreatingLobby::Build(vec);
		userPtr->Send(xml);
	} break;
	case Command::FinalizeCreatingLobby: {
		auto pair = XML::FinalizeCreatingLobby::Parse(request);
		LobbyParams pr{ pair.second };
		LobbyFacade::CreateGame(pair.first, pr, caller);
		// TODO
	}

	case Command::GetFile: {
		std::string fileName  = XML::GetFile::Parse(request);
		std::string fileData = FileRead(fileName + LibraryEXT);
		userPtr->Send(XML::GetFile::Build(fileName, move(fileData)));
	} break;
	default:
		MessageBoxA(nullptr, "YOU SHALL NOT PASS", "3rr0r", MB_OK);
	}
}