aboutsummaryrefslogtreecommitdiff
path: root/src/server
diff options
context:
space:
mode:
Diffstat (limited to 'src/server')
0 files changed, 0 insertions, 0 deletions
f9a8efb99235c86eb61b6deb2bc034d5618e45ea&id2=12e9f3d010f887c3fe0b32f3ddbf25f2ef6b7323'>src/CMakeLists.txt77
-rw-r--r--src/biome.cpp233
-rw-r--r--src/biome.h98
-rw-r--r--src/cguittfont/CGUITTFont.cpp1146
-rw-r--r--src/cguittfont/CGUITTFont.h377
-rw-r--r--src/cguittfont/CMakeLists.txt17
-rw-r--r--src/cguittfont/irrUString.h3877
-rw-r--r--src/cguittfont/xCGUITTFont.cpp5
-rw-r--r--src/cguittfont/xCGUITTFont.h7
-rw-r--r--src/client.cpp20
-rw-r--r--src/clientmap.cpp2
-rw-r--r--src/clientserver.h17
-rw-r--r--src/clouds.cpp3
-rw-r--r--src/cmake_config.h.in1
-rw-r--r--src/config.h3
-rw-r--r--src/content_abm.cpp3
-rw-r--r--src/content_mapblock.cpp12
-rw-r--r--src/defaultsettings.cpp52
-rw-r--r--src/environment.cpp53
-rw-r--r--src/environment.h3
-rw-r--r--src/farmesh.cpp6
-rw-r--r--src/game.cpp12
-rw-r--r--src/gettext.h41
-rw-r--r--src/guiChatConsole.cpp10
-rw-r--r--src/guiConfigureWorld.cpp705
-rw-r--r--src/guiConfigureWorld.h110
-rw-r--r--src/guiKeyChangeMenu.cpp34
-rw-r--r--src/guiMainMenu.cpp241
-rw-r--r--src/guiMainMenu.h18
-rw-r--r--src/guiPauseMenu.cpp506
-rw-r--r--src/guiPauseMenu.h120
-rw-r--r--src/guiTextInputMenu.cpp12
-rw-r--r--src/intlGUIEditBox.cpp1508
-rw-r--r--src/intlGUIEditBox.h178
-rw-r--r--src/irrlichttypes.h3
-rw-r--r--src/itemdef.cpp1
-rw-r--r--src/itemdef.h2
-rw-r--r--src/json/CMakeLists.txt14
-rw-r--r--src/json/UPDATING16
-rw-r--r--src/json/json.h1914
-rw-r--r--src/json/jsoncpp.cpp4367
-rw-r--r--src/localplayer.cpp186
-rw-r--r--src/main.cpp81
-rw-r--r--src/map.cpp335
-rw-r--r--src/map.h98
-rw-r--r--src/mapgen.cpp379
-rw-r--r--src/mapgen.h134
-rw-r--r--src/mapgen_v6.cpp1438
-rw-r--r--src/mapgen_v6.h141
-rw-r--r--src/mods.cpp277
-rw-r--r--src/mods.h90
-rw-r--r--src/nodedef.cpp18
-rw-r--r--src/nodedef.h2
-rw-r--r--src/noise.cpp731
-rw-r--r--src/noise.h171
-rw-r--r--src/player.cpp58
-rw-r--r--src/player.h25
-rw-r--r--src/porting.cpp90
-rw-r--r--src/porting.h24
-rw-r--r--src/scriptapi.cpp513
-rw-r--r--src/server.cpp566
-rw-r--r--src/server.h111
-rw-r--r--src/serverlist.cpp276
-rw-r--r--src/serverlist.h46
-rw-r--r--src/settings.h396
-rw-r--r--src/subgame.cpp6
-rw-r--r--src/subgame.h13
-rw-r--r--src/treegen.cpp126
-rw-r--r--src/treegen.h27
-rw-r--r--src/util/numeric.h1
-rw-r--r--src/util/string.cpp65
-rw-r--r--src/util/string.h8
-rw-r--r--src/voxel.h34
-rw-r--r--src/voxelalgorithms.cpp8
74 files changed, 20451 insertions, 1847 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 24f682f3f..17102e848 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -5,6 +5,7 @@ cmake_minimum_required( VERSION 2.6 )
mark_as_advanced(EXECUTABLE_OUTPUT_PATH LIBRARY_OUTPUT_PATH)
mark_as_advanced(JTHREAD_INCLUDE_DIR JTHREAD_LIBRARY)
mark_as_advanced(SQLITE3_INCLUDE_DIR SQLITE3_LIBRARY)
+mark_as_advanced(JSON_INCLUDE_DIR JSON_LIBRARY)
option(ENABLE_CURL "Enable cURL support for fetching media" 1)
@@ -93,6 +94,12 @@ if(USE_SOUND)
)
endif()
+option(ENABLE_FREETYPE "Enable freetype2 (truetype fonts and basic unicode support)" OFF)
+set(USE_FREETYPE 0)
+if(ENABLE_FREETYPE)
+ set(USE_FREETYPE 1)
+endif(ENABLE_FREETYPE)
+
if(NOT MSVC)
set(USE_GPROF 0 CACHE BOOL "Use -pg flag for g++")
endif()
@@ -117,6 +124,14 @@ if(WIN32)
CACHE FILEPATH "Path to zlibwapi.dll (for installation)")
set(IRRLICHT_SOURCE_DIR "${PROJECT_SOURCE_DIR}/../../irrlicht-1.7.2"
CACHE PATH "irrlicht dir")
+ if(USE_FREETYPE)
+ set(FREETYPE_INCLUDE_DIR_ft2build "${PROJECT_SOURCE_DIR}/../../freetype2/include/"
+ CACHE PATH "freetype include dir")
+ set(FREETYPE_INCLUDE_DIR_freetype2 "${PROJECT_SOURCE_DIR}/../../freetype2/include/freetype"
+ CACHE PATH "freetype include dir")
+ set(FREETYPE_LIBRARY "${PROJECT_SOURCE_DIR}/../../freetype2/objs/win32/vc2005/freetype247.lib"
+ CACHE FILEPATH "Path to freetype247.lib")
+ endif(USE_FREETYPE)
set(MINGWM10_DLL ""
CACHE FILEPATH "Path to mingwm10.dll (for installation)")
if(ENABLE_SOUND)
@@ -156,6 +171,13 @@ endif()
find_package(Jthread REQUIRED)
find_package(Sqlite3 REQUIRED)
+find_package(Json REQUIRED)
+
+if(USE_FREETYPE)
+ find_package(Freetype REQUIRED)
+ set(CGUITTFONT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cguittfont")
+ set(CGUITTFONT_LIBRARY cguittfont)
+endif(USE_FREETYPE)
# Do not use system-wide installation of Lua, because it'll likely be a
# different version and/or has different build options.
@@ -188,6 +210,7 @@ set(common_SRCS
log.cpp
content_sao.cpp
mapgen.cpp
+ mapgen_v6.cpp
treegen.cpp
content_nodemeta.cpp
content_mapnode.cpp
@@ -218,8 +241,10 @@ set(common_SRCS
sha1.cpp
base64.cpp
ban.cpp
+ biome.cpp
clientserver.cpp
staticobject.cpp
+ serverlist.cpp
util/serialize.cpp
util/directiontables.cpp
util/numeric.cpp
@@ -275,6 +300,7 @@ set(minetest_SRCS
guiDeathScreen.cpp
guiChatConsole.cpp
guiCreateWorld.cpp
+ guiConfigureWorld.cpp
guiConfirmMenu.cpp
client.cpp
filecache.cpp
@@ -284,6 +310,13 @@ set(minetest_SRCS
main.cpp
)
+if(USE_FREETYPE)
+ set(minetest_SRCS
+ ${minetest_SRCS}
+ intlGUIEditBox.cpp
+ )
+endif(USE_FREETYPE)
+
# Server sources
set(minetestserver_SRCS
${common_SRCS}
@@ -301,8 +334,22 @@ include_directories(
${JTHREAD_INCLUDE_DIR}
${SQLITE3_INCLUDE_DIR}
${LUA_INCLUDE_DIR}
+ ${JSON_INCLUDE_DIR}
)
+if(USE_FREETYPE)
+ include_directories(
+ ${FREETYPE_INCLUDE_DIRS}
+ ${CGUITTFONT_INCLUDE_DIR}
+ )
+endif(USE_FREETYPE)
+
+if(USE_CURL)
+ include_directories(
+ ${CURL_INCLUDE_DIR}
+ )
+endif(USE_CURL)
+
set(EXECUTABLE_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/bin")
if(BUILD_CLIENT)
@@ -321,19 +368,23 @@ if(BUILD_CLIENT)
${JTHREAD_LIBRARY}
${SQLITE3_LIBRARY}
${LUA_LIBRARY}
+ ${JSON_LIBRARY}
${PLATFORM_LIBS}
${CLIENT_PLATFORM_LIBS}
)
-
if(USE_CURL)
target_link_libraries(
${PROJECT_NAME}
${CURL_LIBRARY}
)
- include_directories(
- ${CURL_INCLUDE_DIR}
- )
endif(USE_CURL)
+ if(USE_FREETYPE)
+ target_link_libraries(
+ ${PROJECT_NAME}
+ ${FREETYPE_LIBRARY}
+ ${CGUITTFONT_LIBRARY}
+ )
+ endif(USE_FREETYPE)
endif(BUILD_CLIENT)
if(BUILD_SERVER)
@@ -343,11 +394,20 @@ if(BUILD_SERVER)
${ZLIB_LIBRARIES}
${JTHREAD_LIBRARY}
${SQLITE3_LIBRARY}
+ ${JSON_LIBRARY}
+ ${GETTEXT_LIBRARY}
${LUA_LIBRARY}
${PLATFORM_LIBS}
)
+ if(USE_CURL)
+ target_link_libraries(
+ ${PROJECT_NAME}server
+ ${CURL_LIBRARY}
+ )
+ endif(USE_CURL)
endif(BUILD_SERVER)
+
#
# Set some optimizations and tweaks
#
@@ -514,9 +574,18 @@ else (SQLITE3_FOUND)
add_subdirectory(sqlite)
endif (SQLITE3_FOUND)
+if (BUILD_CLIENT AND USE_FREETYPE)
+ add_subdirectory(cguittfont)
+endif (BUILD_CLIENT AND USE_FREETYPE)
+
if (LUA_FOUND)
else (LUA_FOUND)
add_subdirectory(lua)
endif (LUA_FOUND)
+if (JSON_FOUND)
+else (JSON_FOUND)
+ add_subdirectory(json)
+endif (JSON_FOUND)
+
#end
diff --git a/src/biome.cpp b/src/biome.cpp
new file mode 100644
index 000000000..34d51839f
--- /dev/null
+++ b/src/biome.cpp
@@ -0,0 +1,233 @@
+/*
+Minetest-c55
+Copyright (C) 2010-2011 kwolekr, Ryan Kwolek <kwolekr2@cs.scranton.edu>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#include "biome.h"
+#include "nodedef.h"
+#include "map.h" //for ManualMapVoxelManipulator
+#include "log.h"
+#include "main.h"
+
+#define BT_NONE 0
+#define BT_OCEAN 1
+#define BT_LAKE 2
+#define BT_SBEACH 3
+#define BT_GBEACH 4
+#define BT_PLAINS 5
+#define BT_HILLS 6
+#define BT_EXTREMEHILLS 7
+#define BT_MOUNTAINS 8
+#define BT_DESERT 9
+#define BT_DESERTHILLS 10
+#define BT_HELL 11
+#define BT_AETHER 12
+
+#define BT_BTMASK 0x3F
+
+#define BTF_SNOW 0x40
+#define BTF_FOREST 0x80
+
+#define BGFREQ_1 ( 0.40)
+#define BGFREQ_2 (BGFREQ_1 + 0.05)
+#define BGFREQ_3 (BGFREQ_2 + 0.08)
+#define BGFREQ_4 (BGFREQ_3 + 0.35)
+#define BGFREQ_5 (BGFREQ_4 + 0.18)
+//BGFREQ_5 is not checked as an upper bound; it ought to sum up to 1.00, but it's okay if it doesn't.
+
+
+/*float bg1_temps[] = {0.0};
+int bg1_biomes[] = {BT_OCEAN};
+
+float bg2_temps[] = {10.0};
+int bg2_biomes[] = {BT_GBEACH, BT_SBEACH};
+
+float bg3_temps[] = {30.0, 40.0};
+int bg3_biomes[] = {BT_HILLS, BT_EXTREMEHILLS, BT_MOUNTAINS};
+
+float bg4_temps[] = {25.0, 30.0, 35.0, 40.0};
+int bg4_biomes[] = {BT_HILLS, BT_EXTREMEHILLS, BT_MOUNTAINS, BT_DESERT, BT_DESERTHILLS};
+
+float bg5_temps[] = {5.0, 40.0};
+int bg5_biomes[] = {BT_LAKE, BT_PLAINS, BT_DESERT};*/
+
+NoiseParams np_default = {20.0, 15.0, v3f(250., 250., 250.), 82341, 5, 0.6};
+
+
+BiomeDefManager::BiomeDefManager(IGameDef *gamedef) {
+ this->m_gamedef = gamedef;
+ this->ndef = gamedef->ndef();
+
+ //the initial biome group
+ bgroups.push_back(new std::vector<Biome *>);
+}
+
+
+BiomeDefManager::~BiomeDefManager() {
+ for (unsigned int i = 0; i != bgroups.size(); i++)
+ delete bgroups[i];
+}
+
+
+Biome *BiomeDefManager::createBiome(BiomeTerrainType btt) {
+ switch (btt) {
+ case BIOME_TERRAIN_NORMAL:
+ return new Biome;
+ case BIOME_TERRAIN_LIQUID:
+ return new BiomeLiquid;
+ case BIOME_TERRAIN_NETHER:
+ return new BiomeHell;
+ case BIOME_TERRAIN_AETHER:
+ return new BiomeAether;
+ case BIOME_TERRAIN_FLAT:
+ return new BiomeSuperflat;
+ }
+ return NULL;
+}
+
+
+void BiomeDefManager::addBiomeGroup(float freq) {
+ int size = bgroup_freqs.size();
+ float newfreq = freq;
+
+ if (size)
+ newfreq += bgroup_freqs[size - 1];
+ bgroup_freqs.push_back(newfreq);
+ bgroups.push_back(new std::vector<Biome *>);
+
+ verbosestream << "BiomeDefManager: added biome group with frequency " <<
+ newfreq << std::endl;
+}
+
+
+void BiomeDefManager::addBiome(Biome *b) {
+ std::vector<Biome *> *bgroup;
+
+ if ((unsigned int)b->groupid >= bgroups.size()) {
+ errorstream << "BiomeDefManager: attempted to add biome '" << b->name
+ << "' to nonexistent biome group " << b->groupid << std::endl;
+ return;
+ }
+
+ bgroup = bgroups[b->groupid];
+ bgroup->push_back(b);
+
+ verbosestream << "BiomeDefManager: added biome '" << b->name <<
+ "' to biome group " << (int)b->groupid << std::endl;
+}
+
+
+void BiomeDefManager::addDefaultBiomes() {
+ Biome *b;
+
+ b = new Biome;
+ b->name = "Default";
+ b->n_top = MapNode(ndef->getId("mapgen_stone"));
+ b->n_filler = b->n_top;
+ b->ntopnodes = 0;
+ b->height_min = -MAP_GENERATION_LIMIT;
+ b->height_max = MAP_GENERATION_LIMIT;
+ b->heat_min = FLT_MIN;
+ b->heat_max = FLT_MAX;
+ b->humidity_min = FLT_MIN;
+ b->humidity_max = FLT_MAX;
+ b->np = &np_default;
+ biome_default = b;
+}
+
+
+Biome *BiomeDefManager::getBiome(float bgfreq, float heat, float humidity) {
+ std::vector<Biome *> *bgroup;
+ Biome *b;
+ int i;
+
+ int ngroups = bgroup_freqs.size();
+ if (!ngroups)
+ return biome_default;
+ for (i = 0; (i != ngroups) && (bgfreq > bgroup_freqs[i]); i++);
+ bgroup = bgroups[i];
+
+ int nbiomes = bgroup->size();
+ for (i = 0; i != nbiomes; i++) {
+ b = bgroup->operator[](i);
+ if (heat >= b->heat_min && heat <= b->heat_max &&
+ humidity >= b->humidity_min && humidity <= b->humidity_max)
+ return b;
+ }
+
+ return biome_default;
+}
+
+
+//////////////////////////// [ Generic biome ] ////////////////////////////////
+
+
+int Biome::getSurfaceHeight(float noise_terrain) {
+ return np->offset + np->scale * noise_terrain;
+}
+
+
+void Biome::genColumn(Mapgen *mapgen, int x, int z, int y1, int y2) {
+
+}
+
+
+///////////////////////////// [ Ocean biome ] /////////////////////////////////
+
+
+void BiomeLiquid::genColumn(Mapgen *mapgen, int x, int z, int y1, int y2) {
+
+}
+
+
+///////////////////////////// [ Nether biome ] /////////////////////////////////
+
+
+int BiomeHell::getSurfaceHeight(float noise_terrain) {
+ return np->offset + np->scale * noise_terrain;
+}
+
+
+void BiomeHell::genColumn(Mapgen *mapgen, int x, int z, int y1, int y2) {
+
+}
+
+
+///////////////////////////// [ Aether biome ] ////////////////////////////////
+
+
+int BiomeAether::getSurfaceHeight(float noise_terrain) {
+ return np->offset + np->scale * noise_terrain;
+}
+
+
+void BiomeAether::genColumn(Mapgen *mapgen, int x, int z, int y1, int y2) {
+
+}
+
+
+/////////////////////////// [ Superflat biome ] ///////////////////////////////
+
+
+int BiomeSuperflat::getSurfaceHeight(float noise_terrain) {
+ return ntopnodes;
+}
+
+
+void BiomeSuperflat::genColumn(Mapgen *mapgen, int x, int z, int y1, int y2) {
+
+}
diff --git a/src/biome.h b/src/biome.h
new file mode 100644
index 000000000..265f1df44
--- /dev/null
+++ b/src/biome.h
@@ -0,0 +1,98 @@
+/*
+Minetest-c55
+Copyright (C) 2010-2011 kwolekr, Ryan Kwolek <kwolekr2@cs.scranton.edu>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#ifndef BIOME_HEADER
+#define BIOME_HEADER
+
+#include <string>
+#include "nodedef.h"
+#include "gamedef.h"
+#include "mapnode.h"
+#include "noise.h"
+#include "mapgen.h"
+
+
+enum BiomeTerrainType
+{
+ BIOME_TERRAIN_NORMAL,
+ BIOME_TERRAIN_LIQUID,
+ BIOME_TERRAIN_NETHER,
+ BIOME_TERRAIN_AETHER,
+ BIOME_TERRAIN_FLAT
+};
+
+class Biome {
+public:
+ MapNode n_top;
+ MapNode n_filler;
+ s16 ntopnodes;
+ s8 groupid;
+ s8 flags;
+ s16 height_min;
+ s16 height_max;
+ float heat_min;
+ float heat_max;
+ float humidity_min;
+ float humidity_max;
+ std::string name;
+ NoiseParams *np;
+
+ virtual void genColumn(Mapgen *mg, int x, int z, int y1, int y2);
+ virtual int getSurfaceHeight(float noise_terrain);
+};
+
+class BiomeLiquid : public Biome {
+ virtual void genColumn(Mapgen *mg, int x, int z, int y1, int y2);
+};
+
+class BiomeHell : public Biome {
+ virtual void genColumn(Mapgen *mg, int x, int z, int y1, int y2);
+ virtual int getSurfaceHeight(float noise_terrain);
+};
+
+class BiomeAether : public Biome {
+ virtual void genColumn(Mapgen *mg, int x, int z, int y1, int y2);
+ virtual int getSurfaceHeight(float noise_terrain);
+};
+
+class BiomeSuperflat : public Biome {
+ virtual void genColumn(Mapgen *mg, int x, int z, int y1, int y2);
+ virtual int getSurfaceHeight(float noise_terrain);
+};
+
+class BiomeDefManager {
+public:
+ std::vector<float> bgroup_freqs;
+ std::vector<std::vector<Biome *> *> bgroups;
+ Biome *biome_default;
+ IGameDef *m_gamedef;
+ INodeDefManager *ndef;
+
+ BiomeDefManager(IGameDef *gamedef);
+ ~BiomeDefManager();
+
+ Biome *createBiome(BiomeTerrainType btt);
+ Biome *getBiome(float bgfreq, float heat, float humidity);
+
+ void addBiomeGroup(float freq);
+ void addBiome(Biome *b);
+ void addDefaultBiomes();
+};
+
+#endif
diff --git a/src/cguittfont/CGUITTFont.cpp b/src/cguittfont/CGUITTFont.cpp
new file mode 100644
index 000000000..fb8199e21
--- /dev/null
+++ b/src/cguittfont/CGUITTFont.cpp
@@ -0,0 +1,1146 @@
+/*
+ CGUITTFont FreeType class for Irrlicht
+ Copyright (c) 2009-2010 John Norman
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any
+ damages arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any
+ purpose, including commercial applications, and to alter it and
+ redistribute it freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you use
+ this software in a product, an acknowledgment in the product
+ documentation would be appreciated but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and
+ must not be misrepresented as being the original software.
+
+ 3. This notice may not be removed or altered from any source
+ distribution.
+
+ The original version of this class can be located at:
+ http://irrlicht.suckerfreegames.com/
+
+ John Norman
+ john@suckerfreegames.com
+*/
+
+#include <irrlicht.h>
+#include "CGUITTFont.h"
+
+namespace irr
+{
+namespace gui
+{
+
+// Manages the FT_Face cache.
+struct SGUITTFace : public virtual irr::IReferenceCounted
+{
+ SGUITTFace() : face_buffer(0), face_buffer_size(0)
+ {
+ memset((void*)&face, 0, sizeof(FT_Face));
+ }
+
+ ~SGUITTFace()
+ {
+ FT_Done_Face(face);
+ delete[] face_buffer;
+ }
+
+ FT_Face face;
+ FT_Byte* face_buffer;
+ FT_Long face_buffer_size;
+};
+
+// Static variables.
+FT_Library CGUITTFont::c_library;
+core::map<io::path, SGUITTFace*> CGUITTFont::c_faces;
+bool CGUITTFont::c_libraryLoaded = false;
+scene::IMesh* CGUITTFont::shared_plane_ptr_ = 0;
+scene::SMesh CGUITTFont::shared_plane_;
+
+//
+
+video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const
+{
+ // Determine what our texture size should be.
+ // Add 1 because textures are inclusive-exclusive.
+ core::dimension2du d(bits.width + 1, bits.rows + 1);
+ core::dimension2du texture_size;
+ //core::dimension2du texture_size(bits.width + 1, bits.rows + 1);
+
+ // Create and load our image now.
+ video::IImage* image = 0;
+ switch (bits.pixel_mode)
+ {
+ case FT_PIXEL_MODE_MONO:
+ {
+ // Create a blank image and fill it with transparent pixels.
+ texture_size = d.getOptimalSize(true, true);
+ image = driver->createImage(video::ECF_A1R5G5B5, texture_size);
+ image->fill(video::SColor(0, 255, 255, 255));
+
+ // Load the monochrome data in.
+ const u32 image_pitch = image->getPitch() / sizeof(u16);
+ u16* image_data = (u16*)image->lock();
+ u8* glyph_data = bits.buffer;
+ for (s32 y = 0; y < bits.rows; ++y)
+ {
+ u16* row = image_data;
+ for (s32 x = 0; x < bits.width; ++x)
+ {
+ // Monochrome bitmaps store 8 pixels per byte. The left-most pixel is the bit 0x80.
+ // So, we go through the data each bit at a time.
+ if ((glyph_data[y * bits.pitch + (x / 8)] & (0x80 >> (x % 8))) != 0)
+ *row = 0xFFFF;
+ ++row;
+ }
+ image_data += image_pitch;
+ }
+ image->unlock();
+ break;
+ }
+
+ case FT_PIXEL_MODE_GRAY:
+ {
+ // Create our blank image.
+ texture_size = d.getOptimalSize(!driver->queryFeature(video::EVDF_TEXTURE_NPOT), !driver->queryFeature(video::EVDF_TEXTURE_NSQUARE), true, 0);
+ image = driver->createImage(video::ECF_A8R8G8B8, texture_size);
+ image->fill(video::SColor(0, 255, 255, 255));
+
+ // Load the grayscale data in.
+ const float gray_count = static_cast<float>(bits.num_grays);
+ const u32 image_pitch = image->getPitch() / sizeof(u32);
+ u32* image_data = (u32*)image->lock();
+ u8* glyph_data = bits.buffer;
+ for (s32 y = 0; y < bits.rows; ++y)
+ {
+ u8* row = glyph_data;
+ for (s32 x = 0; x < bits.width; ++x)
+ {
+ image_data[y * image_pitch + x] |= static_cast<u32>(255.0f * (static_cast<float>(*row++) / gray_count)) << 24;
+ //data[y * image_pitch + x] |= ((u32)(*bitsdata++) << 24);
+ }
+ glyph_data += bits.pitch;
+ }
+ image->unlock();
+ break;
+ }
+ default:
+ // TODO: error message?
+ return 0;
+ }
+ return image;
+}
+
+void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags)
+{
+ if (isLoaded) return;
+
+ // Set the size of the glyph.
+ FT_Set_Pixel_Sizes(face, 0, font_size);
+
+ // Attempt to load the glyph.
+ if (FT_Load_Glyph(face, char_index, loadFlags) != FT_Err_Ok)
+ // TODO: error message?
+ return;
+
+ FT_GlyphSlot glyph = face->glyph;
+ FT_Bitmap bits = glyph->bitmap;
+
+ // Setup the glyph information here:
+ advance = glyph->advance;
+ offset = core::vector2di(glyph->bitmap_left, glyph->bitmap_top);
+
+ // Try to get the last page with available slots.
+ CGUITTGlyphPage* page = parent->getLastGlyphPage();
+
+ // If we need to make a new page, do that now.
+ if (!page)
+ {
+ page = parent->createGlyphPage(bits.pixel_mode);
+ if (!page)
+ // TODO: add error message?
+ return;
+ }
+
+ glyph_page = parent->getLastGlyphPageIndex();
+ u32 texture_side_length = page->texture->getOriginalSize().Width;
+ core::vector2di page_position(
+ (page->used_slots % (texture_side_length / font_size)) * font_size,
+ (page->used_slots / (texture_side_length / font_size)) * font_size
+ );
+ source_rect.UpperLeftCorner = page_position;
+ source_rect.LowerRightCorner = core::vector2di(page_position.X + bits.width, page_position.Y + bits.rows);
+
+ page->dirty = true;
+ ++page->used_slots;
+ --page->available_slots;
+
+ // We grab the glyph bitmap here so the data won't be removed when the next glyph is loaded.
+ surface = createGlyphImage(bits, driver);
+
+ // Set our glyph as loaded.
+ isLoaded = true;
+}
+
+void SGUITTGlyph::unload()
+{
+ if (surface)
+ {
+ surface->drop();
+ surface = 0;
+ }
+ isLoaded = false;
+}
+
+//////////////////////
+
+CGUITTFont* CGUITTFont::createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency)
+{
+ if (!c_libraryLoaded)
+ {
+ if (FT_Init_FreeType(&c_library))
+ return 0;
+ c_libraryLoaded = true;
+ }
+
+ CGUITTFont* font = new CGUITTFont(env);
+ bool ret = font->load(filename, size, antialias, transparency);
+ if (!ret)
+ {
+ font->drop();
+ return 0;
+ }
+
+ return font;
+}
+
+CGUITTFont* CGUITTFont::createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency)
+{
+ if (!c_libraryLoaded)
+ {
+ if (FT_Init_FreeType(&c_library))
+ return 0;
+ c_libraryLoaded = true;
+ }
+
+ CGUITTFont* font = new CGUITTFont(device->getGUIEnvironment());
+ font->Device = device;
+ bool ret = font->load(filename, size, antialias, transparency);
+ if (!ret)
+ {
+ font->drop();
+ return 0;
+ }
+
+ return font;
+}
+
+CGUITTFont* CGUITTFont::create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency)
+{
+ return CGUITTFont::createTTFont(env, filename, size, antialias, transparency);
+}
+
+CGUITTFont* CGUITTFont::create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency)
+{
+ return CGUITTFont::createTTFont(device, filename, size, antialias, transparency);
+}
+
+//////////////////////
+
+//! Constructor.
+CGUITTFont::CGUITTFont(IGUIEnvironment *env)
+: use_monochrome(false), use_transparency(true), use_hinting(true), use_auto_hinting(true),
+batch_load_size(1), Device(0), Environment(env), Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0)
+{
+ #ifdef _DEBUG
+ setDebugName("CGUITTFont");
+ #endif
+
+ if (Environment)
+ {
+ // don't grab environment, to avoid circular references
+ Driver = Environment->getVideoDriver();
+ }
+
+ if (Driver)
+ Driver->grab();
+
+ setInvisibleCharacters(L" ");
+
+ // Glyphs aren't reference counted, so don't try to delete them when we free the array.
+ Glyphs.set_free_when_destroyed(false);
+}
+
+bool CGUITTFont::load(const io::path& filename, const u32 size, const bool antialias, const bool transparency)
+{
+ // Some sanity checks.
+ if (Environment == 0 || Driver == 0) return false;
+ if (size == 0) return false;
+ if (filename.size() == 0) return false;
+
+ io::IFileSystem* filesystem = Environment->getFileSystem();
+ irr::ILogger* logger = (Device != 0 ? Device->getLogger() : 0);
+ this->size = size;
+ this->filename = filename;
+
+ // Update the font loading flags when the font is first loaded.
+ this->use_monochrome = !antialias;
+ this->use_transparency = transparency;
+ update_load_flags();
+
+ // Log.
+ if (logger)
+ logger->log(L"CGUITTFont", core::stringw(core::stringw(L"Creating new font: ") + core::ustring(filename).toWCHAR_s() + L" " + core::stringc(size) + L"pt " + (antialias ? L"+antialias " : L"-antialias ") + (transparency ? L"+transparency" : L"-transparency")).c_str(), irr::ELL_INFORMATION);
+
+ // Grab the face.
+ SGUITTFace* face = 0;
+ core::map<io::path, SGUITTFace*>::Node* node = c_faces.find(filename);
+ if (node == 0)
+ {
+ face = new SGUITTFace();
+ c_faces.set(filename, face);
+
+ if (filesystem)
+ {
+ // Read in the file data.
+ io::IReadFile* file = filesystem->createAndOpenFile(filename);
+ if (file == 0)
+ {
+ if (logger) logger->log(L"CGUITTFont", L"Failed to open the file.", irr::ELL_INFORMATION);
+
+ c_faces.remove(filename);
+ delete face;
+ face = 0;
+ return false;
+ }
+ face->face_buffer = new FT_Byte[file->getSize()];
+ file->read(face->face_buffer, file->getSize());
+ face->face_buffer_size = file->getSize();
+ file->drop();
+
+ // Create the face.
+ if (FT_New_Memory_Face(c_library, face->face_buffer, face->face_buffer_size, 0, &face->face))
+ {
+ if (logger) logger->log(L"CGUITTFont", L"FT_New_Memory_Face failed.", irr::ELL_INFORMATION);
+
+ c_faces.remove(filename);
+ delete face;
+ face = 0;
+ return false;
+ }
+ }
+ else
+ {
+ core::ustring converter(filename);
+ if (FT_New_Face(c_library, reinterpret_cast<const char*>(converter.toUTF8_s().c_str()), 0, &face->face))
+ {
+ if (logger) logger->log(L"CGUITTFont", L"FT_New_Face failed.", irr::ELL_INFORMATION);
+
+ c_faces.remove(filename);
+ delete face;
+ face = 0;
+ return false;
+ }
+ }
+ }
+ else
+ {
+ // Using another instance of this face.
+ face = node->getValue();
+ face->grab();
+ }
+
+ // Store our face.
+ tt_face = face->face;
+
+ // Store font metrics.
+ FT_Set_Pixel_Sizes(tt_face, size, 0);
+ font_metrics = tt_face->size->metrics;
+
+ // Allocate our glyphs.
+ Glyphs.clear();
+ Glyphs.reallocate(tt_face->num_glyphs);
+ Glyphs.set_used(tt_face->num_glyphs);
+ for (FT_Long i = 0; i < tt_face->num_glyphs; ++i)
+ {
+ Glyphs[i].isLoaded = false;
+ Glyphs[i].glyph_page = 0;
+ Glyphs[i].source_rect = core::recti();
+ Glyphs[i].offset = core::vector2di();
+ Glyphs[i].advance = FT_Vector();
+ Glyphs[i].surface = 0;
+ Glyphs[i].parent = this;
+ }
+
+ // Cache the first 127 ascii characters.
+ u32 old_size = batch_load_size;
+ batch_load_size = 127;
+ getGlyphIndexByChar((uchar32_t)0);
+ batch_load_size = old_size;
+
+ return true;
+}
+
+CGUITTFont::~CGUITTFont()
+{
+ // Delete the glyphs and glyph pages.
+ reset_images();
+ CGUITTAssistDelete::Delete(Glyphs);
+ //Glyphs.clear();
+
+ // We aren't using this face anymore.
+ core::map<io::path, SGUITTFace*>::Node* n = c_faces.find(filename);
+ if (n)
+ {
+ SGUITTFace* f = n->getValue();
+
+ // Drop our face. If this was the last face, the destructor will clean up.
+ if (f->drop())
+ c_faces.remove(filename);
+
+ // If there are no more faces referenced by FreeType, clean up.
+ if (c_faces.size() == 0)
+ {
+ FT_Done_FreeType(c_library);
+ c_libraryLoaded = false;
+ }
+ }
+
+ // Drop our driver now.
+ if (Driver)
+ Driver->drop();
+}
+
+void CGUITTFont::reset_images()
+{
+ // Delete the glyphs.
+ for (u32 i = 0; i != Glyphs.size(); ++i)
+ Glyphs[i].unload();
+
+ // Unload the glyph pages from video memory.
+ for (u32 i = 0; i != Glyph_Pages.size(); ++i)
+ delete Glyph_Pages[i];
+ Glyph_Pages.clear();
+
+ // Always update the internal FreeType loading flags after resetting.
+ update_load_flags();
+}
+
+void CGUITTFont::update_glyph_pages() const
+{
+ for (u32 i = 0; i != Glyph_Pages.size(); ++i)
+ {
+ if (Glyph_Pages[i]->dirty)
+ Glyph_Pages[i]->updateTexture();
+ }
+}
+
+CGUITTGlyphPage* CGUITTFont::getLastGlyphPage() const
+{
+ CGUITTGlyphPage* page = 0;
+ if (Glyph_Pages.empty())
+ return 0;
+ else
+ {
+ page = Glyph_Pages[getLastGlyphPageIndex()];
+ if (page->available_slots == 0)
+ page = 0;
+ }
+ return page;
+}
+
+CGUITTGlyphPage* CGUITTFont::createGlyphPage(const u8& pixel_mode)
+{
+ CGUITTGlyphPage* page = 0;
+
+ // Name of our page.
+ io::path name("TTFontGlyphPage_");
+ name += tt_face->family_name;
+ name += ".";
+ name += tt_face->style_name;
+ name += ".";
+ name += size;
+ name += "_";
+ name += Glyph_Pages.size(); // The newly created page will be at the end of the collection.
+
+ // Create the new page.
+ page = new CGUITTGlyphPage(Driver, name);
+
+ // Determine our maximum texture size.
+ // If we keep getting 0, set it to 1024x1024, as that number is pretty safe.
+ core::dimension2du max_texture_size = max_page_texture_size;
+ if (max_texture_size.Width == 0 || max_texture_size.Height == 0)
+ max_texture_size = Driver->getMaxTextureSize();
+ if (max_texture_size.Width == 0 || max_texture_size.Height == 0)
+ max_texture_size = core::dimension2du(1024, 1024);
+
+ // We want to try to put at least 144 glyphs on a single texture.
+ core::dimension2du page_texture_size;
+ if (size <= 21) page_texture_size = core::dimension2du(256, 256);
+ else if (size <= 42) page_texture_size = core::dimension2du(512, 512);
+ else if (size <= 84) page_texture_size = core::dimension2du(1024, 1024);
+ else if (size <= 168) page_texture_size = core::dimension2du(2048, 2048);
+ else page_texture_size = core::dimension2du(4096, 4096);
+
+ if (page_texture_size.Width > max_texture_size.Width || page_texture_size.Height > max_texture_size.Height)
+ page_texture_size = max_texture_size;
+
+ if (!page->createPageTexture(pixel_mode, page_texture_size))
+ // TODO: add error message?
+ return 0;
+
+ if (page)
+ {
+ // Determine the number of glyph slots on the page and add it to the list of pages.
+ page->available_slots = (page_texture_size.Width / size) * (page_texture_size.Height / size);
+ Glyph_Pages.push_back(page);
+ }
+ return page;
+}
+
+void CGUITTFont::setTransparency(const bool flag)
+{
+ use_transparency = flag;
+ reset_images();
+}
+
+void CGUITTFont::setMonochrome(const bool flag)
+{
+ use_monochrome = flag;
+ reset_images();
+}
+
+void CGUITTFont::setFontHinting(const bool enable, const bool enable_auto_hinting)
+{
+ use_hinting = enable;
+ use_auto_hinting = enable_auto_hinting;
+ reset_images();
+}
+
+void CGUITTFont::draw(const core::stringw& text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip)
+{
+ if (!Driver)
+ return;
+
+ // Clear the glyph pages of their render information.
+ for (u32 i = 0; i < Glyph_Pages.size(); ++i)
+ {
+ Glyph_Pages[i]->render_positions.clear();
+ Glyph_Pages[i]->render_source_rects.clear();
+ }
+
+ // Set up some variables.
+ core::dimension2d<s32> textDimension;
+ core::position2d<s32> offset = position.UpperLeftCorner;
+
+ // Determine offset positions.
+ if (hcenter || vcenter)
+ {
+ textDimension = getDimension(text.c_str());
+
+ if (hcenter)
+ offset.X = ((position.getWidth() - textDimension.Width) >> 1) + offset.X;
+
+ if (vcenter)
+ offset.Y = ((position.getHeight() - textDimension.Height) >> 1) + offset.Y;
+ }
+
+ // Convert to a unicode string.
+ core::ustring utext(text);
+
+ // Set up our render map.
+ core::map<u32, CGUITTGlyphPage*> Render_Map;
+
+ // Start parsing characters.
+ u32 n;
+ uchar32_t previousChar = 0;
+ core::ustring::const_iterator iter(utext);
+ while (!iter.atEnd())
+ {
+ uchar32_t currentChar = *iter;
+ n = getGlyphIndexByChar(currentChar);
+ bool visible = (Invisible.findFirst(currentChar) == -1);
+ if (n > 0 && visible)
+ {
+ bool lineBreak=false;
+ if (currentChar == L'\r') // Mac or Windows breaks
+ {
+ lineBreak = true;
+ if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks.
+ currentChar = *(++iter);
+ }
+ else if (currentChar == (uchar32_t)'\n') // Unix breaks
+ {
+ lineBreak = true;
+ }
+
+ if (lineBreak)
+ {
+ previousChar = 0;
+ offset.Y += font_metrics.ascender / 64;
+ offset.X = position.UpperLeftCorner.X;
+
+ if (hcenter)
+ offset.X += (position.getWidth() - textDimension.Width) >> 1;
+ ++iter;
+ continue;
+ }
+
+ // Calculate the glyph offset.
+ s32 offx = Glyphs[n-1].offset.X;
+ s32 offy = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y;
+
+ // Apply kerning.
+ core::vector2di k = getKerning(currentChar, previousChar);
+ offset.X += k.X;
+ offset.Y += k.Y;
+
+ // Determine rendering information.
+ SGUITTGlyph& glyph = Glyphs[n-1];
+ CGUITTGlyphPage* const page = Glyph_Pages[glyph.glyph_page];
+ page->render_positions.push_back(core::position2di(offset.X + offx, offset.Y + offy));
+ page->render_source_rects.push_back(glyph.source_rect);
+ Render_Map.set(glyph.glyph_page, page);
+ }
+ offset.X += getWidthFromCharacter(currentChar);
+
+ previousChar = currentChar;
+ ++iter;
+ }
+
+ // Draw now.
+ update_glyph_pages();
+ core::map<u32, CGUITTGlyphPage*>::Iterator j = Render_Map.getIterator();
+ while (!j.atEnd())
+ {
+ core::map<u32, CGUITTGlyphPage*>::Node* n = j.getNode();
+ j++;
+ if (n == 0) continue;
+
+ CGUITTGlyphPage* page = n->getValue();
+
+ if (!use_transparency) color.color |= 0xff000000;
+ Driver->draw2DImageBatch(page->texture, page->render_positions, page->render_source_rects, clip, color, true);
+ }
+}
+
+core::dimension2d<u32> CGUITTFont::getCharDimension(const wchar_t ch) const
+{
+ return core::dimension2d<u32>(getWidthFromCharacter(ch), getHeightFromCharacter(ch));
+}
+
+core::dimension2d<u32> CGUITTFont::getDimension(const wchar_t* text) const
+{
+ return getDimension(core::ustring(text));
+}
+
+core::dimension2d<u32> CGUITTFont::getDimension(const core::ustring& text) const
+{
+ // Get the maximum font height. Unfortunately, we have to do this hack as
+ // Irrlicht will draw things wrong. In FreeType, the font size is the
+ // maximum size for a single glyph, but that glyph may hang "under" the
+ // draw line, increasing the total font height to beyond the set size.
+ // Irrlicht does not understand this concept when drawing fonts. Also, I
+ // add +1 to give it a 1 pixel blank border. This makes things like
+ // tooltips look nicer.
+ s32 test1 = getHeightFromCharacter((uchar32_t)'g') + 1;
+ s32 test2 = getHeightFromCharacter((uchar32_t)'j') + 1;
+ s32 test3 = getHeightFromCharacter((uchar32_t)'_') + 1;
+ s32 max_font_height = core::max_(test1, core::max_(test2, test3));
+
+ core::dimension2d<u32> text_dimension(0, max_font_height);
+ core::dimension2d<u32> line(0, max_font_height);
+
+ uchar32_t previousChar = 0;
+ core::ustring::const_iterator iter = text.begin();
+ for (; !iter.atEnd(); ++iter)
+ {
+ uchar32_t p = *iter;
+ bool lineBreak = false;
+ if (p == '\r') // Mac or Windows line breaks.
+ {
+ lineBreak = true;
+ if (*(iter + 1) == '\n')
+ {
+ ++iter;
+ p = *iter;
+ }
+ }
+ else if (p == '\n') // Unix line breaks.
+ {
+ lineBreak = true;
+ }
+
+ // Kerning.
+ core::vector2di k = getKerning(p, previousChar);
+ line.Width += k.X;
+ previousChar = p;
+
+ // Check for linebreak.
+ if (lineBreak)
+ {
+ previousChar = 0;
+ text_dimension.Height += line.Height;
+ if (text_dimension.Width < line.Width)
+ text_dimension.Width = line.Width;
+ line.Width = 0;
+ line.Height = max_font_height;
+ continue;
+ }
+ line.Width += getWidthFromCharacter(p);
+ }
+ if (text_dimension.Width < line.Width)
+ text_dimension.Width = line.Width;
+
+ return text_dimension;
+}
+
+inline u32 CGUITTFont::getWidthFromCharacter(wchar_t c) const
+{
+ return getWidthFromCharacter((uchar32_t)c);
+}
+
+inline u32 CGUITTFont::getWidthFromCharacter(uchar32_t c) const
+{
+ // Set the size of the face.
+ // This is because we cache faces and the face may have been set to a different size.
+ //FT_Set_Pixel_Sizes(tt_face, 0, size);
+
+ u32 n = getGlyphIndexByChar(c);
+ if (n > 0)
+ {
+ int w = Glyphs[n-1].advance.x / 64;
+ return w;
+ }
+ if (c >= 0x2000)
+ return (font_metrics.ascender / 64);
+ else return (font_metrics.ascender / 64) / 2;
+}
+
+inline u32 CGUITTFont::getHeightFromCharacter(wchar_t c) const
+{
+ return getHeightFromCharacter((uchar32_t)c);
+}
+
+inline u32 CGUITTFont::getHeightFromCharacter(uchar32_t c) const
+{
+ // Set the size of the face.
+ // This is because we cache faces and the face may have been set to a different size.
+ //FT_Set_Pixel_Sizes(tt_face, 0, size);
+
+ u32 n = getGlyphIndexByChar(c);
+ if (n > 0)
+ {
+ // Grab the true height of the character, taking into account underhanging glyphs.
+ s32 height = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y + Glyphs[n-1].source_rect.getHeight();
+ return height;
+ }
+ if (c >= 0x2000)
+ return (font_metrics.ascender / 64);
+ else return (font_metrics.ascender / 64) / 2;
+}
+
+u32 CGUITTFont::getGlyphIndexByChar(wchar_t c) const
+{
+ return getGlyphIndexByChar((uchar32_t)c);
+}
+
+u32 CGUITTFont::getGlyphIndexByChar(uchar32_t c) const
+{
+ // Get the glyph.
+ u32 glyph = FT_Get_Char_Index(tt_face, c);
+
+ // Check for a valid glyph. If it is invalid, attempt to use the replacement character.
+ if (glyph == 0)
+ glyph = FT_Get_Char_Index(tt_face, core::unicode::UTF_REPLACEMENT_CHARACTER);
+
+ // If our glyph is already loaded, don't bother doing any batch loading code.
+ if (glyph != 0 && Glyphs[glyph - 1].isLoaded)
+ return glyph;
+
+ // Determine our batch loading positions.
+ u32 half_size = (batch_load_size / 2);
+ u32 start_pos = 0;
+ if (c > half_size) start_pos = c - half_size;
+ u32 end_pos = start_pos + batch_load_size;
+
+ // Load all our characters.
+ do
+ {
+ // Get the character we are going to load.
+ u32 char_index = FT_Get_Char_Index(tt_face, start_pos);
+
+ // If the glyph hasn't been loaded yet, do it now.
+ if (char_index)
+ {
+ SGUITTGlyph& glyph = Glyphs[char_index - 1];
+ if (!glyph.isLoaded)
+ {
+ glyph.preload(char_index, tt_face, Driver, size, load_flags);
+ Glyph_Pages[glyph.glyph_page]->pushGlyphToBePaged(&glyph);
+ }
+ }
+ }
+ while (++start_pos < end_pos);
+
+ // Return our original character.
+ return glyph;
+}
+
+s32 CGUITTFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const
+{
+ return getCharacterFromPos(core::ustring(text), pixel_x);
+}
+
+s32 CGUITTFont::getCharacterFromPos(const core::ustring& text, s32 pixel_x) const
+{
+ s32 x = 0;
+ //s32 idx = 0;
+
+ u32 character = 0;
+ uchar32_t previousChar = 0;
+ core::ustring::const_iterator iter = text.begin();
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ x += getWidthFromCharacter(c);
+
+ // Kerning.
+ core::vector2di k = getKerning(c, previousChar);
+ x += k.X;
+
+ if (x >= pixel_x)
+ return character;
+
+ previousChar = c;
+ ++iter;
+ ++character;
+ }
+
+ return -1;
+}
+
+void CGUITTFont::setKerningWidth(s32 kerning)
+{
+ GlobalKerningWidth = kerning;
+}
+
+void CGUITTFont::setKerningHeight(s32 kerning)
+{
+ GlobalKerningHeight = kerning;
+}
+
+s32 CGUITTFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previousLetter) const
+{
+ if (tt_face == 0)
+ return GlobalKerningWidth;
+ if (thisLetter == 0 || previousLetter == 0)
+ return 0;
+
+ return getKerningWidth((uchar32_t)*thisLetter, (uchar32_t)*previousLetter);
+}
+
+s32 CGUITTFont::getKerningWidth(const uchar32_t thisLetter, const uchar32_t previousLetter) const
+{
+ // Return only the kerning width.
+ return getKerning(thisLetter, previousLetter).X;
+}
+
+s32 CGUITTFont::getKerningHeight() const
+{
+ // FreeType 2 currently doesn't return any height kerning information.
+ return GlobalKerningHeight;
+}
+
+core::vector2di CGUITTFont::getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const
+{
+ return getKerning((uchar32_t)thisLetter, (uchar32_t)previousLetter);
+}
+
+core::vector2di CGUITTFont::getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const
+{
+ if (tt_face == 0 || thisLetter == 0 || previousLetter == 0)
+ return core::vector2di();
+
+ // Set the size of the face.
+ // This is because we cache faces and the face may have been set to a different size.
+ FT_Set_Pixel_Sizes(tt_face, 0, size);
+
+ core::vector2di ret(GlobalKerningWidth, GlobalKerningHeight);
+
+ // If we don't have kerning, no point in continuing.
+ if (!FT_HAS_KERNING(tt_face))
+ return ret;
+
+ // Get the kerning information.
+ FT_Vector v;
+ FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), getGlyphIndexByChar(thisLetter), FT_KERNING_DEFAULT, &v);
+
+ // If we have a scalable font, the return value will be in font points.
+ if (FT_IS_SCALABLE(tt_face))
+ {
+ // Font points, so divide by 64.
+ ret.X += (v.x / 64);
+ ret.Y += (v.y / 64);
+ }
+ else
+ {
+ // Pixel units.
+ ret.X += v.x;
+ ret.Y += v.y;
+ }
+ return ret;
+}
+
+void CGUITTFont::setInvisibleCharacters(const wchar_t *s)
+{
+ core::ustring us(s);
+ Invisible = us;
+}
+
+void CGUITTFont::setInvisibleCharacters(const core::ustring& s)
+{
+ Invisible = s;
+}
+
+video::IImage* CGUITTFont::createTextureFromChar(const uchar32_t& ch)
+{
+ u32 n = getGlyphIndexByChar(ch);
+ const SGUITTGlyph& glyph = Glyphs[n-1];
+ CGUITTGlyphPage* page = Glyph_Pages[glyph.glyph_page];
+
+ if (page->dirty)
+ page->updateTexture();
+
+ video::ITexture* tex = page->texture;
+
+ // Acquire a read-only lock of the corresponding page texture.
+ #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8
+ void* ptr = tex->lock(video::ETLM_READ_ONLY);
+ #else
+ void* ptr = tex->lock(true);
+ #endif
+
+ video::ECOLOR_FORMAT format = tex->getColorFormat();
+ core::dimension2du tex_size = tex->getOriginalSize();
+ video::IImage* pageholder = Driver->createImageFromData(format, tex_size, ptr, true, false);
+
+ // Copy the image data out of the page texture.
+ core::dimension2du glyph_size(glyph.source_rect.getSize());
+ video::IImage* image = Driver->createImage(format, glyph_size);
+ pageholder->copyTo(image, core::position2di(0, 0), glyph.source_rect);
+
+ tex->unlock();
+ return image;
+}
+
+video::ITexture* CGUITTFont::getPageTextureByIndex(const u32& page_index) const
+{
+ if (page_index < Glyph_Pages.size())
+ return Glyph_Pages[page_index]->texture;
+ else
+ return 0;
+}
+
+void CGUITTFont::createSharedPlane()
+{
+ /*
+ 2___3
+ | /|
+ | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, -1)
+ |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, 1)
+ 0---1
+ */
+
+ using namespace core;
+ using namespace video;
+ using namespace scene;
+ S3DVertex vertices[4];
+ u16 indices[6] = {0,2,3,3,1,0};
+ vertices[0] = S3DVertex(vector3df(0,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,1));
+ vertices[1] = S3DVertex(vector3df(1,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,1));
+ vertices[2] = S3DVertex(vector3df(0, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,0));
+ vertices[3] = S3DVertex(vector3df(1, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,0));
+
+ SMeshBuffer* buf = new SMeshBuffer();
+ buf->append(vertices, 4, indices, 6);
+
+ shared_plane_.addMeshBuffer( buf );
+
+ shared_plane_ptr_ = &shared_plane_;
+ buf->drop(); //the addMeshBuffer method will grab it, so we can drop this ptr.
+}
+
+core::dimension2d<u32> CGUITTFont::getDimensionUntilEndOfLine(const wchar_t* p) const
+{
+ core::stringw s;
+ for (const wchar_t* temp = p; temp && *temp != '\0' && *temp != L'\r' && *temp != L'\n'; ++temp )
+ s.append(*temp);
+
+ return getDimension(s.c_str());
+}
+
+core::array<scene::ISceneNode*> CGUITTFont::addTextSceneNode(const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent, const video::SColor& color, bool center)
+{
+ using namespace core;
+ using namespace video;
+ using namespace scene;
+
+ array<scene::ISceneNode*> container;
+
+ if (!Driver || !smgr) return container;
+ if (!parent)
+ parent = smgr->addEmptySceneNode(smgr->getRootSceneNode(), -1);
+ // if you don't specify parent, then we add a empty node attached to the root node
+ // this is generally undesirable.
+
+ if (!shared_plane_ptr_) //this points to a static mesh that contains the plane
+ createSharedPlane(); //if it's not initialized, we create one.
+
+ dimension2d<s32> text_size(getDimension(text)); //convert from unsigned to signed.
+ vector3df start_point(0, 0, 0), offset;
+
+ /** NOTICE:
+ Because we are considering adding texts into 3D world, all Y axis vectors are inverted.
+ **/
+
+ // There's currently no "vertical center" concept when you apply text scene node to the 3D world.
+ if (center)
+ {
+ offset.X = start_point.X = -text_size.Width / 2.f;
+ offset.Y = start_point.Y = +text_size.Height/ 2.f;
+ offset.X += (text_size.Width - getDimensionUntilEndOfLine(text).Width) >> 1;
+ }
+
+ // the default font material
+ SMaterial mat;
+ mat.setFlag(video::EMF_LIGHTING, true);
+ mat.setFlag(video::EMF_ZWRITE_ENABLE, false);
+ mat.setFlag(video::EMF_NORMALIZE_NORMALS, true);
+ mat.ColorMaterial = video::ECM_NONE;
+ mat.MaterialType = use_transparency ? video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_SOLID;
+ mat.MaterialTypeParam = 0.01f;
+ mat.DiffuseColor = color;
+
+ wchar_t current_char = 0, previous_char = 0;
+ u32 n = 0;
+
+ array<u32> glyph_indices;
+
+ while (*text)
+ {
+ current_char = *text;
+ bool line_break=false;
+ if (current_char == L'\r') // Mac or Windows breaks
+ {
+ line_break = true;
+ if (*(text + 1) == L'\n') // Windows line breaks.
+ current_char = *(++text);
+ }
+ else if (current_char == L'\n') // Unix breaks
+ {
+ line_break = true;
+ }
+
+ if (line_break)
+ {
+ previous_char = 0;
+ offset.Y -= tt_face->size->metrics.ascender / 64;
+ offset.X = start_point.X;
+ if (center)
+ offset.X += (text_size.Width - getDimensionUntilEndOfLine(text+1).Width) >> 1;
+ ++text;
+ }
+ else
+ {
+ n = getGlyphIndexByChar(current_char);
+ if (n > 0)
+ {
+ glyph_indices.push_back( n );
+
+ // Store glyph size and offset informations.
+ SGUITTGlyph const& glyph = Glyphs[n-1];
+ u32 texw = glyph.source_rect.getWidth();
+ u32 texh = glyph.source_rect.getHeight();
+ s32 offx = glyph.offset.X;
+ s32 offy = (font_metrics.ascender / 64) - glyph.offset.Y;
+
+ // Apply kerning.
+ vector2di k = getKerning(current_char, previous_char);
+ offset.X += k.X;
+ offset.Y += k.Y;
+
+ vector3df current_pos(offset.X + offx, offset.Y - offy, 0);
+ dimension2d<u32> letter_size = dimension2d<u32>(texw, texh);
+
+ // Now we copy planes corresponding to the letter size.
+ IMeshManipulator* mani = smgr->getMeshManipulator();
+ IMesh* meshcopy = mani->createMeshCopy(shared_plane_ptr_);
+ #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8
+ mani->scale(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1));
+ #else
+ mani->scaleMesh(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1));
+ #endif
+
+ ISceneNode* current_node = smgr->addMeshSceneNode(meshcopy, parent, -1, current_pos);
+ meshcopy->drop();
+
+ current_node->getMaterial(0) = mat;
+ current_node->setAutomaticCulling(EAC_OFF);
+ current_node->setIsDebugObject(true); //so the picking won't have any effect on individual letter
+ //current_node->setDebugDataVisible(EDS_BBOX); //de-comment this when debugging
+
+ container.push_back(current_node);
+ }
+ offset.X += getWidthFromCharacter(current_char);
+ previous_char = current_char;
+ ++text;
+ }
+ }
+
+ update_glyph_pages();
+ //only after we update the textures can we use the glyph page textures.
+
+ for (u32 i = 0; i < glyph_indices.size(); ++i)
+ {
+ u32 n = glyph_indices[i];
+ SGUITTGlyph const& glyph = Glyphs[n-1];
+ ITexture* current_tex = Glyph_Pages[glyph.glyph_page]->texture;
+ f32 page_texture_size = (f32)current_tex->getSize().Width;
+ //Now we calculate the UV position according to the texture size and the source rect.
+ //
+ // 2___3
+ // | /|
+ // | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, -1)
+ // |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, 1)
+ // 0---1
+ //
+ f32 u1 = glyph.source_rect.UpperLeftCorner.X / page_texture_size;
+ f32 u2 = u1 + (glyph.source_rect.getWidth() / page_texture_size);
+ f32 v1 = glyph.source_rect.UpperLeftCorner.Y / page_texture_size;
+ f32 v2 = v1 + (glyph.source_rect.getHeight() / page_texture_size);
+
+ //we can be quite sure that this is IMeshSceneNode, because we just added them in the above loop.
+ IMeshSceneNode* node = static_cast<IMeshSceneNode*>(container[i]);
+
+ S3DVertex* pv = static_cast<S3DVertex*>(node->getMesh()->getMeshBuffer(0)->getVertices());
+ //pv[0].TCoords.Y = pv[1].TCoords.Y = (letter_size.Height - 1) / static_cast<f32>(letter_size.Height);
+ //pv[1].TCoords.X = pv[3].TCoords.X = (letter_size.Width - 1) / static_cast<f32>(letter_size.Width);
+ pv[0].TCoords = vector2df(u1, v2);
+ pv[1].TCoords = vector2df(u2, v2);
+ pv[2].TCoords = vector2df(u1, v1);
+ pv[3].TCoords = vector2df(u2, v1);
+
+ container[i]->getMaterial(0).setTexture(0, current_tex);
+ }
+
+ return container;
+}
+
+} // end namespace gui
+} // end namespace irr
diff --git a/src/cguittfont/CGUITTFont.h b/src/cguittfont/CGUITTFont.h
new file mode 100644
index 000000000..12e25e0f3
--- /dev/null
+++ b/src/cguittfont/CGUITTFont.h
@@ -0,0 +1,377 @@
+/*
+ CGUITTFont FreeType class for Irrlicht
+ Copyright (c) 2009-2010 John Norman
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any
+ damages arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any
+ purpose, including commercial applications, and to alter it and
+ redistribute it freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you use
+ this software in a product, an acknowledgment in the product
+ documentation would be appreciated but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and
+ must not be misrepresented as being the original software.
+
+ 3. This notice may not be removed or altered from any source
+ distribution.
+
+ The original version of this class can be located at:
+ http://irrlicht.suckerfreegames.com/
+
+ John Norman
+ john@suckerfreegames.com
+*/
+
+#ifndef __C_GUI_TTFONT_H_INCLUDED__
+#define __C_GUI_TTFONT_H_INCLUDED__
+
+#include <irrlicht.h>
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+namespace irr
+{
+namespace gui
+{
+ struct SGUITTFace;
+ class CGUITTFont;
+
+ //! Class to assist in deleting glyphs.
+ class CGUITTAssistDelete
+ {
+ public:
+ template <class T, typename TAlloc>
+ static void Delete(core::array<T, TAlloc>& a)
+ {
+ TAlloc allocator;
+ allocator.deallocate(a.pointer());
+ }
+ };
+
+ //! Structure representing a single TrueType glyph.
+ struct SGUITTGlyph
+ {
+ //! Constructor.
+ SGUITTGlyph() : isLoaded(false), glyph_page(0), surface(0), parent(0) {}
+
+ //! Destructor.
+ ~SGUITTGlyph() { unload(); }
+
+ //! Preload the glyph.
+ //! The preload process occurs when the program tries to cache the glyph from FT_Library.
+ //! However, it simply defines the SGUITTGlyph's properties and will only create the page
+ //! textures if necessary. The actual creation of the textures should only occur right
+ //! before the batch draw call.
+ void preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags);
+
+ //! Unloads the glyph.
+ void unload();
+
+ //! Creates the IImage object from the FT_Bitmap.
+ video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const;
+
+ //! If true, the glyph has been loaded.
+ bool isLoaded;
+
+ //! The page the glyph is on.
+ u32 glyph_page;
+
+ //! The source rectangle for the glyph.
+ core::recti source_rect;
+
+ //! The offset of glyph when drawn.
+ core::vector2di offset;
+
+ //! Glyph advance information.
+ FT_Vector advance;
+
+ //! This is just the temporary image holder. After this glyph is paged,
+ //! it will be dropped.
+ mutable video::IImage* surface;
+
+ //! The pointer pointing to the parent (CGUITTFont)
+ CGUITTFont* parent;
+ };
+
+ //! Holds a sheet of glyphs.
+ class CGUITTGlyphPage
+ {
+ public:
+ CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {}
+ ~CGUITTGlyphPage()
+ {
+ if (texture)
+ {
+ if (driver)
+ driver->removeTexture(texture);
+ else texture->drop();
+ }
+ }
+
+ //! Create the actual page texture,
+ bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size)
+ {
+ if( texture )
+ return false;
+
+ bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
+ driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
+
+ // Set the texture color format.
+ switch (pixel_mode)
+ {
+ case FT_PIXEL_MODE_MONO:
+ texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5);
+ break;
+ case FT_PIXEL_MODE_GRAY:
+ default:
+ texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8);
+ break;
+ }
+
+ // Restore our texture creation flags.
+ driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip);
+ return texture ? true : false;
+ }
+
+ //! Add the glyph to a list of glyphs to be paged.
+ //! This collection will be cleared after updateTexture is called.
+ void pushGlyphToBePaged(const SGUITTGlyph* glyph)
+ {
+ glyph_to_be_paged.push_back(glyph);
+ }
+
+ //! Updates the texture atlas with new glyphs.
+ void updateTexture()
+ {
+ if (!dirty) return;
+
+ void* ptr = texture->lock();
+ video::ECOLOR_FORMAT format = texture->getColorFormat();
+ core::dimension2du size = texture->getOriginalSize();
+ video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false);
+
+ for (u32 i = 0; i < glyph_to_be_paged.size(); ++i)
+ {
+ const SGUITTGlyph* glyph = glyph_to_be_paged[i];
+ if (glyph && glyph->isLoaded)
+ {
+ if (glyph->surface)
+ {
+ glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner);
+ glyph->surface->drop();
+ glyph->surface = 0;
+ }
+ else
+ {
+ ; // TODO: add error message?
+ //currently, if we failed to create the image, just ignore this operation.
+ }
+ }
+ }
+
+ pageholder->drop();
+ texture->unlock();
+ glyph_to_be_paged.clear();
+ dirty = false;
+ }
+
+ video::ITexture* texture;
+ u32 available_slots;
+ u32 used_slots;
+ bool dirty;
+
+ core::array<core::vector2di> render_positions;
+ core::array<core::recti> render_source_rects;
+
+ private:
+ core::array<const SGUITTGlyph*> glyph_to_be_paged;
+ video::IVideoDriver* driver;
+ io::path name;
+ };
+
+ //! Class representing a TrueType font.
+ class CGUITTFont : public IGUIFont
+ {
+ public:
+ //! Creates a new TrueType font and returns a pointer to it. The pointer must be drop()'ed when finished.
+ //! \param env The IGUIEnvironment the font loads out of.
+ //! \param filename The filename of the font.
+ //! \param size The size of the font glyphs in pixels. Since this is the size of the individual glyphs, the true height of the font may change depending on the characters used.
+ //! \param antialias set the use_monochrome (opposite to antialias) flag
+ //! \param transparency set the use_transparency flag
+ //! \return Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load.
+ static CGUITTFont* createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
+ static CGUITTFont* createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
+ static CGUITTFont* create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
+ static CGUITTFont* create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
+
+ //! Destructor
+ virtual ~CGUITTFont();
+
+ //! Sets the amount of glyphs to batch load.
+ virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; }
+
+ //! Sets the maximum texture size for a page of glyphs.
+ virtual void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; }
+
+ //! Get the font size.
+ virtual u32 getFontSize() const { return size; }
+
+ //! Check the font's transparency.
+ virtual bool isTransparent() const { return use_transparency; }
+
+ //! Check if the font auto-hinting is enabled.
+ //! Auto-hinting is FreeType's built-in font hinting engine.
+ virtual bool useAutoHinting() const { return use_auto_hinting; }
+
+ //! Check if the font hinting is enabled.
+ virtual bool useHinting() const { return use_hinting; }
+
+ //! Check if the font is being loaded as a monochrome font.
+ //! The font can either be a 256 color grayscale font, or a 2 color monochrome font.
+ virtual bool useMonochrome() const { return use_monochrome; }
+
+ //! Tells the font to allow transparency when rendering.
+ //! Default: true.
+ //! \param flag If true, the font draws using transparency.
+ virtual void setTransparency(const bool flag);
+
+ //! Tells the font to use monochrome rendering.
+ //! Default: false.
+ //! \param flag If true, the font draws using a monochrome image. If false, the font uses a grayscale image.
+ virtual void setMonochrome(const bool flag);
+
+ //! Enables or disables font hinting.
+ //! Default: Hinting and auto-hinting true.
+ //! \param enable If false, font hinting is turned off. If true, font hinting is turned on.
+ //! \param enable_auto_hinting If true, FreeType uses its own auto-hinting algorithm. If false, it tries to use the algorithm specified by the font.
+ virtual void setFontHinting(const bool enable, const bool enable_auto_hinting = true);
+
+ //! Draws some text and clips it to the specified rectangle if wanted.
+ virtual void draw(const core::stringw& text, const core::rect<s32>& position,
+ video::SColor color, bool hcenter=false, bool vcenter=false,
+ const core::rect<s32>* clip=0);
+
+ //! Returns the dimension of a character produced by this font.
+ virtual core::dimension2d<u32> getCharDimension(const wchar_t ch) const;
+
+ //! Returns the dimension of a text string.
+ virtual core::dimension2d<u32> getDimension(const wchar_t* text) const;
+ virtual core::dimension2d<u32> getDimension(const core::ustring& text) const;
+
+ //! Calculates the index of the character in the text which is on a specific position.
+ virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const;
+ virtual s32 getCharacterFromPos(const core::ustring& text, s32 pixel_x) const;
+
+ //! Sets global kerning width for the font.
+ virtual void setKerningWidth(s32 kerning);
+
+ //! Sets global kerning height for the font.
+ virtual void setKerningHeight(s32 kerning);
+
+ //! Gets kerning values (distance between letters) for the font. If no parameters are provided,
+ virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const;
+ virtual s32 getKerningWidth(const uchar32_t thisLetter=0, const uchar32_t previousLetter=0) const;
+
+ //! Returns the distance between letters
+ virtual s32 getKerningHeight() const;
+
+ //! Define which characters should not be drawn by the font.
+ virtual void setInvisibleCharacters(const wchar_t *s);
+ virtual void setInvisibleCharacters(const core::ustring& s);
+
+ //! Get the last glyph page if there's still available slots.
+ //! If not, it will return zero.
+ CGUITTGlyphPage* getLastGlyphPage() const;
+
+ //! Create a new glyph page texture.
+ //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode
+ //should be better typed. fix later.
+ CGUITTGlyphPage* createGlyphPage(const u8& pixel_mode);
+
+ //! Get the last glyph page's index.
+ u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; }
+
+ //! Create corresponding character's software image copy from the font,
+ //! so you can use this data just like any ordinary video::IImage.
+ //! \param ch The character you need
+ virtual video::IImage* createTextureFromChar(const uchar32_t& ch);
+
+ //! This function is for debugging mostly. If the page doesn't exist it returns zero.
+ //! \param page_index Simply return the texture handle of a given page index.
+ virtual video::ITexture* getPageTextureByIndex(const u32& page_index) const;
+
+ //! Add a list of scene nodes generated by putting font textures on the 3D planes.
+ virtual core::array<scene::ISceneNode*> addTextSceneNode
+ (const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent = 0,
+ const video::SColor& color = video::SColor(255, 0, 0, 0), bool center = false );
+
+ protected:
+ bool use_monochrome;
+ bool use_transparency;
+ bool use_hinting;
+ bool use_auto_hinting;
+ u32 size;
+ u32 batch_load_size;
+ core::dimension2du max_page_texture_size;
+
+ private:
+ // Manages the FreeType library.
+ static FT_Library c_library;
+ static core::map<io::path, SGUITTFace*> c_faces;
+ static bool c_libraryLoaded;
+ static scene::IMesh* shared_plane_ptr_;
+ static scene::SMesh shared_plane_;
+
+ CGUITTFont(IGUIEnvironment *env);
+ bool load(const io::path& filename, const u32 size, const bool antialias, const bool transparency);
+ void reset_images();
+ void update_glyph_pages() const;
+ void update_load_flags()
+ {
+ // Set up our loading flags.
+ load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER;
+ if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING;
+ if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT;
+ if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO | FT_RENDER_MODE_MONO;
+ else load_flags |= FT_LOAD_TARGET_NORMAL;
+ }
+ u32 getWidthFromCharacter(wchar_t c) const;
+ u32 getWidthFromCharacter(uchar32_t c) const;
+ u32 getHeightFromCharacter(wchar_t c) const;
+ u32 getHeightFromCharacter(uchar32_t c) const;
+ u32 getGlyphIndexByChar(wchar_t c) const;
+ u32 getGlyphIndexByChar(uchar32_t c) const;
+ core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const;
+ core::vector2di getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const;
+ core::dimension2d<u32> getDimensionUntilEndOfLine(const wchar_t* p) const;
+
+ void createSharedPlane();
+
+ irr::IrrlichtDevice* Device;
+ gui::IGUIEnvironment* Environment;
+ video::IVideoDriver* Driver;
+ io::path filename;
+ FT_Face tt_face;
+ FT_Size_Metrics font_metrics;
+ FT_Int32 load_flags;
+
+ mutable core::array<CGUITTGlyphPage*> Glyph_Pages;
+ mutable core::array<SGUITTGlyph> Glyphs;
+
+ s32 GlobalKerningWidth;
+ s32 GlobalKerningHeight;
+ core::ustring Invisible;
+ };
+
+} // end namespace gui
+} // end namespace irr
+
+#endif // __C_GUI_TTFONT_H_INCLUDED__
diff --git a/src/cguittfont/CMakeLists.txt b/src/cguittfont/CMakeLists.txt
new file mode 100644
index 000000000..94d061462
--- /dev/null
+++ b/src/cguittfont/CMakeLists.txt
@@ -0,0 +1,17 @@
+include_directories(
+ ${IRRLICHT_INCLUDE_DIR}
+ ${FREETYPE_INCLUDE_DIRS}
+)
+
+# CGUITTFont authors, y u no include headers you use?
+# Do not add CGUITTFont.cpp to the line below.
+# xCGUITTFont.cpp is a wrapper file that includes
+# additional required headers.
+add_library(cguittfont xCGUITTFont.cpp)
+
+target_link_libraries(
+ cguittfont
+ ${IRRLICHT_LIBRARY}
+ ${FREETYPE_LIBRARY}
+ ${ZLIB_LIBRARIES} # needed by freetype, repeated here for safety
+)
diff --git a/src/cguittfont/irrUString.h b/src/cguittfont/irrUString.h
new file mode 100644
index 000000000..f41fa1f7b
--- /dev/null
+++ b/src/cguittfont/irrUString.h
@@ -0,0 +1,3877 @@
+/*
+ Basic Unicode string class for Irrlicht.
+ Copyright (c) 2009-2011 John Norman
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any
+ damages arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any
+ purpose, including commercial applications, and to alter it and
+ redistribute it freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you use
+ this software in a product, an acknowledgment in the product
+ documentation would be appreciated but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and
+ must not be misrepresented as being the original software.
+
+ 3. This notice may not be removed or altered from any source
+ distribution.
+
+ The original version of this class can be located at:
+ http://irrlicht.suckerfreegames.com/
+
+ John Norman
+ john@suckerfreegames.com
+*/
+
+#ifndef __IRR_USTRING_H_INCLUDED__
+#define __IRR_USTRING_H_INCLUDED__
+
+#if (__cplusplus > 199711L) || (_MSC_VER >= 1600) || defined(__GXX_EXPERIMENTAL_CXX0X__)
+# define USTRING_CPP0X
+# if defined(__GXX_EXPERIMENTAL_CXX0X__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)))
+# define USTRING_CPP0X_NEWLITERALS
+# endif
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef USTRING_CPP0X
+# include <utility>
+#endif
+
+#ifndef USTRING_NO_STL
+# include <string>
+# include <iterator>
+# include <ostream>
+#endif
+
+#include "irrTypes.h"
+#include "irrAllocator.h"
+#include "irrArray.h"
+#include "irrMath.h"
+#include "irrString.h"
+#include "path.h"
+
+//! UTF-16 surrogate start values.
+static const irr::u16 UTF16_HI_SURROGATE = 0xD800;
+static const irr::u16 UTF16_LO_SURROGATE = 0xDC00;
+
+//! Is a UTF-16 code point a surrogate?
+#define UTF16_IS_SURROGATE(c) (((c) & 0xF800) == 0xD800)
+#define UTF16_IS_SURROGATE_HI(c) (((c) & 0xFC00) == 0xD800)
+#define UTF16_IS_SURROGATE_LO(c) (((c) & 0xFC00) == 0xDC00)
+
+
+namespace irr
+{
+
+ // Define our character types.
+#ifdef USTRING_CPP0X_NEWLITERALS // C++0x
+ typedef char32_t uchar32_t;
+ typedef char16_t uchar16_t;
+ typedef char uchar8_t;
+#else
+ typedef u32 uchar32_t;
+ typedef u16 uchar16_t;
+ typedef u8 uchar8_t;
+#endif
+
+namespace core
+{
+
+namespace unicode
+{
+
+//! The unicode replacement character. Used to replace invalid characters.
+const irr::u16 UTF_REPLACEMENT_CHARACTER = 0xFFFD;
+
+//! Convert a UTF-16 surrogate pair into a UTF-32 character.
+//! \param high The high value of the pair.
+//! \param low The low value of the pair.
+//! \return The UTF-32 character expressed by the surrogate pair.
+inline uchar32_t toUTF32(uchar16_t high, uchar16_t low)
+{
+ // Convert the surrogate pair into a single UTF-32 character.
+ uchar32_t x = ((high & ((1 << 6) -1)) << 10) | (low & ((1 << 10) -1));
+ uchar32_t wu = ((high >> 6) & ((1 << 5) - 1)) + 1;
+ return (wu << 16) | x;
+}
+
+//! Swaps the endianness of a 16-bit value.
+//! \return The new value.
+inline uchar16_t swapEndian16(const uchar16_t& c)
+{
+ return ((c >> 8) & 0x00FF) | ((c << 8) & 0xFF00);
+}
+
+//! Swaps the endianness of a 32-bit value.
+//! \return The new value.
+inline uchar32_t swapEndian32(const uchar32_t& c)
+{
+ return ((c >> 24) & 0x000000FF) |
+ ((c >> 8) & 0x0000FF00) |
+ ((c << 8) & 0x00FF0000) |
+ ((c << 24) & 0xFF000000);
+}
+
+//! The Unicode byte order mark.
+const u16 BOM = 0xFEFF;
+
+//! The size of the Unicode byte order mark in terms of the Unicode character size.
+const u8 BOM_UTF8_LEN = 3;
+const u8 BOM_UTF16_LEN = 1;
+const u8 BOM_UTF32_LEN = 1;
+
+//! Unicode byte order marks for file operations.
+const u8 BOM_ENCODE_UTF8[3] = { 0xEF, 0xBB, 0xBF };
+const u8 BOM_ENCODE_UTF16_BE[2] = { 0xFE, 0xFF };
+const u8 BOM_ENCODE_UTF16_LE[2] = { 0xFF, 0xFE };
+const u8 BOM_ENCODE_UTF32_BE[4] = { 0x00, 0x00, 0xFE, 0xFF };
+const u8 BOM_ENCODE_UTF32_LE[4] = { 0xFF, 0xFE, 0x00, 0x00 };
+
+//! The size in bytes of the Unicode byte marks for file operations.
+const u8 BOM_ENCODE_UTF8_LEN = 3;
+const u8 BOM_ENCODE_UTF16_LEN = 2;
+const u8 BOM_ENCODE_UTF32_LEN = 4;
+
+//! Unicode encoding type.
+enum EUTF_ENCODE
+{
+ EUTFE_NONE = 0,
+ EUTFE_UTF8,
+ EUTFE_UTF16,
+ EUTFE_UTF16_LE,
+ EUTFE_UTF16_BE,
+ EUTFE_UTF32,
+ EUTFE_UTF32_LE,
+ EUTFE_UTF32_BE
+};
+
+//! Unicode endianness.
+enum EUTF_ENDIAN
+{
+ EUTFEE_NATIVE = 0,
+ EUTFEE_LITTLE,
+ EUTFEE_BIG
+};
+
+//! Returns the specified unicode byte order mark in a byte array.
+//! The byte order mark is the first few bytes in a text file that signifies its encoding.
+/** \param mode The Unicode encoding method that we want to get the byte order mark for.
+ If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system endianness. **/
+//! \return An array that contains a byte order mark.
+inline core::array<u8> getUnicodeBOM(EUTF_ENCODE mode)
+{
+#define COPY_ARRAY(source, size) \
+ memcpy(ret.pointer(), source, size); \
+ ret.set_used(size)
+
+ core::array<u8> ret(4);
+ switch (mode)
+ {
+ case EUTFE_UTF8:
+ COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN);
+ break;
+ case EUTFE_UTF16:
+ #ifdef __BIG_ENDIAN__
+ COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN);
+ #else
+ COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN);
+ #endif
+ break;
+ case EUTFE_UTF16_BE:
+ COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN);
+ break;
+ case EUTFE_UTF16_LE:
+ COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN);
+ break;
+ case EUTFE_UTF32:
+ #ifdef __BIG_ENDIAN__
+ COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN);
+ #else
+ COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN);
+ #endif
+ break;
+ case EUTFE_UTF32_BE:
+ COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN);
+ break;
+ case EUTFE_UTF32_LE:
+ COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN);
+ break;
+ }
+ return ret;
+
+#undef COPY_ARRAY
+}
+
+//! Detects if the given data stream starts with a unicode BOM.
+//! \param data The data stream to check.
+//! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was found.
+inline EUTF_ENCODE determineUnicodeBOM(const char* data)
+{
+ if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) return EUTFE_UTF8;
+ if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) return EUTFE_UTF16_BE;
+ if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) return EUTFE_UTF16_LE;
+ if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) return EUTFE_UTF32_BE;
+ if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) return EUTFE_UTF32_LE;
+ return EUTFE_NONE;
+}
+
+} // end namespace unicode
+
+
+//! UTF-16 string class.
+template <typename TAlloc = irrAllocator<uchar16_t> >
+class ustring16
+{
+public:
+
+ ///------------------///
+ /// iterator classes ///
+ ///------------------///
+
+ //! Access an element in a unicode string, allowing one to change it.
+ class _ustring16_iterator_access
+ {
+ public:
+ _ustring16_iterator_access(const ustring16<TAlloc>* s, u32 p) : ref(s), pos(p) {}
+
+ //! Allow the class to be interpreted as a single UTF-32 character.
+ operator uchar32_t() const
+ {
+ return _get();
+ }
+
+ //! Allow one to change the character in the unicode string.
+ //! \param c The new character to use.
+ //! \return Myself.
+ _ustring16_iterator_access& operator=(const uchar32_t c)
+ {
+ _set(c);
+ return *this;
+ }
+
+ //! Increments the value by 1.
+ //! \return Myself.
+ _ustring16_iterator_access& operator++()
+ {
+ _set(_get() + 1);
+ return *this;
+ }
+
+ //! Increments the value by 1, returning the old value.
+ //! \return A unicode character.
+ uchar32_t operator++(int)
+ {
+ uchar32_t old = _get();
+ _set(old + 1);
+ return old;
+ }
+
+ //! Decrements the value by 1.
+ //! \return Myself.
+ _ustring16_iterator_access& operator--()
+ {
+ _set(_get() - 1);
+ return *this;
+ }
+
+ //! Decrements the value by 1, returning the old value.
+ //! \return A unicode character.
+ uchar32_t operator--(int)
+ {
+ uchar32_t old = _get();
+ _set(old - 1);
+ return old;
+ }
+
+ //! Adds to the value by a specified amount.
+ //! \param val The amount to add to this character.
+ //! \return Myself.
+ _ustring16_iterator_access& operator+=(int val)
+ {
+ _set(_get() + val);
+ return *this;
+ }
+
+ //! Subtracts from the value by a specified amount.
+ //! \param val The amount to subtract from this character.
+ //! \return Myself.
+ _ustring16_iterator_access& operator-=(int val)
+ {
+ _set(_get() - val);
+ return *this;
+ }
+
+ //! Multiples the value by a specified amount.
+ //! \param val The amount to multiply this character by.
+ //! \return Myself.
+ _ustring16_iterator_access& operator*=(int val)
+ {
+ _set(_get() * val);
+ return *this;
+ }
+
+ //! Divides the value by a specified amount.
+ //! \param val The amount to divide this character by.
+ //! \return Myself.
+ _ustring16_iterator_access& operator/=(int val)
+ {
+ _set(_get() / val);
+ return *this;
+ }
+
+ //! Modulos the value by a specified amount.
+ //! \param val The amount to modulo this character by.
+ //! \return Myself.
+ _ustring16_iterator_access& operator%=(int val)
+ {
+ _set(_get() % val);
+ return *this;
+ }
+
+ //! Adds to the value by a specified amount.
+ //! \param val The amount to add to this character.
+ //! \return A unicode character.
+ uchar32_t operator+(int val) const
+ {
+ return _get() + val;
+ }
+
+ //! Subtracts from the value by a specified amount.
+ //! \param val The amount to subtract from this character.
+ //! \return A unicode character.
+ uchar32_t operator-(int val) const
+ {
+ return _get() - val;
+ }
+
+ //! Multiplies the value by a specified amount.
+ //! \param val The amount to multiply this character by.
+ //! \return A unicode character.
+ uchar32_t operator*(int val) const
+ {
+ return _get() * val;
+ }
+
+ //! Divides the value by a specified amount.
+ //! \param val The amount to divide this character by.
+ //! \return A unicode character.
+ uchar32_t operator/(int val) const
+ {
+ return _get() / val;
+ }
+
+ //! Modulos the value by a specified amount.
+ //! \param val The amount to modulo this character by.
+ //! \return A unicode character.
+ uchar32_t operator%(int val) const
+ {
+ return _get() % val;
+ }
+
+ private:
+ //! Gets a uchar32_t from our current position.
+ uchar32_t _get() const
+ {
+ const uchar16_t* a = ref->c_str();
+ if (!UTF16_IS_SURROGATE(a[pos]))
+ return static_cast<uchar32_t>(a[pos]);
+ else
+ {
+ if (pos + 1 >= ref->size_raw())
+ return 0;
+
+ return unicode::toUTF32(a[pos], a[pos + 1]);
+ }
+ }
+
+ //! Sets a uchar32_t at our current position.
+ void _set(uchar32_t c)
+ {
+ ustring16<TAlloc>* ref2 = const_cast<ustring16<TAlloc>*>(ref);
+ const uchar16_t* a = ref2->c_str();
+ if (c > 0xFFFF)
+ {
+ // c will be multibyte, so split it up into the high and low surrogate pairs.
+ uchar16_t x = static_cast<uchar16_t>(c);
+ uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
+ uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
+
+ // If the previous position was a surrogate pair, just replace them. Else, insert the low pair.
+ if (UTF16_IS_SURROGATE_HI(a[pos]) && pos + 1 != ref2->size_raw())
+ ref2->replace_raw(vl, static_cast<u32>(pos) + 1);
+ else ref2->insert_raw(vl, static_cast<u32>(pos) + 1);
+
+ ref2->replace_raw(vh, static_cast<u32>(pos));
+ }
+ else
+ {
+ // c will be a single byte.
+ uchar16_t vh = static_cast<uchar16_t>(c);
+
+ // If the previous position was a surrogate pair, remove the extra byte.
+ if (UTF16_IS_SURROGATE_HI(a[pos]))
+ ref2->erase_raw(static_cast<u32>(pos) + 1);
+
+ ref2->replace_raw(vh, static_cast<u32>(pos));
+ }
+ }
+
+ const ustring16<TAlloc>* ref;
+ u32 pos;
+ };
+ typedef typename ustring16<TAlloc>::_ustring16_iterator_access access;
+
+
+ //! Iterator to iterate through a UTF-16 string.
+#ifndef USTRING_NO_STL
+ class _ustring16_const_iterator : public std::iterator<
+ std::bidirectional_iterator_tag, // iterator_category
+ access, // value_type
+ ptrdiff_t, // difference_type
+ const access, // pointer
+ const access // reference
+ >
+#else
+ class _ustring16_const_iterator
+#endif
+ {
+ public:
+ typedef _ustring16_const_iterator _Iter;
+ typedef std::iterator<std::bidirectional_iterator_tag, access, ptrdiff_t, const access, const access> _Base;
+ typedef const access const_pointer;
+ typedef const access const_reference;
+
+#ifndef USTRING_NO_STL
+ typedef typename _Base::value_type value_type;
+ typedef typename _Base::difference_type difference_type;
+ typedef typename _Base::difference_type distance_type;
+ typedef typename _Base::pointer pointer;
+ typedef const_reference reference;
+#else
+ typedef access value_type;
+ typedef u32 difference_type;
+ typedef u32 distance_type;
+ typedef const_pointer pointer;
+ typedef const_reference reference;
+#endif
+
+ //! Constructors.
+ _ustring16_const_iterator(const _Iter& i) : ref(i.ref), pos(i.pos) {}
+ _ustring16_const_iterator(const ustring16<TAlloc>& s) : ref(&s), pos(0) {}
+ _ustring16_const_iterator(const ustring16<TAlloc>& s, const u32 p) : ref(&s), pos(0)
+ {
+ if (ref->size_raw() == 0 || p == 0)
+ return;
+
+ // Go to the appropriate position.
+ u32 i = p;
+ u32 sr = ref->size_raw();
+ const uchar16_t* a = ref->c_str();
+ while (i != 0 && pos < sr)
+ {
+ if (UTF16_IS_SURROGATE_HI(a[pos]))
+ pos += 2;
+ else ++pos;
+ --i;
+ }
+ }
+
+ //! Test for equalness.
+ bool operator==(const _Iter& iter) const
+ {
+ if (ref == iter.ref && pos == iter.pos)
+ return true;
+ return false;
+ }
+
+ //! Test for unequalness.
+ bool operator!=(const _Iter& iter) const
+ {
+ if (ref != iter.ref || pos != iter.pos)
+ return true;
+ return false;
+ }
+
+ //! Switch to the next full character in the string.
+ _Iter& operator++()
+ { // ++iterator
+ if (pos == ref->size_raw()) return *this;
+ const uchar16_t* a = ref->c_str();
+ if (UTF16_IS_SURROGATE_HI(a[pos]))
+ pos += 2; // TODO: check for valid low surrogate?
+ else ++pos;
+ if (pos > ref->size_raw()) pos = ref->size_raw();
+ return *this;
+ }
+
+ //! Switch to the next full character in the string, returning the previous position.
+ _Iter operator++(int)
+ { // iterator++
+ _Iter _tmp(*this);
+ ++*this;
+ return _tmp;
+ }
+
+ //! Switch to the previous full character in the string.
+ _Iter& operator--()
+ { // --iterator
+ if (pos == 0) return *this;
+ const uchar16_t* a = ref->c_str();
+ --pos;
+ if (UTF16_IS_SURROGATE_LO(a[pos]) && pos != 0) // low surrogate, go back one more.
+ --pos;
+ return *this;
+ }
+
+ //! Switch to the previous full character in the string, returning the previous position.
+ _Iter operator--(int)
+ { // iterator--
+ _Iter _tmp(*this);
+ --*this;
+ return _tmp;
+ }
+
+ //! Advance a specified number of full characters in the string.
+ //! \return Myself.
+ _Iter& operator+=(const difference_type v)
+ {
+ if (v == 0) return *this;
+ if (v < 0) return operator-=(v * -1);
+
+ if (pos >= ref->size_raw())
+ return *this;
+
+ // Go to the appropriate position.
+ // TODO: Don't force u32 on an x64 OS. Make it agnostic.
+ u32 i = (u32)v;
+ u32 sr = ref->size_raw();
+ const uchar16_t* a = ref->c_str();
+ while (i != 0 && pos < sr)
+ {
+ if (UTF16_IS_SURROGATE_HI(a[pos]))
+ pos += 2;
+ else ++pos;
+ --i;
+ }
+ if (pos > sr)
+ pos = sr;
+
+ return *this;
+ }
+
+ //! Go back a specified number of full characters in the string.
+ //! \return Myself.
+ _Iter& operator-=(const difference_type v)
+ {
+ if (v == 0) return *this;
+ if (v > 0) return operator+=(v * -1);
+
+ if (pos == 0)
+ return *this;
+
+ // Go to the appropriate position.
+ // TODO: Don't force u32 on an x64 OS. Make it agnostic.
+ u32 i = (u32)v;
+ const uchar16_t* a = ref->c_str();
+ while (i != 0 && pos != 0)
+ {
+ --pos;
+ if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0)
+ --pos;
+ --i;
+ }
+
+ return *this;
+ }
+
+ //! Return a new iterator that is a variable number of full characters forward from the current position.
+ _Iter operator+(const difference_type v) const
+ {
+ _Iter ret(*this);
+ ret += v;
+ return ret;
+ }
+
+ //! Return a new iterator that is a variable number of full characters backward from the current position.
+ _Iter operator-(const difference_type v) const
+ {
+ _Iter ret(*this);
+ ret -= v;
+ return ret;
+ }
+
+ //! Returns the distance between two iterators.
+ difference_type operator-(const _Iter& iter) const
+ {
+ // Make sure we reference the same object!
+ if (ref != iter.ref)
+ return difference_type();
+
+ _Iter i = iter;
+ difference_type ret;
+
+ // Walk up.
+ if (pos > i.pos)
+ {
+ while (pos > i.pos)
+ {
+ ++i;
+ ++ret;
+ }
+ return ret;
+ }
+
+ // Walk down.
+ while (pos < i.pos)
+ {
+ --i;
+ --ret;
+ }
+ return ret;
+ }
+
+ //! Accesses the full character at the iterator's position.
+ const_reference operator*() const
+ {
+ if (pos >= ref->size_raw())
+ {
+ const uchar16_t* a = ref->c_str();
+ u32 p = ref->size_raw();
+ if (UTF16_IS_SURROGATE_LO(a[p]))
+ --p;
+ reference ret(ref, p);
+ return ret;
+ }
+ const_reference ret(ref, pos);
+ return ret;
+ }
+
+ //! Accesses the full character at the iterator's position.
+ reference operator*()
+ {
+ if (pos >= ref->size_raw())
+ {
+ const uchar16_t* a = ref->c_str();
+ u32 p = ref->size_raw();
+ if (UTF16_IS_SURROGATE_LO(a[p]))
+ --p;
+ reference ret(ref, p);
+ return ret;
+ }
+ reference ret(ref, pos);
+ return ret;
+ }
+
+ //! Accesses the full character at the iterator's position.
+ const_pointer operator->() const
+ {
+ return operator*();
+ }
+
+ //! Accesses the full character at the iterator's position.
+ pointer operator->()
+ {
+ return operator*();
+ }
+
+ //! Is the iterator at the start of the string?
+ bool atStart() const
+ {
+ return pos == 0;
+ }
+
+ //! Is the iterator at the end of the string?
+ bool atEnd() const
+ {
+ const uchar16_t* a = ref->c_str();
+ if (UTF16_IS_SURROGATE(a[pos]))
+ return (pos + 1) >= ref->size_raw();
+ else return pos >= ref->size_raw();
+ }
+
+ //! Moves the iterator to the start of the string.
+ void toStart()
+ {
+ pos = 0;
+ }
+
+ //! Moves the iterator to the end of the string.
+ void toEnd()
+ {
+ const uchar16_t* a = ref->c_str();
+ pos = ref->size_raw();
+ }
+
+ //! Returns the iterator's position.
+ //! \return The iterator's position.
+ u32 getPos() const
+ {
+ return pos;
+ }
+
+ protected:
+ const ustring16<TAlloc>* ref;
+ u32 pos;
+ };
+
+ //! Iterator to iterate through a UTF-16 string.
+ class _ustring16_iterator : public _ustring16_const_iterator
+ {
+ public:
+ typedef _ustring16_iterator _Iter;
+ typedef _ustring16_const_iterator _Base;
+ typedef typename _Base::const_pointer const_pointer;
+ typedef typename _Base::const_reference const_reference;
+
+ typedef typename _Base::value_type value_type;
+ typedef typename _Base::difference_type difference_type;
+ typedef typename _Base::distance_type distance_type;
+ typedef access pointer;
+ typedef access reference;
+
+ using _Base::pos;
+ using _Base::ref;
+
+ //! Constructors.
+ _ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {}
+ _ustring16_iterator(const ustring16<TAlloc>& s) : _ustring16_const_iterator(s) {}
+ _ustring16_iterator(const ustring16<TAlloc>& s, const u32 p) : _ustring16_const_iterator(s, p) {}
+
+ //! Accesses the full character at the iterator's position.
+ reference operator*() const
+ {
+ if (pos >= ref->size_raw())
+ {
+ const uchar16_t* a = ref->c_str();
+ u32 p = ref->size_raw();
+ if (UTF16_IS_SURROGATE_LO(a[p]))
+ --p;
+ reference ret(ref, p);
+ return ret;
+ }
+ reference ret(ref, pos);
+ return ret;
+ }
+
+ //! Accesses the full character at the iterator's position.
+ reference operator*()
+ {
+ if (pos >= ref->size_raw())
+ {
+ const uchar16_t* a = ref->c_str();
+ u32 p = ref->size_raw();
+ if (UTF16_IS_SURROGATE_LO(a[p]))
+ --p;
+ reference ret(ref, p);
+ return ret;
+ }
+ reference ret(ref, pos);
+ return ret;
+ }
+
+ //! Accesses the full character at the iterator's position.
+ pointer operator->() const
+ {
+ return operator*();
+ }
+
+ //! Accesses the full character at the iterator's position.
+ pointer operator->()
+ {
+ return operator*();
+ }
+ };
+
+ typedef typename ustring16<TAlloc>::_ustring16_iterator iterator;
+ typedef typename ustring16<TAlloc>::_ustring16_const_iterator const_iterator;
+
+ ///----------------------///
+ /// end iterator classes ///
+ ///----------------------///
+
+ //! Default constructor
+ ustring16()
+ : array(0), allocated(1), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+ array = allocator.allocate(1); // new u16[1];
+ array[0] = 0x0;
+ }
+
+
+ //! Constructor
+ ustring16(const ustring16<TAlloc>& other)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+ *this = other;
+ }
+
+
+ //! Constructor from other string types
+ template <class B, class A>
+ ustring16(const string<B, A>& other)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+ *this = other;
+ }
+
+
+#ifndef USTRING_NO_STL
+ //! Constructor from std::string
+ template <class B, class A, typename Alloc>
+ ustring16(const std::basic_string<B, A, Alloc>& other)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+ *this = other.c_str();
+ }
+
+
+ //! Constructor from iterator.
+ template <typename Itr>
+ ustring16(Itr first, Itr last)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+ reserve(std::distance(first, last));
+ array[used] = 0;
+
+ for (; first != last; ++first)
+ append((uchar32_t)*first);
+ }
+#endif
+
+
+#ifndef USTRING_CPP0X_NEWLITERALS
+ //! Constructor for copying a character string from a pointer.
+ ustring16(const char* const c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ loadDataStream(c, strlen(c));
+ //append((uchar8_t*)c);
+ }
+
+
+ //! Constructor for copying a character string from a pointer with a given length.
+ ustring16(const char* const c, u32 length)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ loadDataStream(c, length);
+ }
+#endif
+
+
+ //! Constructor for copying a UTF-8 string from a pointer.
+ ustring16(const uchar8_t* const c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c);
+ }
+
+
+ //! Constructor for copying a UTF-8 string from a single char.
+ ustring16(const char c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append((uchar32_t)c);
+ }
+
+
+ //! Constructor for copying a UTF-8 string from a pointer with a given length.
+ ustring16(const uchar8_t* const c, u32 length)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c, length);
+ }
+
+
+ //! Constructor for copying a UTF-16 string from a pointer.
+ ustring16(const uchar16_t* const c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c);
+ }
+
+
+ //! Constructor for copying a UTF-16 string from a pointer with a given length
+ ustring16(const uchar16_t* const c, u32 length)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c, length);
+ }
+
+
+ //! Constructor for copying a UTF-32 string from a pointer.
+ ustring16(const uchar32_t* const c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c);
+ }
+
+
+ //! Constructor for copying a UTF-32 from a pointer with a given length.
+ ustring16(const uchar32_t* const c, u32 length)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ append(c, length);
+ }
+
+
+ //! Constructor for copying a wchar_t string from a pointer.
+ ustring16(const wchar_t* const c)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ if (sizeof(wchar_t) == 4)
+ append(reinterpret_cast<const uchar32_t* const>(c));
+ else if (sizeof(wchar_t) == 2)
+ append(reinterpret_cast<const uchar16_t* const>(c));
+ else if (sizeof(wchar_t) == 1)
+ append(reinterpret_cast<const uchar8_t* const>(c));
+ }
+
+
+ //! Constructor for copying a wchar_t string from a pointer with a given length.
+ ustring16(const wchar_t* const c, u32 length)
+ : array(0), allocated(0), used(0)
+ {
+#if __BIG_ENDIAN__
+ encoding = unicode::EUTFE_UTF16_BE;
+#else
+ encoding = unicode::EUTFE_UTF16_LE;
+#endif
+
+ if (sizeof(wchar_t) == 4)
+ append(reinterpret_cast<const uchar32_t* const>(c), length);
+ else if (sizeof(wchar_t) == 2)
+ append(reinterpret_cast<const uchar16_t* const>(c), length);
+ else if (sizeof(wchar_t) == 1)
+ append(reinterpret_cast<const uchar8_t* const>(c), length);
+ }
+
+
+#ifdef USTRING_CPP0X
+ //! Constructor for moving a ustring16
+ ustring16(ustring16<TAlloc>&& other)
+ : array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used)
+ {
+ //std::cout << "MOVE constructor" << std::endl;
+ other.array = 0;
+ other.allocated = 0;
+ other.used = 0;
+ }
+#endif
+
+
+ //! Destructor
+ ~ustring16()
+ {
+ allocator.deallocate(array); // delete [] array;
+ }
+
+
+ //! Assignment operator
+ ustring16& operator=(const ustring16<TAlloc>& other)
+ {
+ if (this == &other)
+ return *this;
+
+ used = other.size_raw();
+ if (used >= allocated)
+ {
+ allocator.deallocate(array); // delete [] array;
+ allocated = used + 1;
+ array = allocator.allocate(used + 1); //new u16[used];
+ }
+
+ const uchar16_t* p = other.c_str();
+ for (u32 i=0; i<=used; ++i, ++p)
+ array[i] = *p;
+
+ array[used] = 0;
+
+ // Validate our new UTF-16 string.
+ validate();
+
+ return *this;
+ }
+
+
+#ifdef USTRING_CPP0X
+ //! Move assignment operator
+ ustring16& operator=(ustring16<TAlloc>&& other)
+ {
+ if (this != &other)
+ {
+ //std::cout << "MOVE operator=" << std::endl;
+ allocator.deallocate(array);
+
+ array = other.array;
+ allocated = other.allocated;
+ encoding = other.encoding;
+ used = other.used;
+ other.array = 0;
+ other.used = 0;
+ }
+ return *this;
+ }
+#endif
+
+
+ //! Assignment operator for other string types
+ template <class B, class A>
+ ustring16<TAlloc>& operator=(const string<B, A>& other)
+ {
+ *this = other.c_str();
+ return *this;
+ }
+
+
+ //! Assignment operator for UTF-8 strings
+ ustring16<TAlloc>& operator=(const uchar8_t* const c)
+ {
+ if (!array)
+ {
+ array = allocator.allocate(1); //new u16[1];
+ allocated = 1;
+ }
+ used = 0;
+ array[used] = 0x0;
+ if (!c) return *this;
+
+ //! Append our string now.
+ append(c);
+ return *this;
+ }
+
+
+ //! Assignment operator for UTF-16 strings
+ ustring16<TAlloc>& operator=(const uchar16_t* const c)
+ {
+ if (!array)
+ {
+ array = allocator.allocate(1); //new u16[1];
+ allocated = 1;
+ }
+ used = 0;
+ array[used] = 0x0;
+ if (!c) return *this;
+
+ //! Append our string now.
+ append(c);
+ return *this;
+ }
+
+
+ //! Assignment operator for UTF-32 strings
+ ustring16<TAlloc>& operator=(const uchar32_t* const c)
+ {
+ if (!array)
+ {
+ array = allocator.allocate(1); //new u16[1];
+ allocated = 1;
+ }
+ used = 0;
+ array[used] = 0x0;
+ if (!c) return *this;
+
+ //! Append our string now.
+ append(c);
+ return *this;
+ }
+
+
+ //! Assignment operator for wchar_t strings.
+ /** Note that this assumes that a correct unicode string is stored in the wchar_t string.
+ Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string.
+ This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/
+ ustring16<TAlloc>& operator=(const wchar_t* const c)
+ {
+ if (sizeof(wchar_t) == 4)
+ *this = reinterpret_cast<const uchar32_t* const>(c);
+ else if (sizeof(wchar_t) == 2)
+ *this = reinterpret_cast<const uchar16_t* const>(c);
+ else if (sizeof(wchar_t) == 1)
+ *this = reinterpret_cast<const uchar8_t* const>(c);
+
+ return *this;
+ }
+
+
+ //! Assignment operator for other strings.
+ /** Note that this assumes that a correct unicode string is stored in the string. **/
+ template <class B>
+ ustring16<TAlloc>& operator=(const B* const c)
+ {
+ if (sizeof(B) == 4)
+ *this = reinterpret_cast<const uchar32_t* const>(c);
+ else if (sizeof(B) == 2)
+ *this = reinterpret_cast<const uchar16_t* const>(c);
+ else if (sizeof(B) == 1)
+ *this = reinterpret_cast<const uchar8_t* const>(c);
+
+ return *this;
+ }
+
+
+ //! Direct access operator
+ access operator [](const u32 index)
+ {
+ _IRR_DEBUG_BREAK_IF(index>=size()) // bad index
+ iterator iter(*this, index);
+ return iter.operator*();
+ }
+
+
+ //! Direct access operator
+ const access operator [](const u32 index) const
+ {
+ _IRR_DEBUG_BREAK_IF(index>=size()) // bad index
+ const_iterator iter(*this, index);
+ return iter.operator*();
+ }
+
+
+ //! Equality operator
+ bool operator ==(const uchar16_t* const str) const
+ {
+ if (!str)
+ return false;
+
+ u32 i;
+ for(i=0; array[i] && str[i]; ++i)
+ if (array[i] != str[i])
+ return false;
+
+ return !array[i] && !str[i];
+ }
+
+
+ //! Equality operator
+ bool operator ==(const ustring16<TAlloc>& other) const
+ {
+ for(u32 i=0; array[i] && other.array[i]; ++i)
+ if (array[i] != other.array[i])
+ return false;
+
+ return used == other.used;
+ }
+
+
+ //! Is smaller comparator
+ bool operator <(const ustring16<TAlloc>& other) const
+ {
+ for(u32 i=0; array[i] && other.array[i]; ++i)
+ {
+ s32 diff = array[i] - other.array[i];
+ if ( diff )
+ return diff < 0;
+ }
+
+ return used < other.used;
+ }
+
+
+ //! Inequality operator
+ bool operator !=(const uchar16_t* const str) const
+ {
+ return !(*this == str);
+ }
+
+
+ //! Inequality operator
+ bool operator !=(const ustring16<TAlloc>& other) const
+ {
+ return !(*this == other);
+ }
+
+
+ //! Returns the length of a ustring16 in full characters.
+ //! \return Length of a ustring16 in full characters.
+ u32 size() const
+ {
+ const_iterator i(*this, 0);
+ u32 pos = 0;
+ while (!i.atEnd())
+ {
+ ++i;
+ ++pos;
+ }
+ return pos;
+ }
+
+
+ //! Informs if the ustring is empty or not.
+ //! \return True if the ustring is empty, false if not.
+ bool empty() const
+ {
+ return (size_raw() == 0);
+ }
+
+
+ //! Returns a pointer to the raw UTF-16 string data.
+ //! \return pointer to C-style NUL terminated array of UTF-16 code points.
+ const uchar16_t* c_str() const
+ {
+ return array;
+ }
+
+
+ //! Compares the first n characters of this string with another.
+ //! \param other Other string to compare to.
+ //! \param n Number of characters to compare.
+ //! \return True if the n first characters of both strings are equal.
+ bool equalsn(const ustring16<TAlloc>& other, u32 n) const
+ {
+ u32 i;
+ const uchar16_t* oa = other.c_str();
+ for(i=0; array[i] && oa[i] && i < n; ++i)
+ if (array[i] != oa[i])
+ return false;
+
+ // if one (or both) of the strings was smaller then they
+ // are only equal if they have the same length
+ return (i == n) || (used == other.used);
+ }
+
+
+ //! Compares the first n characters of this string with another.
+ //! \param str Other string to compare to.
+ //! \param n Number of characters to compare.
+ //! \return True if the n first characters of both strings are equal.
+ bool equalsn(const uchar16_t* const str, u32 n) const
+ {
+ if (!str)
+ return false;
+ u32 i;
+ for(i=0; array[i] && str[i] && i < n; ++i)
+ if (array[i] != str[i])
+ return false;
+
+ // if one (or both) of the strings was smaller then they
+ // are only equal if they have the same length
+ return (i == n) || (array[i] == 0 && str[i] == 0);
+ }
+
+
+ //! Appends a character to this ustring16
+ //! \param character The character to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(uchar32_t character)
+ {
+ if (used + 2 >= allocated)
+ reallocate(used + 2);
+
+ if (character > 0xFFFF)
+ {
+ used += 2;
+
+ // character will be multibyte, so split it up into a surrogate pair.
+ uchar16_t x = static_cast<uchar16_t>(character);
+ uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
+ uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
+ array[used-2] = vh;
+ array[used-1] = vl;
+ }
+ else
+ {
+ ++used;
+ array[used-1] = character;
+ }
+ array[used] = 0;
+
+ return *this;
+ }
+
+
+ //! Appends a UTF-8 string to this ustring16
+ //! \param other The UTF-8 string to append.
+ //! \param length The length of the string to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(const uchar8_t* const other, u32 length=0xffffffff)
+ {
+ if (!other)
+ return *this;
+
+ // Determine if the string is long enough for a BOM.
+ u32 len = 0;
+ const uchar8_t* p = other;
+ do
+ {
+ ++len;
+ } while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN);
+
+ // Check for BOM.
+ unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE;
+ if (len == unicode::BOM_ENCODE_UTF8_LEN)
+ {
+ if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0)
+ c_bom = unicode::EUTFE_UTF8;
+ }
+
+ // If a BOM was found, don't include it in the string.
+ const uchar8_t* c2 = other;
+ if (c_bom != unicode::EUTFE_NONE)
+ {
+ c2 = other + unicode::BOM_UTF8_LEN;
+ length -= unicode::BOM_UTF8_LEN;
+ }
+
+ // Calculate the size of the string to read in.
+ len = 0;
+ p = c2;
+ do
+ {
+ ++len;
+ } while(*p++ && len < length);
+ if (len > length)
+ len = length;
+
+ // If we need to grow the array, do it now.
+ if (used + len >= allocated)
+ reallocate(used + (len * 2));
+ u32 start = used;
+
+ // Convert UTF-8 to UTF-16.
+ u32 pos = start;
+ for (u32 l = 0; l<len;)
+ {
+ ++used;
+ if (((c2[l] >> 6) & 0x03) == 0x02)
+ { // Invalid continuation byte.
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ ++l;
+ }
+ else if (c2[l] == 0xC0 || c2[l] == 0xC1)
+ { // Invalid byte - overlong encoding.
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ ++l;
+ }
+ else if ((c2[l] & 0xF8) == 0xF0)
+ { // 4 bytes UTF-8, 2 bytes UTF-16.
+ // Check for a full string.
+ if ((l + 3) >= len)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ l += 3;
+ break;
+ }
+
+ // Validate.
+ bool valid = true;
+ u8 l2 = 0;
+ if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
+ if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
+ if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
+ if (!valid)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ l += l2;
+ continue;
+ }
+
+ // Decode.
+ uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3);
+ uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF);
+ uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F);
+ uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16);
+
+ // Split v up into a surrogate pair.
+ uchar16_t x = static_cast<uchar16_t>(v);
+ uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
+ uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
+
+ array[pos++] = vh;
+ array[pos++] = vl;
+ l += 4;
+ ++used; // Using two shorts this time, so increase used by 1.
+ }
+ else if ((c2[l] & 0xF0) == 0xE0)
+ { // 3 bytes UTF-8, 1 byte UTF-16.
+ // Check for a full string.
+ if ((l + 2) >= len)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ l += 2;
+ break;
+ }
+
+ // Validate.
+ bool valid = true;
+ u8 l2 = 0;
+ if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
+ if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
+ if (!valid)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ l += l2;
+ continue;
+ }
+
+ // Decode.
+ uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF);
+ uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F);
+ uchar16_t ch = b2 | ((uchar16_t)b1 << 8);
+ array[pos++] = ch;
+ l += 3;
+ }
+ else if ((c2[l] & 0xE0) == 0xC0)
+ { // 2 bytes UTF-8, 1 byte UTF-16.
+ // Check for a full string.
+ if ((l + 1) >= len)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ l += 1;
+ break;
+ }
+
+ // Validate.
+ if (((c2[l+1] >> 6) & 0x03) != 0x02)
+ {
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ ++l;
+ continue;
+ }
+
+ // Decode.
+ uchar8_t b1 = (c2[l] >> 2) & 0x7;
+ uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F);
+ uchar16_t ch = b2 | ((uchar16_t)b1 << 8);
+ array[pos++] = ch;
+ l += 2;
+ }
+ else
+ { // 1 byte UTF-8, 1 byte UTF-16.
+ // Validate.
+ if (c2[l] > 0x7F)
+ { // Values above 0xF4 are restricted and aren't used. By now, anything above 0x7F is invalid.
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ }
+ else array[pos++] = static_cast<uchar16_t>(c2[l]);
+ ++l;
+ }
+ }
+ array[used] = 0;
+
+ // Validate our new UTF-16 string.
+ validate();
+
+ return *this;
+ }
+
+
+ //! Appends a UTF-16 string to this ustring16
+ //! \param other The UTF-16 string to append.
+ //! \param length The length of the string to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(const uchar16_t* const other, u32 length=0xffffffff)
+ {
+ if (!other)
+ return *this;
+
+ // Determine if the string is long enough for a BOM.
+ u32 len = 0;
+ const uchar16_t* p = other;
+ do
+ {
+ ++len;
+ } while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN);
+
+ // Check for the BOM to determine the string's endianness.
+ unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE;
+ if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0)
+ c_end = unicode::EUTFEE_LITTLE;
+ else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0)
+ c_end = unicode::EUTFEE_BIG;
+
+ // If a BOM was found, don't include it in the string.
+ const uchar16_t* c2 = other;
+ if (c_end != unicode::EUTFEE_NATIVE)
+ {
+ c2 = other + unicode::BOM_UTF16_LEN;
+ length -= unicode::BOM_UTF16_LEN;
+ }
+
+ // Calculate the size of the string to read in.
+ len = 0;
+ p = c2;
+ do
+ {
+ ++len;
+ } while(*p++ && len < length);
+ if (len > length)
+ len = length;
+
+ // If we need to grow the size of the array, do it now.
+ if (used + len >= allocated)
+ reallocate(used + (len * 2));
+ u32 start = used;
+ used += len;
+
+ // Copy the string now.
+ unicode::EUTF_ENDIAN m_end = getEndianness();
+ for (u32 l = start; l < start + len; ++l)
+ {
+ array[l] = (uchar16_t)c2[l];
+ if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end)
+ array[l] = unicode::swapEndian16(array[l]);
+ }
+
+ array[used] = 0;
+
+ // Validate our new UTF-16 string.
+ validate();
+ return *this;
+ }
+
+
+ //! Appends a UTF-32 string to this ustring16
+ //! \param other The UTF-32 string to append.
+ //! \param length The length of the string to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(const uchar32_t* const other, u32 length=0xffffffff)
+ {
+ if (!other)
+ return *this;
+
+ // Check for the BOM to determine the string's endianness.
+ unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE;
+ if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0)
+ c_end = unicode::EUTFEE_LITTLE;
+ else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0)
+ c_end = unicode::EUTFEE_BIG;
+
+ // If a BOM was found, don't include it in the string.
+ const uchar32_t* c2 = other;
+ if (c_end != unicode::EUTFEE_NATIVE)
+ {
+ c2 = other + unicode::BOM_UTF32_LEN;
+ length -= unicode::BOM_UTF32_LEN;
+ }
+
+ // Calculate the size of the string to read in.
+ u32 len = 0;
+ const uchar32_t* p = c2;
+ do
+ {
+ ++len;
+ } while(*p++ && len < length);
+ if (len > length)
+ len = length;
+
+ // If we need to grow the size of the array, do it now.
+ // In case all of the UTF-32 string is split into surrogate pairs, do len * 2.
+ if (used + (len * 2) >= allocated)
+ reallocate(used + ((len * 2) * 2));
+ u32 start = used;
+
+ // Convert UTF-32 to UTF-16.
+ unicode::EUTF_ENDIAN m_end = getEndianness();
+ u32 pos = start;
+ for (u32 l = 0; l<len; ++l)
+ {
+ ++used;
+
+ uchar32_t ch = c2[l];
+ if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end)
+ ch = unicode::swapEndian32(ch);
+
+ if (ch > 0xFFFF)
+ {
+ // Split ch up into a surrogate pair as it is over 16 bits long.
+ uchar16_t x = static_cast<uchar16_t>(ch);
+ uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
+ uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
+ array[pos++] = vh;
+ array[pos++] = vl;
+ ++used; // Using two shorts, so increased used again.
+ }
+ else if (ch >= 0xD800 && ch <= 0xDFFF)
+ {
+ // Between possible UTF-16 surrogates (invalid!)
+ array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
+ }
+ else array[pos++] = static_cast<uchar16_t>(ch);
+ }
+ array[used] = 0;
+
+ // Validate our new UTF-16 string.
+ validate();
+
+ return *this;
+ }
+
+
+ //! Appends a ustring16 to this ustring16
+ //! \param other The string to append to this one.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(const ustring16<TAlloc>& other)
+ {
+ const uchar16_t* oa = other.c_str();
+
+ u32 len = other.size_raw();
+
+ if (used + len >= allocated)
+ reallocate(used + len);
+
+ for (u32 l=0; l<len; ++l)
+ array[used+l] = oa[l];
+
+ used += len;
+ array[used] = 0;
+
+ return *this;
+ }
+
+
+ //! Appends a certain amount of characters of a ustring16 to this ustring16.
+ //! \param other The string to append to this one.
+ //! \param length How many characters of the other string to add to this one.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& append(const ustring16<TAlloc>& other, u32 length)
+ {
+ if (other.size() == 0)
+ return *this;
+
+ if (other.size() < length)
+ {
+ append(other);
+ return *this;
+ }
+
+ if (used + length * 2 >= allocated)
+ reallocate(used + length * 2);
+
+ const_iterator iter(other, 0);
+ u32 l = length;
+ while (!iter.atEnd() && l)
+ {
+ uchar32_t c = *iter;
+ append(c);
+ ++iter;
+ --l;
+ }
+
+ return *this;
+ }
+
+
+ //! Reserves some memory.
+ //! \param count The amount of characters to reserve.
+ void reserve(u32 count)
+ {
+ if (count < allocated)
+ return;
+
+ reallocate(count);
+ }
+
+
+ //! Finds first occurrence of character.
+ //! \param c The character to search for.
+ //! \return Position where the character has been found, or -1 if not found.
+ s32 findFirst(uchar32_t c) const
+ {
+ const_iterator i(*this, 0);
+
+ s32 pos = 0;
+ while (!i.atEnd())
+ {
+ uchar32_t t = *i;
+ if (c == t)
+ return pos;
+ ++pos;
+ ++i;
+ }
+
+ return -1;
+ }
+
+ //! Finds first occurrence of a character of a list.
+ //! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab".
+ //! \param count The amount of characters in the list. Usually, this should be strlen(c).
+ //! \return Position where one of the characters has been found, or -1 if not found.
+ s32 findFirstChar(const uchar32_t* const c, u32 count=1) const
+ {
+ if (!c || !count)
+ return -1;
+
+ const_iterator i(*this, 0);
+
+ s32 pos = 0;
+ while (!i.atEnd())
+ {
+ uchar32_t t = *i;
+ for (u32 j=0; j<count; ++j)
+ if (t == c[j])
+ return pos;
+ ++pos;
+ ++i;
+ }
+
+ return -1;
+ }
+
+
+ //! Finds first position of a character not in a given list.
+ //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
+ //! \param count The amount of characters in the list. Usually, this should be strlen(c).
+ //! \return Position where the character has been found, or -1 if not found.
+ s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const
+ {
+ if (!c || !count)
+ return -1;
+
+ const_iterator i(*this, 0);
+
+ s32 pos = 0;
+ while (!i.atEnd())
+ {
+ uchar32_t t = *i;
+ u32 j;
+ for (j=0; j<count; ++j)
+ if (t == c[j])
+ break;
+
+ if (j==count)
+ return pos;
+ ++pos;
+ ++i;
+ }
+
+ return -1;
+ }
+
+ //! Finds last position of a character not in a given list.
+ //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
+ //! \param count The amount of characters in the list. Usually, this should be strlen(c).
+ //! \return Position where the character has been found, or -1 if not found.
+ s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const
+ {
+ if (!c || !count)
+ return -1;
+
+ const_iterator i(end());
+ --i;
+
+ s32 pos = size() - 1;
+ while (!i.atStart())
+ {
+ uchar32_t t = *i;
+ u32 j;
+ for (j=0; j<count; ++j)
+ if (t == c[j])
+ break;
+
+ if (j==count)
+ return pos;
+ --pos;
+ --i;
+ }
+
+ return -1;
+ }
+
+ //! Finds next occurrence of character.
+ //! \param c The character to search for.
+ //! \param startPos The position in the string to start searching.
+ //! \return Position where the character has been found, or -1 if not found.
+ s32 findNext(uchar32_t c, u32 startPos) const
+ {
+ const_iterator i(*this, startPos);
+
+ s32 pos = startPos;
+ while (!i.atEnd())
+ {
+ uchar32_t t = *i;
+ if (t == c)
+ return pos;
+ ++pos;
+ ++i;
+ }
+
+ return -1;
+ }
+
+
+ //! Finds last occurrence of character.
+ //! \param c The character to search for.
+ //! \param start The start position of the reverse search ( default = -1, on end ).
+ //! \return Position where the character has been found, or -1 if not found.
+ s32 findLast(uchar32_t c, s32 start = -1) const
+ {
+ u32 s = size();
+ start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1;
+
+ const_iterator i(*this, start);
+ u32 pos = start;
+ while (!i.atStart())
+ {
+ uchar32_t t = *i;
+ if (t == c)
+ return pos;
+ --pos;
+ --i;
+ }
+
+ return -1;
+ }
+
+ //! Finds last occurrence of a character in a list.
+ //! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab".
+ //! \param count The amount of characters in the list. Usually, this should be strlen(c).
+ //! \return Position where one of the characters has been found, or -1 if not found.
+ s32 findLastChar(const uchar32_t* const c, u32 count=1) const
+ {
+ if (!c || !count)
+ return -1;
+
+ const_iterator i(end());
+ --i;
+
+ s32 pos = size();
+ while (!i.atStart())
+ {
+ uchar32_t t = *i;
+ for (u32 j=0; j<count; ++j)
+ if (t == c[j])
+ return pos;
+ --pos;
+ --i;
+ }
+
+ return -1;
+ }
+
+
+ //! Finds another ustring16 in this ustring16.
+ //! \param str The string to find.
+ //! \param start The start position of the search.
+ //! \return Positions where the ustring16 has been found, or -1 if not found.
+ s32 find(const ustring16<TAlloc>& str, const u32 start = 0) const
+ {
+ u32 my_size = size();
+ u32 their_size = str.size();
+
+ if (their_size == 0 || my_size - start < their_size)
+ return -1;
+
+ const_iterator i(*this, start);
+
+ s32 pos = start;
+ while (!i.atEnd())
+ {
+ const_iterator i2(i);
+ const_iterator j(str, 0);
+ uchar32_t t1 = (uchar32_t)*i2;
+ uchar32_t t2 = (uchar32_t)*j;
+ while (t1 == t2)
+ {
+ ++i2;
+ ++j;
+ if (j.atEnd())
+ return pos;
+ t1 = (uchar32_t)*i2;
+ t2 = (uchar32_t)*j;
+ }
+ ++i;
+ ++pos;
+ }
+
+ return -1;
+ }
+
+
+ //! Finds another ustring16 in this ustring16.
+ //! \param str The string to find.
+ //! \param start The start position of the search.
+ //! \return Positions where the string has been found, or -1 if not found.
+ s32 find_raw(const ustring16<TAlloc>& str, const u32 start = 0) const
+ {
+ const uchar16_t* data = str.c_str();
+ if (data && *data)
+ {
+ u32 len = 0;
+
+ while (data[len])
+ ++len;
+
+ if (len > used)
+ return -1;
+
+ for (u32 i=start; i<=used-len; ++i)
+ {
+ u32 j=0;
+
+ while(data[j] && array[i+j] == data[j])
+ ++j;
+
+ if (!data[j])
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+
+ //! Returns a substring.
+ //! \param begin: Start of substring.
+ //! \param length: Length of substring.
+ //! \return A reference to our current string.
+ ustring16<TAlloc> subString(u32 begin, s32 length) const
+ {
+ u32 len = size();
+ // if start after ustring16
+ // or no proper substring length
+ if ((length <= 0) || (begin>=len))
+ return ustring16<TAlloc>("");
+ // clamp length to maximal value
+ if ((length+begin) > len)
+ length = len-begin;
+
+ ustring16<TAlloc> o;
+ o.reserve((length+1) * 2);
+
+ const_iterator i(*this, begin);
+ while (!i.atEnd() && length)
+ {
+ o.append(*i);
+ ++i;
+ --length;
+ }
+
+ return o;
+ }
+
+
+ //! Appends a character to this ustring16.
+ //! \param c Character to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (char c)
+ {
+ append((uchar32_t)c);
+ return *this;
+ }
+
+
+ //! Appends a character to this ustring16.
+ //! \param c Character to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (uchar32_t c)
+ {
+ append(c);
+ return *this;
+ }
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (short c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (unsigned short c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+#ifdef USTRING_CPP0X_NEWLITERALS
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (int c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (unsigned int c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+#endif
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (long c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (unsigned long c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+ //! Appends a number to this ustring16.
+ //! \param c Number to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (double c)
+ {
+ append(core::stringc(c));
+ return *this;
+ }
+
+
+ //! Appends a char ustring16 to this ustring16.
+ //! \param c Char ustring16 to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (const uchar16_t* const c)
+ {
+ append(c);
+ return *this;
+ }
+
+
+ //! Appends a ustring16 to this ustring16.
+ //! \param other ustring16 to append.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& operator += (const ustring16<TAlloc>& other)
+ {
+ append(other);
+ return *this;
+ }
+
+
+ //! Replaces all characters of a given type with another one.
+ //! \param toReplace Character to replace.
+ //! \param replaceWith Character replacing the old one.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& replace(uchar32_t toReplace, uchar32_t replaceWith)
+ {
+ iterator i(*this, 0);
+ while (!i.atEnd())
+ {
+ typename ustring16<TAlloc>::access a = *i;
+ if ((uchar32_t)a == toReplace)
+ a = replaceWith;
+ ++i;
+ }
+ return *this;
+ }
+
+
+ //! Replaces all instances of a string with another one.
+ //! \param toReplace The string to replace.
+ //! \param replaceWith The string replacing the old one.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& replace(const ustring16<TAlloc>& toReplace, const ustring16<TAlloc>& replaceWith)
+ {
+ if (toReplace.size() == 0)
+ return *this;
+
+ const uchar16_t* other = toReplace.c_str();
+ const uchar16_t* replace = replaceWith.c_str();
+ const u32 other_size = toReplace.size_raw();
+ const u32 replace_size = replaceWith.size_raw();
+
+ // Determine the delta. The algorithm will change depending on the delta.
+ s32 delta = replace_size - other_size;
+
+ // A character for character replace. The string will not shrink or grow.
+ if (delta == 0)
+ {
+ s32 pos = 0;
+ while ((pos = find_raw(other, pos)) != -1)
+ {
+ for (u32 i = 0; i < replace_size; ++i)
+ array[pos + i] = replace[i];
+ ++pos;
+ }
+ return *this;
+ }
+
+ // We are going to be removing some characters. The string will shrink.
+ if (delta < 0)
+ {
+ u32 i = 0;
+ for (u32 pos = 0; pos <= used; ++i, ++pos)
+ {
+ // Is this potentially a match?
+ if (array[pos] == *other)
+ {
+ // Check to see if we have a match.
+ u32 j;
+ for (j = 0; j < other_size; ++j)
+ {
+ if (array[pos + j] != other[j])
+ break;
+ }
+
+ // If we have a match, replace characters.
+ if (j == other_size)
+ {
+ for (j = 0; j < replace_size; ++j)
+ array[i + j] = replace[j];
+ i += replace_size - 1;
+ pos += other_size - 1;
+ continue;
+ }
+ }
+
+ // No match found, just copy characters.
+ array[i - 1] = array[pos];
+ }
+ array[i] = 0;
+ used = i;
+
+ return *this;
+ }
+
+ // We are going to be adding characters, so the string size will increase.
+ // Count the number of times toReplace exists in the string so we can allocate the new size.
+ u32 find_count = 0;
+ s32 pos = 0;
+ while ((pos = find_raw(other, pos)) != -1)
+ {
+ ++find_count;
+ ++pos;
+ }
+
+ // Re-allocate the string now, if needed.
+ u32 len = delta * find_count;
+ if (used + len >= allocated)
+ reallocate(used + len);
+
+ // Start replacing.
+ pos = 0;
+ while ((pos = find_raw(other, pos)) != -1)
+ {
+ uchar16_t* start = array + pos + other_size - 1;
+ uchar16_t* ptr = array + used;
+ uchar16_t* end = array + used + delta;
+
+ // Shift characters to make room for the string.
+ while (ptr != start)
+ {
+ *end = *ptr;
+ --ptr;
+ --end;
+ }
+
+ // Add the new string now.
+ for (u32 i = 0; i < replace_size; ++i)
+ array[pos + i] = replace[i];
+
+ pos += replace_size;
+ used += delta;
+ }
+
+ // Terminate the string and return ourself.
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Removes characters from a ustring16..
+ //! \param c The character to remove.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& remove(uchar32_t c)
+ {
+ u32 pos = 0;
+ u32 found = 0;
+ u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character.
+ for (u32 i=0; i<=used; ++i)
+ {
+ uchar32_t uc32 = 0;
+ if (!UTF16_IS_SURROGATE_HI(array[i]))
+ uc32 |= array[i];
+ else if (i + 1 <= used)
+ {
+ // Convert the surrogate pair into a single UTF-32 character.
+ uc32 = unicode::toUTF32(array[i], array[i + 1]);
+ }
+ u32 len2 = (uc32 > 0xFFFF ? 2 : 1);
+
+ if (uc32 == c)
+ {
+ found += len;
+ continue;
+ }
+
+ array[pos++] = array[i];
+ if (len2 == 2)
+ array[pos++] = array[++i];
+ }
+ used -= found;
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Removes a ustring16 from the ustring16.
+ //! \param toRemove The string to remove.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& remove(const ustring16<TAlloc>& toRemove)
+ {
+ u32 size = toRemove.size_raw();
+ if (size == 0) return *this;
+
+ const uchar16_t* tra = toRemove.c_str();
+ u32 pos = 0;
+ u32 found = 0;
+ for (u32 i=0; i<=used; ++i)
+ {
+ u32 j = 0;
+ while (j < size)
+ {
+ if (array[i + j] != tra[j])
+ break;
+ ++j;
+ }
+ if (j == size)
+ {
+ found += size;
+ i += size - 1;
+ continue;
+ }
+
+ array[pos++] = array[i];
+ }
+ used -= found;
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Removes characters from the ustring16.
+ //! \param characters The characters to remove.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& removeChars(const ustring16<TAlloc>& characters)
+ {
+ if (characters.size_raw() == 0)
+ return *this;
+
+ u32 pos = 0;
+ u32 found = 0;
+ const_iterator iter(characters);
+ for (u32 i=0; i<=used; ++i)
+ {
+ uchar32_t uc32 = 0;
+ if (!UTF16_IS_SURROGATE_HI(array[i]))
+ uc32 |= array[i];
+ else if (i + 1 <= used)
+ {
+ // Convert the surrogate pair into a single UTF-32 character.
+ uc32 = unicode::toUTF32(array[i], array[i+1]);
+ }
+ u32 len2 = (uc32 > 0xFFFF ? 2 : 1);
+
+ bool cont = false;
+ iter.toStart();
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ if (uc32 == c)
+ {
+ found += (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character.
+ ++i;
+ cont = true;
+ break;
+ }
+ ++iter;
+ }
+ if (cont) continue;
+
+ array[pos++] = array[i];
+ if (len2 == 2)
+ array[pos++] = array[++i];
+ }
+ used -= found;
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Trims the ustring16.
+ //! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16.
+ //! \param whitespace The characters that are to be considered as whitespace.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& trim(const ustring16<TAlloc>& whitespace = " \t\n\r")
+ {
+ core::array<uchar32_t> utf32white = whitespace.toUTF32();
+
+ // find start and end of the substring without the specified characters
+ const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1);
+ if (begin == -1)
+ return (*this="");
+
+ const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1);
+
+ return (*this = subString(begin, (end +1) - begin));
+ }
+
+
+ //! Erases a character from the ustring16.
+ //! May be slow, because all elements following after the erased element have to be copied.
+ //! \param index Index of element to be erased.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& erase(u32 index)
+ {
+ _IRR_DEBUG_BREAK_IF(index>used) // access violation
+
+ iterator i(*this, index);
+
+ uchar32_t t = *i;
+ u32 len = (t > 0xFFFF ? 2 : 1);
+
+ for (u32 j = static_cast<u32>(i.getPos()) + len; j <= used; ++j)
+ array[j - len] = array[j];
+
+ used -= len;
+ array[used] = 0;
+
+ return *this;
+ }
+
+
+ //! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& validate()
+ {
+ // Validate all unicode characters.
+ for (u32 i=0; i<allocated; ++i)
+ {
+ // Terminate on existing null.
+ if (array[i] == 0)
+ {
+ used = i;
+ return *this;
+ }
+ if (UTF16_IS_SURROGATE(array[i]))
+ {
+ if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i]))
+ array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
+ else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1]))
+ array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
+ ++i;
+ }
+ if (array[i] >= 0xFDD0 && array[i] <= 0xFDEF)
+ array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
+ }
+
+ // terminate
+ used = 0;
+ if (allocated > 0)
+ {
+ used = allocated - 1;
+ array[used] = 0;
+ }
+ return *this;
+ }
+
+
+ //! Gets the last char of the ustring16, or 0.
+ //! \return The last char of the ustring16, or 0.
+ uchar32_t lastChar() const
+ {
+ if (used < 1)
+ return 0;
+
+ if (UTF16_IS_SURROGATE_LO(array[used-1]))
+ {
+ // Make sure we have a paired surrogate.
+ if (used < 2)
+ return 0;
+
+ // Check for an invalid surrogate.
+ if (!UTF16_IS_SURROGATE_HI(array[used-2]))
+ return 0;
+
+ // Convert the surrogate pair into a single UTF-32 character.
+ return unicode::toUTF32(array[used-2], array[used-1]);
+ }
+ else
+ {
+ return array[used-1];
+ }
+ }
+
+
+ //! Split the ustring16 into parts.
+ /** This method will split a ustring16 at certain delimiter characters
+ into the container passed in as reference. The type of the container
+ has to be given as template parameter. It must provide a push_back and
+ a size method.
+ \param ret The result container
+ \param c C-style ustring16 of delimiter characters
+ \param count Number of delimiter characters
+ \param ignoreEmptyTokens Flag to avoid empty substrings in the result
+ container. If two delimiters occur without a character in between, an
+ empty substring would be placed in the result. If this flag is set,
+ only non-empty strings are stored.
+ \param keepSeparators Flag which allows to add the separator to the
+ result ustring16. If this flag is true, the concatenation of the
+ substrings results in the original ustring16. Otherwise, only the
+ characters between the delimiters are returned.
+ \return The number of resulting substrings
+ */
+ template<class container>
+ u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
+ {
+ if (!c)
+ return 0;
+
+ const_iterator i(*this);
+ const u32 oldSize=ret.size();
+ u32 pos = 0;
+ u32 lastpos = 0;
+ u32 lastpospos = 0;
+ bool lastWasSeparator = false;
+ while (!i.atEnd())
+ {
+ uchar32_t ch = *i;
+ bool foundSeparator = false;
+ for (u32 j=0; j<count; ++j)
+ {
+ if (ch == c[j])
+ {
+ if ((!ignoreEmptyTokens || pos - lastpos != 0) &&
+ !lastWasSeparator)
+ ret.push_back(ustring16<TAlloc>(&array[lastpospos], pos - lastpos));
+ foundSeparator = true;
+ lastpos = (keepSeparators ? pos : pos + 1);
+ lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1);
+ break;
+ }
+ }
+ lastWasSeparator = foundSeparator;
+ ++pos;
+ ++i;
+ }
+ u32 s = size() + 1;
+ if (s > lastpos)
+ ret.push_back(ustring16<TAlloc>(&array[lastpospos], s - lastpos));
+ return ret.size()-oldSize;
+ }
+
+
+ //! Split the ustring16 into parts.
+ /** This method will split a ustring16 at certain delimiter characters
+ into the container passed in as reference. The type of the container
+ has to be given as template parameter. It must provide a push_back and
+ a size method.
+ \param ret The result container
+ \param c A unicode string of delimiter characters
+ \param ignoreEmptyTokens Flag to avoid empty substrings in the result
+ container. If two delimiters occur without a character in between, an
+ empty substring would be placed in the result. If this flag is set,
+ only non-empty strings are stored.
+ \param keepSeparators Flag which allows to add the separator to the
+ result ustring16. If this flag is true, the concatenation of the
+ substrings results in the original ustring16. Otherwise, only the
+ characters between the delimiters are returned.
+ \return The number of resulting substrings
+ */
+ template<class container>
+ u32 split(container& ret, const ustring16<TAlloc>& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
+ {
+ core::array<uchar32_t> v = c.toUTF32();
+ return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators);
+ }
+
+
+ //! Gets the size of the allocated memory buffer for the string.
+ //! \return The size of the allocated memory buffer.
+ u32 capacity() const
+ {
+ return allocated;
+ }
+
+
+ //! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates.
+ //! \return The raw number of UTF-16 code points, excluding the trialing NUL.
+ u32 size_raw() const
+ {
+ return used;
+ }
+
+
+ //! Inserts a character into the string.
+ //! \param c The character to insert.
+ //! \param pos The position to insert the character.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& insert(uchar32_t c, u32 pos)
+ {
+ u8 len = (c > 0xFFFF ? 2 : 1);
+
+ if (used + len >= allocated)
+ reallocate(used + len);
+
+ used += len;
+
+ iterator iter(*this, pos);
+ for (u32 i = used - 2; i > iter.getPos(); --i)
+ array[i] = array[i - len];
+
+ if (c > 0xFFFF)
+ {
+ // c will be multibyte, so split it up into a surrogate pair.
+ uchar16_t x = static_cast<uchar16_t>(c);
+ uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
+ uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
+ array[iter.getPos()] = vh;
+ array[iter.getPos()+1] = vl;
+ }
+ else
+ {
+ array[iter.getPos()] = static_cast<uchar16_t>(c);
+ }
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Inserts a string into the string.
+ //! \param c The string to insert.
+ //! \param pos The position to insert the string.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& insert(const ustring16<TAlloc>& c, u32 pos)
+ {
+ u32 len = c.size_raw();
+ if (len == 0) return *this;
+
+ if (used + len >= allocated)
+ reallocate(used + len);
+
+ used += len;
+
+ iterator iter(*this, pos);
+ for (u32 i = used - 2; i > iter.getPos() + len; --i)
+ array[i] = array[i - len];
+
+ const uchar16_t* s = c.c_str();
+ for (u32 i = 0; i < len; ++i)
+ {
+ array[pos++] = *s;
+ ++s;
+ }
+
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Inserts a character into the string.
+ //! \param c The character to insert.
+ //! \param pos The position to insert the character.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& insert_raw(uchar16_t c, u32 pos)
+ {
+ if (used + 1 >= allocated)
+ reallocate(used + 1);
+
+ ++used;
+
+ for (u32 i = used - 1; i > pos; --i)
+ array[i] = array[i - 1];
+
+ array[pos] = c;
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Removes a character from string.
+ //! \param pos Position of the character to remove.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& erase_raw(u32 pos)
+ {
+ for (u32 i=pos; i<=used; ++i)
+ {
+ array[i] = array[i + 1];
+ }
+ --used;
+ array[used] = 0;
+ return *this;
+ }
+
+
+ //! Replaces a character in the string.
+ //! \param c The new character.
+ //! \param pos The position of the character to replace.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& replace_raw(uchar16_t c, u32 pos)
+ {
+ array[pos] = c;
+ return *this;
+ }
+
+
+ //! Returns an iterator to the beginning of the string.
+ //! \return An iterator to the beginning of the string.
+ iterator begin()
+ {
+ iterator i(*this, 0);
+ return i;
+ }
+
+
+ //! Returns an iterator to the beginning of the string.
+ //! \return An iterator to the beginning of the string.
+ const_iterator begin() const
+ {
+ const_iterator i(*this, 0);
+ return i;
+ }
+
+
+ //! Returns an iterator to the beginning of the string.
+ //! \return An iterator to the beginning of the string.
+ const_iterator cbegin() const
+ {
+ const_iterator i(*this, 0);
+ return i;
+ }
+
+
+ //! Returns an iterator to the end of the string.
+ //! \return An iterator to the end of the string.
+ iterator end()
+ {
+ iterator i(*this, 0);
+ i.toEnd();
+ return i;
+ }
+
+
+ //! Returns an iterator to the end of the string.
+ //! \return An iterator to the end of the string.
+ const_iterator end() const
+ {
+ const_iterator i(*this, 0);
+ i.toEnd();
+ return i;
+ }
+
+
+ //! Returns an iterator to the end of the string.
+ //! \return An iterator to the end of the string.
+ const_iterator cend() const
+ {
+ const_iterator i(*this, 0);
+ i.toEnd();
+ return i;
+ }
+
+
+ //! Converts the string to a UTF-8 encoded string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return A string containing the UTF-8 encoded string.
+ core::string<uchar8_t> toUTF8_s(const bool addBOM = false) const
+ {
+ core::string<uchar8_t> ret;
+ ret.reserve(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1);
+ const_iterator iter(*this, 0);
+
+ // Add the byte order mark if the user wants it.
+ if (addBOM)
+ {
+ ret.append(unicode::BOM_ENCODE_UTF8[0]);
+ ret.append(unicode::BOM_ENCODE_UTF8[1]);
+ ret.append(unicode::BOM_ENCODE_UTF8[2]);
+ }
+
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ if (c > 0xFFFF)
+ { // 4 bytes
+ uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7);
+ uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F);
+ uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F);
+ uchar8_t b4 = (0x2 << 6) | (c & 0x3F);
+ ret.append(b1);
+ ret.append(b2);
+ ret.append(b3);
+ ret.append(b4);
+ }
+ else if (c > 0x7FF)
+ { // 3 bytes
+ uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF);
+ uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F);
+ uchar8_t b3 = (0x2 << 6) | (c & 0x3F);
+ ret.append(b1);
+ ret.append(b2);
+ ret.append(b3);
+ }
+ else if (c > 0x7F)
+ { // 2 bytes
+ uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F);
+ uchar8_t b2 = (0x2 << 6) | (c & 0x3F);
+ ret.append(b1);
+ ret.append(b2);
+ }
+ else
+ { // 1 byte
+ ret.append(static_cast<uchar8_t>(c));
+ }
+ ++iter;
+ }
+ return ret;
+ }
+
+
+ //! Converts the string to a UTF-8 encoded string array.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return An array containing the UTF-8 encoded string.
+ core::array<uchar8_t> toUTF8(const bool addBOM = false) const
+ {
+ core::array<uchar8_t> ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1);
+ const_iterator iter(*this, 0);
+
+ // Add the byte order mark if the user wants it.
+ if (addBOM)
+ {
+ ret.push_back(unicode::BOM_ENCODE_UTF8[0]);
+ ret.push_back(unicode::BOM_ENCODE_UTF8[1]);
+ ret.push_back(unicode::BOM_ENCODE_UTF8[2]);
+ }
+
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ if (c > 0xFFFF)
+ { // 4 bytes
+ uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7);
+ uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F);
+ uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F);
+ uchar8_t b4 = (0x2 << 6) | (c & 0x3F);
+ ret.push_back(b1);
+ ret.push_back(b2);
+ ret.push_back(b3);
+ ret.push_back(b4);
+ }
+ else if (c > 0x7FF)
+ { // 3 bytes
+ uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF);
+ uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F);
+ uchar8_t b3 = (0x2 << 6) | (c & 0x3F);
+ ret.push_back(b1);
+ ret.push_back(b2);
+ ret.push_back(b3);
+ }
+ else if (c > 0x7F)
+ { // 2 bytes
+ uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F);
+ uchar8_t b2 = (0x2 << 6) | (c & 0x3F);
+ ret.push_back(b1);
+ ret.push_back(b2);
+ }
+ else
+ { // 1 byte
+ ret.push_back(static_cast<uchar8_t>(c));
+ }
+ ++iter;
+ }
+ ret.push_back(0);
+ return ret;
+ }
+
+
+#ifdef USTRING_CPP0X_NEWLITERALS // C++0x
+ //! Converts the string to a UTF-16 encoded string.
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return A string containing the UTF-16 encoded string.
+ core::string<char16_t> toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ core::string<char16_t> ret;
+ ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1);
+
+ // Add the BOM if specified.
+ if (addBOM)
+ {
+ if (endian == unicode::EUTFEE_NATIVE)
+ ret[0] = unicode::BOM;
+ else if (endian == unicode::EUTFEE_LITTLE)
+ {
+ uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str());
+ *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0];
+ *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1];
+ }
+ else
+ {
+ uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str());
+ *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0];
+ *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1];
+ }
+ }
+
+ ret.append(array);
+ if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
+ {
+ char16_t* ptr = ret.c_str();
+ for (u32 i = 0; i < ret.size(); ++i)
+ *ptr++ = unicode::swapEndian16(*ptr);
+ }
+ return ret;
+ }
+#endif
+
+
+ //! Converts the string to a UTF-16 encoded string array.
+ //! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class.
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return An array containing the UTF-16 encoded string.
+ core::array<uchar16_t> toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ core::array<uchar16_t> ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1);
+ uchar16_t* ptr = ret.pointer();
+
+ // Add the BOM if specified.
+ if (addBOM)
+ {
+ if (endian == unicode::EUTFEE_NATIVE)
+ *ptr = unicode::BOM;
+ else if (endian == unicode::EUTFEE_LITTLE)
+ {
+ uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr);
+ *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0];
+ *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1];
+ }
+ else
+ {
+ uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr);
+ *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0];
+ *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1];
+ }
+ ++ptr;
+ }
+
+ memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t));
+ if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
+ {
+ for (u32 i = 0; i <= used; ++i)
+ *ptr++ = unicode::swapEndian16(*ptr);
+ }
+ ret.set_used(used + (addBOM ? unicode::BOM_UTF16_LEN : 0));
+ ret.push_back(0);
+ return ret;
+ }
+
+
+#ifdef USTRING_CPP0X_NEWLITERALS // C++0x
+ //! Converts the string to a UTF-32 encoded string.
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return A string containing the UTF-32 encoded string.
+ core::string<char32_t> toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ core::string<char32_t> ret;
+ ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0));
+ const_iterator iter(*this, 0);
+
+ // Add the BOM if specified.
+ if (addBOM)
+ {
+ if (endian == unicode::EUTFEE_NATIVE)
+ ret.append(unicode::BOM);
+ else
+ {
+ union
+ {
+ uchar32_t full;
+ u8 chunk[4];
+ } t;
+
+ if (endian == unicode::EUTFEE_LITTLE)
+ {
+ t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0];
+ t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1];
+ t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2];
+ t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3];
+ }
+ else
+ {
+ t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0];
+ t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1];
+ t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2];
+ t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3];
+ }
+ ret.append(t.full);
+ }
+ }
+
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
+ c = unicode::swapEndian32(c);
+ ret.append(c);
+ ++iter;
+ }
+ return ret;
+ }
+#endif
+
+
+ //! Converts the string to a UTF-32 encoded string array.
+ //! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class.
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return An array containing the UTF-32 encoded string.
+ core::array<uchar32_t> toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ core::array<uchar32_t> ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1);
+ const_iterator iter(*this, 0);
+
+ // Add the BOM if specified.
+ if (addBOM)
+ {
+ if (endian == unicode::EUTFEE_NATIVE)
+ ret.push_back(unicode::BOM);
+ else
+ {
+ union
+ {
+ uchar32_t full;
+ u8 chunk[4];
+ } t;
+
+ if (endian == unicode::EUTFEE_LITTLE)
+ {
+ t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0];
+ t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1];
+ t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2];
+ t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3];
+ }
+ else
+ {
+ t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0];
+ t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1];
+ t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2];
+ t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3];
+ }
+ ret.push_back(t.full);
+ }
+ }
+ ret.push_back(0);
+
+ while (!iter.atEnd())
+ {
+ uchar32_t c = *iter;
+ if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
+ c = unicode::swapEndian32(c);
+ ret.push_back(c);
+ ++iter;
+ }
+ return ret;
+ }
+
+
+ //! Converts the string to a wchar_t encoded string.
+ /** The size of a wchar_t changes depending on the platform. This function will store a
+ correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return A string containing the wchar_t encoded string.
+ core::string<wchar_t> toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ if (sizeof(wchar_t) == 4)
+ {
+ core::array<uchar32_t> a(toUTF32(endian, addBOM));
+ core::stringw ret(a.pointer());
+ return ret;
+ }
+ else if (sizeof(wchar_t) == 2)
+ {
+ if (endian == unicode::EUTFEE_NATIVE && addBOM == false)
+ {
+ core::stringw ret(array);
+ return ret;
+ }
+ else
+ {
+ core::array<uchar16_t> a(toUTF16(endian, addBOM));
+ core::stringw ret(a.pointer());
+ return ret;
+ }
+ }
+ else if (sizeof(wchar_t) == 1)
+ {
+ core::array<uchar8_t> a(toUTF8(addBOM));
+ core::stringw ret(a.pointer());
+ return ret;
+ }
+
+ // Shouldn't happen.
+ return core::stringw();
+ }
+
+
+ //! Converts the string to a wchar_t encoded string array.
+ /** The size of a wchar_t changes depending on the platform. This function will store a
+ correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return An array containing the wchar_t encoded string.
+ core::array<wchar_t> toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+ if (sizeof(wchar_t) == 4)
+ {
+ core::array<uchar32_t> a(toUTF32(endian, addBOM));
+ core::array<wchar_t> ret(a.size());
+ ret.set_used(a.size());
+ memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t));
+ return ret;
+ }
+ if (sizeof(wchar_t) == 2)
+ {
+ if (endian == unicode::EUTFEE_NATIVE && addBOM == false)
+ {
+ core::array<wchar_t> ret(used);
+ ret.set_used(used);
+ memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t));
+ return ret;
+ }
+ else
+ {
+ core::array<uchar16_t> a(toUTF16(endian, addBOM));
+ core::array<wchar_t> ret(a.size());
+ ret.set_used(a.size());
+ memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t));
+ return ret;
+ }
+ }
+ if (sizeof(wchar_t) == 1)
+ {
+ core::array<uchar8_t> a(toUTF8(addBOM));
+ core::array<wchar_t> ret(a.size());
+ ret.set_used(a.size());
+ memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t));
+ return ret;
+ }
+
+ // Shouldn't happen.
+ return core::array<wchar_t>();
+ }
+
+ //! Converts the string to a properly encoded io::path string.
+ //! \param endian The desired endianness of the string.
+ //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
+ //! \return An io::path string containing the properly encoded string.
+ io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
+ {
+#if defined(_IRR_WCHAR_FILESYSTEM)
+ return toWCHAR_s(endian, addBOM);
+#else
+ return toUTF8_s(addBOM);
+#endif
+ }
+
+ //! Loads an unknown stream of data.
+ //! Will attempt to determine if the stream is unicode data. Useful for loading from files.
+ //! \param data The data stream to load from.
+ //! \param data_size The length of the data string.
+ //! \return A reference to our current string.
+ ustring16<TAlloc>& loadDataStream(const char* data, size_t data_size)
+ {
+ // Clear our string.
+ *this = "";
+ if (!data)
+ return *this;
+
+ unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data);
+ switch (e)
+ {
+ default:
+ case unicode::EUTFE_UTF8:
+ append((uchar8_t*)data, data_size);
+ break;
+
+ case unicode::EUTFE_UTF16:
+ case unicode::EUTFE_UTF16_BE:
+ case unicode::EUTFE_UTF16_LE:
+ append((uchar16_t*)data, data_size / 2);
+ break;
+
+ case unicode::EUTFE_UTF32:
+ case unicode::EUTFE_UTF32_BE:
+ case unicode::EUTFE_UTF32_LE:
+ append((uchar32_t*)data, data_size / 4);
+ break;
+ }
+
+ return *this;
+ }
+
+ //! Gets the encoding of the Unicode string this class contains.
+ //! \return An enum describing the current encoding of this string.
+ const unicode::EUTF_ENCODE getEncoding() const
+ {
+ return encoding;
+ }
+
+ //! Gets the endianness of the Unicode string this class contains.
+ //! \return An enum describing the endianness of this string.
+ const unicode::EUTF_ENDIAN getEndianness() const
+ {
+ if (encoding == unicode::EUTFE_UTF16_LE ||
+ encoding == unicode::EUTFE_UTF32_LE)
+ return unicode::EUTFEE_LITTLE;
+ else return unicode::EUTFEE_BIG;
+ }
+
+private:
+
+ //! Reallocate the string, making it bigger or smaller.
+ //! \param new_size The new size of the string.
+ void reallocate(u32 new_size)
+ {
+ uchar16_t* old_array = array;
+
+ array = allocator.allocate(new_size + 1); //new u16[new_size];
+ allocated = new_size + 1;
+ if (old_array == 0) return;
+
+ u32 amount = used < new_size ? used : new_size;
+ for (u32 i=0; i<=amount; ++i)
+ array[i] = old_array[i];
+
+ if (allocated <= used)
+ used = allocated - 1;
+
+ array[used] = 0;
+
+ allocator.deallocate(old_array); // delete [] old_array;
+ }
+
+ //--- member variables
+
+ uchar16_t* array;
+ unicode::EUTF_ENCODE encoding;
+ u32 allocated;
+ u32 used;
+ TAlloc allocator;
+ //irrAllocator<uchar16_t> allocator;
+};
+
+typedef ustring16<irrAllocator<uchar16_t> > ustring;
+
+
+//! Appends two ustring16s.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a null-terminated unicode string.
+template <typename TAlloc, class B>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const B* const right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a null-terminated unicode string.
+template <class B, typename TAlloc>
+inline ustring16<TAlloc> operator+(const B* const left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an Irrlicht string.
+template <typename TAlloc, typename B, typename BAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const string<B, BAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an Irrlicht string.
+template <typename TAlloc, typename B, typename BAlloc>
+inline ustring16<TAlloc> operator+(const string<B, BAlloc>& left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a std::basic_string.
+template <typename TAlloc, typename B, typename A, typename BAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const std::basic_string<B, A, BAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a std::basic_string.
+template <typename TAlloc, typename B, typename A, typename BAlloc>
+inline ustring16<TAlloc> operator+(const std::basic_string<B, A, BAlloc>& left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a char.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const char right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a char.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const char left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+#ifdef USTRING_CPP0X_NEWLITERALS
+//! Appends a ustring16 and a uchar32_t.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const uchar32_t right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a uchar32_t.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const uchar32_t left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += right;
+ return ret;
+}
+#endif
+
+
+//! Appends a ustring16 and a short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const short right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and a short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const short left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned short right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned short left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const int right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and an int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const int left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned int right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned int left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const long right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and a long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const long left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned long right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and an unsigned long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned long left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a float.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const float right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and a float.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const float left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+//! Appends a ustring16 and a double.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const double right)
+{
+ ustring16<TAlloc> ret(left);
+ ret += core::stringc(right);
+ return ret;
+}
+
+
+//! Appends a ustring16 and a double.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const double left, const ustring16<TAlloc>& right)
+{
+ ustring16<TAlloc> ret(core::stringc(left));
+ ret += right;
+ return ret;
+}
+
+
+#ifdef USTRING_CPP0X
+//! Appends two ustring16s.
+template <typename TAlloc>
+inline ustring16<TAlloc>&& operator+(const ustring16<TAlloc>& left, ustring16<TAlloc>&& right)
+{
+ //std::cout << "MOVE operator+(&, &&)" << std::endl;
+ right.insert(left, 0);
+ return std::move(right);
+}
+
+
+//! Appends two ustring16s.
+template <typename TAlloc>
+inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const ustring16<TAlloc>& right)
+{
+ //std::cout << "MOVE operator+(&&, &)" << std::endl;
+ left.append(right);
+ return std::move(left);
+}
+
+
+//! Appends two ustring16s.
+template <typename TAlloc>
+inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, ustring16<TAlloc>&& right)
+{
+ //std::cout << "MOVE operator+(&&, &&)" << std::endl;
+ if ((right.size_raw() <= left.capacity() - left.size_raw()) ||
+ (right.capacity() - right.size_raw() < left.size_raw()))
+ {
+ left.append(right);
+ return std::move(left);
+ }
+ else
+ {
+ right.insert(left, 0);
+ return std::move(right);
+ }
+}
+
+
+//! Appends a ustring16 and a null-terminated unicode string.
+template <typename TAlloc, class B>
+inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const B* const right)
+{
+ //std::cout << "MOVE operator+(&&, B*)" << std::endl;
+ left.append(right);
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a null-terminated unicode string.
+template <class B, typename TAlloc>
+inline ustring16<TAlloc>&& operator+(const B* const left, ustring16<TAlloc>&& right)
+{
+ //std::cout << "MOVE operator+(B*, &&)" << std::endl;
+ right.insert(left, 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an Irrlicht string.
+template <typename TAlloc, typename B, typename BAlloc>
+inline ustring16<TAlloc>&& operator+(const string<B, BAlloc>& left, ustring16<TAlloc>&& right)
+{
+ //std::cout << "MOVE operator+(&, &&)" << std::endl;
+ right.insert(left, 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an Irrlicht string.
+template <typename TAlloc, typename B, typename BAlloc>
+inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const string<B, BAlloc>& right)
+{
+ //std::cout << "MOVE operator+(&&, &)" << std::endl;
+ left.append(right);
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a std::basic_string.
+template <typename TAlloc, typename B, typename A, typename BAlloc>
+inline ustring16<TAlloc>&& operator+(const std::basic_string<B, A, BAlloc>& left, ustring16<TAlloc>&& right)
+{
+ //std::cout << "MOVE operator+(&, &&)" << std::endl;
+ right.insert(core::ustring16<TAlloc>(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and a std::basic_string.
+template <typename TAlloc, typename B, typename A, typename BAlloc>
+inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const std::basic_string<B, A, BAlloc>& right)
+{
+ //std::cout << "MOVE operator+(&&, &)" << std::endl;
+ left.append(right);
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a char.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const char right)
+{
+ left.append((uchar32_t)right);
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a char.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const char left, ustring16<TAlloc>&& right)
+{
+ right.insert((uchar32_t)left, 0);
+ return std::move(right);
+}
+
+
+#ifdef USTRING_CPP0X_NEWLITERALS
+//! Appends a ustring16 and a uchar32_t.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const uchar32_t right)
+{
+ left.append(right);
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a uchar32_t.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const uchar32_t left, ustring16<TAlloc>&& right)
+{
+ right.insert(left, 0);
+ return std::move(right);
+}
+#endif
+
+
+//! Appends a ustring16 and a short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const short right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const short left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an unsigned short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned short right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and an unsigned short.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned short left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const int right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and an int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const int left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an unsigned int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned int right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and an unsigned int.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned int left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and a long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const long right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const long left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and an unsigned long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned long right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and an unsigned long.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const unsigned long left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and a float.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const float right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a float.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const float left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+
+
+//! Appends a ustring16 and a double.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const double right)
+{
+ left.append(core::stringc(right));
+ return std::move(left);
+}
+
+
+//! Appends a ustring16 and a double.
+template <typename TAlloc>
+inline ustring16<TAlloc> operator+(const double left, ustring16<TAlloc>&& right)
+{
+ right.insert(core::stringc(left), 0);
+ return std::move(right);
+}
+#endif
+
+
+#ifndef USTRING_NO_STL
+//! Writes a ustring16 to an ostream.
+template <typename TAlloc>
+inline std::ostream& operator<<(std::ostream& out, const ustring16<TAlloc>& in)
+{
+ out << in.toUTF8_s().c_str();
+ return out;
+}
+
+//! Writes a ustring16 to a wostream.
+template <typename TAlloc>
+inline std::wostream& operator<<(std::wostream& out, const ustring16<TAlloc>& in)
+{
+ out << in.toWCHAR_s().c_str();
+ return out;
+}
+#endif
+
+
+#ifndef USTRING_NO_STL
+
+namespace unicode
+{
+
+//! Hashing algorithm for hashing a ustring. Used for things like unordered_maps.
+//! Algorithm taken from std::hash<std::string>.
+class hash : public std::unary_function<core::ustring, size_t>
+{
+ public:
+ size_t operator()(const core::ustring& s) const
+ {
+ size_t ret = 2166136261U;
+ size_t index = 0;
+ size_t stride = 1 + s.size_raw() / 10;
+
+ core::ustring::const_iterator i = s.begin();
+ while (i != s.end())
+ {
+ // TODO: Don't force u32 on an x64 OS. Make it agnostic.
+ ret = 16777619U * ret ^ (size_t)s[(u32)index];
+ index += stride;
+ i += stride;
+ }
+ return (ret);
+ }
+};
+
+} // end namespace unicode
+
+#endif
+
+} // end namespace core
+} // end namespace irr
+
+#endif
diff --git a/src/cguittfont/xCGUITTFont.cpp b/src/cguittfont/xCGUITTFont.cpp
new file mode 100644
index 000000000..c51922e4c
--- /dev/null
+++ b/src/cguittfont/xCGUITTFont.cpp
@@ -0,0 +1,5 @@
+// A wrapper source file to avoid hack with gcc and modifying
+// the CGUITTFont files.
+
+#include "xCGUITTFont.h"
+#include "CGUITTFont.cpp"
diff --git a/src/cguittfont/xCGUITTFont.h b/src/cguittfont/xCGUITTFont.h
new file mode 100644
index 000000000..c3efe7f6f
--- /dev/null
+++ b/src/cguittfont/xCGUITTFont.h
@@ -0,0 +1,7 @@
+// A wrapper header to avoid hack with gcc and modifying
+// the CGUITTFont files.
+
+#include <algorithm>
+#include <stddef.h>
+#include "irrUString.h"
+#include "CGUITTFont.h"
diff --git a/src/client.cpp b/src/client.cpp
index 9969ef538..415f07311 100644
--- a/src/client.cpp
+++ b/src/client.cpp
@@ -1514,6 +1514,26 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
}
}
}
+ else if(command == TOCLIENT_MOVEMENT)
+ {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+ Player *player = m_env.getLocalPlayer();
+ assert(player != NULL);
+
+ player->movement_acceleration_default = readF1000(is) * BS;
+ player->movement_acceleration_air = readF1000(is) * BS;
+ player->movement_acceleration_fast = readF1000(is) * BS;
+ player->movement_speed_walk = readF1000(is) * BS;
+ player->movement_speed_crouch = readF1000(is) * BS;
+ player->movement_speed_fast = readF1000(is) * BS;
+ player->movement_speed_climb = readF1000(is) * BS;
+ player->movement_speed_jump = readF1000(is) * BS;
+ player->movement_liquid_fluidity = readF1000(is) * BS;
+ player->movement_liquid_fluidity_smooth = readF1000(is) * BS;
+ player->movement_liquid_sink = readF1000(is) * BS;
+ player->movement_gravity = readF1000(is) * BS;
+ }
else if(command == TOCLIENT_HP)
{
std::string datastring((char*)&data[2], datasize-2);
diff --git a/src/clientmap.cpp b/src/clientmap.cpp
index 800549a3b..0b30453b8 100644
--- a/src/clientmap.cpp
+++ b/src/clientmap.cpp
@@ -864,7 +864,7 @@ void ClientMap::renderPostFx()
// - If the player is in liquid, draw a semi-transparent overlay.
const ContentFeatures& features = nodemgr->get(n);
video::SColor post_effect_color = features.post_effect_color;
- if(features.solidness == 2 && g_settings->getBool("free_move") == false)
+ if(features.solidness == 2 && !(g_settings->getBool("noclip") && m_gamedef->checkLocalPrivilege("noclip")))
{
post_effect_color = video::SColor(255, 0, 0, 0);
}
diff --git a/src/clientserver.h b/src/clientserver.h
index 52b9dc7b0..7fb3e83d2 100644
--- a/src/clientserver.h
+++ b/src/clientserver.h
@@ -364,6 +364,23 @@ enum ToClientCommand
u16 len
u8[len] formname
*/
+
+ TOCLIENT_MOVEMENT = 0x45,
+ /*
+ u16 command
+ f1000 movement_acceleration_default
+ f1000 movement_acceleration_air
+ f1000 movement_acceleration_fast
+ f1000 movement_speed_walk
+ f1000 movement_speed_crouch
+ f1000 movement_speed_fast
+ f1000 movement_speed_climb
+ f1000 movement_speed_jump
+ f1000 movement_liquid_fluidity
+ f1000 movement_liquid_fluidity_smooth
+ f1000 movement_liquid_sink
+ f1000 movement_gravity
+ */
};
enum ToServerCommand
diff --git a/src/clouds.cpp b/src/clouds.cpp
index 146eeb831..5b980a5ba 100644
--- a/src/clouds.cpp
+++ b/src/clouds.cpp
@@ -45,8 +45,7 @@ Clouds::Clouds(
//m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
m_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
- m_cloud_y = BS*100;
- //m_cloud_y = BS*50;
+ m_cloud_y = BS * g_settings->getS16("cloud_height");
m_box = core::aabbox3d<f32>(-BS*1000000,m_cloud_y-BS,-BS*1000000,
BS*1000000,m_cloud_y+BS,BS*1000000);
diff --git a/src/cmake_config.h.in b/src/cmake_config.h.in
index 4853d854f..51827cce6 100644
--- a/src/cmake_config.h.in
+++ b/src/cmake_config.h.in
@@ -9,6 +9,7 @@
#define CMAKE_USE_GETTEXT @USE_GETTEXT@
#define CMAKE_USE_CURL @USE_CURL@
#define CMAKE_USE_SOUND @USE_SOUND@
+#define CMAKE_USE_FREETYPE @USE_FREETYPE@
#define CMAKE_STATIC_SHAREDIR "@SHAREDIR@"
#ifdef NDEBUG
diff --git a/src/config.h b/src/config.h
index f37ec0fed..37dc6e0ef 100644
--- a/src/config.h
+++ b/src/config.h
@@ -12,6 +12,7 @@
#define USE_GETTEXT 0
#define USE_SOUND 0
#define USE_CURL 0
+#define USE_FREETYPE 0
#define STATIC_SHAREDIR ""
#define BUILD_INFO "non-cmake"
@@ -29,6 +30,8 @@
#define USE_SOUND CMAKE_USE_SOUND
#undef USE_CURL
#define USE_CURL CMAKE_USE_CURL
+ #undef USE_FREETYPE
+ #define USE_FREETYPE CMAKE_USE_FREETYPE
#undef STATIC_SHAREDIR
#define STATIC_SHAREDIR CMAKE_STATIC_SHAREDIR
#undef BUILD_INFO
diff --git a/src/content_abm.cpp b/src/content_abm.cpp
index 9e65a7ab0..ce1751117 100644
--- a/src/content_abm.cpp
+++ b/src/content_abm.cpp
@@ -80,7 +80,8 @@ public:
ServerMap *map = &env->getServerMap();
MapNode n_top = map->getNodeNoEx(p+v3s16(0,1,0));
- if(!ndef->get(n_top).light_propagates ||
+ if((!ndef->get(n_top).light_propagates &&
+ n_top.getContent() != CONTENT_IGNORE) ||
ndef->get(n_top).isLiquid())
{
n.setContent(ndef->getId("mapgen_dirt"));
diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp
index aa3c061d6..290890490 100644
--- a/src/content_mapblock.cpp
+++ b/src/content_mapblock.cpp
@@ -733,7 +733,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data,
u16 l = getInteriorLight(n, 1, data);
video::SColor c = MapBlock_LightColor(255, l, decode_light(f.light_source));
- for(u32 j=0; j<4; j++)
+ for(u32 j=0; j<2; j++)
{
video::S3DVertex vertices[4] =
{
@@ -759,16 +759,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data,
for(u16 i=0; i<4; i++)
vertices[i].Pos.rotateXZBy(-45);
}
- else if(j == 2)
- {
- for(u16 i=0; i<4; i++)
- vertices[i].Pos.rotateXZBy(135);
- }
- else if(j == 3)
- {
- for(u16 i=0; i<4; i++)
- vertices[i].Pos.rotateXZBy(-135);
- }
for(u16 i=0; i<4; i++)
{
diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp
index ca5f33609..6cdaaa496 100644
--- a/src/defaultsettings.cpp
+++ b/src/defaultsettings.cpp
@@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
*/
#include "settings.h"
+#include "filesys.h"
void set_default_settings(Settings *settings)
{
@@ -107,6 +108,7 @@ void set_default_settings(Settings *settings)
settings->setDefault("screenshot_path", ".");
settings->setDefault("view_bobbing_amount", "1.0");
settings->setDefault("enable_3d_clouds", "true");
+ settings->setDefault("cloud_height", "120");
settings->setDefault("opaque_water", "false");
settings->setDefault("console_color", "(0,0,0)");
settings->setDefault("console_alpha", "200");
@@ -128,6 +130,19 @@ void set_default_settings(Settings *settings)
settings->setDefault("media_fetch_threads", "8");
+ settings->setDefault("serverlist_url", "servers.minetest.net");
+ settings->setDefault("serverlist_file", "favoriteservers.txt");
+ settings->setDefault("server_announce", "false");
+ settings->setDefault("server_url", "");
+ settings->setDefault("server_address", "");
+ settings->setDefault("server_name", "");
+ settings->setDefault("server_description", "");
+
+ settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "liberationsans.ttf"));
+ settings->setDefault("font_size", "13");
+ settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "liberationmono.ttf"));
+ settings->setDefault("mono_font_size", "13");
+
// Server stuff
// "map-dir" doesn't exist by default.
settings->setDefault("default_game", "minetest");
@@ -168,5 +183,42 @@ void set_default_settings(Settings *settings)
settings->setDefault("congestion_control_max_rate", "400");
settings->setDefault("congestion_control_min_rate", "10");
settings->setDefault("remote_media", "");
+ settings->setDefault("debug_log_level", "0");
+ // physics stuff
+ settings->setDefault("movement_acceleration_default", "3");
+ settings->setDefault("movement_acceleration_air", "2");
+ settings->setDefault("movement_acceleration_fast", "10");
+ settings->setDefault("movement_speed_walk", "4");
+ settings->setDefault("movement_speed_crouch", "1.35");
+ settings->setDefault("movement_speed_fast", "20");
+ settings->setDefault("movement_speed_climb", "2");
+ settings->setDefault("movement_speed_jump", "6.5");
+ settings->setDefault("movement_liquid_fluidity", "1");
+ settings->setDefault("movement_liquid_fluidity_smooth", "0.5");
+ settings->setDefault("movement_liquid_sink", "10");
+ settings->setDefault("movement_gravity", "9.81");
+
+ //mapgen related things
+ settings->setDefault("mg_name", "v6");
+ settings->setDefault("water_level", "1");
+ settings->setDefault("chunksize", "5");
+ settings->setDefault("mg_flags", "trees, caves, v6_biome_blend");
+ settings->setDefault("mgv6_freq_desert", "0.45");
+ settings->setDefault("mgv6_freq_beach", "0.15");
+
+ settings->setDefault("mgv6_np_terrain_base", "-4, 20, (250.0, 250, 250), 82341, 5, 0.6");
+ settings->setDefault("mgv6_np_terrain_higher", "20, 16, (500, 500, 500), 85039, 5, 0.6");
+ settings->setDefault("mgv6_np_steepness", "0.85, 0.5, (125, 125, 125), -932, 5, 0.7");
+ settings->setDefault("mgv6_np_height_select", "0.5, 1, (250, 250, 250), 4213, 5, 0.69");
+ settings->setDefault("mgv6_np_trees", "0, 1, (125, 125, 125), 2, 4, 0.66");
+ settings->setDefault("mgv6_np_mud", "4, 2, (200, 200, 200), 91013, 3, 0.55");
+ settings->setDefault("mgv6_np_beach", "0, 1, (250, 250, 250), 59420, 3, 0.50");
+ settings->setDefault("mgv6_np_biome", "0, 1, (250, 250, 250), 9130, 3, 0.50");
+ settings->setDefault("mgv6_np_cave", "6, 6, (250, 250, 250), 34329, 3, 0.50");
+
+ settings->setDefault("mgv7_np_terrain", "10, 12, (350, 350, 350), 82341, 5, 0.6");
+ settings->setDefault("mgv7_np_bgroup", "0.5, 0.3125, (350, 350, 350), 5923, 2, 0.6");
+ settings->setDefault("mgv7_np_heat", "25, 50, (500, 500, 500), 35293, 1, 0");
+ settings->setDefault("mgv7_np_humidity", "50, 31.25, (750, 750, 750), 12094, 2, 0.6");
}
diff --git a/src/environment.cpp b/src/environment.cpp
index 3f94484fe..ebf5e9a63 100644
--- a/src/environment.cpp
+++ b/src/environment.cpp
@@ -1301,6 +1301,7 @@ u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
return id;
}
+#if 0
bool ServerEnvironment::addActiveObjectAsStatic(ServerActiveObject *obj)
{
assert(obj);
@@ -1343,6 +1344,7 @@ bool ServerEnvironment::addActiveObjectAsStatic(ServerActiveObject *obj)
return succeeded;
}
+#endif
/*
Finds out what new objects have been added to
@@ -1563,13 +1565,15 @@ void ServerEnvironment::removeRemovedObjects()
*/
if(obj->m_static_exists && obj->m_removed)
{
- MapBlock *block = m_map->emergeBlock(obj->m_static_block);
- if(block)
- {
+ MapBlock *block = m_map->emergeBlock(obj->m_static_block, false);
+ if (block) {
block->m_static_objects.remove(id);
block->raiseModified(MOD_STATE_WRITE_NEEDED,
"removeRemovedObjects");
obj->m_static_exists = false;
+ } else {
+ infostream << "failed to emerge block from which "
+ "an object to be removed was loaded from. id="<<id<<std::endl;
}
}
@@ -1717,6 +1721,8 @@ void ServerEnvironment::activateObjects(MapBlock *block, u32 dtime_s)
If force_delete is set, active object is deleted nevertheless. It
shall only be set so in the destructor of the environment.
+
+ If block wasn't generated (not in memory or on disk),
*/
void ServerEnvironment::deactivateFarObjects(bool force_delete)
{
@@ -2059,20 +2065,37 @@ void ClientEnvironment::step(float dtime)
{
// Gravity
v3f speed = lplayer->getSpeed();
- if(lplayer->swimming_up == false)
- speed.Y -= 9.81 * BS * dtime_part * 2;
+ if(lplayer->in_liquid == false)
+ speed.Y -= lplayer->movement_gravity * dtime_part * 2;
- // Water resistance
- if(lplayer->in_water_stable || lplayer->in_water)
- {
- f32 max_down = 2.0*BS;
- if(speed.Y < -max_down) speed.Y = -max_down;
+ // Liquid floating / sinking
+ if(lplayer->in_liquid && !lplayer->swimming_vertical)
+ speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
- f32 max = 2.5*BS;
- if(speed.getLength() > max)
- {
- speed = speed / speed.getLength() * max;
- }
+ // Liquid resistance
+ if(lplayer->in_liquid_stable || lplayer->in_liquid)
+ {
+ // How much the node's viscosity blocks movement, ranges between 0 and 1
+ // Should match the scale at which viscosity increase affects other liquid attributes
+ const f32 viscosity_factor = 0.3;
+
+ v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
+ f32 dl = d_wanted.getLength();
+ if(dl > lplayer->movement_liquid_fluidity_smooth)
+ dl = lplayer->movement_liquid_fluidity_smooth;
+ dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
+
+ v3f d = d_wanted.normalize() * dl;
+ speed += d;
+
+#if 0 // old code
+ if(speed.X > lplayer->movement_liquid_fluidity + lplayer->movement_liquid_fluidity_smooth) speed.X -= lplayer->movement_liquid_fluidity_smooth;
+ if(speed.X < -lplayer->movement_liquid_fluidity - lplayer->movement_liquid_fluidity_smooth) speed.X += lplayer->movement_liquid_fluidity_smooth;
+ if(speed.Y > lplayer->movement_liquid_fluidity + lplayer->movement_liquid_fluidity_smooth) speed.Y -= lplayer->movement_liquid_fluidity_smooth;
+ if(speed.Y < -lplayer->movement_liquid_fluidity - lplayer->movement_liquid_fluidity_smooth) speed.Y += lplayer->movement_liquid_fluidity_smooth;
+ if(speed.Z > lplayer->movement_liquid_fluidity + lplayer->movement_liquid_fluidity_smooth) speed.Z -= lplayer->movement_liquid_fluidity_smooth;
+ if(speed.Z < -lplayer->movement_liquid_fluidity - lplayer->movement_liquid_fluidity_smooth) speed.Z += lplayer->movement_liquid_fluidity_smooth;
+#endif
}
lplayer->setSpeed(speed);
diff --git a/src/environment.h b/src/environment.h
index d17edeacd..d1e61967f 100644
--- a/src/environment.h
+++ b/src/environment.h
@@ -241,8 +241,9 @@ public:
MapBlock.
Caller allocates memory, ServerEnvironment frees memory.
Return value: true if succeeded, false if failed.
+ (note: not used, pending removal from engine)
*/
- bool addActiveObjectAsStatic(ServerActiveObject *object);
+ //bool addActiveObjectAsStatic(ServerActiveObject *object);
/*
Find out what new objects have been added to
diff --git a/src/farmesh.cpp b/src/farmesh.cpp
index bd08acadc..23f3db5f6 100644
--- a/src/farmesh.cpp
+++ b/src/farmesh.cpp
@@ -120,14 +120,14 @@ HeightPoint ground_height(u64 seed, v2s16 p2d)
if(n)
return n->getValue();
HeightPoint hp;
- s16 level = mapgen::find_ground_level_from_noise(seed, p2d, 3);
+ s16 level = Mapgen::find_ground_level_from_noise(seed, p2d, 3);
hp.gh = (level-4)*BS;
hp.ma = (4)*BS;
/*hp.gh = BS*base_rock_level_2d(seed, p2d);
hp.ma = BS*get_mud_add_amount(seed, p2d);*/
- hp.have_sand = mapgen::get_have_beach(seed, p2d);
+ hp.have_sand = Mapgen::get_have_beach(seed, p2d);
if(hp.gh > BS*WATER_LEVEL)
- hp.tree_amount = mapgen::tree_amount_2d(seed, p2d);
+ hp.tree_amount = Mapgen::tree_amount_2d(seed, p2d);
else
hp.tree_amount = 0;
// No mud has been added if mud amount is less than 1
diff --git a/src/game.cpp b/src/game.cpp
index 588a0fef3..c77754b5f 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1262,7 +1262,7 @@ void the_game(
gui::IGUIStaticText *guitext_info = guienv->addStaticText(
L"",
core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
- false, false);
+ false, true);
// Status text (displays info when showing and hiding GUI stuff, etc.)
gui::IGUIStaticText *guitext_status = guienv->addStaticText(
@@ -2482,7 +2482,9 @@ void the_game(
// Sign special case, at least until formspec is properly implemented.
// Deprecated?
- if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
+ if(meta && meta->getString("formspec") == "hack:sign_text_input"
+ && !random_input
+ && !input->isKeyDown(getKeySetting("keymap_sneak")))
{
infostream<<"Launching metadata text input"<<std::endl;
@@ -2497,7 +2499,8 @@ void the_game(
wtext))->drop();
}
// If metadata provides an inventory view, activate it
- else if(meta && meta->getString("formspec") != "" && !random_input)
+ else if(meta && meta->getString("formspec") != "" && !random_input
+ && !input->isKeyDown(getKeySetting("keymap_sneak")))
{
infostream<<"Launching custom inventory view"<<std::endl;
@@ -2528,7 +2531,8 @@ void the_game(
// make that happen
const ItemDefinition &def =
playeritem.getDefinition(itemdef);
- if(def.node_placement_prediction != "")
+ if(def.node_placement_prediction != ""
+ && !nodedef->get(map.getNode(nodepos)).rightclickable)
do{ // breakable
verbosestream<<"Node placement prediction for "
<<playeritem.name<<" is "
diff --git a/src/gettext.h b/src/gettext.h
index 54470cb0d..452787de4 100644
--- a/src/gettext.h
+++ b/src/gettext.h
@@ -12,6 +12,11 @@
#define gettext_noop(String) String
#define N_(String) gettext_noop (String)
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
inline void init_gettext(const char *path) {
#if USE_GETTEXT
// don't do this if MSVC compiler is used, it gives an assertion fail
@@ -20,14 +25,44 @@ inline void init_gettext(const char *path) {
#endif
bindtextdomain(PROJECT_NAME, path);
textdomain(PROJECT_NAME);
+#if defined(_WIN32)
+ // As linux is successfully switched to UTF-8 completely at about year 2005
+ // Windows still uses obsolete codepage based locales because you
+ // cannot recompile closed-source applications
+
+ // Set character encoding for Win32
+ char *tdomain = textdomain( (char *) NULL );
+ if( tdomain == NULL )
+ {
+ fprintf( stderr, "warning: domainname parameter is the null pointer, default domain is not set\n" );
+ tdomain = (char *) "messages";
+ }
+ /*char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" );
+ //fprintf( stdout, "%s: debug: domainname = %s; codeset = %s\n", argv[0], tdomain, codeset );
+#endif // defined(_WIN32)
#endif
}
inline wchar_t* chartowchar_t(const char *str)
{
+ wchar_t* nstr = 0;
+#if defined(_WIN32)
+ int nResult = MultiByteToWideChar( CP_UTF8, 0, (LPCSTR) str, -1, 0, 0 );
+ if( nResult == 0 )
+ {
+ fprintf( stderr, "error: MultiByteToWideChar returned null\n" );
+ }
+ else
+ {
+ nstr = new wchar_t[nResult];
+ MultiByteToWideChar( CP_UTF8, 0, (LPCSTR) str, -1, (WCHAR *) nstr, nResult );
+ }
+#else
size_t l = strlen(str)+1;
- wchar_t* nstr = new wchar_t[l];
+ nstr = new wchar_t[l];
mbstowcs(nstr, str, l);
+#endif
+
return nstr;
}
@@ -38,12 +73,12 @@ inline wchar_t* wgettext(const char *str)
inline void changeCtype(const char *l)
{
- char *ret = NULL;
+ /*char *ret = NULL;
ret = setlocale(LC_CTYPE, l);
if(ret == NULL)
infostream<<"locale could not be set"<<std::endl;
else
- infostream<<"locale has been set to:"<<ret<<std::endl;
+ infostream<<"locale has been set to:"<<ret<<std::endl;*/
}
#define GETTEXT_HEADER
#endif
diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp
index 0101b99bb..13883901e 100644
--- a/src/guiChatConsole.cpp
+++ b/src/guiChatConsole.cpp
@@ -32,6 +32,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gettext.h"
+#if USE_FREETYPE
+#include "xCGUITTFont.h"
+#endif
+
inline u32 clamp_u8(s32 value)
{
return (u32) MYMIN(MYMAX(value, 0), 255);
@@ -90,8 +94,14 @@ GUIChatConsole::GUIChatConsole(
// load the font
// FIXME should a custom texture_path be searched too?
+ #if USE_FREETYPE
+ std::string font_name = g_settings->get("mono_font_path");
+ u16 font_size = g_settings->getU16("mono_font_size");
+ m_font = gui::CGUITTFont::createTTFont(env, font_name.c_str(), font_size);
+ #else
std::string font_name = "fontdejavusansmono.png";
m_font = env->getFont(getTexturePath(font_name).c_str());
+ #endif
if (m_font == NULL)
{
dstream << "Unable to load font: " << font_name << std::endl;
diff --git a/src/guiConfigureWorld.cpp b/src/guiConfigureWorld.cpp
new file mode 100644
index 000000000..fdcd0d3e8
--- /dev/null
+++ b/src/guiConfigureWorld.cpp
@@ -0,0 +1,705 @@
+/*
+Minetest-c55
+Copyright (C) 2012 celeron55, Perttu Ahola <celeron55@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+
+#include <iostream>
+#include <string>
+#include <map>
+
+#include "guiConfigureWorld.h"
+#include "guiMessageMenu.h"
+#include <IGUIButton.h>
+#include <IGUICheckBox.h>
+#include <IGUIListBox.h>
+#include <IGUIStaticText.h>
+#include <IGUITreeView.h>
+#include "gettext.h"
+#include "util/string.h"
+#include "settings.h"
+#include "filesys.h"
+
+enum
+{
+ GUI_ID_MOD_TREEVIEW = 101,
+ GUI_ID_ENABLED_CHECKBOX,
+ GUI_ID_ENABLEALL,
+ GUI_ID_DISABLEALL,
+ GUI_ID_DEPENDS_LISTBOX,
+ GUI_ID_RDEPENDS_LISTBOX,
+ GUI_ID_CANCEL,
+ GUI_ID_SAVE
+};
+
+#define QUESTIONMARK_STR L"?"
+#define CHECKMARK_STR L"\411"
+#define CROSS_STR L"\403"
+
+GUIConfigureWorld::GUIConfigureWorld(gui::IGUIEnvironment* env,
+ gui::IGUIElement* parent, s32 id,
+ IMenuManager *menumgr, WorldSpec wspec):
+ GUIModalMenu(env, parent, id, menumgr),
+ m_wspec(wspec),
+ m_gspec(findWorldSubgame(m_wspec.path)),
+ m_menumgr(menumgr)
+{
+ //will be initialized in regenerateGUI()
+ m_treeview=NULL;
+
+ // game mods
+ m_gamemods = flattenModTree(getModsInPath(m_gspec.gamemods_path));
+
+ // world mods
+ std::string worldmods_path = wspec.path + DIR_DELIM + "worldmods";
+ m_worldmods = flattenModTree(getModsInPath(worldmods_path));
+
+ // fill m_addontree with add-on mods
+ std::set<std::string> paths = m_gspec.addon_mods_paths;
+ for(std::set<std::string>::iterator it=paths.begin();
+ it != paths.end(); ++it)
+ {
+ std::map<std::string,ModSpec> mods = getModsInPath(*it);
+ m_addontree.insert(mods.begin(), mods.end());
+ }
+
+ // expand modpacks
+ m_addonmods = flattenModTree(m_addontree);
+
+ // collect reverse dependencies
+ for(std::map<std::string, ModSpec>::iterator it = m_addonmods.begin();
+ it != m_addonmods.end(); ++it)
+ {
+ std::string modname = (*it).first;
+ ModSpec mod = (*it).second;
+ for(std::set<std::string>::iterator dep_it = mod.depends.begin();
+ dep_it != mod.depends.end(); ++dep_it)
+ {
+ m_reverse_depends.insert(std::make_pair((*dep_it),modname));
+ }
+ }
+
+ m_settings.readConfigFile((m_wspec.path + DIR_DELIM + "world.mt").c_str());
+ std::vector<std::string> names = m_settings.getNames();
+
+ // mod_names contains the names of mods mentioned in the world.mt file
+ std::set<std::string> mod_names;
+ for(std::vector<std::string>::iterator it = names.begin();
+ it != names.end(); ++it)
+ {
+ std::string name = *it;
+ if (name.compare(0,9,"load_mod_")==0)
+ mod_names.insert(name.substr(9));
+ }
+
+ // find new mods (installed but not mentioned in world.mt)
+ for(std::map<std::string, ModSpec>::iterator it = m_addonmods.begin();
+ it != m_addonmods.end(); ++it)
+ {
+ std::string modname = (*it).first;
+ ModSpec mod = (*it).second;
+ // a mod is new if it is not a modpack, and does not occur in
+ // mod_names
+ if(!mod.is_modpack &&
+ mod_names.count(modname) == 0)
+ m_new_mod_names.insert(modname);
+ }
+ if(!m_new_mod_names.empty())
+ {
+ GUIMessageMenu *menu =
+ new GUIMessageMenu(Environment, Parent, -1, m_menumgr,
+ wgettext("Warning: Some mods are not configured yet.\n"
+ "They will be enabled by default when you save the configuration. "));
+ menu->drop();
+ }
+
+
+ // find missing mods (mentioned in world.mt, but not installed)
+ std::set<std::string> missing_mods;
+ for(std::set<std::string>::iterator it = mod_names.begin();
+ it != mod_names.end(); ++it)
+ {
+ std::string modname = *it;
+ if(m_addonmods.count(modname) == 0)
+ missing_mods.insert(modname);
+ }
+ if(!missing_mods.empty())
+ {
+ GUIMessageMenu *menu =
+ new GUIMessageMenu(Environment, Parent, -1, m_menumgr,
+ wgettext("Warning: Some configured mods are missing.\n"
+ "Their setting will be removed when you save the configuration. "));
+ for(std::set<std::string>::iterator it = missing_mods.begin();
+ it != missing_mods.end(); ++it)
+ m_settings.remove("load_mod_"+(*it));
+ menu->drop();
+ }
+}
+
+void GUIConfigureWorld::drawMenu()
+{
+ gui::IGUISkin* skin = Environment->getSkin();
+ if (!skin)
+ return;
+ video::IVideoDriver* driver = Environment->getVideoDriver();
+
+ video::SColor bgcolor(140,0,0,0);
+ driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect);
+
+ gui::IGUIElement::draw();
+}
+
+
+void GUIConfigureWorld::regenerateGui(v2u32 screensize)
+{
+
+ /*
+ Remove stuff
+ */
+ removeChildren();
+
+ /*
+ Calculate new sizes and positions
+ */
+ core::rect<s32> rect(
+ screensize.X/2 - 580/2,
+ screensize.Y/2 - 300/2,
+ screensize.X/2 + 580/2,
+ screensize.Y/2 + 300/2
+ );
+
+ DesiredRect = rect;
+ recalculateAbsolutePosition(false);
+
+ v2s32 size = rect.getSize();
+
+ v2s32 topleft = v2s32(10, 10);
+
+ /*
+ Add stuff
+ */
+ changeCtype("");
+ {
+ core::rect<s32> rect(0, 0, 200, 20);
+ rect += topleft;
+ //proper text is set below, when a mod is selected
+ m_modname_text = Environment->addStaticText(L"Mod: N/A", rect, false,
+ false, this, -1);
+ }
+ {
+ core::rect<s32> rect(0, 0, 200, 20);
+ rect += v2s32(0, 25) + topleft;
+ m_enabled_checkbox =
+ Environment->addCheckBox(false, rect, this, GUI_ID_ENABLED_CHECKBOX,
+ wgettext("enabled"));
+ m_enabled_checkbox->setVisible(false);
+ }
+ {
+ core::rect<s32> rect(0, 0, 85, 30);
+ rect = rect + v2s32(0, 25) + topleft;
+ m_enableall = Environment->addButton(rect, this, GUI_ID_ENABLEALL,
+ wgettext("Enable All"));
+ m_enableall->setVisible(false);
+ }
+ {
+ core::rect<s32> rect(0, 0, 85, 30);
+ rect = rect + v2s32(115, 25) + topleft;
+ m_disableall = Environment->addButton(rect, this, GUI_ID_DISABLEALL,
+ wgettext("Disable All"));
+ m_disableall->setVisible(false);
+ }
+ {
+ core::rect<s32> rect(0, 0, 200, 20);
+ rect += v2s32(0, 60) + topleft;
+ Environment->addStaticText(wgettext("depends on:"),
+ rect, false, false, this, -1);
+ }
+ {
+ core::rect<s32> rect(0, 0, 200, 85);
+ rect += v2s32(0, 80) + topleft;
+ m_dependencies_listbox =
+ Environment->addListBox(rect, this, GUI_ID_DEPENDS_LISTBOX, true);
+ }
+ {
+ core::rect<s32> rect(0, 0, 200, 20);
+ rect += v2s32(0, 175) + topleft;
+ Environment->addStaticText(wgettext("is required by:"),
+ rect, false, false, this, -1);
+ }
+ {
+ core::rect<s32> rect(0, 0, 200, 85);
+ rect += v2s32(0, 195) + topleft;
+ m_rdependencies_listbox =
+ Environment->addListBox(rect,this, GUI_ID_RDEPENDS_LISTBOX,true);
+ }
+ {
+ core::rect<s32> rect(0, 0, 340, 250);
+ rect += v2s32(220, 0) + topleft;
+ m_treeview = Environment->addTreeView(rect, this,
+ GUI_ID_MOD_TREEVIEW,true);
+ gui::IGUITreeViewNode* node
+ = m_treeview->getRoot()->addChildBack(L"Add-Ons");
+ buildTreeView(m_addontree, node);
+ }
+ {
+ core::rect<s32> rect(0, 0, 120, 30);
+ rect = rect + v2s32(330, 270) - topleft;
+ Environment->addButton(rect, this, GUI_ID_CANCEL,
+ wgettext("Cancel"));
+ }
+ {
+ core::rect<s32> rect(0, 0, 120, 30);
+ rect = rect + v2s32(460, 270) - topleft;
+ Environment->addButton(rect, this, GUI_ID_SAVE,
+ wgettext("Save"));
+ }
+ changeCtype("C");
+
+ // at start, none of the treeview nodes is selected, so we select
+ // the first element in the treeview of mods manually here.
+ if(m_treeview->getRoot()->hasChilds())
+ {
+ m_treeview->getRoot()->getFirstChild()->setExpanded(true);
+ m_treeview->getRoot()->getFirstChild()->setSelected(true);
+ // Because a manual ->setSelected() doesn't cause an event, we
+ // have to do this here:
+ adjustSidebar();
+ }
+}
+
+bool GUIConfigureWorld::OnEvent(const SEvent& event)
+{
+
+ gui::IGUITreeViewNode* selected_node = NULL;
+ if(m_treeview != NULL)
+ selected_node = m_treeview->getSelected();
+
+ if(event.EventType==EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
+ {
+ switch (event.KeyInput.Key) {
+ case KEY_ESCAPE: {
+ quitMenu();
+ return true;
+ }
+ // irrlicht's built-in TreeView gui has no keyboard control,
+ // so we do it here: up/down to select prev/next node,
+ // left/right to collapse/expand nodes, space to toggle
+ // enabled/disabled.
+ case KEY_DOWN: {
+ if(selected_node != NULL)
+ {
+ gui::IGUITreeViewNode* node = selected_node->getNextVisible();
+ if(node != NULL)
+ {
+ node->setSelected(true);
+ adjustSidebar();
+ }
+ }
+ return true;
+ }
+ case KEY_UP: {
+ if(selected_node != NULL)
+ {
+ gui::IGUITreeViewNode* node = selected_node->getPrevSibling();
+ if(node!=NULL)
+ {
+ node->setSelected(true);
+ adjustSidebar();
+ }
+ else
+ {
+ gui::IGUITreeViewNode* parent = selected_node->getParent();
+ if(selected_node == parent->getFirstChild() &&
+ parent != m_treeview->getRoot())
+ {
+ parent->setSelected(true);
+ adjustSidebar();
+ }
+ }
+ }
+ return true;
+ }
+ case KEY_RIGHT: {
+ if(selected_node != NULL && selected_node->hasChilds())
+ selected_node->setExpanded(true);
+ return true;
+ }
+ case KEY_LEFT: {
+ if(selected_node != NULL && selected_node->hasChilds())
+ selected_node->setExpanded(false);
+ return true;
+ }
+ case KEY_SPACE: {
+ if(selected_node != NULL && !selected_node->hasChilds() &&
+ selected_node->getText() != NULL)
+ {
+ std::string modname = wide_to_narrow(selected_node->getText());
+ bool checked = m_enabled_checkbox->isChecked();
+ m_enabled_checkbox->setChecked(!checked);
+ setEnabled(modname,!checked);
+ }
+ return true;
+ }
+ default: {}
+ }
+ }
+ if(event.EventType==EET_GUI_EVENT)
+ {
+ if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
+ && isVisible())
+ {
+ if(!canTakeFocus(event.GUIEvent.Element))
+ {
+ dstream<<"GUIConfigureWorld: Not allowing focus change."
+ <<std::endl;
+ // Returning true disables focus change
+ return true;
+ }
+ }
+ if(event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED){
+ switch(event.GUIEvent.Caller->getID()){
+ case GUI_ID_CANCEL: {
+ quitMenu();
+ return true;
+ }
+ case GUI_ID_SAVE: {
+ for(std::set<std::string>::iterator it = m_new_mod_names.begin();
+ it!= m_new_mod_names.end(); ++it)
+ {
+ m_settings.setBool("load_mod_"+(*it),true);
+ }
+ std::string worldmtfile = m_wspec.path+DIR_DELIM+"world.mt";
+ m_settings.updateConfigFile(worldmtfile.c_str());
+
+ // The trailing spaces are because there seems to be a
+ // bug in the text-size calculation. if the trailing
+ // spaces are removed from the message text, the
+ // message gets wrapped and parts of it are cut off:
+ GUIMessageMenu *menu =
+ new GUIMessageMenu(Environment, Parent, -1, m_menumgr,
+ wgettext("Configuration saved. "));
+ menu->drop();
+
+ ModConfiguration modconf(m_wspec.path);
+ if(!modconf.isConsistent())
+ {
+ GUIMessageMenu *menu =
+ new GUIMessageMenu(Environment, Parent, -1, m_menumgr,
+ wgettext("Warning: Configuration not consistent. "));
+ menu->drop();
+ }
+
+ quitMenu();
+ return true;
+ }
+ case GUI_ID_ENABLEALL: {
+ if(selected_node != NULL && selected_node->getParent() == m_treeview->getRoot())
+ {
+ enableAllMods(m_addonmods,true);
+ }
+ else if(selected_node != NULL && selected_node->getText() != NULL)
+ {
+ std::string modname = wide_to_narrow(selected_node->getText());
+ std::map<std::string, ModSpec>::iterator mod_it = m_addonmods.find(modname);
+ if(mod_it != m_addonmods.end())
+ enableAllMods(mod_it->second.modpack_content,true);
+ }
+ return true;
+ }
+ case GUI_ID_DISABLEALL: {
+ if(selected_node != NULL && selected_node->getParent() == m_treeview->getRoot())
+ {
+ enableAllMods(m_addonmods,false);
+ }
+ if(selected_node != NULL && selected_node->getText() != NULL)
+ {
+ std::string modname = wide_to_narrow(selected_node->getText());
+ std::map<std::string, ModSpec>::iterator mod_it = m_addonmods.find(modname);
+ if(mod_it != m_addonmods.end())
+ enableAllMods(mod_it->second.modpack_content,false);
+ }
+ return true;
+ }
+ }
+ }
+ if(event.GUIEvent.EventType==gui::EGET_CHECKBOX_CHANGED &&
+ event.GUIEvent.Caller->getID() == GUI_ID_ENABLED_CHECKBOX)
+ {
+ if(selected_node != NULL && !selected_node->hasChilds() &&
+ selected_node->getText() != NULL)
+ {
+ std::string modname = wide_to_narrow(selected_node->getText());
+ setEnabled(modname, m_enabled_checkbox->isChecked());
+ }
+ return true;
+ }
+ if(event.GUIEvent.EventType==gui::EGET_TREEVIEW_NODE_SELECT &&
+ event.GUIEvent.Caller->getID() == GUI_ID_MOD_TREEVIEW)
+ {
+ selecting_dep = -1;
+ selecting_rdep = -1;
+ adjustSidebar();
+ return true;
+ }
+ if(event.GUIEvent.EventType==gui::EGET_LISTBOX_CHANGED &&
+ event.GUIEvent.Caller->getID() == GUI_ID_DEPENDS_LISTBOX)
+ {
+ selecting_dep = m_dependencies_listbox->getSelected();
+ selecting_rdep = -1;
+ return true;
+ }
+ if(event.GUIEvent.EventType==gui::EGET_LISTBOX_CHANGED &&
+ event.GUIEvent.Caller->getID() == GUI_ID_RDEPENDS_LISTBOX)
+ {
+ selecting_dep = -1;
+ selecting_rdep = m_rdependencies_listbox->getSelected();
+ return true;
+ }
+
+ //double click in a dependency listbox: find corresponding
+ //treeviewnode and select it:
+ if(event.GUIEvent.EventType==gui::EGET_LISTBOX_SELECTED_AGAIN)
+ {
+ gui::IGUIListBox* box = NULL;
+ if(event.GUIEvent.Caller->getID() == GUI_ID_DEPENDS_LISTBOX)
+ {
+ box = m_dependencies_listbox;
+ if(box->getSelected() != selecting_dep)
+ return true;
+ }
+ if(event.GUIEvent.Caller->getID() == GUI_ID_RDEPENDS_LISTBOX)
+ {
+ box = m_rdependencies_listbox;
+ if(box->getSelected() != selecting_rdep)
+ return true;
+ }
+ if(box != NULL && box->getSelected() != -1 &&
+ box->getListItem(box->getSelected()) != NULL)
+ {
+ std::string modname =
+ wide_to_narrow(box->getListItem(box->getSelected()));
+ std::map<std::string, gui::IGUITreeViewNode*>::iterator it =
+ m_nodes.find(modname);
+ if(it != m_nodes.end())
+ {
+ // select node and make sure node is visible by
+ // expanding all parents
+ gui::IGUITreeViewNode* node = (*it).second;
+ node->setSelected(true);
+ while(!node->isVisible() &&
+ node->getParent() != m_treeview->getRoot())
+ {
+ node = node->getParent();
+ node->setExpanded(true);
+ }
+ adjustSidebar();
+ }
+ }
+ return true;
+ }
+ }
+
+ return Parent ? Parent->OnEvent(event) : false;
+}
+
+void GUIConfigureWorld::buildTreeView(std::map<std::string, ModSpec> mods,
+ gui::IGUITreeViewNode* node)
+{
+ for(std::map<std::string,ModSpec>::iterator it = mods.begin();
+ it != mods.end(); ++it)
+ {
+ std::string modname = (*it).first;
+ ModSpec mod = (*it).second;
+ gui::IGUITreeViewNode* new_node =
+ node->addChildBack(narrow_to_wide(modname).c_str());
+ m_nodes.insert(std::make_pair(modname, new_node));
+ if(mod.is_modpack)
+ buildTreeView(mod.modpack_content, new_node);
+ else
+ {
+ // set icon for node: ? for new mods, x for disabled mods,
+ // checkmark for enabled mods
+ if(m_new_mod_names.count(modname) > 0)
+ {
+ new_node->setIcon(QUESTIONMARK_STR);
+ }
+ else
+ {
+ bool mod_enabled = true;
+ if(m_settings.exists("load_mod_"+modname))
+ mod_enabled = m_settings.getBool("load_mod_"+modname);
+ if(mod_enabled)
+ new_node->setIcon(CHECKMARK_STR);
+ else
+ new_node->setIcon(CROSS_STR);
+ }
+ }
+ }
+}
+
+
+void GUIConfigureWorld::adjustSidebar()
+{
+ gui::IGUITreeViewNode* node = m_treeview->getSelected();
+ std::wstring modname_w;
+ if(node->getText() != NULL)
+ modname_w = node->getText();
+ else
+ modname_w = L"N/A";
+ std::string modname = wide_to_narrow(modname_w);
+
+ ModSpec mspec;
+ std::map<std::string, ModSpec>::iterator it = m_addonmods.find(modname);
+ if(it != m_addonmods.end())
+ mspec = it->second;
+
+ m_dependencies_listbox->clear();
+ m_rdependencies_listbox->clear();
+
+ // if no mods installed, there is nothing to enable/disable, so we
+ // don't show buttons or checkbox on the sidebar
+ if(node->getParent() == m_treeview->getRoot() && !node->hasChilds())
+ {
+ m_disableall->setVisible(false);
+ m_enableall->setVisible(false);
+ m_enabled_checkbox->setVisible(false);
+ return;
+ }
+
+ // a modpack is not enabled/disabled by itself, only its cotnents
+ // are. so we show show enable/disable all buttons, but hide the
+ // checkbox
+ if(node->getParent() == m_treeview->getRoot() ||
+ mspec.is_modpack)
+ {
+ m_enabled_checkbox->setVisible(false);
+ m_disableall->setVisible(true);
+ m_enableall->setVisible(true);
+ m_modname_text->setText((L"Modpack: "+modname_w).c_str());
+ return;
+ }
+
+ // for a normal mod, we hide the enable/disable all buttons, but show the checkbox.
+ m_disableall->setVisible(false);
+ m_enableall->setVisible(false);
+ m_enabled_checkbox->setVisible(true);
+ m_modname_text->setText((L"Mod: "+modname_w).c_str());
+
+ // the mod is enabled unless it is disabled in the world.mt settings.
+ bool mod_enabled = true;
+ if(m_settings.exists("load_mod_"+modname))
+ mod_enabled = m_settings.getBool("load_mod_"+modname);
+ m_enabled_checkbox->setChecked(mod_enabled);
+
+ for(std::set<std::string>::iterator it=mspec.depends.begin();
+ it != mspec.depends.end(); ++it)
+ {
+ // check if it is an add-on mod or a game/world mod. We only
+ // want to show add-ons
+ std::string dependency = (*it);
+ if(m_gamemods.count(dependency) > 0)
+ dependency += " (" + m_gspec.id + ")";
+ else if(m_worldmods.count(dependency) > 0)
+ dependency += " (" + m_wspec.name + ")";
+ else if(m_addonmods.count(dependency) == 0)
+ dependency += " (missing)";
+ m_dependencies_listbox->addItem(narrow_to_wide(dependency).c_str());
+ }
+
+ // reverse dependencies of this mod:
+ std::pair< std::multimap<std::string, std::string>::iterator,
+ std::multimap<std::string, std::string>::iterator > rdep =
+ m_reverse_depends.equal_range(modname);
+ for(std::multimap<std::string,std::string>::iterator it = rdep.first;
+ it != rdep.second; ++it)
+ {
+ // check if it is an add-on mod or a game/world mod. We only
+ // want to show add-ons
+ std::string rdependency = (*it).second;
+ if(m_addonmods.count(rdependency) > 0)
+ m_rdependencies_listbox->addItem(narrow_to_wide(rdependency).c_str());
+ }
+}
+
+void GUIConfigureWorld::enableAllMods(std::map<std::string, ModSpec> mods,bool enable)
+{
+ for(std::map<std::string, ModSpec>::iterator it = mods.begin();
+ it != mods.end(); ++it)
+ {
+ ModSpec mod = (*it).second;
+ if(mod.is_modpack)
+ // a modpack, recursively enable all mods in it
+ enableAllMods(mod.modpack_content,enable);
+ else // not a modpack
+ setEnabled(mod.name, enable);
+
+ }
+}
+
+void GUIConfigureWorld::enableMod(std::string modname)
+{
+ std::map<std::string, ModSpec>::iterator mod_it = m_addonmods.find(modname);
+ if(mod_it == m_addonmods.end()){
+ errorstream << "enableMod() called with invalid mod name \"" << modname << "\"" << std::endl;
+ return;
+ }
+ ModSpec mspec = mod_it->second;
+ m_settings.setBool("load_mod_"+modname,true);
+ std::map<std::string,gui::IGUITreeViewNode*>::iterator it =
+ m_nodes.find(modname);
+ if(it != m_nodes.end())
+ (*it).second->setIcon(CHECKMARK_STR);
+ m_new_mod_names.erase(modname);
+ //also enable all dependencies
+ for(std::set<std::string>::iterator it=mspec.depends.begin();
+ it != mspec.depends.end(); ++it)
+ {
+ std::string dependency = *it;
+ // only enable it if it is an add-on mod
+ if(m_addonmods.count(dependency) > 0)
+ enableMod(dependency);
+ }
+}
+
+void GUIConfigureWorld::disableMod(std::string modname)
+{
+ std::map<std::string, ModSpec>::iterator mod_it = m_addonmods.find(modname);
+ if(mod_it == m_addonmods.end()){
+ errorstream << "disableMod() called with invalid mod name \"" << modname << "\"" << std::endl;
+ return;
+ }
+
+ m_settings.setBool("load_mod_"+modname,false);
+ std::map<std::string,gui::IGUITreeViewNode*>::iterator it =
+ m_nodes.find(modname);
+ if(it != m_nodes.end())
+ (*it).second->setIcon(CROSS_STR);
+ m_new_mod_names.erase(modname);
+ //also disable all mods that depend on this one
+ std::pair<std::multimap<std::string, std::string>::iterator,
+ std::multimap<std::string, std::string>::iterator > rdep =
+ m_reverse_depends.equal_range(modname);
+ for(std::multimap<std::string,std::string>::iterator it = rdep.first;
+ it != rdep.second; ++it)
+ {
+ std::string rdependency = (*it).second;
+ // only disable it if it is an add-on mod
+ if(m_addonmods.count(rdependency) > 0)
+ disableMod(rdependency);
+ }
+}
+
diff --git a/src/guiConfigureWorld.h b/src/guiConfigureWorld.h
new file mode 100644
index 000000000..2280c6dbe
--- /dev/null
+++ b/src/guiConfigureWorld.h
@@ -0,0 +1,110 @@
+/*
+Minetest-c55
+Copyright (C) 2012 celeron55, Perttu Ahola <celeron55@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#ifndef GUICONFIGUREWORLD_HEADER
+#define GUICONFIGUREWORLD_HEADER
+
+#include "irrlichttypes_extrabloated.h"
+#include "modalMenu.h"
+#include "mods.h"
+#include "subgame.h"
+#include "settings.h"
+
+
+namespace irr{
+ namespace gui{
+ class IGUITreeViewNode;
+ }
+}
+
+class GUIConfigureWorld : public GUIModalMenu
+{
+public:
+ GUIConfigureWorld(gui::IGUIEnvironment* env,
+ gui::IGUIElement* parent, s32 id,
+ IMenuManager *menumgr, WorldSpec wspec);
+
+ void regenerateGui(v2u32 screensize);
+
+ void drawMenu();
+
+ bool OnEvent(const SEvent& event);
+
+private:
+ WorldSpec m_wspec;
+ SubgameSpec m_gspec;
+
+ // tree of installed add-on mods. key is the mod name, modpacks
+ // are not expanded.
+ std::map<std::string, ModSpec> m_addontree;
+
+ // like m_addontree, but modpacks are expanded.
+ std::map<std::string, ModSpec> m_addonmods;
+
+ // list of game mods (flattened)
+ std::map<std::string, ModSpec> m_gamemods;
+
+ // list of world mods (flattened)
+ std::map<std::string, ModSpec> m_worldmods;
+
+ // for each mod, the set of mods depending on it
+ std::multimap<std::string, std::string> m_reverse_depends;
+
+ // the settings in the world.mt file
+ Settings m_settings;
+
+ // mods that are installed but not mentioned in world.mt file
+ std::set<std::string> m_new_mod_names;
+
+ // maps modnames to nodes in m_treeview
+ std::map<std::string,gui::IGUITreeViewNode*> m_nodes;
+
+ gui::IGUIStaticText* m_modname_text;
+ gui::IGUITreeView* m_treeview;
+ gui::IGUIButton* m_enableall;
+ gui::IGUIButton* m_disableall;
+ gui::IGUICheckBox* m_enabled_checkbox;
+ gui::IGUIListBox* m_dependencies_listbox;
+ gui::IGUIListBox* m_rdependencies_listbox;
+ void buildTreeView(std::map<std::string,ModSpec> mods,
+ gui::IGUITreeViewNode* node);
+ void adjustSidebar();
+ void enableAllMods(std::map<std::string,ModSpec> mods, bool enable);
+ void setEnabled(std::string modname, bool enable)
+ {
+ if(enable)
+ enableMod(modname);
+ else
+ disableMod(modname);
+ };
+
+ void enableMod(std::string modname);
+ void disableMod(std::string modname);
+
+ // hack to work around wonky handling of double-click in
+ // irrlicht. store selected index of listbox items here so event
+ // handling can check whether it was a real double click on the
+ // same item. (irrlicht also reports a double click if you rapidly
+ // select two different items.)
+ int selecting_dep;
+ int selecting_rdep;
+
+ IMenuManager* m_menumgr;
+};
+#endif
diff --git a/src/guiKeyChangeMenu.cpp b/src/guiKeyChangeMenu.cpp
index 6b0412821..3f6d03ebb 100644
--- a/src/guiKeyChangeMenu.cpp
+++ b/src/guiKeyChangeMenu.cpp
@@ -369,21 +369,21 @@ void GUIKeyChangeMenu::add_key(int id, std::string button_name, std::string sett
void GUIKeyChangeMenu::init_keys()
{
- this->add_key(GUI_ID_KEY_FORWARD_BUTTON, "Forward", "keymap_forward");
- this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, "Backward", "keymap_backward");
- this->add_key(GUI_ID_KEY_LEFT_BUTTON, "Left", "keymap_left");
- this->add_key(GUI_ID_KEY_RIGHT_BUTTON, "Right", "keymap_right");
- this->add_key(GUI_ID_KEY_USE_BUTTON, "Use", "keymap_special1");
- this->add_key(GUI_ID_KEY_JUMP_BUTTON, "Jump", "keymap_jump");
- this->add_key(GUI_ID_KEY_SNEAK_BUTTON, "Sneak", "keymap_sneak");
- this->add_key(GUI_ID_KEY_DROP_BUTTON, "Drop", "keymap_drop");
- this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, "Inventory", "keymap_inventory");
- this->add_key(GUI_ID_KEY_CHAT_BUTTON, "Chat", "keymap_chat");
- this->add_key(GUI_ID_KEY_CMD_BUTTON, "Command", "keymap_cmd");
- this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, "Console", "keymap_console");
- this->add_key(GUI_ID_KEY_FLY_BUTTON, "Toggle fly", "keymap_freemove");
- this->add_key(GUI_ID_KEY_FAST_BUTTON, "Toggle fast", "keymap_fastmove");
- this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, "Toggle noclip", "keymap_noclip");
- this->add_key(GUI_ID_KEY_RANGE_BUTTON, "Range select", "keymap_rangeselect");
- this->add_key(GUI_ID_KEY_DUMP_BUTTON, "Print stacks", "keymap_print_debug_stacks");
+ this->add_key(GUI_ID_KEY_FORWARD_BUTTON, gettext("Forward"), "keymap_forward");
+ this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, gettext("Backward"), "keymap_backward");
+ this->add_key(GUI_ID_KEY_LEFT_BUTTON, gettext("Left"), "keymap_left");
+ this->add_key(GUI_ID_KEY_RIGHT_BUTTON, gettext("Right"), "keymap_right");
+ this->add_key(GUI_ID_KEY_USE_BUTTON, gettext("Use"), "keymap_special1");
+ this->add_key(GUI_ID_KEY_JUMP_BUTTON, gettext("Jump"), "keymap_jump");
+ this->add_key(GUI_ID_KEY_SNEAK_BUTTON, gettext("Sneak"), "keymap_sneak");
+ this->add_key(GUI_ID_KEY_DROP_BUTTON, gettext("Drop"), "keymap_drop");
+ this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, gettext("Inventory"), "keymap_inventory");
+ this->add_key(GUI_ID_KEY_CHAT_BUTTON, gettext("Chat"), "keymap_chat");
+ this->add_key(GUI_ID_KEY_CMD_BUTTON, gettext("Command"), "keymap_cmd");
+ this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, gettext("Console"), "keymap_console");
+ this->add_key(GUI_ID_KEY_FLY_BUTTON, gettext("Toggle fly"), "keymap_freemove");
+ this->add_key(GUI_ID_KEY_FAST_BUTTON, gettext("Toggle fast"), "keymap_fastmove");
+ this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, gettext("Toggle noclip"), "keymap_noclip");
+ this->add_key(GUI_ID_KEY_RANGE_BUTTON, gettext("Range select"), "keymap_rangeselect");
+ this->add_key(GUI_ID_KEY_DUMP_BUTTON, gettext("Print stacks"), "keymap_print_debug_stacks");
}
diff --git a/src/guiMainMenu.cpp b/src/guiMainMenu.cpp
index bac9052b9..ca334198f 100644
--- a/src/guiMainMenu.cpp
+++ b/src/guiMainMenu.cpp
@@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "guiMainMenu.h"
#include "guiKeyChangeMenu.h"
#include "guiCreateWorld.h"
+#include "guiConfigureWorld.h"
#include "guiMessageMenu.h"
#include "guiConfirmMenu.h"
#include "debug.h"
@@ -107,6 +108,7 @@ enum
GUI_ID_ENABLE_PARTICLES_CB,
GUI_ID_DAMAGE_CB,
GUI_ID_CREATIVE_CB,
+ GUI_ID_PUBLIC_CB,
GUI_ID_JOIN_GAME_BUTTON,
GUI_ID_CHANGE_KEYS_BUTTON,
GUI_ID_DELETE_WORLD_BUTTON,
@@ -114,6 +116,9 @@ enum
GUI_ID_CONFIGURE_WORLD_BUTTON,
GUI_ID_WORLD_LISTBOX,
GUI_ID_TAB_CONTROL,
+ GUI_ID_SERVERLIST,
+ GUI_ID_SERVERLIST_TOGGLE,
+ GUI_ID_SERVERLIST_DELETE,
};
enum
@@ -256,7 +261,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
//const wchar_t *text = L"H\nY\nB\nR\nI\nD";
const wchar_t *text = L"T\nA\nP\nE\n\nA\nN\nD\n\nG\nL\nU\nE";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
u32 bs = 5;
@@ -355,20 +360,20 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
rect += m_topleft_client + v2s32(15, 0);
const wchar_t *text = L"C\nL\nI\nE\nN\nT";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
// Nickname + password
{
core::rect<s32> rect(0, 0, 110, 20);
- rect += m_topleft_client + v2s32(35+30, 50+6);
+ rect += m_topleft_client + v2s32(m_size_client.X-60-100, 10+6);
Environment->addStaticText(wgettext("Name/Password"),
rect, false, true, this, -1);
}
changeCtype("C");
{
- core::rect<s32> rect(0, 0, 230, 30);
- rect += m_topleft_client + v2s32(160+30, 50);
+ core::rect<s32> rect(0, 0, 120, 30);
+ rect += m_topleft_client + v2s32(m_size_client.X-60-100, 50);
gui::IGUIElement *e =
Environment->addEditBox(m_data->name.c_str(), rect, true, this, GUI_ID_NAME_INPUT);
if(m_data->name == L"")
@@ -376,7 +381,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
}
{
core::rect<s32> rect(0, 0, 120, 30);
- rect += m_topleft_client + v2s32(m_size_client.X-60-100, 50);
+ rect += m_topleft_client + v2s32(m_size_client.X-60-100, 90);
gui::IGUIEditBox *e =
Environment->addEditBox(L"", rect, true, this, 264);
e->setPasswordBox(true);
@@ -385,17 +390,29 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
}
changeCtype("");
+ // Server List
+ {
+ core::rect<s32> rect(0, 0, 390, 160);
+ rect += m_topleft_client + v2s32(50, 10);
+ gui::IGUIListBox *e = Environment->addListBox(rect, this,
+ GUI_ID_SERVERLIST);
+ e->setDrawBackground(true);
+ if (m_data->serverlist_show_available == false)
+ m_data->servers = ServerList::getLocal();
+ updateGuiServerList();
+ e->setSelected(0);
+ }
// Address + port
{
core::rect<s32> rect(0, 0, 110, 20);
- rect += m_topleft_client + v2s32(35+30, 100+6);
+ rect += m_topleft_client + v2s32(50, m_size_client.Y-50-15+6);
Environment->addStaticText(wgettext("Address/Port"),
rect, false, true, this, -1);
}
changeCtype("C");
{
- core::rect<s32> rect(0, 0, 230, 30);
- rect += m_topleft_client + v2s32(160+30, 100);
+ core::rect<s32> rect(0, 0, 260, 30);
+ rect += m_topleft_client + v2s32(50, m_size_client.Y-25-15);
gui::IGUIElement *e =
Environment->addEditBox(m_data->address.c_str(), rect, true,
this, GUI_ID_ADDRESS_INPUT);
@@ -404,18 +421,43 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
}
{
core::rect<s32> rect(0, 0, 120, 30);
- rect += m_topleft_client + v2s32(m_size_client.X-60-100, 100);
+ rect += m_topleft_client + v2s32(50+260+10, m_size_client.Y-25-15);
Environment->addEditBox(m_data->port.c_str(), rect, true,
this, GUI_ID_PORT_INPUT);
}
changeCtype("");
+ #if USE_CURL
+ // Toggle Serverlist (Favorites/Online)
+ {
+ core::rect<s32> rect(0, 0, 260, 30);
+ rect += m_topleft_client + v2s32(50,
+ 180);
+ gui::IGUIButton *e = Environment->addButton(rect, this, GUI_ID_SERVERLIST_TOGGLE,
+ wgettext("Show Public"));
+ e->setIsPushButton(true);
+ if (m_data->serverlist_show_available)
+ {
+ e->setText(wgettext("Show Favorites"));
+ e->setPressed();
+ }
+ }
+ #endif
+ // Delete Local Favorite
+ {
+ core::rect<s32> rect(0, 0, 120, 30);
+ rect += m_topleft_client + v2s32(50+260+10, 180);
+ gui::IGUIButton *e = Environment->addButton(rect, this, GUI_ID_SERVERLIST_DELETE,
+ wgettext("Delete"));
+ if (m_data->serverlist_show_available) // Hidden on Show-Online mode
+ e->setVisible(false);
+ }
// Start game button
{
- core::rect<s32> rect(0, 0, 180, 30);
- rect += m_topleft_client + v2s32(m_size_client.X-180-30,
- m_size_client.Y-30-15);
+ core::rect<s32> rect(0, 0, 120, 30);
+ rect += m_topleft_client + v2s32(m_size_client.X-130-30,
+ m_size_client.Y-25-15);
Environment->addButton(rect, this, GUI_ID_JOIN_GAME_BUTTON,
- wgettext("Start Game / Connect"));
+ wgettext("Connect"));
}
changeCtype("C");
}
@@ -428,7 +470,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
rect += m_topleft_client + v2s32(15, 0);
const wchar_t *text = L"C\nL\nI\nE\nN\nT";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
// Nickname + password
@@ -505,7 +547,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
rect += m_topleft_server + v2s32(15, 0);
const wchar_t *text = L"S\nE\nR\nV\nE\nR";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
// Server parameters
@@ -521,6 +563,14 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
Environment->addCheckBox(m_data->enable_damage, rect, this, GUI_ID_DAMAGE_CB,
wgettext("Enable Damage"));
}
+ #if USE_CURL
+ {
+ core::rect<s32> rect(0, 0, 250, 30);
+ rect += m_topleft_server + v2s32(30+20+250+20, 60);
+ Environment->addCheckBox(m_data->enable_public, rect, this, GUI_ID_PUBLIC_CB,
+ wgettext("Public"));
+ }
+ #endif
// Delete world button
{
core::rect<s32> rect(0, 0, 130, 30);
@@ -557,7 +607,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
rect += m_topleft_client + v2s32(15, 0);
const wchar_t *text = L"S\nE\nT\nT\nI\nN\nG\nS";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
s32 option_x = 70;
@@ -660,7 +710,7 @@ void GUIMainMenu::regenerateGui(v2u32 screensize)
rect += m_topleft_client + v2s32(15, 0);
const wchar_t *text = L"C\nR\nE\nD\nI\nT\nS";
gui::IGUIStaticText *t =
- Environment->addStaticText(text, rect, false, false, this, -1);
+ Environment->addStaticText(text, rect, false, true, this, -1);
t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
}
{
@@ -801,6 +851,11 @@ void GUIMainMenu::readInput(MainMenuData *dst)
dst->enable_damage = ((gui::IGUICheckBox*)e)->isChecked();
}
{
+ gui::IGUIElement *e = getElementFromId(GUI_ID_PUBLIC_CB);
+ if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX)
+ dst->enable_public = ((gui::IGUICheckBox*)e)->isChecked();
+ }
+ {
gui::IGUIElement *e = getElementFromId(GUI_ID_FANCYTREE_CB);
if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX)
dst->fancy_trees = ((gui::IGUICheckBox*)e)->isChecked();
@@ -868,6 +923,12 @@ void GUIMainMenu::readInput(MainMenuData *dst)
if(e != NULL && e->getType() == gui::EGUIET_LIST_BOX)
dst->selected_world = ((gui::IGUIListBox*)e)->getSelected();
}
+ {
+ ServerListSpec server =
+ getServerListSpec(wide_to_narrow(dst->address), wide_to_narrow(dst->port));
+ dst->servername = server["name"].asString();
+ dst->serverdescription = server["description"].asString();
+ }
}
void GUIMainMenu::acceptInput()
@@ -912,6 +973,11 @@ bool GUIMainMenu::OnEvent(const SEvent& event)
regenerateGui(m_screensize_old);
return true;
}
+ if(event.GUIEvent.EventType==gui::EGET_LISTBOX_CHANGED && event.GUIEvent.Caller->getID() == GUI_ID_SERVERLIST)
+ {
+ serverListOnSelected();
+ return true;
+ }
if(event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED)
{
switch(event.GUIEvent.Caller->getID())
@@ -919,7 +985,8 @@ bool GUIMainMenu::OnEvent(const SEvent& event)
case GUI_ID_JOIN_GAME_BUTTON: {
MainMenuData cur;
readInput(&cur);
- if(cur.address == L"" && getTab() == TAB_MULTIPLAYER){
+ if (getTab() == TAB_MULTIPLAYER && cur.address == L"")
+ {
(new GUIMessageMenu(env, parent, -1, menumgr,
wgettext("Address required."))
)->drop();
@@ -981,12 +1048,62 @@ bool GUIMainMenu::OnEvent(const SEvent& event)
return true;
}
case GUI_ID_CONFIGURE_WORLD_BUTTON: {
- GUIMessageMenu *menu = new GUIMessageMenu(env, parent,
- -1, menumgr,
- wgettext("Nothing here"));
- menu->drop();
+ MainMenuData cur;
+ readInput(&cur);
+ if(cur.selected_world == -1)
+ {
+ (new GUIMessageMenu(env, parent, -1, menumgr,
+ wgettext("Cannot configure world: Nothing selected"))
+ )->drop();
+ }
+ else
+ {
+ WorldSpec wspec = m_data->worlds[cur.selected_world];
+ GUIConfigureWorld *menu = new GUIConfigureWorld(env, parent,
+ -1, menumgr, wspec);
+ menu->drop();
+ }
return true;
}
+ case GUI_ID_SERVERLIST_DELETE: {
+ gui::IGUIListBox *serverlist = (gui::IGUIListBox*)getElementFromId(GUI_ID_SERVERLIST);
+ s32 selected = ((gui::IGUIListBox*)serverlist)->getSelected();
+ if (selected == -1) return true;
+ ServerList::deleteEntry(m_data->servers[selected]);
+ m_data->servers = ServerList::getLocal();
+ updateGuiServerList();
+ if (selected > 0)
+ selected -= 1;
+ serverlist->setSelected(selected);
+ serverListOnSelected();
+ return true;
+ }
+ #if USE_CURL
+ case GUI_ID_SERVERLIST_TOGGLE: {
+ gui::IGUIElement *togglebutton = getElementFromId(GUI_ID_SERVERLIST_TOGGLE);
+ gui::IGUIElement *deletebutton = getElementFromId(GUI_ID_SERVERLIST_DELETE);
+ gui::IGUIListBox *serverlist = (gui::IGUIListBox*)getElementFromId(GUI_ID_SERVERLIST);
+ if (m_data->serverlist_show_available) // switch to favorite list
+ {
+ m_data->servers = ServerList::getLocal();
+ togglebutton->setText(wgettext("Show Public"));
+ deletebutton->setVisible(true);
+ updateGuiServerList();
+ serverlist->setSelected(0);
+ }
+ else // switch to online list
+ {
+ m_data->servers = ServerList::getOnline();
+ togglebutton->setText(wgettext("Show Favorites"));
+ deletebutton->setVisible(false);
+ updateGuiServerList();
+ serverlist->setSelected(0);
+ }
+ serverListOnSelected();
+
+ m_data->serverlist_show_available = !m_data->serverlist_show_available;
+ }
+ #endif
}
}
if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER)
@@ -1009,6 +1126,14 @@ bool GUIMainMenu::OnEvent(const SEvent& event)
m_data->address = L""; // Force local game
quitMenu();
return true;
+ case GUI_ID_SERVERLIST:
+ gui::IGUIListBox *serverlist = (gui::IGUIListBox*)getElementFromId(GUI_ID_SERVERLIST);
+ if (serverlist->getSelected() > -1)
+ {
+ acceptInput();
+ quitMenu();
+ return true;
+ }
}
}
}
@@ -1053,3 +1178,73 @@ void GUIMainMenu::displayMessageMenu(std::wstring msg)
{
(new GUIMessageMenu(env, parent, -1, menumgr, msg))->drop();
}
+
+void GUIMainMenu::updateGuiServerList()
+{
+ gui::IGUIListBox *serverlist = (gui::IGUIListBox *)getElementFromId(GUI_ID_SERVERLIST);
+ serverlist->clear();
+
+ for(std::vector<ServerListSpec>::iterator i = m_data->servers.begin();
+ i != m_data->servers.end(); i++)
+ {
+ std::string text;
+
+ if ((*i)["clients"].asString().size())
+ text += (*i)["clients"].asString();
+ if ((*i)["clients_max"].asString().size())
+ text += "/" + (*i)["clients_max"].asString();
+ text += " ";
+ if ((*i)["version"].asString().size())
+ text += (*i)["version"].asString() + " ";
+ if ((*i)["password"].asString().size())
+ text += "*";
+ if ((*i)["creative"].asString().size())
+ text += "C";
+ if ((*i)["damage"].asString().size())
+ text += "D";
+ if ((*i)["pvp"].asString().size())
+ text += "P";
+ text += " ";
+
+ if ((*i)["name"] != "" && (*i)["description"] != "")
+ text += (*i)["name"].asString() + " (" + (*i)["description"].asString() + ")";
+ else if ((*i)["name"] !="")
+ text += (*i)["name"].asString();
+ else
+ text += (*i)["address"].asString() + ":" + (*i)["port"].asString();
+
+ serverlist->addItem(narrow_to_wide(text).c_str());
+ }
+}
+
+void GUIMainMenu::serverListOnSelected()
+{
+ if (!m_data->servers.empty())
+ {
+ gui::IGUIListBox *serverlist = (gui::IGUIListBox*)getElementFromId(GUI_ID_SERVERLIST);
+ u16 id = serverlist->getSelected();
+ //if (id < 0) return; // u16>0!
+ ((gui::IGUIEditBox*)getElementFromId(GUI_ID_ADDRESS_INPUT))
+ ->setText(narrow_to_wide(m_data->servers[id]["address"].asString()).c_str());
+ ((gui::IGUIEditBox*)getElementFromId(GUI_ID_PORT_INPUT))
+ ->setText(narrow_to_wide(m_data->servers[id]["port"].asString()).c_str());
+ }
+}
+
+ServerListSpec GUIMainMenu::getServerListSpec(std::string address, std::string port)
+{
+ ServerListSpec server;
+ server["address"] = address;
+ server["port"] = port;
+ for(std::vector<ServerListSpec>::iterator i = m_data->servers.begin();
+ i != m_data->servers.end(); i++)
+ {
+ if ((*i)["address"] == address && (*i)["port"] == port)
+ {
+ server["description"] = (*i)["description"];
+ server["name"] = (*i)["name"];
+ break;
+ }
+ }
+ return server;
+}
diff --git a/src/guiMainMenu.h b/src/guiMainMenu.h
index f87ad0fdb..558a05d59 100644
--- a/src/guiMainMenu.h
+++ b/src/guiMainMenu.h
@@ -25,6 +25,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <string>
#include <list>
#include "subgame.h"
+#include "serverlist.h"
+
class IGameCallback;
struct MainMenuData
@@ -33,6 +35,8 @@ struct MainMenuData
// Generic
int selected_tab;
// Client options
+ std::string servername;
+ std::string serverdescription;
std::wstring address;
std::wstring port;
std::wstring name;
@@ -51,6 +55,7 @@ struct MainMenuData
// Server options
bool creative_mode;
bool enable_damage;
+ bool enable_public;
int selected_world;
bool simple_singleplayer_mode;
// Actions
@@ -58,8 +63,11 @@ struct MainMenuData
std::string create_world_gameid;
bool only_refresh;
+ bool serverlist_show_available; // if false show local favorites only
+
std::vector<WorldSpec> worlds;
std::vector<SubgameSpec> games;
+ std::vector<ServerListSpec> servers;
MainMenuData():
// Generic
@@ -70,10 +78,13 @@ struct MainMenuData
// Server opts
creative_mode(false),
enable_damage(false),
+ enable_public(false),
selected_world(0),
simple_singleplayer_mode(false),
// Actions
- only_refresh(false)
+ only_refresh(false),
+
+ serverlist_show_available(false)
{}
};
@@ -110,12 +121,15 @@ private:
gui::IGUIElement* parent;
s32 id;
IMenuManager *menumgr;
-
+
bool m_is_regenerating;
v2s32 m_topleft_client;
v2s32 m_size_client;
v2s32 m_topleft_server;
v2s32 m_size_server;
+ void updateGuiServerList();
+ void serverListOnSelected();
+ ServerListSpec getServerListSpec(std::string address, std::string port);
};
#endif
diff --git a/src/guiPauseMenu.cpp b/src/guiPauseMenu.cpp
index c800cf952..f6cbf248f 100644
--- a/src/guiPauseMenu.cpp
+++ b/src/guiPauseMenu.cpp
@@ -1,253 +1,253 @@
-/*
-Minetest-c55
-Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation; either version 2.1 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along
-with this program; if not, write to the Free Software Foundation, Inc.,
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-*/
-
-#include "guiPauseMenu.h"
-#include "debug.h"
-#include "serialization.h"
-#include "porting.h"
-#include "config.h"
-#include "main.h"
-#include <IGUICheckBox.h>
-#include <IGUIEditBox.h>
-#include <IGUIButton.h>
-#include <IGUIStaticText.h>
-#include <IGUIFont.h>
-#include "gettext.h"
-#include "util/string.h"
-
-GUIPauseMenu::GUIPauseMenu(gui::IGUIEnvironment* env,
- gui::IGUIElement* parent, s32 id,
- IGameCallback *gamecallback,
- IMenuManager *menumgr,
- bool simple_singleplayer_mode):
- GUIModalMenu(env, parent, id, menumgr),
- m_gamecallback(gamecallback),
- m_simple_singleplayer_mode(simple_singleplayer_mode)
-{
-}
-
-GUIPauseMenu::~GUIPauseMenu()
-{
- removeChildren();
-}
-
-void GUIPauseMenu::removeChildren()
-{
- {
- gui::IGUIElement *e = getElementFromId(256);
- if(e != NULL)
- e->remove();
- }
- {
- gui::IGUIElement *e = getElementFromId(257);
- if(e != NULL)
- e->remove();
- }
- {
- gui::IGUIElement *e = getElementFromId(258);
- if(e != NULL)
- e->remove();
- }
- {
- gui::IGUIElement *e = getElementFromId(259);
- if(e != NULL)
- e->remove();
- }
- {
- gui::IGUIElement *e = getElementFromId(260);
- if(e != NULL)
- e->remove();
- }
- {
- gui::IGUIElement *e = getElementFromId(261);
- if(e != NULL)
- e->remove();
- }
-}
-
-void GUIPauseMenu::regenerateGui(v2u32 screensize)
-{
- /*
- Remove stuff
- */
- removeChildren();
-
- /*
- Calculate new sizes and positions
- */
- core::rect<s32> rect(
- screensize.X/2 - 580/2,
- screensize.Y/2 - 300/2,
- screensize.X/2 + 580/2,
- screensize.Y/2 + 300/2
- );
-
- DesiredRect = rect;
- recalculateAbsolutePosition(false);
-
- v2s32 size = rect.getSize();
-
- /*
- Add stuff
- */
- const s32 btn_height = 30;
- const s32 btn_gap = 20;
- const s32 btn_num = m_simple_singleplayer_mode ? 3 : 4;
- s32 btn_y = size.Y/2-((btn_num*btn_height+(btn_num-1)*btn_gap))/2;
- changeCtype("");
- {
- core::rect<s32> rect(0, 0, 140, btn_height);
- rect = rect + v2s32(size.X/2-140/2, btn_y);
- Environment->addButton(rect, this, 256,
- wgettext("Continue"));
- }
- btn_y += btn_height + btn_gap;
- if(!m_simple_singleplayer_mode)
- {
- {
- core::rect<s32> rect(0, 0, 140, btn_height);
- rect = rect + v2s32(size.X/2-140/2, btn_y);
- Environment->addButton(rect, this, 261,
- wgettext("Change Password"));
- }
- btn_y += btn_height + btn_gap;
- }
- {
- core::rect<s32> rect(0, 0, 140, btn_height);
- rect = rect + v2s32(size.X/2-140/2, btn_y);
- Environment->addButton(rect, this, 260,
- wgettext("Exit to Menu"));
- }
- btn_y += btn_height + btn_gap;
- {
- core::rect<s32> rect(0, 0, 140, btn_height);
- rect = rect + v2s32(size.X/2-140/2, btn_y);
- Environment->addButton(rect, this, 257,
- wgettext("Exit to OS"));
- }
-
- {
- core::rect<s32> rect(0, 0, 180, 240);
- rect = rect + v2s32(size.X/2 + 90, size.Y/2-rect.getHeight()/2);
- Environment->addStaticText(chartowchar_t(gettext(
- "Default Controls:\n"
- "- WASD: Walk\n"
- "- Mouse left: dig/hit\n"
- "- Mouse right: place/use\n"
- "- Mouse wheel: select item\n"
- "- 0...9: select item\n"
- "- Shift: sneak\n"
- "- R: Toggle viewing all loaded chunks\n"
- "- I: Inventory menu\n"
- "- ESC: This menu\n"
- "- T: Chat\n"
- )), rect, false, true, this, 258);
- }
- {
- core::rect<s32> rect(0, 0, 180, 220);
- rect = rect + v2s32(size.X/2 - 90 - rect.getWidth(), size.Y/2-rect.getHeight()/2);
-
- v2u32 max_texture_size;
- {
- video::IVideoDriver* driver = Environment->getVideoDriver();
- max_texture_size = driver->getMaxTextureSize();
- }
-
- std::ostringstream os;
- os<<"Minetest\n";
- os<<BUILD_INFO<<"\n";
- os<<"path_user = "<<wrap_rows(porting::path_user, 20)<<"\n";
-
- Environment->addStaticText(narrow_to_wide(os.str()).c_str(), rect, false, true, this, 259);
- }
- changeCtype("C");
-}
-
-void GUIPauseMenu::drawMenu()
-{
- gui::IGUISkin* skin = Environment->getSkin();
- if (!skin)
- return;
- video::IVideoDriver* driver = Environment->getVideoDriver();
-
- video::SColor bgcolor(140,0,0,0);
- driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect);
-
- gui::IGUIElement::draw();
-}
-
-bool GUIPauseMenu::OnEvent(const SEvent& event)
-{
-
- if(event.EventType==EET_KEY_INPUT_EVENT)
- {
- if(event.KeyInput.PressedDown)
- {
- if(event.KeyInput.Key==KEY_ESCAPE)
- {
- quitMenu();
- return true;
- }
- else if(event.KeyInput.Key==KEY_RETURN)
- {
- quitMenu();
- return true;
- }
- }
- }
- if(event.EventType==EET_GUI_EVENT)
- {
- if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
- && isVisible())
- {
- if(!canTakeFocus(event.GUIEvent.Element))
- {
- dstream<<"GUIPauseMenu: Not allowing focus change."
- <<std::endl;
- // Returning true disables focus change
- return true;
- }
- }
- if(event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED)
- {
- switch(event.GUIEvent.Caller->getID())
- {
- case 256: // continue
- quitMenu();
- // ALWAYS return immediately after quitMenu()
- return true;
- case 261:
- quitMenu();
- m_gamecallback->changePassword();
- return true;
- case 260: // disconnect
- m_gamecallback->disconnect();
- quitMenu();
- return true;
- case 257: // exit
- m_gamecallback->exitToOS();
- quitMenu();
- return true;
- }
- }
- }
-
- return Parent ? Parent->OnEvent(event) : false;
-}
-
+/*
+Minetest-c55
+Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#include "guiPauseMenu.h"
+#include "debug.h"
+#include "serialization.h"
+#include "porting.h"
+#include "config.h"
+#include "main.h"
+#include <IGUICheckBox.h>
+#include <IGUIEditBox.h>
+#include <IGUIButton.h>
+#include <IGUIStaticText.h>
+#include <IGUIFont.h>
+#include "gettext.h"
+#include "util/string.h"
+
+GUIPauseMenu::GUIPauseMenu(gui::IGUIEnvironment* env,
+ gui::IGUIElement* parent, s32 id,
+ IGameCallback *gamecallback,
+ IMenuManager *menumgr,
+ bool simple_singleplayer_mode):
+ GUIModalMenu(env, parent, id, menumgr),
+ m_gamecallback(gamecallback),
+ m_simple_singleplayer_mode(simple_singleplayer_mode)
+{
+}
+
+GUIPauseMenu::~GUIPauseMenu()
+{
+ removeChildren();
+}
+
+void GUIPauseMenu::removeChildren()
+{
+ {
+ gui::IGUIElement *e = getElementFromId(256);
+ if(e != NULL)
+ e->remove();
+ }
+ {
+ gui::IGUIElement *e = getElementFromId(257);
+ if(e != NULL)
+ e->remove();
+ }
+ {
+ gui::IGUIElement *e = getElementFromId(258);
+ if(e != NULL)
+ e->remove();
+ }
+ {
+ gui::IGUIElement *e = getElementFromId(259);
+ if(e != NULL)
+ e->remove();
+ }
+ {
+ gui::IGUIElement *e = getElementFromId(260);
+ if(e != NULL)
+ e->remove();
+ }
+ {
+ gui::IGUIElement *e = getElementFromId(261);
+ if(e != NULL)
+ e->remove();
+ }
+}
+
+void GUIPauseMenu::regenerateGui(v2u32 screensize)
+{
+ /*
+ Remove stuff
+ */
+ removeChildren();
+
+ /*
+ Calculate new sizes and positions
+ */
+ core::rect<s32> rect(
+ screensize.X/2 - 580/2,
+ screensize.Y/2 - 300/2,
+ screensize.X/2 + 580/2,
+ screensize.Y/2 + 300/2
+ );
+
+ DesiredRect = rect;
+ recalculateAbsolutePosition(false);
+
+ v2s32 size = rect.getSize();
+
+ /*
+ Add stuff
+ */
+ const s32 btn_height = 30;
+ const s32 btn_gap = 20;
+ const s32 btn_num = m_simple_singleplayer_mode ? 3 : 4;
+ s32 btn_y = size.Y/2-((btn_num*btn_height+(btn_num-1)*btn_gap))/2;
+ changeCtype("");
+ {
+ core::rect<s32> rect(0, 0, 140, btn_height);
+ rect = rect + v2s32(size.X/2-140/2, btn_y);
+ Environment->addButton(rect, this, 256,
+ wgettext("Continue"));
+ }
+ btn_y += btn_height + btn_gap;
+ if(!m_simple_singleplayer_mode)
+ {
+ {
+ core::rect<s32> rect(0, 0, 140, btn_height);
+ rect = rect + v2s32(size.X/2-140/2, btn_y);
+ Environment->addButton(rect, this, 261,
+ wgettext("Change Password"));
+ }
+ btn_y += btn_height + btn_gap;
+ }
+ {
+ core::rect<s32> rect(0, 0, 140, btn_height);
+ rect = rect + v2s32(size.X/2-140/2, btn_y);
+ Environment->addButton(rect, this, 260,
+ wgettext("Exit to Menu"));
+ }
+ btn_y += btn_height + btn_gap;
+ {
+ core::rect<s32> rect(0, 0, 140, btn_height);
+ rect = rect + v2s32(size.X/2-140/2, btn_y);
+ Environment->addButton(rect, this, 257,
+ wgettext("Exit to OS"));
+ }
+
+ {
+ core::rect<s32> rect(0, 0, 180, 240);
+ rect = rect + v2s32(size.X/2 + 90, size.Y/2-rect.getHeight()/2);
+ Environment->addStaticText(chartowchar_t(gettext(
+ "Default Controls:\n"
+ "- WASD: Walk\n"
+ "- Mouse left: dig/hit\n"
+ "- Mouse right: place/use\n"
+ "- Mouse wheel: select item\n"
+ "- 0...9: select item\n"
+ "- Shift: sneak\n"
+ "- R: Toggle viewing all loaded chunks\n"
+ "- I: Inventory menu\n"
+ "- ESC: This menu\n"
+ "- T: Chat\n"
+ )), rect, false, true, this, 258);
+ }
+ {
+ core::rect<s32> rect(0, 0, 180, 220);
+ rect = rect + v2s32(size.X/2 - 90 - rect.getWidth(), size.Y/2-rect.getHeight()/2);
+
+ v2u32 max_texture_size;
+ {
+ video::IVideoDriver* driver = Environment->getVideoDriver();
+ max_texture_size = driver->getMaxTextureSize();
+ }
+
+ std::ostringstream os;
+ os<<"Minetest\n";
+ os<<BUILD_INFO<<"\n";
+ os<<"path_user = "<<wrap_rows(porting::path_user, 20)<<"\n";
+
+ Environment->addStaticText(narrow_to_wide(os.str()).c_str(), rect, false, true, this, 259);
+ }
+ changeCtype("C");
+}
+
+void GUIPauseMenu::drawMenu()
+{
+ gui::IGUISkin* skin = Environment->getSkin();
+ if (!skin)
+ return;
+ video::IVideoDriver* driver = Environment->getVideoDriver();
+
+ video::SColor bgcolor(140,0,0,0);
+ driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect);
+
+ gui::IGUIElement::draw();
+}
+
+bool GUIPauseMenu::OnEvent(const SEvent& event)
+{
+
+ if(event.EventType==EET_KEY_INPUT_EVENT)
+ {
+ if(event.KeyInput.PressedDown)
+ {
+ if(event.KeyInput.Key==KEY_ESCAPE)
+ {
+ quitMenu();
+ return true;
+ }
+ else if(event.KeyInput.Key==KEY_RETURN)
+ {
+ quitMenu();
+ return true;
+ }
+ }
+ }
+ if(event.EventType==EET_GUI_EVENT)
+ {
+ if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
+ && isVisible())
+ {
+ if(!canTakeFocus(event.GUIEvent.Element))
+ {
+ dstream<<"GUIPauseMenu: Not allowing focus change."
+ <<std::endl;
+ // Returning true disables focus change
+ return true;
+ }
+ }
+ if(event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED)
+ {
+ switch(event.GUIEvent.Caller->getID())
+ {
+ case 256: // continue
+ quitMenu();
+ // ALWAYS return immediately after quitMenu()
+ return true;
+ case 261:
+ quitMenu();
+ m_gamecallback->changePassword();
+ return true;
+ case 260: // disconnect
+ m_gamecallback->disconnect();
+ quitMenu();
+ return true;
+ case 257: // exit
+ m_gamecallback->exitToOS();
+ quitMenu();
+ return true;
+ }
+ }
+ }
+
+ return Parent ? Parent->OnEvent(event) : false;
+}
+
diff --git a/src/guiPauseMenu.h b/src/guiPauseMenu.h
index e28159a93..4b15fc74f 100644
--- a/src/guiPauseMenu.h
+++ b/src/guiPauseMenu.h
@@ -1,60 +1,60 @@
-/*
-Minetest-c55
-Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation; either version 2.1 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along
-with this program; if not, write to the Free Software Foundation, Inc.,
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-*/
-
-#ifndef GUIPAUSEMENU_HEADER
-#define GUIPAUSEMENU_HEADER
-
-#include "irrlichttypes_extrabloated.h"
-#include "modalMenu.h"
-
-class IGameCallback
-{
-public:
- virtual void exitToOS() = 0;
- virtual void disconnect() = 0;
- virtual void changePassword() = 0;
-};
-
-class GUIPauseMenu : public GUIModalMenu
-{
-public:
- GUIPauseMenu(gui::IGUIEnvironment* env,
- gui::IGUIElement* parent, s32 id,
- IGameCallback *gamecallback,
- IMenuManager *menumgr,
- bool simple_singleplayer_mode);
- ~GUIPauseMenu();
-
- void removeChildren();
- /*
- Remove and re-add (or reposition) stuff
- */
- void regenerateGui(v2u32 screensize);
-
- void drawMenu();
-
- bool OnEvent(const SEvent& event);
-
-private:
- IGameCallback *m_gamecallback;
- bool m_simple_singleplayer_mode;
-};
-
-#endif
-
+/*
+Minetest-c55
+Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#ifndef GUIPAUSEMENU_HEADER
+#define GUIPAUSEMENU_HEADER
+
+#include "irrlichttypes_extrabloated.h"
+#include "modalMenu.h"
+
+class IGameCallback
+{
+public:
+ virtual void exitToOS() = 0;
+ virtual void disconnect() = 0;
+ virtual void changePassword() = 0;
+};
+
+class GUIPauseMenu : public GUIModalMenu
+{
+public:
+ GUIPauseMenu(gui::IGUIEnvironment* env,
+ gui::IGUIElement* parent, s32 id,
+ IGameCallback *gamecallback,
+ IMenuManager *menumgr,
+ bool simple_singleplayer_mode);
+ ~GUIPauseMenu();
+
+ void removeChildren();
+ /*
+ Remove and re-add (or reposition) stuff
+ */
+ void regenerateGui(v2u32 screensize);
+
+ void drawMenu();
+
+ bool OnEvent(const SEvent& event);
+
+private:
+ IGameCallback *m_gamecallback;
+ bool m_simple_singleplayer_mode;
+};
+
+#endif
+
diff --git a/src/guiTextInputMenu.cpp b/src/guiTextInputMenu.cpp
index 094532a62..857c26a45 100644
--- a/src/guiTextInputMenu.cpp
+++ b/src/guiTextInputMenu.cpp
@@ -29,6 +29,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gettext.h"
+#if USE_FREETYPE
+#include "intlGUIEditBox.h"
+#endif
+
GUITextInputMenu::GUITextInputMenu(gui::IGUIEnvironment* env,
gui::IGUIElement* parent, s32 id,
IMenuManager *menumgr,
@@ -105,8 +109,12 @@ void GUITextInputMenu::regenerateGui(v2u32 screensize)
{
core::rect<s32> rect(0, 0, 300, 30);
rect = rect + v2s32(size.X/2-300/2, size.Y/2-30/2-25);
- gui::IGUIElement *e =
- Environment->addEditBox(text.c_str(), rect, true, this, 256);
+ #if USE_FREETYPE
+ gui::IGUIElement *e = (gui::IGUIElement *) new gui::intlGUIEditBox(text.c_str(), true, Environment, this, 256, rect);
+ e->drop();
+ #else
+ gui::IGUIElement *e = Environment->addEditBox(text.c_str(), rect, true, this, 256);
+ #endif
Environment->setFocus(e);
irr::SEvent evt;
diff --git a/src/intlGUIEditBox.cpp b/src/intlGUIEditBox.cpp
new file mode 100644
index 000000000..4add61e20
--- /dev/null
+++ b/src/intlGUIEditBox.cpp
@@ -0,0 +1,1508 @@
+// 11.11.2011 11:11 ValkaTR
+//
+// This is a copy of intlGUIEditBox from the irrlicht, but with a
+// fix in the OnEvent function, which doesn't allowed input of
+// other keyboard layouts than latin-1
+//
+// Characters like: ä ö ü õ ы й ю я ъ № € ° ...
+//
+// This fix is only needed for linux, because of a bug
+// in the CIrrDeviceLinux.cpp:1014-1015 of the irrlicht
+//
+// Also locale in the programm should not be changed to
+// a "C", "POSIX" or whatever, it should be set to "",
+// or XLookupString will return nothing for the international
+// characters.
+//
+// From the "man setlocale":
+//
+// On startup of the main program, the portable "C" locale
+// is selected as default. A program may be made
+// portable to all locales by calling:
+//
+// setlocale(LC_ALL, "");
+//
+// after program initialization....
+//
+
+// Copyright (C) 2002-2010 Nikolaus Gebhardt
+// This file is part of the "Irrlicht Engine".
+// For conditions of distribution and use, see copyright notice in irrlicht.h
+
+#include "intlGUIEditBox.h"
+
+#ifdef _IRR_COMPILE_WITH_GUI_
+
+#include "IGUISkin.h"
+#include "IGUIEnvironment.h"
+#include "IGUIFont.h"
+#include "IVideoDriver.h"
+//#include "rect.h"
+//#include "irrlicht/os.cpp"
+#include "porting.h"
+//#include "Keycodes.h"
+
+/*
+ todo:
+ optional scrollbars
+ ctrl+left/right to select word
+ double click/ctrl click: word select + drag to select whole words, triple click to select line
+ optional? dragging selected text
+ numerical
+*/
+
+namespace irr
+{
+namespace gui
+{
+
+//! constructor
+intlGUIEditBox::intlGUIEditBox(const wchar_t* text, bool border,
+ IGUIEnvironment* environment, IGUIElement* parent, s32 id,
+ const core::rect<s32>& rectangle)
+ : IGUIEditBox(environment, parent, id, rectangle), MouseMarking(false),
+ Border(border), OverrideColorEnabled(false), MarkBegin(0), MarkEnd(0),
+ OverrideColor(video::SColor(101,255,255,255)), OverrideFont(0), LastBreakFont(0),
+ Operator(0), BlinkStartTime(0), CursorPos(0), HScrollPos(0), VScrollPos(0), Max(0),
+ WordWrap(false), MultiLine(false), AutoScroll(true), PasswordBox(false),
+ PasswordChar(L'*'), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_CENTER),
+ CurrentTextRect(0,0,1,1), FrameRect(rectangle)
+{
+ #ifdef _DEBUG
+ setDebugName("intlintlGUIEditBox");
+ #endif
+
+ Text = text;
+
+ if (Environment)
+ Operator = Environment->getOSOperator();
+
+ if (Operator)
+ Operator->grab();
+
+ // this element can be tabbed to
+ setTabStop(true);
+ setTabOrder(-1);
+
+ IGUISkin *skin = 0;
+ if (Environment)
+ skin = Environment->getSkin();
+ if (Border && skin)
+ {
+ FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1;
+ FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1;
+ FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1;
+ FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1;
+ }
+
+ breakText();
+
+ calculateScrollPos();
+}
+
+
+//! destructor
+intlGUIEditBox::~intlGUIEditBox()
+{
+ if (OverrideFont)
+ OverrideFont->drop();
+
+ if (Operator)
+ Operator->drop();
+}
+
+
+//! Sets another skin independent font.
+void intlGUIEditBox::setOverrideFont(IGUIFont* font)
+{
+ if (OverrideFont == font)
+ return;
+
+ if (OverrideFont)
+ OverrideFont->drop();
+
+ OverrideFont = font;
+
+ if (OverrideFont)
+ OverrideFont->grab();
+
+ breakText();
+}
+
+IGUIFont * intlGUIEditBox::getOverrideFont() const
+{
+ return OverrideFont;
+}
+
+//! Get the font which is used right now for drawing
+IGUIFont* intlGUIEditBox::getActiveFont() const
+{
+ if ( OverrideFont )
+ return OverrideFont;
+ IGUISkin* skin = Environment->getSkin();
+ if (skin)
+ return skin->getFont();
+ return 0;
+}
+
+//! Sets another color for the text.
+void intlGUIEditBox::setOverrideColor(video::SColor color)
+{
+ OverrideColor = color;
+ OverrideColorEnabled = true;
+}
+
+video::SColor intlGUIEditBox::getOverrideColor() const
+{
+ return OverrideColor;
+}
+
+//! Turns the border on or off
+void intlGUIEditBox::setDrawBorder(bool border)
+{
+ Border = border;
+}
+
+//! Sets whether to draw the background
+void intlGUIEditBox::setDrawBackground(bool draw)
+{
+}
+
+//! Sets if the text should use the overide color or the color in the gui skin.
+void intlGUIEditBox::enableOverrideColor(bool enable)
+{
+ OverrideColorEnabled = enable;
+}
+
+bool intlGUIEditBox::isOverrideColorEnabled() const
+{
+ _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
+ return OverrideColorEnabled;
+}
+
+//! Enables or disables word wrap
+void intlGUIEditBox::setWordWrap(bool enable)
+{
+ WordWrap = enable;
+ breakText();
+}
+
+
+void intlGUIEditBox::updateAbsolutePosition()
+{
+ core::rect<s32> oldAbsoluteRect(AbsoluteRect);
+ IGUIElement::updateAbsolutePosition();
+ if ( oldAbsoluteRect != AbsoluteRect )
+ {
+ breakText();
+ }
+}
+
+
+//! Checks if word wrap is enabled
+bool intlGUIEditBox::isWordWrapEnabled() const
+{
+ _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
+ return WordWrap;
+}
+
+
+//! Enables or disables newlines.
+void intlGUIEditBox::setMultiLine(bool enable)
+{
+ MultiLine = enable;
+}
+
+
+//! Checks if multi line editing is enabled
+bool intlGUIEditBox::isMultiLineEnabled() const
+{
+ _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
+ return MultiLine;
+}
+
+
+void intlGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar)
+{
+ PasswordBox = passwordBox;
+ if (PasswordBox)
+ {
+ PasswordChar = passwordChar;
+ setMultiLine(false);
+ setWordWrap(false);
+ BrokenText.clear();
+ }
+}
+
+
+bool intlGUIEditBox::isPasswordBox() const
+{
+ _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
+ return PasswordBox;
+}
+
+
+//! Sets text justification
+void intlGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical)
+{
+ HAlign = horizontal;
+ VAlign = vertical;
+}
+
+
+//! called if an event happened.
+bool intlGUIEditBox::OnEvent(const SEvent& event)
+{
+ if (IsEnabled)
+ {
+
+ switch(event.EventType)
+ {
+ case EET_GUI_EVENT:
+ if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
+ {
+ if (event.GUIEvent.Caller == this)
+ {
+ MouseMarking = false;
+ setTextMarkers(0,0);
+ }
+ }
+ break;
+ case EET_KEY_INPUT_EVENT:
+ {
+#if defined(linux)
+ // ################################################################
+ // ValkaTR:
+ // This part is the difference from the original intlGUIEditBox
+ // It converts UTF-8 character into a UCS-2 (wchar_t)
+ wchar_t wc = L'_';
+ mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) );
+
+ //printf( "char: %lc (%u) \r\n", wc, wc );
+
+ SEvent irrevent(event);
+ irrevent.KeyInput.Char = wc;
+ // ################################################################
+
+ if (processKey(irrevent))
+ return true;
+#else
+ if (processKey(event))
+ return true;
+#endif // defined(linux)
+
+ break;
+ }
+ case EET_MOUSE_INPUT_EVENT:
+ if (processMouse(event))
+ return true;
+ break;
+ default:
+ break;
+ }
+ }
+
+ return IGUIElement::OnEvent(event);
+}
+
+
+bool intlGUIEditBox::processKey(const SEvent& event)
+{
+ if (!event.KeyInput.PressedDown)
+ return false;
+
+ bool textChanged = false;
+ s32 newMarkBegin = MarkBegin;
+ s32 newMarkEnd = MarkEnd;
+
+ // control shortcut handling
+
+ if (event.KeyInput.Control)
+ {
+ // german backlash '\' entered with control + '?'
+ if ( event.KeyInput.Char == '\\' )
+ {
+ inputChar(event.KeyInput.Char);
+ return true;
+ }
+
+ switch(event.KeyInput.Key)
+ {
+ case KEY_KEY_A:
+ // select all
+ newMarkBegin = 0;
+ newMarkEnd = Text.size();
+ break;
+ case KEY_KEY_C:
+ // copy to clipboard
+ if (!PasswordBox && Operator && MarkBegin != MarkEnd)
+ {
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ core::stringc s;
+ s = Text.subString(realmbgn, realmend - realmbgn).c_str();
+ Operator->copyToClipboard(s.c_str());
+ }
+ break;
+ case KEY_KEY_X:
+ // cut to the clipboard
+ if (!PasswordBox && Operator && MarkBegin != MarkEnd)
+ {
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ // copy
+ core::stringc sc;
+ sc = Text.subString(realmbgn, realmend - realmbgn).c_str();
+ Operator->copyToClipboard(sc.c_str());
+
+ if (IsEnabled)
+ {
+ // delete
+ core::stringw s;
+ s = Text.subString(0, realmbgn);
+ s.append( Text.subString(realmend, Text.size()-realmend) );
+ Text = s;
+
+ CursorPos = realmbgn;
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ textChanged = true;
+ }
+ }
+ break;
+ case KEY_KEY_V:
+ if ( !IsEnabled )
+ break;
+
+ // paste from the clipboard
+ if (Operator)
+ {
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ // add new character
+ const c8* p = Operator->getTextFromClipboard();
+ if (p)
+ {
+ if (MarkBegin == MarkEnd)
+ {
+ // insert text
+ core::stringw s = Text.subString(0, CursorPos);
+ s.append(p);
+ s.append( Text.subString(CursorPos, Text.size()-CursorPos) );
+
+ if (!Max || s.size()<=Max) // thx to Fish FH for fix
+ {
+ Text = s;
+ s = p;
+ CursorPos += s.size();
+ }
+ }
+ else
+ {
+ // replace text
+
+ core::stringw s = Text.subString(0, realmbgn);
+ s.append(p);
+ s.append( Text.subString(realmend, Text.size()-realmend) );
+
+ if (!Max || s.size()<=Max) // thx to Fish FH for fix
+ {
+ Text = s;
+ s = p;
+ CursorPos = realmbgn + s.size();
+ }
+ }
+ }
+
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ textChanged = true;
+ }
+ break;
+ case KEY_HOME:
+ // move/highlight to start of text
+ if (event.KeyInput.Shift)
+ {
+ newMarkEnd = CursorPos;
+ newMarkBegin = 0;
+ CursorPos = 0;
+ }
+ else
+ {
+ CursorPos = 0;
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+ break;
+ case KEY_END:
+ // move/highlight to end of text
+ if (event.KeyInput.Shift)
+ {
+ newMarkBegin = CursorPos;
+ newMarkEnd = Text.size();
+ CursorPos = 0;
+ }
+ else
+ {
+ CursorPos = Text.size();
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+ break;
+ default:
+ return false;
+ }
+ }
+ // default keyboard handling
+ else
+ switch(event.KeyInput.Key)
+ {
+ case KEY_END:
+ {
+ s32 p = Text.size();
+ if (WordWrap || MultiLine)
+ {
+ p = getLineFromPos(CursorPos);
+ p = BrokenTextPositions[p] + (s32)BrokenText[p].size();
+ if (p > 0 && (Text[p-1] == L'\r' || Text[p-1] == L'\n' ))
+ p-=1;
+ }
+
+ if (event.KeyInput.Shift)
+ {
+ if (MarkBegin == MarkEnd)
+ newMarkBegin = CursorPos;
+
+ newMarkEnd = p;
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+ CursorPos = p;
+ BlinkStartTime = porting::getTimeMs();
+ }
+ break;
+ case KEY_HOME:
+ {
+
+ s32 p = 0;
+ if (WordWrap || MultiLine)
+ {
+ p = getLineFromPos(CursorPos);
+ p = BrokenTextPositions[p];
+ }
+
+ if (event.KeyInput.Shift)
+ {
+ if (MarkBegin == MarkEnd)
+ newMarkBegin = CursorPos;
+ newMarkEnd = p;
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+ CursorPos = p;
+ BlinkStartTime = porting::getTimeMs();
+ }
+ break;
+ case KEY_RETURN:
+ if (MultiLine)
+ {
+ inputChar(L'\n');
+ return true;
+ }
+ else
+ {
+ sendGuiEvent( EGET_EDITBOX_ENTER );
+ }
+ break;
+ case KEY_LEFT:
+
+ if (event.KeyInput.Shift)
+ {
+ if (CursorPos > 0)
+ {
+ if (MarkBegin == MarkEnd)
+ newMarkBegin = CursorPos;
+
+ newMarkEnd = CursorPos-1;
+ }
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+
+ if (CursorPos > 0) CursorPos--;
+ BlinkStartTime = porting::getTimeMs();
+ break;
+
+ case KEY_RIGHT:
+ if (event.KeyInput.Shift)
+ {
+ if (Text.size() > (u32)CursorPos)
+ {
+ if (MarkBegin == MarkEnd)
+ newMarkBegin = CursorPos;
+
+ newMarkEnd = CursorPos+1;
+ }
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+
+ if (Text.size() > (u32)CursorPos) CursorPos++;
+ BlinkStartTime = porting::getTimeMs();
+ break;
+ case KEY_UP:
+ if (MultiLine || (WordWrap && BrokenText.size() > 1) )
+ {
+ s32 lineNo = getLineFromPos(CursorPos);
+ s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin > MarkEnd ? MarkBegin : MarkEnd);
+ if (lineNo > 0)
+ {
+ s32 cp = CursorPos - BrokenTextPositions[lineNo];
+ if ((s32)BrokenText[lineNo-1].size() < cp)
+ CursorPos = BrokenTextPositions[lineNo-1] + (s32)BrokenText[lineNo-1].size()-1;
+ else
+ CursorPos = BrokenTextPositions[lineNo-1] + cp;
+ }
+
+ if (event.KeyInput.Shift)
+ {
+ newMarkBegin = mb;
+ newMarkEnd = CursorPos;
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+
+ }
+ else
+ {
+ return false;
+ }
+ break;
+ case KEY_DOWN:
+ if (MultiLine || (WordWrap && BrokenText.size() > 1) )
+ {
+ s32 lineNo = getLineFromPos(CursorPos);
+ s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin < MarkEnd ? MarkBegin : MarkEnd);
+ if (lineNo < (s32)BrokenText.size()-1)
+ {
+ s32 cp = CursorPos - BrokenTextPositions[lineNo];
+ if ((s32)BrokenText[lineNo+1].size() < cp)
+ CursorPos = BrokenTextPositions[lineNo+1] + BrokenText[lineNo+1].size()-1;
+ else
+ CursorPos = BrokenTextPositions[lineNo+1] + cp;
+ }
+
+ if (event.KeyInput.Shift)
+ {
+ newMarkBegin = mb;
+ newMarkEnd = CursorPos;
+ }
+ else
+ {
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ }
+
+ }
+ else
+ {
+ return false;
+ }
+ break;
+
+ case KEY_BACK:
+ if ( !this->IsEnabled )
+ break;
+
+ if (Text.size())
+ {
+ core::stringw s;
+
+ if (MarkBegin != MarkEnd)
+ {
+ // delete marked text
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ s = Text.subString(0, realmbgn);
+ s.append( Text.subString(realmend, Text.size()-realmend) );
+ Text = s;
+
+ CursorPos = realmbgn;
+ }
+ else
+ {
+ // delete text behind cursor
+ if (CursorPos>0)
+ s = Text.subString(0, CursorPos-1);
+ else
+ s = L"";
+ s.append( Text.subString(CursorPos, Text.size()-CursorPos) );
+ Text = s;
+ --CursorPos;
+ }
+
+ if (CursorPos < 0)
+ CursorPos = 0;
+ BlinkStartTime = porting::getTimeMs();
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ textChanged = true;
+ }
+ break;
+ case KEY_DELETE:
+ if ( !this->IsEnabled )
+ break;
+
+ if (Text.size() != 0)
+ {
+ core::stringw s;
+
+ if (MarkBegin != MarkEnd)
+ {
+ // delete marked text
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ s = Text.subString(0, realmbgn);
+ s.append( Text.subString(realmend, Text.size()-realmend) );
+ Text = s;
+
+ CursorPos = realmbgn;
+ }
+ else
+ {
+ // delete text before cursor
+ s = Text.subString(0, CursorPos);
+ s.append( Text.subString(CursorPos+1, Text.size()-CursorPos-1) );
+ Text = s;
+ }
+
+ if (CursorPos > (s32)Text.size())
+ CursorPos = (s32)Text.size();
+
+ BlinkStartTime = porting::getTimeMs();
+ newMarkBegin = 0;
+ newMarkEnd = 0;
+ textChanged = true;
+ }
+ break;
+
+ case KEY_ESCAPE:
+ case KEY_TAB:
+ case KEY_SHIFT:
+ case KEY_F1:
+ case KEY_F2:
+ case KEY_F3:
+ case KEY_F4:
+ case KEY_F5:
+ case KEY_F6:
+ case KEY_F7:
+ case KEY_F8:
+ case KEY_F9:
+ case KEY_F10:
+ case KEY_F11:
+ case KEY_F12:
+ case KEY_F13:
+ case KEY_F14:
+ case KEY_F15:
+ case KEY_F16:
+ case KEY_F17:
+ case KEY_F18:
+ case KEY_F19:
+ case KEY_F20:
+ case KEY_F21:
+ case KEY_F22:
+ case KEY_F23:
+ case KEY_F24:
+ // ignore these keys
+ return false;
+
+ default:
+ inputChar(event.KeyInput.Char);
+ return true;
+ }
+
+ // Set new text markers
+ setTextMarkers( newMarkBegin, newMarkEnd );
+
+ // break the text if it has changed
+ if (textChanged)
+ {
+ breakText();
+ sendGuiEvent(EGET_EDITBOX_CHANGED);
+ }
+
+ calculateScrollPos();
+
+ return true;
+}
+
+
+//! draws the element and its children
+void intlGUIEditBox::draw()
+{
+ if (!IsVisible)
+ return;
+
+ const bool focus = Environment->hasFocus(this);
+
+ IGUISkin* skin = Environment->getSkin();
+ if (!skin)
+ return;
+
+ FrameRect = AbsoluteRect;
+
+ // draw the border
+
+ if (Border)
+ {
+ skin->draw3DSunkenPane(this, skin->getColor(EGDC_WINDOW),
+ false, true, FrameRect, &AbsoluteClippingRect);
+
+ FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1;
+ FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1;
+ FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1;
+ FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1;
+ }
+ core::rect<s32> localClipRect = FrameRect;
+ localClipRect.clipAgainst(AbsoluteClippingRect);
+
+ // draw the text
+
+ IGUIFont* font = OverrideFont;
+ if (!OverrideFont)
+ font = skin->getFont();
+
+ s32 cursorLine = 0;
+ s32 charcursorpos = 0;
+
+ if (font)
+ {
+ if (LastBreakFont != font)
+ {
+ breakText();
+ }
+
+ // calculate cursor pos
+
+ core::stringw *txtLine = &Text;
+ s32 startPos = 0;
+
+ core::stringw s, s2;
+
+ // get mark position
+ const bool ml = (!PasswordBox && (WordWrap || MultiLine));
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+ const s32 hlineStart = ml ? getLineFromPos(realmbgn) : 0;
+ const s32 hlineCount = ml ? getLineFromPos(realmend) - hlineStart + 1 : 1;
+ const s32 lineCount = ml ? BrokenText.size() : 1;
+
+ // Save the override color information.
+ // Then, alter it if the edit box is disabled.
+ const bool prevOver = OverrideColorEnabled;
+ const video::SColor prevColor = OverrideColor;
+
+ if (Text.size())
+ {
+ if (!IsEnabled && !OverrideColorEnabled)
+ {
+ OverrideColorEnabled = true;
+ OverrideColor = skin->getColor(EGDC_GRAY_TEXT);
+ }
+
+ for (s32 i=0; i < lineCount; ++i)
+ {
+ setTextRect(i);
+
+ // clipping test - don't draw anything outside the visible area
+ core::rect<s32> c = localClipRect;
+ c.clipAgainst(CurrentTextRect);
+ if (!c.isValid())
+ continue;
+
+ // get current line
+ if (PasswordBox)
+ {
+ if (BrokenText.size() != 1)
+ {
+ BrokenText.clear();
+ BrokenText.push_back(core::stringw());
+ }
+ if (BrokenText[0].size() != Text.size())
+ {
+ BrokenText[0] = Text;
+ for (u32 q = 0; q < Text.size(); ++q)
+ {
+ BrokenText[0] [q] = PasswordChar;
+ }
+ }
+ txtLine = &BrokenText[0];
+ startPos = 0;
+ }
+ else
+ {
+ txtLine = ml ? &BrokenText[i] : &Text;
+ startPos = ml ? BrokenTextPositions[i] : 0;
+ }
+
+
+ // draw normal text
+ font->draw(txtLine->c_str(), CurrentTextRect,
+ OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT),
+ false, true, &localClipRect);
+
+ // draw mark and marked text
+ if (focus && MarkBegin != MarkEnd && i >= hlineStart && i < hlineStart + hlineCount)
+ {
+
+ s32 mbegin = 0, mend = 0;
+ s32 lineStartPos = 0, lineEndPos = txtLine->size();
+
+ if (i == hlineStart)
+ {
+ // highlight start is on this line
+ s = txtLine->subString(0, realmbgn - startPos);
+ mbegin = font->getDimension(s.c_str()).Width;
+
+ // deal with kerning
+ mbegin += font->getKerningWidth(
+ &((*txtLine)[realmbgn - startPos]),
+ realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0);
+
+ lineStartPos = realmbgn - startPos;
+ }
+ if (i == hlineStart + hlineCount - 1)
+ {
+ // highlight end is on this line
+ s2 = txtLine->subString(0, realmend - startPos);
+ mend = font->getDimension(s2.c_str()).Width;
+ lineEndPos = (s32)s2.size();
+ }
+ else
+ mend = font->getDimension(txtLine->c_str()).Width;
+
+ CurrentTextRect.UpperLeftCorner.X += mbegin;
+ CurrentTextRect.LowerRightCorner.X = CurrentTextRect.UpperLeftCorner.X + mend - mbegin;
+
+ // draw mark
+ skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), CurrentTextRect, &localClipRect);
+
+ // draw marked text
+ s = txtLine->subString(lineStartPos, lineEndPos - lineStartPos);
+
+ if (s.size())
+ font->draw(s.c_str(), CurrentTextRect,
+ OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT),
+ false, true, &localClipRect);
+
+ }
+ }
+
+ // Return the override color information to its previous settings.
+ OverrideColorEnabled = prevOver;
+ OverrideColor = prevColor;
+ }
+
+ // draw cursor
+
+ if (WordWrap || MultiLine)
+ {
+ cursorLine = getLineFromPos(CursorPos);
+ txtLine = &BrokenText[cursorLine];
+ startPos = BrokenTextPositions[cursorLine];
+ }
+ s = txtLine->subString(0,CursorPos-startPos);
+ charcursorpos = font->getDimension(s.c_str()).Width +
+ font->getKerningWidth(L"_", CursorPos-startPos > 0 ? &((*txtLine)[CursorPos-startPos-1]) : 0);
+
+ if (focus && (porting::getTimeMs() - BlinkStartTime) % 700 < 350)
+ {
+ setTextRect(cursorLine);
+ CurrentTextRect.UpperLeftCorner.X += charcursorpos;
+
+ font->draw(L"_", CurrentTextRect,
+ OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT),
+ false, true, &localClipRect);
+ }
+ }
+
+ // draw children
+ IGUIElement::draw();
+}
+
+
+//! Sets the new caption of this element.
+void intlGUIEditBox::setText(const wchar_t* text)
+{
+ Text = text;
+ if (u32(CursorPos) > Text.size())
+ CursorPos = Text.size();
+ HScrollPos = 0;
+ breakText();
+}
+
+
+//! Enables or disables automatic scrolling with cursor position
+//! \param enable: If set to true, the text will move around with the cursor position
+void intlGUIEditBox::setAutoScroll(bool enable)
+{
+ AutoScroll = enable;
+}
+
+
+//! Checks to see if automatic scrolling is enabled
+//! \return true if automatic scrolling is enabled, false if not
+bool intlGUIEditBox::isAutoScrollEnabled() const
+{
+ _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
+ return AutoScroll;
+}
+
+
+//! Gets the area of the text in the edit box
+//! \return Returns the size in pixels of the text
+core::dimension2du intlGUIEditBox::getTextDimension()
+{
+ core::rect<s32> ret;
+
+ setTextRect(0);
+ ret = CurrentTextRect;
+
+ for (u32 i=1; i < BrokenText.size(); ++i)
+ {
+ setTextRect(i);
+ ret.addInternalPoint(CurrentTextRect.UpperLeftCorner);
+ ret.addInternalPoint(CurrentTextRect.LowerRightCorner);
+ }
+
+ return core::dimension2du(ret.getSize());
+}
+
+
+//! Sets the maximum amount of characters which may be entered in the box.
+//! \param max: Maximum amount of characters. If 0, the character amount is
+//! infinity.
+void intlGUIEditBox::setMax(u32 max)
+{
+ Max = max;
+
+ if (Text.size() > Max && Max != 0)
+ Text = Text.subString(0, Max);
+}
+
+
+//! Returns maximum amount of characters, previously set by setMax();
+u32 intlGUIEditBox::getMax() const
+{
+ return Max;
+}
+
+
+bool intlGUIEditBox::processMouse(const SEvent& event)
+{
+ switch(event.MouseInput.Event)
+ {
+ case irr::EMIE_LMOUSE_LEFT_UP:
+ if (Environment->hasFocus(this))
+ {
+ CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y);
+ if (MouseMarking)
+ {
+ setTextMarkers( MarkBegin, CursorPos );
+ }
+ MouseMarking = false;
+ calculateScrollPos();
+ return true;
+ }
+ break;
+ case irr::EMIE_MOUSE_MOVED:
+ {
+ if (MouseMarking)
+ {
+ CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y);
+ setTextMarkers( MarkBegin, CursorPos );
+ calculateScrollPos();
+ return true;
+ }
+ }
+ break;
+ case EMIE_LMOUSE_PRESSED_DOWN:
+ if (!Environment->hasFocus(this))
+ {
+ BlinkStartTime = porting::getTimeMs();
+ MouseMarking = true;
+ CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y);
+ setTextMarkers(CursorPos, CursorPos );
+ calculateScrollPos();
+ return true;
+ }
+ else
+ {
+ if (!AbsoluteClippingRect.isPointInside(
+ core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y)))
+ {
+ return false;
+ }
+ else
+ {
+ // move cursor
+ CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y);
+
+ s32 newMarkBegin = MarkBegin;
+ if (!MouseMarking)
+ newMarkBegin = CursorPos;
+
+ MouseMarking = true;
+ setTextMarkers( newMarkBegin, CursorPos);
+ calculateScrollPos();
+ return true;
+ }
+ }
+ default:
+ break;
+ }
+
+ return false;
+}
+
+
+s32 intlGUIEditBox::getCursorPos(s32 x, s32 y)
+{
+ IGUIFont* font = OverrideFont;
+ IGUISkin* skin = Environment->getSkin();
+ if (!OverrideFont)
+ font = skin->getFont();
+
+ const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1;
+
+ core::stringw *txtLine=0;
+ s32 startPos=0;
+ x+=3;
+
+ for (u32 i=0; i < lineCount; ++i)
+ {
+ setTextRect(i);
+ if (i == 0 && y < CurrentTextRect.UpperLeftCorner.Y)
+ y = CurrentTextRect.UpperLeftCorner.Y;
+ if (i == lineCount - 1 && y > CurrentTextRect.LowerRightCorner.Y )
+ y = CurrentTextRect.LowerRightCorner.Y;
+
+ // is it inside this region?
+ if (y >= CurrentTextRect.UpperLeftCorner.Y && y <= CurrentTextRect.LowerRightCorner.Y)
+ {
+ // we've found the clicked line
+ txtLine = (WordWrap || MultiLine) ? &BrokenText[i] : &Text;
+ startPos = (WordWrap || MultiLine) ? BrokenTextPositions[i] : 0;
+ break;
+ }
+ }
+
+ if (x < CurrentTextRect.UpperLeftCorner.X)
+ x = CurrentTextRect.UpperLeftCorner.X;
+
+ s32 idx = font->getCharacterFromPos(Text.c_str(), x - CurrentTextRect.UpperLeftCorner.X);
+
+ // click was on or left of the line
+ if (idx != -1)
+ return idx + startPos;
+
+ // click was off the right edge of the line, go to end.
+ return txtLine->size() + startPos;
+}
+
+
+//! Breaks the single text line.
+void intlGUIEditBox::breakText()
+{
+ IGUISkin* skin = Environment->getSkin();
+
+ if ((!WordWrap && !MultiLine) || !skin)
+ return;
+
+ BrokenText.clear(); // need to reallocate :/
+ BrokenTextPositions.set_used(0);
+
+ IGUIFont* font = OverrideFont;
+ if (!OverrideFont)
+ font = skin->getFont();
+
+ if (!font)
+ return;
+
+ LastBreakFont = font;
+
+ core::stringw line;
+ core::stringw word;
+ core::stringw whitespace;
+ s32 lastLineStart = 0;
+ s32 size = Text.size();
+ s32 length = 0;
+ s32 elWidth = RelativeRect.getWidth() - 6;
+ wchar_t c;
+
+ for (s32 i=0; i<size; ++i)
+ {
+ c = Text[i];
+ bool lineBreak = false;
+
+ if (c == L'\r') // Mac or Windows breaks
+ {
+ lineBreak = true;
+ c = ' ';
+ if (Text[i+1] == L'\n') // Windows breaks
+ {
+ Text.erase(i+1);
+ --size;
+ }
+ }
+ else if (c == L'\n') // Unix breaks
+ {
+ lineBreak = true;
+ c = ' ';
+ }
+
+ // don't break if we're not a multi-line edit box
+ if (!MultiLine)
+ lineBreak = false;
+
+ if (c == L' ' || c == 0 || i == (size-1))
+ {
+ if (word.size())
+ {
+ // here comes the next whitespace, look if
+ // we can break the last word to the next line.
+ s32 whitelgth = font->getDimension(whitespace.c_str()).Width;
+ s32 worldlgth = font->getDimension(word.c_str()).Width;
+
+ if (WordWrap && length + worldlgth + whitelgth > elWidth)
+ {
+ // break to next line
+ length = worldlgth;
+ BrokenText.push_back(line);
+ BrokenTextPositions.push_back(lastLineStart);
+ lastLineStart = i - (s32)word.size();
+ line = word;
+ }
+ else
+ {
+ // add word to line
+ line += whitespace;
+ line += word;
+ length += whitelgth + worldlgth;
+ }
+
+ word = L"";
+ whitespace = L"";
+ }
+
+ whitespace += c;
+
+ // compute line break
+ if (lineBreak)
+ {
+ line += whitespace;
+ line += word;
+ BrokenText.push_back(line);
+ BrokenTextPositions.push_back(lastLineStart);
+ lastLineStart = i+1;
+ line = L"";
+ word = L"";
+ whitespace = L"";
+ length = 0;
+ }
+ }
+ else
+ {
+ // yippee this is a word..
+ word += c;
+ }
+ }
+
+ line += whitespace;
+ line += word;
+ BrokenText.push_back(line);
+ BrokenTextPositions.push_back(lastLineStart);
+}
+
+
+void intlGUIEditBox::setTextRect(s32 line)
+{
+ core::dimension2du d;
+
+ IGUISkin* skin = Environment->getSkin();
+ if (!skin)
+ return;
+
+ IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont();
+
+ if (!font)
+ return;
+
+ // get text dimension
+ const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1;
+ if (WordWrap || MultiLine)
+ {
+ d = font->getDimension(BrokenText[line].c_str());
+ }
+ else
+ {
+ d = font->getDimension(Text.c_str());
+ d.Height = AbsoluteRect.getHeight();
+ }
+ d.Height += font->getKerningHeight();
+
+ // justification
+ switch (HAlign)
+ {
+ case EGUIA_CENTER:
+ // align to h centre
+ CurrentTextRect.UpperLeftCorner.X = (FrameRect.getWidth()/2) - (d.Width/2);
+ CurrentTextRect.LowerRightCorner.X = (FrameRect.getWidth()/2) + (d.Width/2);
+ break;
+ case EGUIA_LOWERRIGHT:
+ // align to right edge
+ CurrentTextRect.UpperLeftCorner.X = FrameRect.getWidth() - d.Width;
+ CurrentTextRect.LowerRightCorner.X = FrameRect.getWidth();
+ break;
+ default:
+ // align to left edge
+ CurrentTextRect.UpperLeftCorner.X = 0;
+ CurrentTextRect.LowerRightCorner.X = d.Width;
+
+ }
+
+ switch (VAlign)
+ {
+ case EGUIA_CENTER:
+ // align to v centre
+ CurrentTextRect.UpperLeftCorner.Y =
+ (FrameRect.getHeight()/2) - (lineCount*d.Height)/2 + d.Height*line;
+ break;
+ case EGUIA_LOWERRIGHT:
+ // align to bottom edge
+ CurrentTextRect.UpperLeftCorner.Y =
+ FrameRect.getHeight() - lineCount*d.Height + d.Height*line;
+ break;
+ default:
+ // align to top edge
+ CurrentTextRect.UpperLeftCorner.Y = d.Height*line;
+ break;
+ }
+
+ CurrentTextRect.UpperLeftCorner.X -= HScrollPos;
+ CurrentTextRect.LowerRightCorner.X -= HScrollPos;
+ CurrentTextRect.UpperLeftCorner.Y -= VScrollPos;
+ CurrentTextRect.LowerRightCorner.Y = CurrentTextRect.UpperLeftCorner.Y + d.Height;
+
+ CurrentTextRect += FrameRect.UpperLeftCorner;
+
+}
+
+
+s32 intlGUIEditBox::getLineFromPos(s32 pos)
+{
+ if (!WordWrap && !MultiLine)
+ return 0;
+
+ s32 i=0;
+ while (i < (s32)BrokenTextPositions.size())
+ {
+ if (BrokenTextPositions[i] > pos)
+ return i-1;
+ ++i;
+ }
+ return (s32)BrokenTextPositions.size() - 1;
+}
+
+
+void intlGUIEditBox::inputChar(wchar_t c)
+{
+ if (!IsEnabled)
+ return;
+
+ if (c != 0)
+ {
+ if (Text.size() < Max || Max == 0)
+ {
+ core::stringw s;
+
+ if (MarkBegin != MarkEnd)
+ {
+ // replace marked text
+ const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd;
+ const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin;
+
+ s = Text.subString(0, realmbgn);
+ s.append(c);
+ s.append( Text.subString(realmend, Text.size()-realmend) );
+ Text = s;
+ CursorPos = realmbgn+1;
+ }
+ else
+ {
+ // add new character
+ s = Text.subString(0, CursorPos);
+ s.append(c);
+ s.append( Text.subString(CursorPos, Text.size()-CursorPos) );
+ Text = s;
+ ++CursorPos;
+ }
+
+ BlinkStartTime = porting::getTimeMs();
+ setTextMarkers(0, 0);
+ }
+ }
+ breakText();
+ sendGuiEvent(EGET_EDITBOX_CHANGED);
+ calculateScrollPos();
+}
+
+
+void intlGUIEditBox::calculateScrollPos()
+{
+ if (!AutoScroll)
+ return;
+
+ // calculate horizontal scroll position
+ s32 cursLine = getLineFromPos(CursorPos);
+ setTextRect(cursLine);
+
+ // don't do horizontal scrolling when wordwrap is enabled.
+ if (!WordWrap)
+ {
+ // get cursor position
+ IGUISkin* skin = Environment->getSkin();
+ if (!skin)
+ return;
+ IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont();
+ if (!font)
+ return;
+
+ core::stringw *txtLine = MultiLine ? &BrokenText[cursLine] : &Text;
+ s32 cPos = MultiLine ? CursorPos - BrokenTextPositions[cursLine] : CursorPos;
+
+ s32 cStart = CurrentTextRect.UpperLeftCorner.X + HScrollPos +
+ font->getDimension(txtLine->subString(0, cPos).c_str()).Width;
+
+ s32 cEnd = cStart + font->getDimension(L"_ ").Width;
+
+ if (FrameRect.LowerRightCorner.X < cEnd)
+ HScrollPos = cEnd - FrameRect.LowerRightCorner.X;
+ else if (FrameRect.UpperLeftCorner.X > cStart)
+ HScrollPos = cStart - FrameRect.UpperLeftCorner.X;
+ else
+ HScrollPos = 0;
+
+ // todo: adjust scrollbar
+ }
+
+ // vertical scroll position
+ if (FrameRect.LowerRightCorner.Y < CurrentTextRect.LowerRightCorner.Y + VScrollPos)
+ VScrollPos = CurrentTextRect.LowerRightCorner.Y - FrameRect.LowerRightCorner.Y + VScrollPos;
+
+ else if (FrameRect.UpperLeftCorner.Y > CurrentTextRect.UpperLeftCorner.Y + VScrollPos)
+ VScrollPos = CurrentTextRect.UpperLeftCorner.Y - FrameRect.UpperLeftCorner.Y + VScrollPos;
+ else
+ VScrollPos = 0;
+
+ // todo: adjust scrollbar
+}
+
+//! set text markers
+void intlGUIEditBox::setTextMarkers(s32 begin, s32 end)
+{
+ if ( begin != MarkBegin || end != MarkEnd )
+ {
+ MarkBegin = begin;
+ MarkEnd = end;
+ sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED);
+ }
+}
+
+//! send some gui event to parent
+void intlGUIEditBox::sendGuiEvent(EGUI_EVENT_TYPE type)
+{
+ if ( Parent )
+ {
+ SEvent e;
+ e.EventType = EET_GUI_EVENT;
+ e.GUIEvent.Caller = this;
+ e.GUIEvent.Element = 0;
+ e.GUIEvent.EventType = type;
+
+ Parent->OnEvent(e);
+ }
+}
+
+//! Writes attributes of the element.
+void intlGUIEditBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
+{
+ // IGUIEditBox::serializeAttributes(out,options);
+
+ out->addBool ("OverrideColorEnabled",OverrideColorEnabled );
+ out->addColor ("OverrideColor", OverrideColor);
+ // out->addFont("OverrideFont",OverrideFont);
+ out->addInt ("MaxChars", Max);
+ out->addBool ("WordWrap", WordWrap);
+ out->addBool ("MultiLine", MultiLine);
+ out->addBool ("AutoScroll", AutoScroll);
+ out->addBool ("PasswordBox", PasswordBox);
+ core::stringw ch = L" ";
+ ch[0] = PasswordChar;
+ out->addString("PasswordChar", ch.c_str());
+ out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames);
+ out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames);
+
+ IGUIEditBox::serializeAttributes(out,options);
+}
+
+
+//! Reads attributes of the element
+void intlGUIEditBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
+{
+ IGUIEditBox::deserializeAttributes(in,options);
+
+ setOverrideColor(in->getAttributeAsColor("OverrideColor"));
+ enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled"));
+ setMax(in->getAttributeAsInt("MaxChars"));
+ setWordWrap(in->getAttributeAsBool("WordWrap"));
+ setMultiLine(in->getAttributeAsBool("MultiLine"));
+ setAutoScroll(in->getAttributeAsBool("AutoScroll"));
+ core::stringw ch = in->getAttributeAsStringW("PasswordChar");
+
+ if (!ch.size())
+ setPasswordBox(in->getAttributeAsBool("PasswordBox"));
+ else
+ setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]);
+
+ setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames),
+ (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames));
+
+ // setOverrideFont(in->getAttributeAsFont("OverrideFont"));
+}
+
+
+} // end namespace gui
+} // end namespace irr
+
+#endif // _IRR_COMPILE_WITH_GUI_
diff --git a/src/intlGUIEditBox.h b/src/intlGUIEditBox.h
new file mode 100644
index 000000000..f888fb620
--- /dev/null
+++ b/src/intlGUIEditBox.h
@@ -0,0 +1,178 @@
+// Copyright (C) 2002-2010 Nikolaus Gebhardt
+// This file is part of the "Irrlicht Engine".
+// For conditions of distribution and use, see copyright notice in irrlicht.h
+
+#ifndef __C_INTL_GUI_EDIT_BOX_H_INCLUDED__
+#define __C_INTL_GUI_EDIT_BOX_H_INCLUDED__
+
+#include "IrrCompileConfig.h"
+//#ifdef _IRR_COMPILE_WITH_GUI_
+
+#include "IGUIEditBox.h"
+#include "irrArray.h"
+#include "IOSOperator.h"
+
+namespace irr
+{
+namespace gui
+{
+ class intlGUIEditBox : public IGUIEditBox
+ {
+ public:
+
+ //! constructor
+ intlGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment,
+ IGUIElement* parent, s32 id, const core::rect<s32>& rectangle);
+
+ //! destructor
+ virtual ~intlGUIEditBox();
+
+ //! Sets another skin independent font.
+ virtual void setOverrideFont(IGUIFont* font=0);
+
+ //! Gets the override font (if any)
+ /** \return The override font (may be 0) */
+ virtual IGUIFont* getOverrideFont() const;
+
+ //! Get the font which is used right now for drawing
+ /** Currently this is the override font when one is set and the
+ font of the active skin otherwise */
+ virtual IGUIFont* getActiveFont() const;
+
+ //! Sets another color for the text.
+ virtual void setOverrideColor(video::SColor color);
+
+ //! Gets the override color
+ virtual video::SColor getOverrideColor() const;
+
+ //! Sets if the text should use the overide color or the
+ //! color in the gui skin.
+ virtual void enableOverrideColor(bool enable);
+
+ //! Checks if an override color is enabled
+ /** \return true if the override color is enabled, false otherwise */
+ virtual bool isOverrideColorEnabled(void) const;
+
+ //! Sets whether to draw the background
+ virtual void setDrawBackground(bool draw);
+
+ //! Turns the border on or off
+ virtual void setDrawBorder(bool border);
+
+ //! Enables or disables word wrap for using the edit box as multiline text editor.
+ virtual void setWordWrap(bool enable);
+
+ //! Checks if word wrap is enabled
+ //! \return true if word wrap is enabled, false otherwise
+ virtual bool isWordWrapEnabled() const;
+
+ //! Enables or disables newlines.
+ /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired,
+ instead a newline character will be inserted. */
+ virtual void setMultiLine(bool enable);
+
+ //! Checks if multi line editing is enabled
+ //! \return true if mult-line is enabled, false otherwise
+ virtual bool isMultiLineEnabled() const;
+
+ //! Enables or disables automatic scrolling with cursor position
+ //! \param enable: If set to true, the text will move around with the cursor position
+ virtual void setAutoScroll(bool enable);
+
+ //! Checks to see if automatic scrolling is enabled
+ //! \return true if automatic scrolling is enabled, false if not
+ virtual bool isAutoScrollEnabled() const;
+
+ //! Gets the size area of the text in the edit box
+ //! \return Returns the size in pixels of the text
+ virtual core::dimension2du getTextDimension();
+
+ //! Sets text justification
+ virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical);
+
+ //! called if an event happened.
+ virtual bool OnEvent(const SEvent& event);
+
+ //! draws the element and its children
+ virtual void draw();
+
+ //! Sets the new caption of this element.
+ virtual void setText(const wchar_t* text);
+
+ //! Sets the maximum amount of characters which may be entered in the box.
+ //! \param max: Maximum amount of characters. If 0, the character amount is
+ //! infinity.
+ virtual void setMax(u32 max);
+
+ //! Returns maximum amount of characters, previously set by setMax();
+ virtual u32 getMax() const;
+
+ //! Sets whether the edit box is a password box. Setting this to true will
+ /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x
+ \param passwordBox: true to enable password, false to disable
+ \param passwordChar: the character that is displayed instead of letters */
+ virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*');
+
+ //! Returns true if the edit box is currently a password box.
+ virtual bool isPasswordBox() const;
+
+ //! Updates the absolute position, splits text if required
+ virtual void updateAbsolutePosition();
+
+ //! Writes attributes of the element.
+ virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const;
+
+ //! Reads attributes of the element
+ virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options);
+
+ protected:
+ //! Breaks the single text line.
+ void breakText();
+ //! sets the area of the given line
+ void setTextRect(s32 line);
+ //! returns the line number that the cursor is on
+ s32 getLineFromPos(s32 pos);
+ //! adds a letter to the edit box
+ void inputChar(wchar_t c);
+ //! calculates the current scroll position
+ void calculateScrollPos();
+ //! send some gui event to parent
+ void sendGuiEvent(EGUI_EVENT_TYPE type);
+ //! set text markers
+ void setTextMarkers(s32 begin, s32 end);
+
+ bool processKey(const SEvent& event);
+ bool processMouse(const SEvent& event);
+ s32 getCursorPos(s32 x, s32 y);
+
+ bool MouseMarking;
+ bool Border;
+ bool OverrideColorEnabled;
+ s32 MarkBegin;
+ s32 MarkEnd;
+
+ video::SColor OverrideColor;
+ gui::IGUIFont *OverrideFont, *LastBreakFont;
+ IOSOperator* Operator;
+
+ u32 BlinkStartTime;
+ s32 CursorPos;
+ s32 HScrollPos, VScrollPos; // scroll position in characters
+ u32 Max;
+
+ bool WordWrap, MultiLine, AutoScroll, PasswordBox;
+ wchar_t PasswordChar;
+ EGUI_ALIGNMENT HAlign, VAlign;
+
+ core::array< core::stringw > BrokenText;
+ core::array< s32 > BrokenTextPositions;
+
+ core::rect<s32> CurrentTextRect, FrameRect; // temporary values
+ };
+
+
+} // end namespace gui
+} // end namespace irr
+
+//#endif // _IRR_COMPILE_WITH_GUI_
+#endif // __C_GUI_EDIT_BOX_H_INCLUDED__
diff --git a/src/irrlichttypes.h b/src/irrlichttypes.h
index 998992e05..2db744a48 100644
--- a/src/irrlichttypes.h
+++ b/src/irrlichttypes.h
@@ -28,12 +28,13 @@ using namespace irr;
#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
#ifdef _MSC_VER
// Windows
+ typedef long long s64;
typedef unsigned long long u64;
#else
// Posix
#include <stdint.h>
+ typedef int64_t s64;
typedef uint64_t u64;
- //typedef unsigned long long u64;
#endif
#endif
diff --git a/src/itemdef.cpp b/src/itemdef.cpp
index 260baadc0..a4f3895e0 100644
--- a/src/itemdef.cpp
+++ b/src/itemdef.cpp
@@ -100,6 +100,7 @@ void ItemDefinition::reset()
wield_scale = v3f(1.0, 1.0, 1.0);
stack_max = 99;
usable = false;
+ rightclickable = false;
liquids_pointable = false;
if(tool_capabilities)
{
diff --git a/src/itemdef.h b/src/itemdef.h
index 699d727bd..ae3600868 100644
--- a/src/itemdef.h
+++ b/src/itemdef.h
@@ -62,6 +62,8 @@ struct ItemDefinition
*/
s16 stack_max;
bool usable;
+ // If true, don't use node placement prediction
+ bool rightclickable;
bool liquids_pointable;
// May be NULL. If non-NULL, deleted by destructor
ToolCapabilities *tool_capabilities;
diff --git a/src/json/CMakeLists.txt b/src/json/CMakeLists.txt
new file mode 100644
index 000000000..0957799aa
--- /dev/null
+++ b/src/json/CMakeLists.txt
@@ -0,0 +1,14 @@
+if( UNIX )
+ set(json_SRCS jsoncpp.cpp)
+ set(json_platform_LIBS "")
+else( UNIX )
+ set(json_SRCS jsoncpp.cpp)
+ set(json_platform_LIBS "")
+endif( UNIX )
+
+add_library(json ${json_SRCS})
+
+target_link_libraries(
+ json
+ ${json_platform_LIBS}
+)
diff --git a/src/json/UPDATING b/src/json/UPDATING
new file mode 100644
index 000000000..d00076601
--- /dev/null
+++ b/src/json/UPDATING
@@ -0,0 +1,16 @@
+#!/bin/sh
+cd ..
+svn co https://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/trunk/jsoncpp jsoncpp
+svn up jsoncpp
+cd jsoncpp
+python amalgamate.py
+cp -R dist/json ..
+cp dist/jsoncpp.cpp ../json
+
+# maybe you need to patch:
+# src/json/jsoncpp.cpp:
+# -#include <json/json.h>
+# +#include "json/json.h"
+
+#svn export --force https://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/trunk/jsoncpp/src/lib_json json
+#svn export --force https://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/trunk/jsoncpp/include/json json
diff --git a/src/json/json.h b/src/json/json.h
new file mode 100644
index 000000000..396aafa82
--- /dev/null
+++ b/src/json/json.h
@@ -0,0 +1,1914 @@
+/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
+/// It is intented to be used with #include <json/json.h>
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use, copy,
+modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#ifndef JSON_AMALGATED_H_INCLUDED
+# define JSON_AMALGATED_H_INCLUDED
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+#define JSON_IS_AMALGAMATION
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_CONFIG_H_INCLUDED
+# define JSON_CONFIG_H_INCLUDED
+
+/// If defined, indicates that json library is embedded in CppTL library.
+//# define JSON_IN_CPPTL 1
+
+/// If defined, indicates that json may leverage CppTL library
+//# define JSON_USE_CPPTL 1
+/// If defined, indicates that cpptl vector based map should be used instead of std::map
+/// as Value container.
+//# define JSON_USE_CPPTL_SMALLMAP 1
+/// If defined, indicates that Json specific container should be used
+/// (hash table & simple deque container with customizable allocator).
+/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332
+//# define JSON_VALUE_USE_INTERNAL_MAP 1
+/// Force usage of standard new/malloc based allocator instead of memory pool based allocator.
+/// The memory pools allocator used optimization (initializing Value and ValueInternalLink
+/// as if it was a POD) that may cause some validation tool to report errors.
+/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
+//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
+
+// If non-zero, the library uses exceptions to report bad input instead of C
+// assertion macros. The default is to use exceptions.
+# ifndef JSON_USE_EXCEPTION
+# define JSON_USE_EXCEPTION 1
+# endif
+
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+/// Remarks: it is automatically defined in the generated amalgated header.
+// #define JSON_IS_AMALGAMATION
+
+
+# ifdef JSON_IN_CPPTL
+# include <cpptl/config.h>
+# ifndef JSON_USE_CPPTL
+# define JSON_USE_CPPTL 1
+# endif
+# endif
+
+# ifdef JSON_IN_CPPTL
+# define JSON_API CPPTL_API
+# elif defined(JSON_DLL_BUILD)
+# define JSON_API __declspec(dllexport)
+# elif defined(JSON_DLL)
+# define JSON_API __declspec(dllimport)
+# else
+# define JSON_API
+# endif
+
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
+
+#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
+// Microsoft Visual Studio 6 only support conversion from __int64 to double
+// (no conversion from unsigned __int64).
+#define JSON_USE_INT64_DOUBLE_CONVERSION 1
+#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
+
+#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
+/// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+#endif
+
+#if !defined(JSONCPP_DEPRECATED)
+# define JSONCPP_DEPRECATED(message)
+#endif // if !defined(JSONCPP_DEPRECATED)
+
+namespace Json {
+ typedef int Int;
+ typedef unsigned int UInt;
+# if defined(JSON_NO_INT64)
+ typedef int LargestInt;
+ typedef unsigned int LargestUInt;
+# undef JSON_HAS_INT64
+# else // if defined(JSON_NO_INT64)
+ // For Microsoft Visual use specific types as long long is not supported
+# if defined(_MSC_VER) // Microsoft Visual Studio
+ typedef __int64 Int64;
+ typedef unsigned __int64 UInt64;
+# else // if defined(_MSC_VER) // Other platforms, use long long
+ typedef long long int Int64;
+ typedef unsigned long long int UInt64;
+# endif // if defined(_MSC_VER)
+ typedef Int64 LargestInt;
+ typedef UInt64 LargestUInt;
+# define JSON_HAS_INT64
+# endif // if defined(JSON_NO_INT64)
+} // end namespace Json
+
+
+#endif // JSON_CONFIG_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_FORWARDS_H_INCLUDED
+# define JSON_FORWARDS_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+ // writer.h
+ class FastWriter;
+ class StyledWriter;
+
+ // reader.h
+ class Reader;
+
+ // features.h
+ class Features;
+
+ // value.h
+ typedef unsigned int ArrayIndex;
+ class StaticString;
+ class Path;
+ class PathArgument;
+ class Value;
+ class ValueIteratorBase;
+ class ValueIterator;
+ class ValueConstIterator;
+#ifdef JSON_VALUE_USE_INTERNAL_MAP
+ class ValueMapAllocator;
+ class ValueInternalLink;
+ class ValueInternalArray;
+ class ValueInternalMap;
+#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
+
+} // namespace Json
+
+
+#endif // JSON_FORWARDS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
+# define CPPTL_JSON_FEATURES_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+ /** \brief Configuration passed to reader and writer.
+ * This configuration object can be used to force the Reader or Writer
+ * to behave in a standard conforming way.
+ */
+ class JSON_API Features
+ {
+ public:
+ /** \brief A configuration that allows all features and assumes all strings are UTF-8.
+ * - C & C++ comments are allowed
+ * - Root object can be any JSON value
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features all();
+
+ /** \brief A configuration that is strictly compatible with the JSON specification.
+ * - Comments are forbidden.
+ * - Root object must be either an array or an object value.
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features strictMode();
+
+ /** \brief Initialize the configuration like JsonConfig::allFeatures;
+ */
+ Features();
+
+ /// \c true if comments are allowed. Default: \c true.
+ bool allowComments_;
+
+ /// \c true if root must be either an array or an object value. Default: \c false.
+ bool strictRoot_;
+ };
+
+} // namespace Json
+
+#endif // CPPTL_JSON_FEATURES_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_H_INCLUDED
+# define CPPTL_JSON_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+# include <string>
+# include <vector>
+
+# ifndef JSON_USE_CPPTL_SMALLMAP
+# include <map>
+# else
+# include <cpptl/smallmap.h>
+# endif
+# ifdef JSON_USE_CPPTL
+# include <cpptl/forwards.h>
+# endif
+
+/** \brief JSON (JavaScript Object Notation).
+ */
+namespace Json {
+
+ /** \brief Type of the value held by a Value object.
+ */
+ enum ValueType
+ {
+ nullValue = 0, ///< 'null' value
+ intValue, ///< signed integer value
+ uintValue, ///< unsigned integer value
+ realValue, ///< double value
+ stringValue, ///< UTF-8 string value
+ booleanValue, ///< bool value
+ arrayValue, ///< array value (ordered list)
+ objectValue ///< object value (collection of name/value pairs).
+ };
+
+ enum CommentPlacement
+ {
+ commentBefore = 0, ///< a comment placed on the line before a value
+ commentAfterOnSameLine, ///< a comment just after a value on the same line
+ commentAfter, ///< a comment on the line after a value (only make sense for root value)
+ numberOfCommentPlacement
+ };
+
+//# ifdef JSON_USE_CPPTL
+// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
+// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
+//# endif
+
+ /** \brief Lightweight wrapper to tag static string.
+ *
+ * Value constructor and objectValue member assignement takes advantage of the
+ * StaticString and avoid the cost of string duplication when storing the
+ * string or the member name.
+ *
+ * Example of usage:
+ * \code
+ * Json::Value aValue( StaticString("some text") );
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+ class JSON_API StaticString
+ {
+ public:
+ explicit StaticString( const char *czstring )
+ : str_( czstring )
+ {
+ }
+
+ operator const char *() const
+ {
+ return str_;
+ }
+
+ const char *c_str() const
+ {
+ return str_;
+ }
+
+ private:
+ const char *str_;
+ };
+
+ /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
+ *
+ * This class is a discriminated union wrapper that can represents a:
+ * - signed integer [range: Value::minInt - Value::maxInt]
+ * - unsigned integer (range: 0 - Value::maxUInt)
+ * - double
+ * - UTF-8 string
+ * - boolean
+ * - 'null'
+ * - an ordered list of Value
+ * - collection of name/value pairs (javascript object)
+ *
+ * The type of the held value is represented by a #ValueType and
+ * can be obtained using type().
+ *
+ * values of an #objectValue or #arrayValue can be accessed using operator[]() methods.
+ * Non const methods will automatically create the a #nullValue element
+ * if it does not exist.
+ * The sequence of an #arrayValue will be automatically resize and initialized
+ * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
+ *
+ * The get() methods can be used to obtanis default value in the case the required element
+ * does not exist.
+ *
+ * It is possible to iterate over the list of a #objectValue values using
+ * the getMemberNames() method.
+ */
+ class JSON_API Value
+ {
+ friend class ValueIteratorBase;
+# ifdef JSON_VALUE_USE_INTERNAL_MAP
+ friend class ValueInternalLink;
+ friend class ValueInternalMap;
+# endif
+ public:
+ typedef std::vector<std::string> Members;
+ typedef ValueIterator iterator;
+ typedef ValueConstIterator const_iterator;
+ typedef Json::UInt UInt;
+ typedef Json::Int Int;
+# if defined(JSON_HAS_INT64)
+ typedef Json::UInt64 UInt64;
+ typedef Json::Int64 Int64;
+#endif // defined(JSON_HAS_INT64)
+ typedef Json::LargestInt LargestInt;
+ typedef Json::LargestUInt LargestUInt;
+ typedef Json::ArrayIndex ArrayIndex;
+
+ static const Value null;
+ /// Minimum signed integer value that can be stored in a Json::Value.
+ static const LargestInt minLargestInt;
+ /// Maximum signed integer value that can be stored in a Json::Value.
+ static const LargestInt maxLargestInt;
+ /// Maximum unsigned integer value that can be stored in a Json::Value.
+ static const LargestUInt maxLargestUInt;
+
+ /// Minimum signed int value that can be stored in a Json::Value.
+ static const Int minInt;
+ /// Maximum signed int value that can be stored in a Json::Value.
+ static const Int maxInt;
+ /// Maximum unsigned int value that can be stored in a Json::Value.
+ static const UInt maxUInt;
+
+# if defined(JSON_HAS_INT64)
+ /// Minimum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 minInt64;
+ /// Maximum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 maxInt64;
+ /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
+ static const UInt64 maxUInt64;
+#endif // defined(JSON_HAS_INT64)
+
+ private:
+#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+# ifndef JSON_VALUE_USE_INTERNAL_MAP
+ class CZString
+ {
+ public:
+ enum DuplicationPolicy
+ {
+ noDuplication = 0,
+ duplicate,
+ duplicateOnCopy
+ };
+ CZString( ArrayIndex index );
+ CZString( const char *cstr, DuplicationPolicy allocate );
+ CZString( const CZString &other );
+ ~CZString();
+ CZString &operator =( const CZString &other );
+ bool operator<( const CZString &other ) const;
+ bool operator==( const CZString &other ) const;
+ ArrayIndex index() const;
+ const char *c_str() const;
+ bool isStaticString() const;
+ private:
+ void swap( CZString &other );
+ const char *cstr_;
+ ArrayIndex index_;
+ };
+
+ public:
+# ifndef JSON_USE_CPPTL_SMALLMAP
+ typedef std::map<CZString, Value> ObjectValues;
+# else
+ typedef CppTL::SmallMap<CZString, Value> ObjectValues;
+# endif // ifndef JSON_USE_CPPTL_SMALLMAP
+# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
+#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+
+ public:
+ /** \brief Create a default Value of the given type.
+
+ This is a very useful constructor.
+ To create an empty array, pass arrayValue.
+ To create an empty object, pass objectValue.
+ Another Value can then be set to this one by assignment.
+ This is useful since clear() and resize() will not alter types.
+
+ Examples:
+ \code
+ Json::Value null_value; // null
+ Json::Value arr_value(Json::arrayValue); // []
+ Json::Value obj_value(Json::objectValue); // {}
+ \endcode
+ */
+ Value( ValueType type = nullValue );
+ Value( Int value );
+ Value( UInt value );
+#if defined(JSON_HAS_INT64)
+ Value( Int64 value );
+ Value( UInt64 value );
+#endif // if defined(JSON_HAS_INT64)
+ Value( double value );
+ Value( const char *value );
+ Value( const char *beginValue, const char *endValue );
+ /** \brief Constructs a value from a static string.
+
+ * Like other value string constructor but do not duplicate the string for
+ * internal storage. The given string must remain alive after the call to this
+ * constructor.
+ * Example of usage:
+ * \code
+ * Json::Value aValue( StaticString("some text") );
+ * \endcode
+ */
+ Value( const StaticString &value );
+ Value( const std::string &value );
+# ifdef JSON_USE_CPPTL
+ Value( const CppTL::ConstString &value );
+# endif
+ Value( bool value );
+ Value( const Value &other );
+ ~Value();
+
+ Value &operator=( const Value &other );
+ /// Swap values.
+ /// \note Currently, comments are intentionally not swapped, for
+ /// both logic and efficiency.
+ void swap( Value &other );
+
+ ValueType type() const;
+
+ bool operator <( const Value &other ) const;
+ bool operator <=( const Value &other ) const;
+ bool operator >=( const Value &other ) const;
+ bool operator >( const Value &other ) const;
+
+ bool operator ==( const Value &other ) const;
+ bool operator !=( const Value &other ) const;
+
+ int compare( const Value &other ) const;
+
+ const char *asCString() const;
+ std::string asString() const;
+# ifdef JSON_USE_CPPTL
+ CppTL::ConstString asConstString() const;
+# endif
+ Int asInt() const;
+ UInt asUInt() const;
+#if defined(JSON_HAS_INT64)
+ Int64 asInt64() const;
+ UInt64 asUInt64() const;
+#endif // if defined(JSON_HAS_INT64)
+ LargestInt asLargestInt() const;
+ LargestUInt asLargestUInt() const;
+ float asFloat() const;
+ double asDouble() const;
+ bool asBool() const;
+
+ bool isNull() const;
+ bool isBool() const;
+ bool isInt() const;
+ bool isInt64() const;
+ bool isUInt() const;
+ bool isUInt64() const;
+ bool isIntegral() const;
+ bool isDouble() const;
+ bool isNumeric() const;
+ bool isString() const;
+ bool isArray() const;
+ bool isObject() const;
+
+ bool isConvertibleTo( ValueType other ) const;
+
+ /// Number of values in array or object
+ ArrayIndex size() const;
+
+ /// \brief Return true if empty array, empty object, or null;
+ /// otherwise, false.
+ bool empty() const;
+
+ /// Return isNull()
+ bool operator!() const;
+
+ /// Remove all object members and array elements.
+ /// \pre type() is arrayValue, objectValue, or nullValue
+ /// \post type() is unchanged
+ void clear();
+
+ /// Resize the array to size elements.
+ /// New elements are initialized to null.
+ /// May only be called on nullValue or arrayValue.
+ /// \pre type() is arrayValue or nullValue
+ /// \post type() is arrayValue
+ void resize( ArrayIndex size );
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value &operator[]( ArrayIndex index );
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value &operator[]( int index );
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value &operator[]( ArrayIndex index ) const;
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value &operator[]( int index ) const;
+
+ /// If the array contains at least index+1 elements, returns the element value,
+ /// otherwise returns defaultValue.
+ Value get( ArrayIndex index,
+ const Value &defaultValue ) const;
+ /// Return true if index < size().
+ bool isValidIndex( ArrayIndex index ) const;
+ /// \brief Append value to array at the end.
+ ///
+ /// Equivalent to jsonvalue[jsonvalue.size()] = value;
+ Value &append( const Value &value );
+
+ /// Access an object value by name, create a null member if it does not exist.
+ Value &operator[]( const char *key );
+ /// Access an object value by name, returns null if there is no member with that name.
+ const Value &operator[]( const char *key ) const;
+ /// Access an object value by name, create a null member if it does not exist.
+ Value &operator[]( const std::string &key );
+ /// Access an object value by name, returns null if there is no member with that name.
+ const Value &operator[]( const std::string &key ) const;
+ /** \brief Access an object value by name, create a null member if it does not exist.
+
+ * If the object as no entry for that name, then the member name used to store
+ * the new entry is not duplicated.
+ * Example of use:
+ * \code
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+ Value &operator[]( const StaticString &key );
+# ifdef JSON_USE_CPPTL
+ /// Access an object value by name, create a null member if it does not exist.
+ Value &operator[]( const CppTL::ConstString &key );
+ /// Access an object value by name, returns null if there is no member with that name.
+ const Value &operator[]( const CppTL::ConstString &key ) const;
+# endif
+ /// Return the member named key if it exist, defaultValue otherwise.
+ Value get( const char *key,
+ const Value &defaultValue ) const;
+ /// Return the member named key if it exist, defaultValue otherwise.
+ Value get( const std::string &key,
+ const Value &defaultValue ) const;
+# ifdef JSON_USE_CPPTL
+ /// Return the member named key if it exist, defaultValue otherwise.
+ Value get( const CppTL::ConstString &key,
+ const Value &defaultValue ) const;
+# endif
+ /// \brief Remove and return the named member.
+ ///
+ /// Do nothing if it did not exist.
+ /// \return the removed Value, or null.
+ /// \pre type() is objectValue or nullValue
+ /// \post type() is unchanged
+ Value removeMember( const char* key );
+ /// Same as removeMember(const char*)
+ Value removeMember( const std::string &key );
+
+ /// Return true if the object has a member named key.
+ bool isMember( const char *key ) const;
+ /// Return true if the object has a member named key.
+ bool isMember( const std::string &key ) const;
+# ifdef JSON_USE_CPPTL
+ /// Return true if the object has a member named key.
+ bool isMember( const CppTL::ConstString &key ) const;
+# endif
+
+ /// \brief Return a list of the member names.
+ ///
+ /// If null, return an empty list.
+ /// \pre type() is objectValue or nullValue
+ /// \post if type() was nullValue, it remains nullValue
+ Members getMemberNames() const;
+
+//# ifdef JSON_USE_CPPTL
+// EnumMemberNames enumMemberNames() const;
+// EnumValues enumValues() const;
+//# endif
+
+ /// Comments must be //... or /* ... */
+ void setComment( const char *comment,
+ CommentPlacement placement );
+ /// Comments must be //... or /* ... */
+ void setComment( const std::string &comment,
+ CommentPlacement placement );
+ bool hasComment( CommentPlacement placement ) const;
+ /// Include delimiters and embedded newlines.
+ std::string getComment( CommentPlacement placement ) const;
+
+ std::string toStyledString() const;
+
+ const_iterator begin() const;
+ const_iterator end() const;
+
+ iterator begin();
+ iterator end();
+
+ private:
+ Value &resolveReference( const char *key,
+ bool isStatic );
+
+# ifdef JSON_VALUE_USE_INTERNAL_MAP
+ inline bool isItemAvailable() const
+ {
+ return itemIsUsed_ == 0;
+ }
+
+ inline void setItemUsed( bool isUsed = true )
+ {
+ itemIsUsed_ = isUsed ? 1 : 0;
+ }
+
+ inline bool isMemberNameStatic() const
+ {
+ return memberNameIsStatic_ == 0;
+ }
+
+ inline void setMemberNameIsStatic( bool isStatic )
+ {
+ memberNameIsStatic_ = isStatic ? 1 : 0;
+ }
+# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
+
+ private:
+ struct CommentInfo
+ {
+ CommentInfo();
+ ~CommentInfo();
+
+ void setComment( const char *text );
+
+ char *comment_;
+ };
+
+ //struct MemberNamesTransform
+ //{
+ // typedef const char *result_type;
+ // const char *operator()( const CZString &name ) const
+ // {
+ // return name.c_str();
+ // }
+ //};
+
+ union ValueHolder
+ {
+ LargestInt int_;
+ LargestUInt uint_;
+ double real_;
+ bool bool_;
+ char *string_;
+# ifdef JSON_VALUE_USE_INTERNAL_MAP
+ ValueInternalArray *array_;
+ ValueInternalMap *map_;
+#else
+ ObjectValues *map_;
+# endif
+ } value_;
+ ValueType type_ : 8;
+ int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
+# ifdef JSON_VALUE_USE_INTERNAL_MAP
+ unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
+ int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
+# endif
+ CommentInfo *comments_;
+ };
+
+
+ /** \brief Experimental and untested: represents an element of the "path" to access a node.
+ */
+ class PathArgument
+ {
+ public:
+ friend class Path;
+
+ PathArgument();
+ PathArgument( ArrayIndex index );
+ PathArgument( const char *key );
+ PathArgument( const std::string &key );
+
+ private:
+ enum Kind
+ {
+ kindNone = 0,
+ kindIndex,
+ kindKey
+ };
+ std::string key_;
+ ArrayIndex index_;
+ Kind kind_;
+ };
+
+ /** \brief Experimental and untested: represents a "path" to access a node.
+ *
+ * Syntax:
+ * - "." => root node
+ * - ".[n]" => elements at index 'n' of root node (an array value)
+ * - ".name" => member named 'name' of root node (an object value)
+ * - ".name1.name2.name3"
+ * - ".[0][1][2].name1[3]"
+ * - ".%" => member name is provided as parameter
+ * - ".[%]" => index is provied as parameter
+ */
+ class Path
+ {
+ public:
+ Path( const std::string &path,
+ const PathArgument &a1 = PathArgument(),
+ const PathArgument &a2 = PathArgument(),
+ const PathArgument &a3 = PathArgument(),
+ const PathArgument &a4 = PathArgument(),
+ const PathArgument &a5 = PathArgument() );
+
+ const Value &resolve( const Value &root ) const;
+ Value resolve( const Value &root,
+ const Value &defaultValue ) const;
+ /// Creates the "path" to access the specified node and returns a reference on the node.
+ Value &make( Value &root ) const;
+
+ private:
+ typedef std::vector<const PathArgument *> InArgs;
+ typedef std::vector<PathArgument> Args;
+
+ void makePath( const std::string &path,
+ const InArgs &in );
+ void addPathInArg( const std::string &path,
+ const InArgs &in,
+ InArgs::const_iterator &itInArg,
+ PathArgument::Kind kind );
+ void invalidPath( const std::string &path,
+ int location );
+
+ Args args_;
+ };
+
+
+
+#ifdef JSON_VALUE_USE_INTERNAL_MAP
+ /** \brief Allocator to customize Value internal map.
+ * Below is an example of a simple implementation (default implementation actually
+ * use memory pool for speed).
+ * \code
+ class DefaultValueMapAllocator : public ValueMapAllocator
+ {
+ public: // overridden from ValueMapAllocator
+ virtual ValueInternalMap *newMap()
+ {
+ return new ValueInternalMap();
+ }
+
+ virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
+ {
+ return new ValueInternalMap( other );
+ }
+
+ virtual void destructMap( ValueInternalMap *map )
+ {
+ delete map;
+ }
+
+ virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
+ {
+ return new ValueInternalLink[size];
+ }
+
+ virtual void releaseMapBuckets( ValueInternalLink *links )
+ {
+ delete [] links;
+ }
+
+ virtual ValueInternalLink *allocateMapLink()
+ {
+ return new ValueInternalLink();
+ }
+
+ virtual void releaseMapLink( ValueInternalLink *link )
+ {
+ delete link;
+ }
+ };
+ * \endcode
+ */
+ class JSON_API ValueMapAllocator
+ {
+ public:
+ virtual ~ValueMapAllocator();
+ virtual ValueInternalMap *newMap() = 0;
+ virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0;
+ virtual void destructMap( ValueInternalMap *map ) = 0;
+ virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0;
+ virtual void releaseMapBuckets( ValueInternalLink *links ) = 0;
+ virtual ValueInternalLink *allocateMapLink() = 0;
+ virtual void releaseMapLink( ValueInternalLink *link ) = 0;
+ };
+
+ /** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
+ * \internal previous_ & next_ allows for bidirectional traversal.
+ */
+ class JSON_API ValueInternalLink
+ {
+ public:
+ enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
+ enum InternalFlags {
+ flagAvailable = 0,
+ flagUsed = 1
+ };
+
+ ValueInternalLink();
+
+ ~ValueInternalLink();
+
+ Value items_[itemPerLink];
+ char *keys_[itemPerLink];
+ ValueInternalLink *previous_;
+ ValueInternalLink *next_;
+ };
+
+
+ /** \brief A linked page based hash-table implementation used internally by Value.
+ * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked
+ * list in each bucket to handle collision. There is an addional twist in that
+ * each node of the collision linked list is a page containing a fixed amount of
+ * value. This provides a better compromise between memory usage and speed.
+ *
+ * Each bucket is made up of a chained list of ValueInternalLink. The last
+ * link of a given bucket can be found in the 'previous_' field of the following bucket.
+ * The last link of the last bucket is stored in tailLink_ as it has no following bucket.
+ * Only the last link of a bucket may contains 'available' item. The last link always
+ * contains at least one element unless is it the bucket one very first link.
+ */
+ class JSON_API ValueInternalMap
+ {
+ friend class ValueIteratorBase;
+ friend class Value;
+ public:
+ typedef unsigned int HashKey;
+ typedef unsigned int BucketIndex;
+
+# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+ struct IteratorState
+ {
+ IteratorState()
+ : map_(0)
+ , link_(0)
+ , itemIndex_(0)
+ , bucketIndex_(0)
+ {
+ }
+ ValueInternalMap *map_;
+ ValueInternalLink *link_;
+ BucketIndex itemIndex_;
+ BucketIndex bucketIndex_;
+ };
+# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+
+ ValueInternalMap();
+ ValueInternalMap( const ValueInternalMap &other );
+ ValueInternalMap &operator =( const ValueInternalMap &other );
+ ~ValueInternalMap();
+
+ void swap( ValueInternalMap &other );
+
+ BucketIndex size() const;
+
+ void clear();
+
+ bool reserveDelta( BucketIndex growth );
+
+ bool reserve( BucketIndex newItemCount );
+
+ const Value *find( const char *key ) const;
+
+ Value *find( const char *key );
+
+ Value &resolveReference( const char *key,
+ bool isStatic );
+
+ void remove( const char *key );
+
+ void doActualRemove( ValueInternalLink *link,
+ BucketIndex index,
+ BucketIndex bucketIndex );
+
+ ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex );
+
+ Value &setNewItem( const char *key,
+ bool isStatic,
+ ValueInternalLink *link,
+ BucketIndex index );
+
+ Value &unsafeAdd( const char *key,
+ bool isStatic,
+ HashKey hashedKey );
+
+ HashKey hash( const char *key ) const;
+
+ int compare( const ValueInternalMap &other ) const;
+
+ private:
+ void makeBeginIterator( IteratorState &it ) const;
+ void makeEndIterator( IteratorState &it ) const;
+ static bool equals( const IteratorState &x, const IteratorState &other );
+ static void increment( IteratorState &iterator );
+ static void incrementBucket( IteratorState &iterator );
+ static void decrement( IteratorState &iterator );
+ static const char *key( const IteratorState &iterator );
+ static const char *key( const IteratorState &iterator, bool &isStatic );
+ static Value &value( const IteratorState &iterator );
+ static int distance( const IteratorState &x, const IteratorState &y );
+
+ private:
+ ValueInternalLink *buckets_;
+ ValueInternalLink *tailLink_;
+ BucketIndex bucketsSize_;
+ BucketIndex itemCount_;
+ };
+
+ /** \brief A simplified deque implementation used internally by Value.
+ * \internal
+ * It is based on a list of fixed "page", each page contains a fixed number of items.
+ * Instead of using a linked-list, a array of pointer is used for fast item look-up.
+ * Look-up for an element is as follow:
+ * - compute page index: pageIndex = itemIndex / itemsPerPage
+ * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
+ *
+ * Insertion is amortized constant time (only the array containing the index of pointers
+ * need to be reallocated when items are appended).
+ */
+ class JSON_API ValueInternalArray
+ {
+ friend class Value;
+ friend class ValueIteratorBase;
+ public:
+ enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo.
+ typedef Value::ArrayIndex ArrayIndex;
+ typedef unsigned int PageIndex;
+
+# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+ struct IteratorState // Must be a POD
+ {
+ IteratorState()
+ : array_(0)
+ , currentPageIndex_(0)
+ , currentItemIndex_(0)
+ {
+ }
+ ValueInternalArray *array_;
+ Value **currentPageIndex_;
+ unsigned int currentItemIndex_;
+ };
+# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+
+ ValueInternalArray();
+ ValueInternalArray( const ValueInternalArray &other );
+ ValueInternalArray &operator =( const ValueInternalArray &other );
+ ~ValueInternalArray();
+ void swap( ValueInternalArray &other );
+
+ void clear();
+ void resize( ArrayIndex newSize );
+
+ Value &resolveReference( ArrayIndex index );
+
+ Value *find( ArrayIndex index ) const;
+
+ ArrayIndex size() const;
+
+ int compare( const ValueInternalArray &other ) const;
+
+ private:
+ static bool equals( const IteratorState &x, const IteratorState &other );
+ static void increment( IteratorState &iterator );
+ static void decrement( IteratorState &iterator );
+ static Value &dereference( const IteratorState &iterator );
+ static Value &unsafeDereference( const IteratorState &iterator );
+ static int distance( const IteratorState &x, const IteratorState &y );
+ static ArrayIndex indexOf( const IteratorState &iterator );
+ void makeBeginIterator( IteratorState &it ) const;
+ void makeEndIterator( IteratorState &it ) const;
+ void makeIterator( IteratorState &it, ArrayIndex index ) const;
+
+ void makeIndexValid( ArrayIndex index );
+
+ Value **pages_;
+ ArrayIndex size_;
+ PageIndex pageCount_;
+ };
+
+ /** \brief Experimental: do not use. Allocator to customize Value internal array.
+ * Below is an example of a simple implementation (actual implementation use
+ * memory pool).
+ \code
+class DefaultValueArrayAllocator : public ValueArrayAllocator
+{
+public: // overridden from ValueArrayAllocator
+ virtual ~DefaultValueArrayAllocator()
+ {
+ }
+
+ virtual ValueInternalArray *newArray()
+ {
+ return new ValueInternalArray();
+ }
+
+ virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
+ {
+ return new ValueInternalArray( other );
+ }
+
+ virtual void destruct( ValueInternalArray *array )
+ {
+ delete array;
+ }
+
+ virtual void reallocateArrayPageIndex( Value **&indexes,
+ ValueInternalArray::PageIndex &indexCount,
+ ValueInternalArray::PageIndex minNewIndexCount )
+ {
+ ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
+ if ( minNewIndexCount > newIndexCount )
+ newIndexCount = minNewIndexCount;
+ void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
+ if ( !newIndexes )
+ throw std::bad_alloc();
+ indexCount = newIndexCount;
+ indexes = static_cast<Value **>( newIndexes );
+ }
+ virtual void releaseArrayPageIndex( Value **indexes,
+ ValueInternalArray::PageIndex indexCount )
+ {
+ if ( indexes )
+ free( indexes );
+ }
+
+ virtual Value *allocateArrayPage()
+ {
+ return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
+ }
+
+ virtual void releaseArrayPage( Value *value )
+ {
+ if ( value )
+ free( value );
+ }
+};
+ \endcode
+ */
+ class JSON_API ValueArrayAllocator
+ {
+ public:
+ virtual ~ValueArrayAllocator();
+ virtual ValueInternalArray *newArray() = 0;
+ virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0;
+ virtual void destructArray( ValueInternalArray *array ) = 0;
+ /** \brief Reallocate array page index.
+ * Reallocates an array of pointer on each page.
+ * \param indexes [input] pointer on the current index. May be \c NULL.
+ * [output] pointer on the new index of at least
+ * \a minNewIndexCount pages.
+ * \param indexCount [input] current number of pages in the index.
+ * [output] number of page the reallocated index can handle.
+ * \b MUST be >= \a minNewIndexCount.
+ * \param minNewIndexCount Minimum number of page the new index must be able to
+ * handle.
+ */
+ virtual void reallocateArrayPageIndex( Value **&indexes,
+ ValueInternalArray::PageIndex &indexCount,
+ ValueInternalArray::PageIndex minNewIndexCount ) = 0;
+ virtual void releaseArrayPageIndex( Value **indexes,
+ ValueInternalArray::PageIndex indexCount ) = 0;
+ virtual Value *allocateArrayPage() = 0;
+ virtual void releaseArrayPage( Value *value ) = 0;
+ };
+#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
+
+
+ /** \brief base class for Value iterators.
+ *
+ */
+ class ValueIteratorBase
+ {
+ public:
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef ValueIteratorBase SelfType;
+
+ ValueIteratorBase();
+#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ explicit ValueIteratorBase( const Value::ObjectValues::iterator &current );
+#else
+ ValueIteratorBase( const ValueInternalArray::IteratorState &state );
+ ValueIteratorBase( const ValueInternalMap::IteratorState &state );
+#endif
+
+ bool operator ==( const SelfType &other ) const
+ {
+ return isEqual( other );
+ }
+
+ bool operator !=( const SelfType &other ) const
+ {
+ return !isEqual( other );
+ }
+
+ difference_type operator -( const SelfType &other ) const
+ {
+ return computeDistance( other );
+ }
+
+ /// Return either the index or the member name of the referenced value as a Value.
+ Value key() const;
+
+ /// Return the index of the referenced Value. -1 if it is not an arrayValue.
+ UInt index() const;
+
+ /// Return the member name of the referenced Value. "" if it is not an objectValue.
+ const char *memberName() const;
+
+ protected:
+ Value &deref() const;
+
+ void increment();
+
+ void decrement();
+
+ difference_type computeDistance( const SelfType &other ) const;
+
+ bool isEqual( const SelfType &other ) const;
+
+ void copy( const SelfType &other );
+
+ private:
+#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ Value::ObjectValues::iterator current_;
+ // Indicates that iterator is for a null value.
+ bool isNull_;
+#else
+ union
+ {
+ ValueInternalArray::IteratorState array_;
+ ValueInternalMap::IteratorState map_;
+ } iterator_;
+ bool isArray_;
+#endif
+ };
+
+ /** \brief const iterator for object and array value.
+ *
+ */
+ class ValueConstIterator : public ValueIteratorBase
+ {
+ friend class Value;
+ public:
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef const Value &reference;
+ typedef const Value *pointer;
+ typedef ValueConstIterator SelfType;
+
+ ValueConstIterator();
+ private:
+ /*! \internal Use by Value to create an iterator.
+ */
+#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ explicit ValueConstIterator( const Value::ObjectValues::iterator &current );
+#else
+ ValueConstIterator( const ValueInternalArray::IteratorState &state );
+ ValueConstIterator( const ValueInternalMap::IteratorState &state );
+#endif
+ public:
+ SelfType &operator =( const ValueIteratorBase &other );
+
+ SelfType operator++( int )
+ {
+ SelfType temp( *this );
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--( int )
+ {
+ SelfType temp( *this );
+ --*this;
+ return temp;
+ }
+
+ SelfType &operator--()
+ {
+ decrement();
+ return *this;
+ }
+
+ SelfType &operator++()
+ {
+ increment();
+ return *this;
+ }
+
+ reference operator *() const
+ {
+ return deref();
+ }
+ };
+
+
+ /** \brief Iterator for object and array value.
+ */
+ class ValueIterator : public ValueIteratorBase
+ {
+ friend class Value;
+ public:
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef Value &reference;
+ typedef Value *pointer;
+ typedef ValueIterator SelfType;
+
+ ValueIterator();
+ ValueIterator( const ValueConstIterator &other );
+ ValueIterator( const ValueIterator &other );
+ private:
+ /*! \internal Use by Value to create an iterator.
+ */
+#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ explicit ValueIterator( const Value::ObjectValues::iterator &current );
+#else
+ ValueIterator( const ValueInternalArray::IteratorState &state );
+ ValueIterator( const ValueInternalMap::IteratorState &state );
+#endif
+ public:
+
+ SelfType &operator =( const SelfType &other );
+
+ SelfType operator++( int )
+ {
+ SelfType temp( *this );
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--( int )
+ {
+ SelfType temp( *this );
+ --*this;
+ return temp;
+ }
+
+ SelfType &operator--()
+ {
+ decrement();
+ return *this;
+ }
+
+ SelfType &operator++()
+ {
+ increment();
+ return *this;
+ }
+
+ reference operator *() const
+ {
+ return deref();
+ }
+ };
+
+
+} // namespace Json
+
+
+#endif // CPPTL_JSON_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_READER_H_INCLUDED
+# define CPPTL_JSON_READER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include "features.h"
+# include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+# include <deque>
+# include <stack>
+# include <string>
+
+namespace Json {
+
+ /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value.
+ *
+ */
+ class JSON_API Reader
+ {
+ public:
+ typedef char Char;
+ typedef const Char *Location;
+
+ /** \brief Constructs a Reader allowing all features
+ * for parsing.
+ */
+ Reader();
+
+ /** \brief Constructs a Reader allowing the specified feature set
+ * for parsing.
+ */
+ Reader( const Features &features );
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
+ * \param document UTF-8 encoded string containing the document to read.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an error occurred.
+ */
+ bool parse( const std::string &document,
+ Value &root,
+ bool collectComments = true );
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read.
+ \ Must be >= beginDoc.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an error occurred.
+ */
+ bool parse( const char *beginDoc, const char *endDoc,
+ Value &root,
+ bool collectComments = true );
+
+ /// \brief Parse from input stream.
+ /// \see Json::operator>>(std::istream&, Json::Value&).
+ bool parse( std::istream &is,
+ Value &root,
+ bool collectComments = true );
+
+ /** \brief Returns a user friendly string that list errors in the parsed document.
+ * \return Formatted error message with the list of errors with their location in
+ * the parsed document. An empty string is returned if no error occurred
+ * during parsing.
+ * \deprecated Use getFormattedErrorMessages() instead (typo fix).
+ */
+ JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead")
+ std::string getFormatedErrorMessages() const;
+
+ /** \brief Returns a user friendly string that list errors in the parsed document.
+ * \return Formatted error message with the list of errors with their location in
+ * the parsed document. An empty string is returned if no error occurred
+ * during parsing.
+ */
+ std::string getFormattedErrorMessages() const;
+
+ private:
+ enum TokenType
+ {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token
+ {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo
+ {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool expectToken( TokenType type, Token &token, const char *message );
+ bool readToken( Token &token );
+ void skipSpaces();
+ bool match( Location pattern,
+ int patternLength );
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ void readNumber();
+ bool readValue();
+ bool readObject( Token &token );
+ bool readArray( Token &token );
+ bool decodeNumber( Token &token );
+ bool decodeString( Token &token );
+ bool decodeString( Token &token, std::string &decoded );
+ bool decodeDouble( Token &token );
+ bool decodeUnicodeCodePoint( Token &token,
+ Location &current,
+ Location end,
+ unsigned int &unicode );
+ bool decodeUnicodeEscapeSequence( Token &token,
+ Location &current,
+ Location end,
+ unsigned int &unicode );
+ bool addError( const std::string &message,
+ Token &token,
+ Location extra = 0 );
+ bool recoverFromError( TokenType skipUntilToken );
+ bool addErrorAndRecover( const std::string &message,
+ Token &token,
+ TokenType skipUntilToken );
+ void skipUntilSpace();
+ Value &currentValue();
+ Char getNextChar();
+ void getLocationLineAndColumn( Location location,
+ int &line,
+ int &column ) const;
+ std::string getLocationLineAndColumn( Location location ) const;
+ void addComment( Location begin,
+ Location end,
+ CommentPlacement placement );
+ void skipCommentTokens( Token &token );
+
+ typedef std::stack<Value *> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value *lastValue_;
+ std::string commentsBefore_;
+ Features features_;
+ bool collectComments_;
+ };
+
+ /** \brief Read from 'sin' into 'root'.
+
+ Always keep comments from the input JSON.
+
+ This can be used to read a file into a particular sub-object.
+ For example:
+ \code
+ Json::Value root;
+ cin >> root["dir"]["file"];
+ cout << root;
+ \endcode
+ Result:
+ \verbatim
+ {
+ "dir": {
+ "file": {
+ // The input stream JSON would be nested here.
+ }
+ }
+ }
+ \endverbatim
+ \throw std::exception on parse error.
+ \see Json::operator<<()
+ */
+ std::istream& operator>>( std::istream&, Value& );
+
+} // namespace Json
+
+#endif // CPPTL_JSON_READER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_WRITER_H_INCLUDED
+# define JSON_WRITER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+# include <vector>
+# include <string>
+
+namespace Json {
+
+ class Value;
+
+ /** \brief Abstract class for writers.
+ */
+ class JSON_API Writer
+ {
+ public:
+ virtual ~Writer();
+
+ virtual std::string write( const Value &root ) = 0;
+ };
+
+ /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format without formatting (not human friendly).
+ *
+ * The JSON document is written in a single line. It is not intended for 'human' consumption,
+ * but may be usefull to support feature such as RPC where bandwith is limited.
+ * \sa Reader, Value
+ */
+ class JSON_API FastWriter : public Writer
+ {
+ public:
+ FastWriter();
+ virtual ~FastWriter(){}
+
+ void enableYAMLCompatibility();
+
+ /** \brief Drop the "null" string from the writer's output for nullValues.
+ * Strictly speaking, this is not valid JSON. But when the output is being
+ * fed to a browser's Javascript, it makes for smaller output and the
+ * browser can handle the output just fine.
+ */
+ void dropNullPlaceholders();
+
+ public: // overridden from Writer
+ virtual std::string write( const Value &root );
+
+ private:
+ void writeValue( const Value &value );
+
+ std::string document_;
+ bool yamlCompatiblityEnabled_;
+ bool dropNullPlaceholders_;
+ };
+
+ /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value types,
+ * and all the values fit on one lines, then print the array on a single line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their #CommentPlacement.
+ *
+ * \sa Reader, Value, Value::setComment()
+ */
+ class JSON_API StyledWriter: public Writer
+ {
+ public:
+ StyledWriter();
+ virtual ~StyledWriter(){}
+
+ public: // overridden from Writer
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param root Value to serialize.
+ * \return String containing the JSON document that represents the root value.
+ */
+ virtual std::string write( const Value &root );
+
+ private:
+ void writeValue( const Value &value );
+ void writeArrayValue( const Value &value );
+ bool isMultineArray( const Value &value );
+ void pushValue( const std::string &value );
+ void writeIndent();
+ void writeWithIndent( const std::string &value );
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue( const Value &root );
+ void writeCommentAfterValueOnSameLine( const Value &root );
+ bool hasCommentForValue( const Value &value );
+ static std::string normalizeEOL( const std::string &text );
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::string document_;
+ std::string indentString_;
+ int rightMargin_;
+ int indentSize_;
+ bool addChildValues_;
+ };
+
+ /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way,
+ to a stream rather than to a string.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value types,
+ * and all the values fit on one lines, then print the array on a single line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their #CommentPlacement.
+ *
+ * \param indentation Each level will be indented by this amount extra.
+ * \sa Reader, Value, Value::setComment()
+ */
+ class JSON_API StyledStreamWriter
+ {
+ public:
+ StyledStreamWriter( std::string indentation="\t" );
+ ~StyledStreamWriter(){}
+
+ public:
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param out Stream to write to. (Can be ostringstream, e.g.)
+ * \param root Value to serialize.
+ * \note There is no point in deriving from Writer, since write() should not return a value.
+ */
+ void write( std::ostream &out, const Value &root );
+
+ private:
+ void writeValue( const Value &value );
+ void writeArrayValue( const Value &value );
+ bool isMultineArray( const Value &value );
+ void pushValue( const std::string &value );
+ void writeIndent();
+ void writeWithIndent( const std::string &value );
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue( const Value &root );
+ void writeCommentAfterValueOnSameLine( const Value &root );
+ bool hasCommentForValue( const Value &value );
+ static std::string normalizeEOL( const std::string &text );
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::ostream* document_;
+ std::string indentString_;
+ int rightMargin_;
+ std::string indentation_;
+ bool addChildValues_;
+ };
+
+# if defined(JSON_HAS_INT64)
+ std::string JSON_API valueToString( Int value );
+ std::string JSON_API valueToString( UInt value );
+# endif // if defined(JSON_HAS_INT64)
+ std::string JSON_API valueToString( LargestInt value );
+ std::string JSON_API valueToString( LargestUInt value );
+ std::string JSON_API valueToString( double value );
+ std::string JSON_API valueToString( bool value );
+ std::string JSON_API valueToQuotedString( const char *value );
+
+ /// \brief Output using the StyledStreamWriter.
+ /// \see Json::operator>>()
+ std::ostream& operator<<( std::ostream&, const Value &root );
+
+} // namespace Json
+
+
+
+#endif // JSON_WRITER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
+# define CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+#include <stdlib.h>
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include <json/config.h>
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+#if JSON_USE_EXCEPTION
+#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw
+#define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message );
+#else // JSON_USE_EXCEPTION
+#define JSON_ASSERT( condition ) assert( condition );
+
+// The call to assert() will show the failure message in debug builds. In
+// release bugs we write to invalid memory in order to crash hard, so that a
+// debugger or crash reporter gets the chance to take over. We still call exit()
+// afterward in order to tell the compiler that this macro doesn't return.
+#define JSON_FAIL_MESSAGE( message ) { assert(false && message); strcpy(reinterpret_cast<char*>(666), message); exit(123); }
+
+#endif
+
+#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) { JSON_FAIL_MESSAGE( message ) }
+
+#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#endif //ifndef JSON_AMALGATED_H_INCLUDED
diff --git a/src/json/jsoncpp.cpp b/src/json/jsoncpp.cpp
new file mode 100644
index 000000000..7a04736de
--- /dev/null
+++ b/src/json/jsoncpp.cpp
@@ -0,0 +1,4367 @@
+/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
+/// It is intented to be used with #include <json/json.h>
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use, copy,
+modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+#include "json.h"
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+# define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+/* This header provides common string manipulation support, such as UTF-8,
+ * portable conversion from/to string...
+ *
+ * It is an internal header that must not be exposed.
+ */
+
+namespace Json {
+
+/// Converts a unicode code-point to UTF-8.
+static inline std::string
+codePointToUTF8(unsigned int cp)
+{
+ std::string result;
+
+ // based on description from http://en.wikipedia.org/wiki/UTF-8
+
+ if (cp <= 0x7f)
+ {
+ result.resize(1);
+ result[0] = static_cast<char>(cp);
+ }
+ else if (cp <= 0x7FF)
+ {
+ result.resize(2);
+ result[1] = static_cast<char>(0x80 | (0x3f & cp));
+ result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
+ }
+ else if (cp <= 0xFFFF)
+ {
+ result.resize(3);
+ result[2] = static_cast<char>(0x80 | (0x3f & cp));
+ result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
+ result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
+ }
+ else if (cp <= 0x10FFFF)
+ {
+ result.resize(4);
+ result[3] = static_cast<char>(0x80 | (0x3f & cp));
+ result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
+ result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
+ }
+
+ return result;
+}
+
+
+/// Returns true if ch is a control character (in range [0,32[).
+static inline bool
+isControlCharacter(char ch)
+{
+ return ch > 0 && ch <= 0x1F;
+}
+
+
+enum {
+ /// Constant that specify the size of the buffer that must be passed to uintToString.
+ uintToStringBufferSize = 3*sizeof(LargestUInt)+1
+};
+
+// Defines a char buffer for use with uintToString().
+typedef char UIntToStringBuffer[uintToStringBufferSize];
+
+
+/** Converts an unsigned integer to string.
+ * @param value Unsigned interger to convert to string
+ * @param current Input/Output string buffer.
+ * Must have at least uintToStringBufferSize chars free.
+ */
+static inline void
+uintToString( LargestUInt value,
+ char *&current )
+{
+ *--current = 0;
+ do
+ {
+ *--current = char(value % 10) + '0';
+ value /= 10;
+ }
+ while ( value != 0 );
+}
+
+} // namespace Json {
+
+#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_reader.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+# include <json/assertions.h>
+# include <json/reader.h>
+# include <json/value.h>
+# include "json_tool.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <utility>
+#include <cstdio>
+#include <cassert>
+#include <cstring>
+#include <stdexcept>
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
+#endif
+
+namespace Json {
+
+// Implementation of class Features
+// ////////////////////////////////
+
+Features::Features()
+ : allowComments_( true )
+ , strictRoot_( false )
+{
+}
+
+
+Features
+Features::all()
+{
+ return Features();
+}
+
+
+Features
+Features::strictMode()
+{
+ Features features;
+ features.allowComments_ = false;
+ features.strictRoot_ = true;
+ return features;
+}
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+
+static inline bool
+in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
+{
+ return c == c1 || c == c2 || c == c3 || c == c4;
+}
+
+static inline bool
+in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
+{
+ return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
+}
+
+
+static bool
+containsNewLine( Reader::Location begin,
+ Reader::Location end )
+{
+ for ( ;begin < end; ++begin )
+ if ( *begin == '\n' || *begin == '\r' )
+ return true;
+ return false;
+}
+
+
+// Class Reader
+// //////////////////////////////////////////////////////////////////
+
+Reader::Reader()
+ : errors_(),
+ document_(),
+ begin_(),
+ end_(),
+ current_(),
+ lastValueEnd_(),
+ lastValue_(),
+ commentsBefore_(),
+ features_( Features::all() ),
+ collectComments_()
+{
+}
+
+
+Reader::Reader( const Features &features )
+ : errors_(),
+ document_(),
+ begin_(),
+ end_(),
+ current_(),
+ lastValueEnd_(),
+ lastValue_(),
+ commentsBefore_(),
+ features_( features ),
+ collectComments_()
+{
+}
+
+
+bool
+Reader::parse( const std::string &document,
+ Value &root,
+ bool collectComments )
+{
+ document_ = document;
+ const char *begin = document_.c_str();
+ const char *end = begin + document_.length();
+ return parse( begin, end, root, collectComments );
+}
+
+
+bool
+Reader::parse( std::istream& sin,
+ Value &root,
+ bool collectComments )
+{
+ //std::istream_iterator<char> begin(sin);
+ //std::istream_iterator<char> end;
+ // Those would allow streamed input from a file, if parse() were a
+ // template function.
+
+ // Since std::string is reference-counted, this at least does not
+ // create an extra copy.
+ std::string doc;
+ std::getline(sin, doc, (char)EOF);
+ return parse( doc, root, collectComments );
+}
+
+bool
+Reader::parse( const char *beginDoc, const char *endDoc,
+ Value &root,
+ bool collectComments )
+{
+ if ( !features_.allowComments_ )
+ {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while ( !nodes_.empty() )
+ nodes_.pop();
+ nodes_.push( &root );
+
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens( token );
+ if ( collectComments_ && !commentsBefore_.empty() )
+ root.setComment( commentsBefore_, commentAfter );
+ if ( features_.strictRoot_ )
+ {
+ if ( !root.isArray() && !root.isObject() )
+ {
+ // Set error location to start of doc, ideally should be first token found in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError( "A valid JSON document must be either an array or an object value.",
+ token );
+ return false;
+ }
+ }
+ return successful;
+}
+
+
+bool
+Reader::readValue()
+{
+ Token token;
+ skipCommentTokens( token );
+ bool successful = true;
+
+ if ( collectComments_ && !commentsBefore_.empty() )
+ {
+ currentValue().setComment( commentsBefore_, commentBefore );
+ commentsBefore_ = "";
+ }
+
+
+ switch ( token.type_ )
+ {
+ case tokenObjectBegin:
+ successful = readObject( token );
+ break;
+ case tokenArrayBegin:
+ successful = readArray( token );
+ break;
+ case tokenNumber:
+ successful = decodeNumber( token );
+ break;
+ case tokenString:
+ successful = decodeString( token );
+ break;
+ case tokenTrue:
+ currentValue() = true;
+ break;
+ case tokenFalse:
+ currentValue() = false;
+ break;
+ case tokenNull:
+ currentValue() = Value();
+ break;
+ default:
+ return addError( "Syntax error: value, object or array expected.", token );
+ }
+
+ if ( collectComments_ )
+ {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ return successful;
+}
+
+
+void
+Reader::skipCommentTokens( Token &token )
+{
+ if ( features_.allowComments_ )
+ {
+ do
+ {
+ readToken( token );
+ }
+ while ( token.type_ == tokenComment );
+ }
+ else
+ {
+ readToken( token );
+ }
+}
+
+
+bool
+Reader::expectToken( TokenType type, Token &token, const char *message )
+{
+ readToken( token );
+ if ( token.type_ != type )
+ return addError( message, token );
+ return true;
+}
+
+
+bool
+Reader::readToken( Token &token )
+{
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch ( c )
+ {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '-':
+ token.type_ = tokenNumber;
+ readNumber();
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match( "rue", 3 );
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match( "alse", 4 );
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match( "ull", 3 );
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;