示例#1
0
s32 GUITable::allocString(const std::string &text)
{
	std::map<std::string, s32>::iterator it = m_alloc_strings.find(text);
	if (it == m_alloc_strings.end()) {
		s32 id = m_strings.size();
		std::wstring wtext = utf8_to_wide(text);
		m_strings.push_back(core::stringw(wtext.c_str()));
		m_alloc_strings.insert(std::make_pair(text, id));
		return id;
	}
	else {
		return it->second;
	}
}
示例#2
0
文件: camera.cpp 项目: Jeija/minetest
void Camera::drawNametags()
{
	core::matrix4 trans = m_cameranode->getProjectionMatrix();
	trans *= m_cameranode->getViewMatrix();

	for (std::list<Nametag *>::const_iterator
			i = m_nametags.begin();
			i != m_nametags.end(); ++i) {
		Nametag *nametag = *i;
		if (nametag->nametag_color.getAlpha() == 0) {
			// Enforce hiding nametag,
			// because if freetype is enabled, a grey
			// shadow can remain.
			continue;
		}
		v3f pos = nametag->parent_node->getPosition() + v3f(0.0, 1.1 * BS, 0.0);
		f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f };
		trans.multiplyWith1x4Matrix(transformed_pos);
		if (transformed_pos[3] > 0) {
			core::dimension2d<u32> textsize =
				g_fontengine->getFont()->getDimension(
				utf8_to_wide(nametag->nametag_text).c_str());
			f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
				core::reciprocal(transformed_pos[3]);
			v2u32 screensize = m_driver->getScreenSize();
			v2s32 screen_pos;
			screen_pos.X = screensize.X *
				(0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2;
			screen_pos.Y = screensize.Y *
				(0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
			core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
			g_fontengine->getFont()->draw(utf8_to_wide(nametag->nametag_text).c_str(),
					size + screen_pos, nametag->nametag_color);
		}
	}
}
示例#3
0
文件: l_server.cpp 项目: 00c/minetest
// kick_player(name, [reason]) -> success
int ModApiServer::l_kick_player(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	const char *name = luaL_checkstring(L, 1);
	std::string message;
	if (lua_isstring(L, 2))
	{
		message = std::string("Kicked: ") + lua_tostring(L, 2);
	}
	else
	{
		message = "Kicked.";
	}
	Player *player = getEnv(L)->getPlayer(name);
	if (player == NULL)
	{
		lua_pushboolean(L, false); // No such player
		return 1;
	}
	getServer(L)->DenyAccess_Legacy(player->peer_id, utf8_to_wide(message));
	lua_pushboolean(L, true);
	return 1;
}
示例#4
0
文件: discovery.c 项目: ccpgames/wine
static void UnPublish_tests(void)
{
    IWSDiscoveryPublisher *publisher = NULL;
    IWSDiscoveryPublisherNotify *sink1 = NULL;
    char endpoint_reference_string[MAX_PATH], app_sequence_string[MAX_PATH];
    LPWSTR publisherIdW = NULL, sequenceIdW = NULL;
    messageStorage *msg_storage;
    WSADATA wsa_data;
    BOOL message_ok, hello_message_seen = FALSE, endpoint_reference_seen = FALSE, app_sequence_seen = FALSE;
    BOOL wine_ns_seen = FALSE, body_hello_seen = FALSE, any_body_seen = FALSE;
    int ret, i;
    HRESULT rc;
    ULONG ref;
    char *msg;
    WSDXML_ELEMENT *body_any_element;
    WSDXML_NAME body_any_name;
    WSDXML_NAMESPACE ns;
    WCHAR body_any_name_text[] = {'B','e','e','r',0};
    static const WCHAR body_any_text[] = {'B','o','d','y','T','e','s','t',0};
    static const WCHAR uri[] = {'h','t','t','p',':','/','/','w','i','n','e','.','t','e','s','t','/',0};
    static const WCHAR prefix[] = {'w','i','n','e',0};

    rc = WSDCreateDiscoveryPublisher(NULL, &publisher);
    ok(rc == S_OK, "WSDCreateDiscoveryPublisher(NULL, &publisher) failed: %08x\n", rc);
    ok(publisher != NULL, "WSDCreateDiscoveryPublisher(NULL, &publisher) failed: publisher == NULL\n");

    rc = IWSDiscoveryPublisher_SetAddressFamily(publisher, WSDAPI_ADDRESSFAMILY_IPV4);
    ok(rc == S_OK, "IWSDiscoveryPublisher_SetAddressFamily(WSDAPI_ADDRESSFAMILY_IPV4) failed: %08x\n", rc);

    /* Create notification sink */
    ok(create_discovery_publisher_notify(&sink1) == TRUE, "create_discovery_publisher_notify failed\n");
    rc = IWSDiscoveryPublisher_RegisterNotificationSink(publisher, sink1);
    ok(rc == S_OK, "IWSDiscoveryPublisher_RegisterNotificationSink failed: %08x\n", rc);

    /* Set up network listener */
    publisherIdW = utf8_to_wide(publisherId);
    if (publisherIdW == NULL) goto after_unpublish_test;

    sequenceIdW = utf8_to_wide(sequenceId);
    if (sequenceIdW == NULL) goto after_unpublish_test;

    msg_storage = heap_alloc_zero(sizeof(messageStorage));
    if (msg_storage == NULL) goto after_unpublish_test;

    msg_storage->running = TRUE;
    InitializeCriticalSection(&msg_storage->criticalSection);

    ret = WSAStartup(MAKEWORD(2, 2), &wsa_data);
    ok(ret == 0, "WSAStartup failed (ret = %d)\n", ret);

    ret = start_listening_on_all_addresses(msg_storage, AF_INET);
    ok(ret == TRUE, "Unable to listen on IPv4 addresses (ret == %d)\n", ret);

    /* Create "any" elements for header */
    ns.Uri = uri;
    ns.PreferredPrefix = prefix;

    body_any_name.LocalName = body_any_name_text;
    body_any_name.Space = &ns;

    rc = WSDXMLBuildAnyForSingleElement(&body_any_name, body_any_text, &body_any_element);
    ok(rc == S_OK, "WSDXMLBuildAnyForSingleElement failed with %08x\n", rc);

    /* Unpublish the service */
    rc = IWSDiscoveryPublisher_UnPublish(publisher, publisherIdW, 1, 1, sequenceIdW, body_any_element);

    WSDFreeLinkedMemory(body_any_element);

    ok(rc == S_OK, "Unpublish failed: %08x\n", rc);

    /* Wait up to 2 seconds for messages to be received */
    if (WaitForMultipleObjects(msg_storage->numThreadHandles, msg_storage->threadHandles, TRUE, 2000) == WAIT_TIMEOUT)
    {
        /* Wait up to 1 more second for threads to terminate */
        msg_storage->running = FALSE;
        WaitForMultipleObjects(msg_storage->numThreadHandles, msg_storage->threadHandles, TRUE, 1000);
    }

    DeleteCriticalSection(&msg_storage->criticalSection);

    /* Verify we've received a message */
    ok(msg_storage->messageCount >= 1, "No messages received\n");

    sprintf(endpoint_reference_string, "<wsa:EndpointReference><wsa:Address>%s</wsa:Address></wsa:EndpointReference>",
        publisherId);
    sprintf(app_sequence_string, "<wsd:AppSequence InstanceId=\"1\" SequenceId=\"%s\" MessageNumber=\"1\"></wsd:AppSequence>",
        sequenceId);

    message_ok = FALSE;

    /* Check we're received the correct message */
    for (i = 0; i < msg_storage->messageCount; i++)
    {
        msg = msg_storage->messages[i];
        message_ok = FALSE;

        hello_message_seen = (strstr(msg, "<wsa:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Bye</wsa:Action>") != NULL);
        endpoint_reference_seen = (strstr(msg, endpoint_reference_string) != NULL);
        app_sequence_seen = (strstr(msg, app_sequence_string) != NULL);
        wine_ns_seen = (strstr(msg, "xmlns:wine=\"http://wine.test/\"") != NULL);
        body_hello_seen = (strstr(msg, "<soap:Body><wsd:Bye") != NULL);
        any_body_seen = (strstr(msg, "<wine:Beer>BodyTest</wine:Beer>") != NULL);
        message_ok = hello_message_seen && endpoint_reference_seen && app_sequence_seen && wine_ns_seen &&
            body_hello_seen && any_body_seen;

        if (message_ok) break;
    }

    for (i = 0; i < msg_storage->messageCount; i++)
    {
        heap_free(msg_storage->messages[i]);
    }

    heap_free(msg_storage);

    ok(hello_message_seen == TRUE, "Bye message not received\n");
    ok(endpoint_reference_seen == TRUE, "EndpointReference not received\n");
    ok(app_sequence_seen == TRUE, "AppSequence not received\n");
    ok(message_ok == TRUE, "Bye message metadata not received\n");
    ok(wine_ns_seen == TRUE, "Wine namespace not received\n");
    ok(body_hello_seen == TRUE, "Body and Bye elements not received\n");
    ok(any_body_seen == TRUE, "Custom body element not received\n");

after_unpublish_test:

    heap_free(publisherIdW);
    heap_free(sequenceIdW);

    ref = IWSDiscoveryPublisher_Release(publisher);
    ok(ref == 0, "IWSDiscoveryPublisher_Release() has %d references, should have 0\n", ref);

    /* Release the sinks */
    IWSDiscoveryPublisherNotify_Release(sink1);

    WSACleanup();
}
示例#5
0
文件: discovery.c 项目: ccpgames/wine
static void Publish_tests(void)
{
    IWSDiscoveryPublisher *publisher = NULL;
    IWSDiscoveryPublisherNotify *sink1 = NULL, *sink2 = NULL;
    IWSDiscoveryPublisherNotifyImpl *sink1Impl = NULL, *sink2Impl = NULL;
    char endpointReferenceString[MAX_PATH], app_sequence_string[MAX_PATH];
    LPWSTR publisherIdW = NULL, sequenceIdW = NULL;
    messageStorage *msgStorage;
    WSADATA wsaData;
    BOOL messageOK, hello_message_seen = FALSE, endpoint_reference_seen = FALSE, app_sequence_seen = FALSE;
    BOOL metadata_version_seen = FALSE, any_header_seen = FALSE, wine_ns_seen = FALSE, body_hello_seen = FALSE;
    BOOL any_body_seen = FALSE, types_seen = FALSE, xml_namespaces_seen = FALSE, scopes_seen = FALSE;
    BOOL xaddrs_seen = FALSE;
    int ret, i;
    HRESULT rc;
    ULONG ref;
    char *msg;
    WSDXML_ELEMENT *header_any_element, *body_any_element, *endpoint_any_element, *ref_param_any_element;
    WSDXML_NAME header_any_name, another_name;
    WSDXML_NAMESPACE ns, ns2;
    WCHAR header_any_name_text[] = {'B','e','e','r',0};
    static const WCHAR header_any_text[] = {'P','u','b','l','i','s','h','T','e','s','t',0};
    static const WCHAR body_any_text[] = {'B','o','d','y','T','e','s','t',0};
    static const WCHAR endpoint_any_text[] = {'E','n','d','P','T','e','s','t',0};
    static const WCHAR ref_param_any_text[] = {'R','e','f','P','T','e','s','t',0};
    static const WCHAR uri[] = {'h','t','t','p',':','/','/','w','i','n','e','.','t','e','s','t','/',0};
    static const WCHAR prefix[] = {'w','i','n','e',0};
    static const WCHAR uri3[] = {'h','t','t','p',':','/','/','t','h','i','r','d','.','u','r','l','/',0};
    WSD_NAME_LIST types_list;
    WSD_URI_LIST scopes_list, xaddrs_list;
    unsigned char *probe_uuid_str;

    rc = WSDCreateDiscoveryPublisher(NULL, &publisher);
    ok(rc == S_OK, "WSDCreateDiscoveryPublisher(NULL, &publisher) failed: %08x\n", rc);
    ok(publisher != NULL, "WSDCreateDiscoveryPublisher(NULL, &publisher) failed: publisher == NULL\n");

    /* Test SetAddressFamily */
    rc = IWSDiscoveryPublisher_SetAddressFamily(publisher, 12345);
    ok(rc == E_INVALIDARG, "IWSDiscoveryPublisher_SetAddressFamily(12345) returned unexpected result: %08x\n", rc);

    rc = IWSDiscoveryPublisher_SetAddressFamily(publisher, WSDAPI_ADDRESSFAMILY_IPV4);
    ok(rc == S_OK, "IWSDiscoveryPublisher_SetAddressFamily(WSDAPI_ADDRESSFAMILY_IPV4) failed: %08x\n", rc);

    /* Try to update the address family after already setting it */
    rc = IWSDiscoveryPublisher_SetAddressFamily(publisher, WSDAPI_ADDRESSFAMILY_IPV6);
    ok(rc == STG_E_INVALIDFUNCTION, "IWSDiscoveryPublisher_SetAddressFamily(WSDAPI_ADDRESSFAMILY_IPV6) returned unexpected result: %08x\n", rc);

    /* Create notification sinks */
    ok(create_discovery_publisher_notify(&sink1) == TRUE, "create_discovery_publisher_notify failed\n");
    ok(create_discovery_publisher_notify(&sink2) == TRUE, "create_discovery_publisher_notify failed\n");

    /* Get underlying implementation so we can check the ref count */
    sink1Impl = impl_from_IWSDiscoveryPublisherNotify(sink1);
    sink2Impl = impl_from_IWSDiscoveryPublisherNotify(sink2);

    /* Attempt to unregister sink before registering it */
    rc = IWSDiscoveryPublisher_UnRegisterNotificationSink(publisher, sink1);
    ok(rc == E_FAIL, "IWSDiscoveryPublisher_UnRegisterNotificationSink returned unexpected result: %08x\n", rc);

    /* Register notification sinks */
    rc = IWSDiscoveryPublisher_RegisterNotificationSink(publisher, sink1);
    ok(rc == S_OK, "IWSDiscoveryPublisher_RegisterNotificationSink failed: %08x\n", rc);
    ok(sink1Impl->ref == 2, "Ref count for sink 1 is not as expected: %d\n", sink1Impl->ref);

    rc = IWSDiscoveryPublisher_RegisterNotificationSink(publisher, sink2);
    ok(rc == S_OK, "IWSDiscoveryPublisher_RegisterNotificationSink failed: %08x\n", rc);
    ok(sink2Impl->ref == 2, "Ref count for sink 2 is not as expected: %d\n", sink2Impl->ref);

    /* Unregister the first sink */
    rc = IWSDiscoveryPublisher_UnRegisterNotificationSink(publisher, sink1);
    ok(rc == S_OK, "IWSDiscoveryPublisher_UnRegisterNotificationSink failed: %08x\n", rc);
    ok(sink1Impl->ref == 1, "Ref count for sink 1 is not as expected: %d\n", sink1Impl->ref);

    /* Set up network listener */
    publisherIdW = utf8_to_wide(publisherId);
    if (publisherIdW == NULL) goto after_publish_test;

    sequenceIdW = utf8_to_wide(sequenceId);
    if (sequenceIdW == NULL) goto after_publish_test;

    msgStorage = heap_alloc_zero(sizeof(messageStorage));
    if (msgStorage == NULL) goto after_publish_test;

    msgStorage->running = TRUE;
    InitializeCriticalSection(&msgStorage->criticalSection);

    ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
    ok(ret == 0, "WSAStartup failed (ret = %d)\n", ret);

    ret = start_listening_on_all_addresses(msgStorage, AF_INET);
    ok(ret == TRUE, "Unable to listen on IPv4 addresses (ret == %d)\n", ret);

    /* Create "any" elements for header */
    ns.Uri = uri;
    ns.PreferredPrefix = prefix;

    header_any_name.LocalName = header_any_name_text;
    header_any_name.Space = &ns;

    rc = WSDXMLBuildAnyForSingleElement(&header_any_name, header_any_text, &header_any_element);
    ok(rc == S_OK, "WSDXMLBuildAnyForSingleElement failed with %08x\n", rc);

    rc = WSDXMLBuildAnyForSingleElement(&header_any_name, body_any_text, &body_any_element);
    ok(rc == S_OK, "WSDXMLBuildAnyForSingleElement failed with %08x\n", rc);

    rc = WSDXMLBuildAnyForSingleElement(&header_any_name, endpoint_any_text, &endpoint_any_element);
    ok(rc == S_OK, "WSDXMLBuildAnyForSingleElement failed with %08x\n", rc);

    rc = WSDXMLBuildAnyForSingleElement(&header_any_name, ref_param_any_text, &ref_param_any_element);
    ok(rc == S_OK, "WSDXMLBuildAnyForSingleElement failed with %08x\n", rc);

    /* Create types list */
    ns2.Uri = uri_more_tests;
    ns2.PreferredPrefix = prefix_grog;

    another_name.LocalName = (WCHAR *) name_cider;
    another_name.Space = &ns2;

    types_list.Next = malloc(sizeof(WSD_NAME_LIST));
    types_list.Element = &another_name;

    types_list.Next->Next = NULL;
    types_list.Next->Element = &header_any_name;

    /* Create scopes and xaddrs lists */
    scopes_list.Next = malloc(sizeof(WSD_URI_LIST));
    scopes_list.Element = uri;

    scopes_list.Next->Next = NULL;
    scopes_list.Next->Element = uri_more_tests;

    xaddrs_list.Next = malloc(sizeof(WSD_URI_LIST));
    xaddrs_list.Element = uri_more_tests;

    xaddrs_list.Next->Next = NULL;
    xaddrs_list.Next->Element = uri3;

    /* Publish the service */
    rc = IWSDiscoveryPublisher_PublishEx(publisher, publisherIdW, 1, 1, 1, sequenceIdW, &types_list, &scopes_list,
        &xaddrs_list, header_any_element, ref_param_any_element, NULL, endpoint_any_element, body_any_element);

    WSDFreeLinkedMemory(header_any_element);
    WSDFreeLinkedMemory(body_any_element);
    WSDFreeLinkedMemory(endpoint_any_element);
    WSDFreeLinkedMemory(ref_param_any_element);
    free(types_list.Next);
    free(scopes_list.Next);
    free(xaddrs_list.Next);

    ok(rc == S_OK, "Publish failed: %08x\n", rc);

    /* Wait up to 2 seconds for messages to be received */
    if (WaitForMultipleObjects(msgStorage->numThreadHandles, msgStorage->threadHandles, TRUE, 2000) == WAIT_TIMEOUT)
    {
        /* Wait up to 1 more second for threads to terminate */
        msgStorage->running = FALSE;
        WaitForMultipleObjects(msgStorage->numThreadHandles, msgStorage->threadHandles, TRUE, 1000);
    }

    DeleteCriticalSection(&msgStorage->criticalSection);

    /* Verify we've received a message */
    ok(msgStorage->messageCount >= 1, "No messages received\n");

    sprintf(endpointReferenceString, "<wsa:EndpointReference><wsa:Address>%s</wsa:Address><wsa:ReferenceParameters>"
        "<wine:Beer>RefPTest</wine:Beer></wsa:ReferenceParameters><wine:Beer>EndPTest</wine:Beer>"
        "</wsa:EndpointReference>", publisherId);

    sprintf(app_sequence_string, "<wsd:AppSequence InstanceId=\"1\" SequenceId=\"%s\" MessageNumber=\"1\"></wsd:AppSequence>",
        sequenceId);

    messageOK = FALSE;

    /* Check we're received the correct message */
    for (i = 0; i < msgStorage->messageCount; i++)
    {
        msg = msgStorage->messages[i];
        messageOK = FALSE;

        hello_message_seen = (strstr(msg, "<wsa:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Hello</wsa:Action>") != NULL);
        endpoint_reference_seen = (strstr(msg, endpointReferenceString) != NULL);
        app_sequence_seen = (strstr(msg, app_sequence_string) != NULL);
        metadata_version_seen = (strstr(msg, "<wsd:MetadataVersion>1</wsd:MetadataVersion>") != NULL);
        any_header_seen = (strstr(msg, "<wine:Beer>PublishTest</wine:Beer>") != NULL);
        wine_ns_seen = (strstr(msg, "xmlns:wine=\"http://wine.test/\"") != NULL);
        body_hello_seen = (strstr(msg, "<soap:Body><wsd:Hello") != NULL);
        any_body_seen = (strstr(msg, "<wine:Beer>BodyTest</wine:Beer>") != NULL);
        types_seen = (strstr(msg, "<wsd:Types>grog:Cider wine:Beer</wsd:Types>") != NULL);
        scopes_seen = (strstr(msg, "<wsd:Scopes>http://wine.test/ http://more.tests/</wsd:Scopes>") != NULL);
        xaddrs_seen = (strstr(msg, "<wsd:XAddrs>http://more.tests/ http://third.url/</wsd:XAddrs>") != NULL);
        xml_namespaces_seen = (strstr(msg, "xmlns:wine=\"http://wine.test/\" xmlns:grog=\"http://more.tests/\"") != NULL);
        messageOK = hello_message_seen && endpoint_reference_seen && app_sequence_seen && metadata_version_seen &&
            any_header_seen && wine_ns_seen && body_hello_seen && any_body_seen && types_seen && xml_namespaces_seen &&
            scopes_seen && xaddrs_seen;

        if (messageOK) break;
    }

    for (i = 0; i < msgStorage->messageCount; i++)
    {
        heap_free(msgStorage->messages[i]);
    }

    heap_free(msgStorage);

    ok(hello_message_seen == TRUE, "Hello message not received\n");
    ok(endpoint_reference_seen == TRUE, "EndpointReference not received\n");
    ok(app_sequence_seen == TRUE, "AppSequence not received\n");
    ok(metadata_version_seen == TRUE, "MetadataVersion not received\n");
    ok(messageOK == TRUE, "Hello message metadata not received\n");
    ok(any_header_seen == TRUE, "Custom header not received\n");
    ok(wine_ns_seen == TRUE, "Wine namespace not received\n");
    ok(body_hello_seen == TRUE, "Body and Hello elements not received\n");
    ok(any_body_seen == TRUE, "Custom body element not received\n");
    ok(types_seen == TRUE, "Types not received\n");
    ok(xml_namespaces_seen == TRUE, "XML namespaces not received\n");
    ok(scopes_seen == TRUE, "Scopes not received\n");
    ok(xaddrs_seen == TRUE, "XAddrs not received\n");

after_publish_test:

    heap_free(publisherIdW);
    heap_free(sequenceIdW);

    /* Test the receiving of a probe message */
    probe_event = CreateEventW(NULL, TRUE, FALSE, NULL);

    UuidCreate(&probe_message_id);
    UuidToStringA(&probe_message_id, &probe_uuid_str);

    ok(probe_uuid_str != NULL, "Failed to create UUID for probe message\n");

    if (probe_uuid_str != NULL)
    {
        char probe_message[sizeof(testProbeMessage) + 50];
        sprintf(probe_message, testProbeMessage, probe_uuid_str);

        ok(send_udp_multicast_of_type(probe_message, strlen(probe_message), AF_INET) == TRUE, "Sending Probe message failed\n");
        todo_wine ok(WaitForSingleObject(probe_event, 2000) == WAIT_OBJECT_0, "Probe message not received\n");

        RpcStringFreeA(&probe_uuid_str);
    }

    CloseHandle(probe_event);

    ref = IWSDiscoveryPublisher_Release(publisher);
    ok(ref == 0, "IWSDiscoveryPublisher_Release() has %d references, should have 0\n", ref);

    /* Check that the sinks have been released by the publisher */
    ok(sink1Impl->ref == 1, "Ref count for sink 1 is not as expected: %d\n", sink1Impl->ref);
    ok(sink2Impl->ref == 1, "Ref count for sink 2 is not as expected: %d\n", sink2Impl->ref);

    /* Release the sinks */
    IWSDiscoveryPublisherNotify_Release(sink1);
    IWSDiscoveryPublisherNotify_Release(sink2);

    WSACleanup();
}
示例#6
0
void TerminalChatConsole::step(int ch)
{
	bool complete_redraw_needed = false;

	// empty queues
	while (!m_chat_interface->outgoing_queue.empty()) {
		ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
		switch (evt->type) {
			case CET_NICK_REMOVE:
				m_nicks.remove(((ChatEventNick *)evt)->nick);
				break;
			case CET_NICK_ADD:
				m_nicks.push_back(((ChatEventNick *)evt)->nick);
				break;
			case CET_CHAT:
				complete_redraw_needed = true;
				// This is only used for direct replies from commands
				// or for lua's print() functionality
				m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
				break;
			case CET_TIME_INFO:
				ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
				m_game_time = tevt->game_time;
				m_time_of_day = tevt->time;
		};
		delete evt;
	}
	while (!m_log_output.queue.empty()) {
		complete_redraw_needed = true;
		std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
		if (p.first > m_log_level)
			continue;

		m_chat_backend.addMessage(
			utf8_to_wide(Logger::getLevelLabel(p.first)),
			utf8_to_wide(p.second));
	}

	// handle input
	if (!m_esc_mode) {
		handleInput(ch, complete_redraw_needed);
	} else {
		switch (ch) {
			case ERR: // no input
				break;
			case 27: // ESC
				// Toggle ESC mode
				m_esc_mode = !m_esc_mode;
				break;
			case 'L':
				m_log_level--;
				m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
				break;
			case 'l':
				m_log_level++;
				m_log_level = MYMIN(m_log_level, LL_MAX - 1);
				break;
		}
	}

	// was there a resize?
	int xn, yn;
	getmaxyx(stdscr, yn, xn);
	if (xn != m_cols || yn != m_rows) {
		m_cols = xn;
		m_rows = yn;
		m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
		complete_redraw_needed = true;
	}

	// draw title
	move(0, 0);
	clrtoeol();
	addstr(PROJECT_NAME_C);
	addstr(" ");
	addstr(g_version_hash);

	u32 minutes = m_time_of_day % 1000;
	u32 hours = m_time_of_day / 1000;
	minutes = (float)minutes / 1000 * 60;

	if (m_game_time)
		printw(" | Game %d Time of day %02d:%02d ",
			m_game_time, hours, minutes);

	// draw text
	if (complete_redraw_needed && m_can_draw_text)
		draw_text();

	// draw prompt
	if (!m_esc_mode) {
		// normal prompt
		ChatPrompt& prompt = m_chat_backend.getPrompt();
		std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
		move(m_rows - 1, 0);
		clrtoeol();
		addstr(prompt_text.c_str());
		// Draw cursor
		s32 cursor_pos = prompt.getVisibleCursorPosition();
		if (cursor_pos >= 0) {
			move(m_rows - 1, cursor_pos);
		}
	} else {
		// esc prompt
		move(m_rows - 1, 0);
		clrtoeol();
		printw("[ESC] Toggle ESC mode |"
			" [CTRL+C] Shut down |"
			" (L) in-, (l) decrease loglevel %s",
			Logger::getLevelLabel((LogLevel) m_log_level).c_str());
	}

	refresh();
}
示例#7
0
void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed)
{
	ChatPrompt &prompt = m_chat_backend.getPrompt();
	// Helpful if you want to collect key codes that aren't documented
	/*if (ch != ERR) {
		m_chat_backend.addMessage(L"",
			(std::wstring)L"Pressed key " + utf8_to_wide(
			std::string(keyname(ch)) + " (code " + itos(ch) + ")"));
		complete_redraw_needed = true;
	}//*/

	// All the key codes below are compatible to xterm
	// Only add new ones if you have tried them there,
	// to ensure compatibility with not just xterm but the wide
	// range of terminals that are compatible to xterm.

	switch (ch) {
		case ERR: // no input
			break;
		case 27: // ESC
			// Toggle ESC mode
			m_esc_mode = !m_esc_mode;
			break;
		case KEY_PPAGE:
			m_chat_backend.scrollPageUp();
			complete_redraw_needed = true;
			break;
		case KEY_NPAGE:
			m_chat_backend.scrollPageDown();
			complete_redraw_needed = true;
			break;
		case KEY_ENTER:
		case '\r':
		case '\n': {
			prompt.addToHistory(prompt.getLine());
			typeChatMessage(prompt.replace(L""));
			break;
		}
		case KEY_UP:
			prompt.historyPrev();
			break;
		case KEY_DOWN:
			prompt.historyNext();
			break;
		case KEY_LEFT:
			// Left pressed
			// move character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 545:
			// Ctrl-Left pressed
			// move word to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_RIGHT:
			// Right pressed
			// move character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 560:
			// Ctrl-Right pressed
			// move word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_HOME:
			// Home pressed
			// move to beginning of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_END:
			// End pressed
			// move to end of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_BACKSPACE:
		case '\b':
		case 127:
			// Backspace pressed
			// delete character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case KEY_DC:
			// Delete pressed
			// delete character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 519:
			// Ctrl-Delete pressed
			// delete word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case 21:
			// Ctrl-U pressed
			// kill line to left end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case 11:
			// Ctrl-K pressed
			// kill line to right end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_TAB:
			// Tab pressed
			// Nick completion
			prompt.nickCompletion(m_nicks, false);
			break;
		default:
			// Add character to the prompt,
			// assuming UTF-8.
			if (IS_UTF8_MULTB_START(ch)) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1;
			} else if (m_utf8_bytes_to_wait != 0) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait--;
				if (m_utf8_bytes_to_wait == 0) {
					std::wstring w = utf8_to_wide(m_pending_utf8_bytes);
					m_pending_utf8_bytes = "";
					// hopefully only one char in the wstring...
					for (size_t i = 0; i < w.size(); i++) {
						prompt.input(w.c_str()[i]);
					}
				}
			} else if (IS_ASCII_PRINTABLE_CHAR(ch)) {
				prompt.input(ch);
			} else {
				// Silently ignore characters we don't handle

				//warningstream << "Pressed invalid character '"
				//	<< keyname(ch) << "' (code " << itos(ch) << ")" << std::endl;
			}
			break;
	}
}
示例#8
0
GUIEngine::GUIEngine(	irr::IrrlichtDevice* dev,
						gui::IGUIElement* parent,
						IMenuManager *menumgr,
						scene::ISceneManager* smgr,
						MainMenuData* data,
						bool& kill) :
	m_device(dev),
	m_parent(parent),
	m_menumanager(menumgr),
	m_smgr(smgr),
	m_data(data),
	m_texture_source(NULL),
	m_sound_manager(NULL),
	m_formspecgui(0),
	m_buttonhandler(0),
	m_menu(0),
	m_kill(kill),
	m_startgame(false),
	m_script(0),
	m_scriptdir(""),
	m_irr_toplefttext(0),
	m_clouds_enabled(true),
	m_cloud()
{
	//initialize texture pointers
	for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) {
		m_textures[i].texture = NULL;
	}
	// is deleted by guiformspec!
	m_buttonhandler = new TextDestGuiEngine(this);

	//create texture source
	m_texture_source = new MenuTextureSource(m_device->getVideoDriver());

	//create soundmanager
	MenuMusicFetcher soundfetcher;
#if USE_SOUND
	m_sound_manager = createOpenALSoundManager(&soundfetcher);
#endif
	if(!m_sound_manager)
		m_sound_manager = &dummySoundManager;

	//create topleft header
	std::wstring t = utf8_to_wide(std::string(""));

	core::rect<s32> rect(0, 0, g_fontengine->getTextWidth(t), g_fontengine->getTextHeight());
	rect += v2s32(4, 0);

	m_irr_toplefttext =
		m_device->getGUIEnvironment()->addStaticText(t.c_str(),
		rect,false,true,0,-1);

	//create formspecsource
	m_formspecgui = new FormspecFormSource("");

	/* Create menu */
	m_menu = new GUIFormSpecMenu(m_device,
			m_parent,
			-1,
			m_menumanager,
			NULL /* &client */,
			NULL /* gamedef */,
			m_texture_source,
			m_formspecgui,
			m_buttonhandler,
			NULL,
			false);

	m_menu->allowClose(false);
	m_menu->lockSize(true,v2u32(800,600));

	// Initialize scripting

	infostream << "GUIEngine: Initializing Lua" << std::endl;

	m_script = new MainMenuScripting(this);

	try {
		m_script->setMainMenuData(&m_data->script_data);
		m_data->script_data.errormessage = "";

		if (!loadMainMenuScript()) {
			errorstream << "No future without mainmenu" << std::endl;
			abort();
		}

		run();
	} catch (LuaError &e) {
		errorstream << "MAINMENU ERROR: " << e.what() << std::endl;
		m_data->script_data.errormessage = e.what();
	}

	m_menu->quitMenu();
	m_menu->drop();
	m_menu = NULL;
}
示例#9
0
	void data_ptr::operator = (const std::string& data) {
		ptr.reset(new DataValue(utf8_to_wide(data)));
	}
示例#10
0
	data_ptr& data_map::operator [](const std::string& key) {
		return data[utf8_to_wide(key)];
	}
示例#11
0
void ProfilerGraph::draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
		gui::IGUIFont *font) const
{
	// Do *not* use UNORDERED_MAP here as the order needs
	// to be the same for each call to prevent flickering
	std::map<std::string, Meta> m_meta;

	for (const Piece &piece : m_log) {
		for (const auto &i : piece.values) {
			const std::string &id = i.first;
			const float &value = i.second;
			std::map<std::string, Meta>::iterator j = m_meta.find(id);

			if (j == m_meta.end()) {
				m_meta[id] = Meta(value);
				continue;
			}

			if (value < j->second.min)
				j->second.min = value;

			if (value > j->second.max)
				j->second.max = value;
		}
	}

	// Assign colors
	static const video::SColor usable_colors[] = {video::SColor(255, 255, 100, 100),
			video::SColor(255, 90, 225, 90),
			video::SColor(255, 100, 100, 255),
			video::SColor(255, 255, 150, 50),
			video::SColor(255, 220, 220, 100)};
	static const u32 usable_colors_count =
			sizeof(usable_colors) / sizeof(*usable_colors);
	u32 next_color_i = 0;

	for (auto &i : m_meta) {
		Meta &meta = i.second;
		video::SColor color(255, 200, 200, 200);

		if (next_color_i < usable_colors_count)
			color = usable_colors[next_color_i++];

		meta.color = color;
	}

	s32 graphh = 50;
	s32 textx = x_left + m_log_max_size + 15;
	s32 textx2 = textx + 200 - 15;
	s32 meta_i = 0;

	for (const auto &p : m_meta) {
		const std::string &id = p.first;
		const Meta &meta = p.second;
		s32 x = x_left;
		s32 y = y_bottom - meta_i * 50;
		float show_min = meta.min;
		float show_max = meta.max;

		if (show_min >= -0.0001 && show_max >= -0.0001) {
			if (show_min <= show_max * 0.5)
				show_min = 0;
		}

		s32 texth = 15;
		char buf[10];
		porting::mt_snprintf(buf, sizeof(buf), "%.3g", show_max);
		font->draw(utf8_to_wide(buf).c_str(),
				core::rect<s32>(textx, y - graphh, textx2,
						y - graphh + texth),
				meta.color);
		porting::mt_snprintf(buf, sizeof(buf), "%.3g", show_min);
		font->draw(utf8_to_wide(buf).c_str(),
				core::rect<s32>(textx, y - texth, textx2, y), meta.color);
		font->draw(utf8_to_wide(id).c_str(),
				core::rect<s32>(textx, y - graphh / 2 - texth / 2, textx2,
						y - graphh / 2 + texth / 2),
				meta.color);
		s32 graph1y = y;
		s32 graph1h = graphh;
		bool relativegraph = (show_min != 0 && show_min != show_max);
		float lastscaledvalue = 0.0;
		bool lastscaledvalue_exists = false;

		for (const Piece &piece : m_log) {
			float value = 0;
			bool value_exists = false;
			Profiler::GraphValues::const_iterator k = piece.values.find(id);

			if (k != piece.values.end()) {
				value = k->second;
				value_exists = true;
			}

			if (!value_exists) {
				x++;
				lastscaledvalue_exists = false;
				continue;
			}

			float scaledvalue = 1.0;

			if (show_max != show_min)
				scaledvalue = (value - show_min) / (show_max - show_min);

			if (scaledvalue == 1.0 && value == 0) {
				x++;
				lastscaledvalue_exists = false;
				continue;
			}

			if (relativegraph) {
				if (lastscaledvalue_exists) {
					s32 ivalue1 = lastscaledvalue * graph1h;
					s32 ivalue2 = scaledvalue * graph1h;
					driver->draw2DLine(
							v2s32(x - 1, graph1y - ivalue1),
							v2s32(x, graph1y - ivalue2),
							meta.color);
				}

				lastscaledvalue = scaledvalue;
				lastscaledvalue_exists = true;
			} else {
				s32 ivalue = scaledvalue * graph1h;
				driver->draw2DLine(v2s32(x, graph1y),
						v2s32(x, graph1y - ivalue), meta.color);
			}

			x++;
		}

		meta_i++;
	}
}
示例#12
0
void GUIEngine::setTopleftText(const std::string &text)
{
	m_toplefttext = utf8_to_wide(text);

	updateTopLeftTextSize();
}
示例#13
0
void TestUtilities::testUTF8()
{
	UASSERT(wide_to_utf8(utf8_to_wide("")) == "");
	UASSERT(wide_to_utf8(utf8_to_wide("the shovel dug a crumbly node!"))
		== "the shovel dug a crumbly node!");
}
示例#14
0
void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_control,
	const CameraOrientation &cam, const PointedThing &pointed_old, float dtime)
{
	v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();

	if (m_flags.show_debug) {
		static float drawtime_avg = 0;
		drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
		u16 fps = 1.0 / stats.dtime_jitter.avg;

		std::ostringstream os(std::ios_base::binary);
		os << std::fixed
			<< PROJECT_NAME_C " " << g_version_hash
			<< ", FPS: " << fps
			<< std::setprecision(0)
			<< ", drawtime: " << drawtime_avg << "ms"
			<< std::setprecision(1)
			<< ", dtime jitter: "
			<< (stats.dtime_jitter.max_fraction * 100.0) << "%"
			<< std::setprecision(1)
			<< ", view range: "
			<< (draw_control->range_all ? "All" : itos(draw_control->wanted_range))
			<< std::setprecision(3)
			<< ", RTT: " << client->getRTT() << "s";
		setStaticText(m_guitext, utf8_to_wide(os.str()).c_str());

		m_guitext->setRelativePosition(core::rect<s32>(5, 5, screensize.X,
			5 + g_fontengine->getTextHeight()));
	}

	// Finally set the guitext visible depending on the flag
	m_guitext->setVisible(m_flags.show_debug);

	if (m_flags.show_debug) {
		LocalPlayer *player = client->getEnv().getLocalPlayer();
		v3f player_position = player->getPosition();

		std::ostringstream os(std::ios_base::binary);
		os << std::setprecision(1) << std::fixed
			<< "pos: (" << (player_position.X / BS)
			<< ", " << (player_position.Y / BS)
			<< ", " << (player_position.Z / BS)
			<< "), yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "° "
			<< yawToDirectionString(cam.camera_yaw)
			<< ", seed: " << ((u64)client->getMapSeed());

		if (pointed_old.type == POINTEDTHING_NODE) {
			ClientMap &map = client->getEnv().getClientMap();
			const NodeDefManager *nodedef = client->getNodeDefManager();
			MapNode n = map.getNodeNoEx(pointed_old.node_undersurface);

			if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
				os << ", pointed: " << nodedef->get(n).name
					<< ", param2: " << (u64) n.getParam2();
			}
		}

		setStaticText(m_guitext2, utf8_to_wide(os.str()).c_str());

		m_guitext2->setRelativePosition(core::rect<s32>(5,
			5 + g_fontengine->getTextHeight(), screensize.X,
			5 + g_fontengine->getTextHeight() * 2
		));
	}

	m_guitext2->setVisible(m_flags.show_debug);

	setStaticText(m_guitext_info, translate_string(m_infotext).c_str());
	m_guitext_info->setVisible(m_flags.show_hud && g_menumgr.menuCount() == 0);

	static const float statustext_time_max = 1.5f;

	if (!m_statustext.empty()) {
		m_statustext_time += dtime;

		if (m_statustext_time >= statustext_time_max) {
			clearStatusText();
			m_statustext_time = 0.0f;
		}
	}

	setStaticText(m_guitext_status, translate_string(m_statustext).c_str());
	m_guitext_status->setVisible(!m_statustext.empty());

	if (!m_statustext.empty()) {
		s32 status_width  = m_guitext_status->getTextWidth();
		s32 status_height = m_guitext_status->getTextHeight();
		s32 status_y = screensize.Y - 150;
		s32 status_x = (screensize.X - status_width) / 2;

		m_guitext_status->setRelativePosition(core::rect<s32>(status_x ,
			status_y - status_height, status_x + status_width, status_y));

		// Fade out
		video::SColor final_color = m_statustext_initial_color;
		final_color.setAlpha(0);
		video::SColor fade_color = m_statustext_initial_color.getInterpolated_quadratic(
			m_statustext_initial_color, final_color, m_statustext_time / statustext_time_max);
		m_guitext_status->setOverrideColor(fade_color);
		m_guitext_status->enableOverrideColor(true);
	}
}
示例#15
0
bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
{
	init_args(game_params, cmd_args);

	// List video modes if requested
	if (list_video_modes)
		return print_video_modes();

	if (!init_engine()) {
		errorstream << "Could not initialize game engine." << std::endl;
		return false;
	}

	// Create time getter
	g_timegetter = new IrrlichtTimeGetter(device);

	// Speed tests (done after irrlicht is loaded to get timer)
	if (cmd_args.getFlag("speedtests")) {
		dstream << "Running speed tests" << std::endl;
		speed_tests();
		return true;
	}

	video::IVideoDriver *video_driver = device->getVideoDriver();
	if (video_driver == NULL) {
		errorstream << "Could not initialize video driver." << std::endl;
		return false;
	}

	porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);

	/*
		This changes the minimum allowed number of vertices in a VBO.
		Default is 500.
	*/
	//driver->setMinHardwareBufferVertexCount(50);
	video_driver->setMinHardwareBufferVertexCount(100);

	// Create game callback for menus
	g_gamecallback = new MainGameCallback(device);

	device->setResizable(true);

	if (random_input)
		input = new RandomInputHandler();
	else
		input = new RealInputHandler(device, receiver);

	smgr = device->getSceneManager();
	smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);

	guienv = device->getGUIEnvironment();
	skin = guienv->getSkin();

	skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
	skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
	skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
	skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
	skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 56, 121, 65));
	skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));

	g_fontengine = new FontEngine(g_settings, guienv);
	FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");

#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
	// Irrlicht 1.8 input colours
	skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
	skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 97, 173, 109));
#endif

	// Create the menu clouds
	if (!g_menucloudsmgr)
		g_menucloudsmgr = smgr->createNewSceneManager();
	if (!g_menuclouds)
		g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
				g_menucloudsmgr, -1, rand(), 100);
	g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
	scene::ICameraSceneNode* camera;
	camera = g_menucloudsmgr->addCameraSceneNode(0,
				v3f(0, 0, 0), v3f(0, 60, 100));
	camera->setFarValue(10000);

	/*
		GUI stuff
	*/

	ChatBackend chat_backend;

	// If an error occurs, this is set to something by menu().
	// It is then displayed before the menu shows on the next call to menu()
	std::string error_message;
	bool reconnect_requested = false;

	bool first_loop = true;

	/*
		Menu-game loop
	*/
	bool retval = true;
	bool *kill = porting::signal_handler_killstatus();

	while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
	{
		// Set the window caption
		const wchar_t *text = wgettext("Main Menu");
		device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) + L" [" + text + L"]").c_str());
		delete[] text;

#ifdef __ANDROID__
		porting::handleAndroidActivityEvents(5);
#endif

		try {	// This is used for catching disconnects

			guienv->clear();

			/*
				We need some kind of a root node to be able to add
				custom gui elements directly on the screen.
				Otherwise they won't be automatically drawn.
			*/
			guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));

			bool game_has_run = launch_game(error_message, reconnect_requested,
				game_params, cmd_args);

			// If skip_main_menu, we only want to startup once
			if (skip_main_menu && !first_loop)
				break;

			first_loop = false;

			if (!game_has_run) {
				if (skip_main_menu)
					break;
				else
					continue;
			}

			if (g_settings_path != "")
				g_settings->updateConfigFile(g_settings_path.c_str());

			// Break out of menu-game loop to shut down cleanly
			if (!device->run() || *kill) {
				break;
			}

/*
			if (current_playername.length() > PLAYERNAME_SIZE-1) {
				error_message = gettext("Player name too long.");
				playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
				g_settings->set("name", playername);
				continue;
			}
*/

			device->getVideoDriver()->setTextureCreationFlag(
					video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));

#ifdef HAVE_TOUCHSCREENGUI
			receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
			g_touchscreengui = receiver->m_touchscreengui;
#endif
			int tries = simple_singleplayer_mode ? 1 : g_settings->getU16("reconnects");
			int n = 0;

			while(!*kill && ++n <= tries &&
			the_game(
				kill,
				random_input,
				input,
				device,
				worldspec.path,
				current_playername,
				current_password,
				current_address,
				current_port,
				error_message,
				chat_backend,
				&reconnect_requested,
				gamespec,
				simple_singleplayer_mode
				, autoexit
			)
			){
				smgr->clear();
				errorstream << "Reconnecting "<< n << "/" << tries << " ..." << std::endl;
			}
			smgr->clear();

#ifdef HAVE_TOUCHSCREENGUI
			delete g_touchscreengui;
			g_touchscreengui = NULL;
			receiver->m_touchscreengui = NULL;
#endif

		} //try
		catch (con::PeerNotFoundException &e) {
			error_message = _("Connection error (timed out?)");
			errorstream << error_message << std::endl;
		}

#ifdef NDEBUG
		catch (std::exception &e) {
			std::string error_message = "Some exception: \"";
			error_message += e.what();
			error_message += "\"";
			errorstream << error_message << std::endl;
		}
#endif

		// If no main menu, show error and exit
		if (skip_main_menu) {
			if (!error_message.empty()) {
				verbosestream << "error_message = "
				              << error_message << std::endl;
				retval = false;
			}
			break;
		}
	} // Menu-game loop

	g_menuclouds->drop();
	g_menucloudsmgr->drop();

#ifdef _IRR_COMPILE_WITH_LEAK_HUNTER_
	auto objects = LeakHunter::getReferenceCountedObjects();
	infostream<<"irrlicht leaked objects="<<objects.size()<<std::endl;
	for (unsigned int i = 0; i < objects.size(); ++i) {
		if (!objects[i])
			continue;
		infostream<<i<<":" <<objects[i]<< " cnt="<<objects[i]->getReferenceCount()<<" desc="<<(objects[i]->getDebugName() ? objects[i]->getDebugName() : "")<<std::endl;
	}
#endif

	return retval;
}
示例#16
0
	std::string parse(std::string templ_text, data_map &data)
	{
		return wide_to_utf8(parse(utf8_to_wide(templ_text), data));
	}
示例#17
0
	std::wstring convert_path(const std::string& aString)
	{
		return boost::filesystem::path(utf8_to_wide(aString)).generic_wstring();
	}