소스 검색

Merge branch 'master' into lua-env

Conflicts:
	samples/terrain/terrain.cpp
Daniele Bartolini 12 년 전
부모
커밋
59d61a2965
100개의 변경된 파일2047개의 추가작업 그리고 3536개의 파일을 삭제
  1. 1 0
      CMakeLists.txt
  2. 6 3
      android/jni/Android.mk
  3. 0 3
      samples/CMakeLists.txt
  4. 0 332
      samples/collision/collision.cpp
  5. 0 246
      samples/intersection/intersection.cpp
  6. BIN
      samples/res/closebutton_x.bmp
  7. BIN
      samples/res/crw_dir_icon.bmp
  8. BIN
      samples/res/crw_file_icon.bmp
  9. 0 36
      samples/res/editor_editorwindow.xml
  10. 0 13
      samples/res/editor_mainwindow.xml
  11. BIN
      samples/res/terrain.bmp
  12. 0 12
      samples/res/window.xml
  13. 0 45
      samples/res/window_fractal.xml
  14. 0 30
      samples/res/window_listview.xml
  15. 0 33
      samples/res/window_loader.xml
  16. 13 6
      samples/terrain/Terrain.cpp
  17. 6 0
      samples/terrain/Terrain.h
  18. 5 2
      samples/terrain/terrain.cpp
  19. BIN
      samples/textrenderer/res/arial.tga
  20. 0 95
      samples/textrenderer/res/arial.tga.txt
  21. BIN
      samples/textrenderer/res/arialbd.ttf
  22. BIN
      samples/textrenderer/res/times.ttf
  23. 0 113
      samples/textrenderer/textrenderer.cpp
  24. BIN
      samples/texturing/ress/crate.tga
  25. BIN
      samples/texturing/ress/grass.tga
  26. BIN
      samples/texturing/ress/red_down.tga
  27. BIN
      samples/texturing/ress/red_east.tga
  28. BIN
      samples/texturing/ress/red_north.tga
  29. BIN
      samples/texturing/ress/red_south.tga
  30. BIN
      samples/texturing/ress/red_up.tga
  31. BIN
      samples/texturing/ress/red_west.tga
  32. 0 222
      samples/texturing/texturing.cpp
  33. 8 1
      src/ArchiveResourceArchive.cpp
  34. 5 1
      src/ArchiveResourceArchive.h
  35. 6 14
      src/CMakeLists.txt
  36. 3 2
      src/Crown.h
  37. 2 7
      src/Device.cpp
  38. 7 4
      src/FileResourceArchive.cpp
  39. 17 1
      src/FileResourceArchive.h
  40. 1 1
      src/Filesystem.h
  41. 14 10
      src/Resource.h
  42. 10 1
      src/ResourceArchive.h
  43. 25 5
      src/ResourceManager.cpp
  44. 9 6
      src/ResourceManager.h
  45. 3 1
      src/ScriptResource.cpp
  46. 3 1
      src/TextResource.cpp
  47. 3 1
      src/TextureResource.cpp
  48. 1 1
      src/TextureResource.h
  49. 161 0
      src/core/containers/IdTable.h
  50. 0 1
      src/core/streams/BinaryReader.h
  51. 0 1
      src/core/streams/BinaryWriter.h
  52. 29 58
      src/core/streams/FileStream.cpp
  53. 4 4
      src/core/streams/FileStream.h
  54. 0 3
      src/core/streams/MemoryStream.h
  55. 0 1
      src/core/streams/NullStream.h
  56. 0 1
      src/core/streams/TextReader.h
  57. 0 1
      src/core/streams/TextWriter.h
  58. 39 57
      src/network/BitMessage.cpp
  59. 31 10
      src/network/BitMessage.h
  60. 158 0
      src/os/NetAddress.h
  61. 0 185
      src/os/OS.h
  62. 2 5
      src/os/android/AndroidDevice.cpp
  63. 0 67
      src/os/android/AndroidOS.cpp
  64. 0 87
      src/os/android/AndroidTimer.cpp
  65. 0 73
      src/os/android/AndroidTimer.h
  66. 61 28
      src/os/android/File.cpp
  67. 41 29
      src/os/android/File.h
  68. 12 6
      src/os/linux/CMakeLists.txt
  69. 0 308
      src/os/linux/EGLRenderWindow.cpp
  70. 0 101
      src/os/linux/EGLRenderWindow.h
  71. 0 83
      src/os/linux/LinuxOS.cpp
  72. 0 182
      src/os/linux/LinuxTCPSocket.cpp
  73. 0 127
      src/os/linux/LinuxUDPSocket.cpp
  74. 12 31
      src/os/posix/Cond.cpp
  75. 15 18
      src/os/posix/Cond.h
  76. 63 44
      src/os/posix/File.cpp
  77. 90 0
      src/os/posix/File.h
  78. 12 27
      src/os/posix/Mutex.cpp
  79. 15 21
      src/os/posix/Mutex.h
  80. 216 0
      src/os/posix/TCPSocket.cpp
  81. 30 30
      src/os/posix/TCPSocket.h
  82. 27 25
      src/os/posix/Thread.cpp
  83. 16 17
      src/os/posix/Thread.h
  84. 161 0
      src/os/posix/UDPSocket.cpp
  85. 67 0
      src/os/posix/UDPSocket.h
  86. 0 92
      src/os/win/WinInputManager.h
  87. 3 23
      src/renderers/IndexBuffer.h
  88. 0 118
      src/renderers/Pixel.h
  89. 16 19
      src/renderers/PixelFormat.cpp
  90. 118 0
      src/renderers/PixelFormat.h
  91. 36 0
      src/renderers/RenderBuffer.h
  92. 104 71
      src/renderers/Renderer.h
  93. 3 6
      src/renderers/Texture.h
  94. 4 32
      src/renderers/VertexBuffer.h
  95. 26 31
      src/renderers/VertexFormat.cpp
  96. 63 0
      src/renderers/VertexFormat.h
  97. 0 6
      src/renderers/gl/CMakeLists.txt
  98. 0 67
      src/renderers/gl/GLIndexBuffer.cpp
  99. 0 72
      src/renderers/gl/GLOcclusionQuery.cpp
  100. 264 120
      src/renderers/gl/GLRenderer.cpp

+ 1 - 0
CMakeLists.txt

@@ -26,6 +26,7 @@ set (INCLUDES
 	${CMAKE_SOURCE_DIR}/src/core/threads
 	${CMAKE_SOURCE_DIR}/src/core/settings
 	${CMAKE_SOURCE_DIR}/src/os
+	${CMAKE_SOURCE_DIR}/src/os/posix
 	${CMAKE_SOURCE_DIR}/src/os/linux
 	${CMAKE_SOURCE_DIR}/src/input
 	${CMAKE_SOURCE_DIR}/src/renderers

+ 6 - 3
android/jni/Android.mk

@@ -36,8 +36,6 @@ LOCAL_SRC_FILES :=\
 	core/streams/FileStream.cpp\
 	core/streams/MemoryStream.cpp\
 	core/streams/Stream.cpp\
-	core/threads/Thread.cpp\
-	core/threads/Mutex.cpp\
 \
 	input/EventDispatcher.cpp\
 	input/InputManager.cpp\
@@ -47,6 +45,11 @@ LOCAL_SRC_FILES :=\
 	os/android/AndroidInput.cpp\
 	os/android/AndroidDevice.cpp\
 	os/android/File.cpp\
+	os/posix/Thread.cpp\
+	os/posix/Mutex.cpp\
+	os/posix/Cond.cpp\
+	os/posix/TCPSocket.cpp\
+	os/posix/UDPSocket.cpp\
 \
 	Filesystem.cpp\
 \
@@ -102,4 +105,4 @@ LOCAL_C_INCLUDES	:=\
 LOCAL_CPPFLAGS	:= -g -fexceptions
 LOCAL_LDLIBS	:= -llog -landroid -lGLESv1_CM
 include $(BUILD_SHARED_LIBRARY)
-#(call import-module, android/native_app_glue)
+#(call import-module, android/native_app_glue)

+ 0 - 3
samples/CMakeLists.txt

@@ -5,8 +5,5 @@ project(crown-samples)
 link_directories(${CROWN_BINARY_DIR})
 
 add_subdirectory(terrain)
-#add_subdirectory(texturing)
-#add_subdirectory(textrenderer)
-#add_subdirectory(collision)
 add_subdirectory(json)
 add_subdirectory(lua)

+ 0 - 332
samples/collision/collision.cpp

@@ -1,332 +0,0 @@
-#include "Crown.h"
-#include <cstdlib>
-#include <GL/glu.h>
-
-using namespace Crown;
-
-class WndCtrl: public KeyboardListener
-{
-public:
-
-	WndCtrl()
-	{
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual void KeyReleased(const KeyboardEvent& event)
-	{
-		if (event.key == KC_ESCAPE)
-		{
-			GetDevice()->StopRunning();
-		}
-	}
-};
-
-class MainScene: public MouseListener//, public KeyboardListener
-{
-
-public:
-
-	MainScene()
-	{
-		GetDevice()->GetInputManager()->RegisterMouseListener(this);
-		//GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-
-		sphereCount = 0;
-	}
-
-	virtual ~MainScene()
-	{
-		if (quadric)
-			gluDeleteQuadric(quadric);
-	}
-
-	virtual void ButtonPressed(const MouseEvent& event)
-	{
-		if (event.button == MB_LEFT)
-		{
-			if (sphereCount < 12)
-			{
-				sphere[sphereCount].c = cam->GetPosition();
-				velocity[sphereCount] = cam->GetLookAt() * 0.7f;
-				sphereCount++;
-			}
-		}
-
-		if (event.button == MB_RIGHT)
-		{
-			sphereCount = 0;
-		}
-	}
-
-	virtual void OnLoad()
-	{
-		Crown::Renderer* renderer = Crown::GetDevice()->GetRenderer();
-		renderer->SetClearColor(Crown::Color4(0.0f, 0.0f, 0.0f, 1.0f));
-
-		// Add a movable camera
-		cam = new MovableCamera(Vec3::ZERO, Angles::ZERO, true, 90.0f, 1.6f, 0.01, 2.5, true);
-
-		if (cam)
-		{
-			cam->SetActive(true);
-			cam->SetSpeed(0.1);
-			cam->SetFarClipDistance(1000.0f);
-			cam->SetPosition(Vec3(0, 10, 15));
-
-		}
-
-		grass = GetTextureManager()->Load("res/test_texture1.tga");
-
-		dplane = GetMeshManager()->LoadPlane("3dplane", 128.0f, 128.0f);
-
-		ray.origin = Vec3(0, 0, 10);
-		ray.direction = Vec3(0, 0, -1);
-
-		for (int i = 0; i < 12; i++)
-		{
-			sphere[i].r = 1.5f;
-		}
-
-		plane[0].n			= Vec3(0, 1, 0);
-		plane[0].d			= 0;
-
-		plane[1].n 			= Vec3(0, 0, 1);
-		plane[1].d			= 0;
-
-		plane[2].n			= Vec3(1, 0, 0);
-		plane[2].d			= 0;
-
-		gravity				= Vec3(0, -0.003, 0);
-
-		quadric = gluNewQuadric();
-	}
-
-	virtual void RenderScene()
-	{
-		Renderer* renderer = GetDevice()->GetRenderer();
-
-		renderer->_SetLighting(false);
-		renderer->_SetBlending(false);
-		renderer->_SetAlphaTest(false);
-		renderer->_SetBackfaceCulling(false);
-		renderer->_SetTexturing(0, false);
-		renderer->_SetTexturing(1, false);
-		renderer->_SetTexturing(2, false);
-
-		cam->Render();
-
-		for (int i = 0; i < sphereCount; i++)
-		{
-			velocity[i] += gravity;
-			for (int j = 0; j < 3; j++)
-			{
-				real itt;
-				Vec3 intersectionPoint;
-				if (Intersection::TestDynamicSpherePlane(sphere[i], velocity[i], plane[j], itt, intersectionPoint))
-				{
-					real velLength = velocity[i].GetLength();
-
-					velocity[i].Normalize();
-					Vec3 nuovo = ((2.0f * (-velocity[i].Dot(plane[j].n))) * plane[j].n) + velocity[i];
-					velocity[i] = nuovo * velLength * 0.7f;
-				}
-			}
-		}
-
-		for (int i = 0; i < sphereCount; i++)
-		{
-			if (velocity[i] == Vec3::ZERO)
-			{
-				velocity[i].Zero();
-			}
-			sphere[i].c += velocity[i];
-		}
-
-		if (cam->IsActive())
-		{
-			ray.origin = cam->GetPosition();
-			ray.direction = cam->GetLookAt();
-		}
-
-		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-
-		for (int j = 0; j < sphereCount; j++)
-		{
-			// Draw spheres
-			glColor3f(1, 0, 0);
-			tr.LoadIdentity();
-			tr.SetTranslation(sphere[j].c);
-			renderer->SetMatrix(MT_MODEL, tr);
-			gluSphere(quadric, sphere[j].r, 64, 64);
-		}
-
-//		tr.SetTranslation(sphere[1].c);
-//		renderer->SetMatrix(MT_MODEL, tr);
-//		gluSphere(quadric, sphere[1].r, 64, 64);
-
-//		tr.SetTranslation(sphere[2].c);
-//		renderer->SetMatrix(MT_MODEL, tr);
-//		gluSphere(quadric, sphere[2].r, 64, 64);
-		// End Draw spheres
-
-//		// Draw velocity segments
-//		glColor3f(1, 0, 0);
-//		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-
-//		glBegin(GL_LINES);
-//		glVertex3fv(sphere[0].c.ToFloatPtr());
-//		glVertex3fv((sphere[0].c + velocity[0]).ToFloatPtr());
-//		glEnd();
-
-//		glBegin(GL_LINES);
-//		glVertex3fv(sphere[1].c.ToFloatPtr());
-//		glVertex3fv((sphere[1].c + velocity[1]).ToFloatPtr());
-//		glEnd();
-
-//		glBegin(GL_LINES);
-//		glVertex3fv(sphere[2].c.ToFloatPtr());
-//		glVertex3fv((sphere[2].c + velocity[2]).ToFloatPtr());
-//		glEnd();
-//		// End Draw velocity segments
-
-//		// Draw end spheres
-//		glColor3f(1.0, 0.0, 0.0);
-//		tr.LoadIdentity();
-//		tr.SetTranslation(sphere[0].c + velocity[0]);
-//		renderer->SetMatrix(MT_MODEL, tr);
-//		gluSphere(quadric, sphere[0].r, 64, 64);
-
-//		tr.SetTranslation(sphere[1].c + velocity[1]);
-//		renderer->SetMatrix(MT_MODEL, tr);
-//		gluSphere(quadric, sphere[1].r, 64, 64);
-
-//		tr.SetTranslation(sphere[2].c + velocity[2]);
-//		renderer->SetMatrix(MT_MODEL, tr);
-//		gluSphere(quadric, sphere[2].r, 64, 64);
-//		// End Draw end spheres
-
-//		// Draw spheres at collision time
-//		glColor3f(0.0, 1.0, 0.0);
-//		real it;
-//		if (Intersection::TestDynamicSphereSphere(sphere[0], velocity[0], sphere[1], velocity[1], it))
-//		{
-//			tr.LoadIdentity();
-
-//			tr.SetTranslation(sphere[0].c + (velocity[0] * it));
-//			renderer->SetMatrix(MT_MODEL, tr);
-//			gluSphere(quadric, sphere[0].r, 64, 64);
-
-
-//			tr.SetTranslation(sphere[1].c + (velocity[1] * it));
-//			renderer->SetMatrix(MT_MODEL, tr);
-//			gluSphere(quadric, sphere[1].r, 64, 64);
-//		}
-
-//		if (Intersection::TestDynamicSpherePlane(sphere[2], velocity[2], plane, it))
-//		{
-//			tr.LoadIdentity();
-
-//			tr.SetTranslation(sphere[2].c + (velocity[2] * it));
-//			renderer->SetMatrix(MT_MODEL, tr);
-//			gluSphere(quadric, sphere[2].r, 64, 64);
-//		}
-//		// End Draw spheres at collision time
-
-		renderer->_SetTexture(0, grass);
-		renderer->_SetTexturing(0, true);
-		renderer->_SetTextureMode(0, grass->GetMode(), grass->GetBlendColor());
-		renderer->_SetTextureFilter(0, grass->GetFilter());
-
-		tr.BuildRotationX(Math::PI / 2.0f);
-		tr.SetTranslation(Vec3(0, 0, 0));
-		renderer->SetMatrix(MT_MODEL, tr);
-		renderer->RenderVertexIndexBuffer(dplane->GetVertexBuffer(), dplane->GetIndexBuffer());
-
-		tr.LoadIdentity();
-		tr.SetTranslation(Vec3(0, 0, 0));
-		renderer->SetMatrix(MT_MODEL, tr);
-		renderer->RenderVertexIndexBuffer(dplane->GetVertexBuffer(), dplane->GetIndexBuffer());
-
-		tr.BuildRotationY(Math::PI / 2.0f);
-		tr.SetTranslation(Vec3(0, 0, 0));
-		renderer->SetMatrix(MT_MODEL, tr);
-		renderer->RenderVertexIndexBuffer(dplane->GetVertexBuffer(), dplane->GetIndexBuffer());
-	}
-
-private:
-
-	Mesh* dplane;
-	Mat4 ortho;
-	Mat4 crateModel;
-	Mat4 tr;
-	Texture* grass;
-
-	Ray ray;
-	Plane plane[3];
-	Sphere sphere[12];
-	Vec3 velocity[12];
-	Vec3 gravity;
-	GLUquadric* quadric;
-	MovableCamera* cam;
-	int sphereCount;
-};
-
-int main(int argc, char** argv)
-{
-	Device* mDevice = GetDevice();
-	EventLoop loop;
-
-	if (!mDevice->Init(argc, argv))
-	{
-		return 0;
-	}
-
-	WndCtrl ctrl;
-
-	MainScene scene;
-	scene.OnLoad();
-
-	mDevice->GetMainWindow()->SetTitle("Crown Engine v0.1 - Collision Test");
-
-	while (mDevice->IsRunning())
-	{
-		InputManager* mInputManager = GetDevice()->GetInputManager();
-
-		if (mInputManager)
-		{
-			if (mInputManager->IsMouseAvailable())
-			{
-				if (mInputManager->IsMouseAvailable())
-				{
-					mInputManager->GetMouse()->EventLoop();
-				}
-				if (mInputManager->IsKeyboardAvailable())
-				{
-					mInputManager->GetKeyboard()->EventLoop();
-				}
-				if (mInputManager->IsTouchAvailable())
-				{
-					mInputManager->GetTouch()->EventLoop();
-				}
-			}
-		}
-
-		mDevice->GetMainWindow()->EventLoop();
-
-		GetDevice()->GetRenderer()->_BeginFrame();
-
-		scene.RenderScene();
-
-		GetDevice()->GetRenderer()->_EndFrame();
-
-		mDevice->GetMainWindow()->Update();
-	}
-
-	mDevice->Shutdown();
-
-	mDevice->Shutdown();
-
-	return 0;
-}
-

+ 0 - 246
samples/intersection/intersection.cpp

@@ -1,246 +0,0 @@
-#include "Crown.h"
-#include <cstdlib>
-#include <GL/glu.h>
-
-using namespace Crown;
-
-class WndCtrl: public KeyboardListener
-{
-public:
-
-	WndCtrl()
-	{
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual void KeyReleased(const KeyboardEvent& event)
-	{
-		if (event.key == KC_ESCAPE)
-		{
-			GetDevice()->StopRunning();
-		}
-	}
-};
-
-class MainScene: public Scene, public KeyboardListener, public MouseListener
-{
-
-public:
-
-	MainScene(uint windowWidth, uint windowHeight)
-	{
-		GetDevice()->GetInputManager()->RegisterMouseListener(this);
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual ~MainScene()
-	{
-		if (quadric)
-			gluDeleteQuadric(quadric);
-	}
-
-	virtual void ButtonReleased(const MouseEvent& event)
-	{
-		if (event.button == MB_LEFT)
-		{
-			GLint view[4];
-			GLdouble proj[16], model[16];
-
-			glGetDoublev(GL_MODELVIEW_MATRIX, model);
-			glGetDoublev(GL_PROJECTION_MATRIX, proj);
-			glGetIntegerv(GL_VIEWPORT, view);
-
-			int x = event.x;
-			int y = event.y;
-
-			// Adjust y wndCoord
-			y = (625 - y);
-
-			double sX, sY, sZ;
-			double eX, eY, eZ;
-
-			gluUnProject(x, y, 0.0f, model, proj, view, &sX, &sY, &sZ);
-			gluUnProject(x, y, 1.0f, model, proj, view, &eX, &eY, &eZ);
-
-			Vec3 dir = Vec3(eX, eY, eZ) - Vec3(sX, sY, sZ);
-
-			dir.Normalize();
-
-			ray.origin = cam->GetPosition();
-			ray.direction = dir;
-
-			//std::cout << x << " " << y << std::endl;
-			//std::cout << "Ori: " << ray.origin.ToStr().c_str() << std::endl;
-			//std::cout << "Dir: " << ray.direction.ToStr().c_str() << std::endl;
-		}
-	}
-
-	virtual void KeyPressed(const KeyboardEvent& event)
-	{
-		if (event.key == KC_UP)
-		{
-			ray.origin += Vec3(0, 0, -0.1);
-		}
-
-		if (event.key == KC_DOWN)
-		{
-			ray.origin += Vec3(0, 0, 0.1);
-		}
-
-		if (event.key == KC_LCONTROL)
-		{
-			cam->SetActive(!cam->IsActive());
-		}
-	}
-		
-
-	virtual void OnLoad()
-	{
-		Scene::OnLoad();
-
-		Crown::Renderer* renderer = Crown::GetDevice()->GetRenderer();
-		renderer->SetClearColor(Crown::Color4(0.0f, 0.0f, 0.0f, 1.0f));
-
-		// Add a movable camera
-		cam = AddMovableCamera();
-
-		if (cam)
-		{
-			cam->SetActive(true);
-			cam->SetSpeed(0.1);
-			cam->SetFarClipDistance(1000.0f);
-			//cam->SetPosition(Vec3(25, 0, 15));
-
-		}
-
-		grid = GetMeshManager()->LoadGrid("grid", 32);
-
-		ray.origin = Vec3(0, 0, 10);
-		ray.direction = Vec3(0, 0, -1);
-
-		sphere[0].c = Vec3(0, 0, 0);
-		sphere[0].r = 2.0f;
-
-		sphere[1].c = Vec3(3, -1, -5);
-		sphere[1].r = 1.0f;
-
-		sphere[2].c = Vec3(-5, 3, 2);
-		sphere[2].r = 3.0f;
-
-		quadric = gluNewQuadric();
-	}
-
-	virtual void RenderScene()
-	{
-		Renderer* renderer = GetDevice()->GetRenderer();
-
-		renderer->_SetLighting(false);
-		renderer->_SetBlending(false);
-		renderer->_SetAlphaTest(false);
-		Scene::RenderScene();
-
-		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-		renderer->_SetTexturing(0, false);
-		renderer->_SetTexturing(1, false);
-		renderer->_SetTexturing(2, false);
-
-		if (cam->IsActive())
-		{
-			ray.origin = cam->GetPosition();
-			ray.direction = cam->GetLookAt();
-			//std::cout << ray.direction.ToStr().c_str() << std::endl;
-		}
-
-		int sphereIndex = -1;
-		real lastDist = 1000000.0f;
-		// Check ray-sphere intersection
-		for (int i = 0; i < 3; i++)
-		{
-			real dist;
-			if (Intersection::TestRaySphere(ray, sphere[i], dist))
-			{
-				if (dist <= lastDist)
-				{
-					lastDist = dist;
-					sphereIndex = i;
-				}
-			}
-		}
-
-		for (int i = 0; i < 3; i++)
-		{
-			if (sphereIndex == i)
-			{
-				glColor3f(1, 0, 0);
-			}
-			else
-			{
-				glColor3f(0, 1, 0);
-			}
-
-			tr.LoadIdentity();
-			tr.SetTranslation(sphere[i].c);
-			renderer->SetMatrix(MT_MODEL, tr);
-			gluSphere(quadric, sphere[i].r, 64, 64);
-		}
-
-		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-		glColor3f(0, 0, 1);
-		glBegin(GL_LINES);
-		glVertex3fv(ray.origin.ToFloatPtr());
-		glVertex3fv((ray.origin + ray.direction).ToFloatPtr());
-		glEnd();
-
-		tr.SetTranslation(Vec3(0, -2, 0));
-		renderer->SetMatrix(MT_MODEL, tr);
-		renderer->RenderMesh(grid.GetPointer());
-	}
-
-private:
-
-	MeshPtr grid;
-	Mat4 ortho;
-	Mat4 crateModel;
-	Mat4 tr;
-
-	Ray ray;
-	Sphere sphere[3];
-	GLUquadric* quadric;
-	MovableCamera* cam;
-	Mouse* mouse;
-	Keyboard* keyboard;
-	InputManager* input;
-};
-
-int main(int argc, char** argv)
-{
-	int wndW = 1000;
-	int wndH = 625;
-
-	if (argc == 3)
-	{
-		wndW = atoi(argv[1]);
-		wndH = atoi(argv[2]);
-	}
-
-	Device* mDevice = GetDevice();
-
-	if (!mDevice->Init(wndW, wndH, 32, false))
-	{
-		return 0;
-	}
-
-	WndCtrl ctrl;
-
-	MainScene* mainScene = new MainScene(wndW, wndH);
-	GetDevice()->GetSceneManager()->SelectNextScene(mainScene);
-
-	mDevice->GetMainWindow()->SetTitle("Crown Engine v0.1 - Intersection Test");
-
-	mDevice->Run();
-
-	mDevice->Shutdown();
-
-	return 0;
-}
-

BIN
samples/res/closebutton_x.bmp


BIN
samples/res/crw_dir_icon.bmp


BIN
samples/res/crw_file_icon.bmp


+ 0 - 36
samples/res/editor_editorwindow.xml

@@ -1,36 +0,0 @@
-<Window Name="editorWindow" Title="Editor Window" Height="400" Width="850">
-  <StackLayout Orientation="Horizontal" >
-    <TreeView Name="twCrwLibrary" Width="200" BindingContext="{Bind CrwObjectModel}" Items="{Bind Root}" OnSelectionChanged="{Action UpdateCrwFilePreview}">
-	  <TreeView.ItemTemplate Items="{Bind Children}" ItemTemplate="{Bind ItemTemplate,Source=LogicalParent}">
-	    <StackLayout Orientation="Horizontal">
-		  <ImageWidget DesiredSize="16,16" Margins="2,2,2,2" ImageSource="{Bind Type,Converter=CrwIconConverter}" />
-		  <Label Text="{Bind Name}" Height="18"/>
-		</StackLayout>
-	  </TreeView.ItemTemplate>
-	</TreeView>
-	
-	<StackLayout Width="200" BindingContext="{Bind twCrwLibrary.SelectedItem,Source=Widget}" FitToChildren="Vertically" Margins="2,2,2,-1">
-	  <StackLayout Orientation="Horizontal">
-		<Label Text="ID: " DesiredSize="{Bind MinimumSize,Source=Self}" />
-		<Label Text="{Bind ID}" HorizontalTextAlign="Left" />
-	  </StackLayout>
-	  <StackLayout Orientation="Horizontal">
-		<Label Text="Name: " DesiredSize="{Bind MinimumSize,Source=Self}" />
-		<Label Text="{Bind Name}" />
-	  </StackLayout>
-	  <StackLayout Orientation="Horizontal">
-		<Label Text="Type: " DesiredSize="{Bind MinimumSize,Source=Self}" />
-		<Label Text="{Bind Type}" HorizontalTextAlign="Left" />
-	  </StackLayout>
-	  <StackLayout Orientation="Horizontal">
-		<Label Text="Offset: " DesiredSize="{Bind MinimumSize,Source=Self}" />
-		<Label Text="{Bind ContentOffset}" HorizontalTextAlign="Left" />
-	  </StackLayout>
-	  <StackLayout Orientation="Horizontal">
-		<Label Text="Size: " DesiredSize="{Bind MinimumSize,Source=Self}" />
-		<Label Text="{Bind ContentSize}" HorizontalTextAlign="Left" />
-	  </StackLayout>
-	  <ImageWidget DesiredSize="100, 100" ImageSource="{Bind BindingContext,Source=Self,Converter=CrwDescriptorToFullPathConverter}" />
-	</StackLayout>
-  </StackLayout>
-</Window>

+ 0 - 13
samples/res/editor_mainwindow.xml

@@ -1,13 +0,0 @@
-<Window Name="mainWindow" Title="Main Window" DesiredSize="90, 80">
-  <StackLayout Orientation="Vertical">
-    <Button Name="btnNewLibrary" Margins="0,0,0,1" OnClick="{Action NewLibrary}">
-      <Label Text="New Library" HorizontalTextAlign="Center" />
-    </Button>
-	<Button Name="btnOpenLibrary" Margins="0,1,0,1" OnClick="{Action OpenLibrary}">
-      <Label Text="Open Library" HorizontalTextAlign="Center" />
-    </Button>
-    <Button Name="btnClose" Margins="0,1,0,0" OnClick="{Action QuitApplication}">
-      <Label Text="Close" HorizontalTextAlign="Center" />
-    </Button>
-  </StackLayout>
-</Window>

BIN
samples/res/terrain.bmp


+ 0 - 12
samples/res/window.xml

@@ -1,12 +0,0 @@
-<Window Name="mainWindow" Title="A Window">
-  <StackLayout Margins="2, 0, 2, 0">
-    <Button Name="btnQuit" OnClick="{Action QuitApplication}" DesiredSize="35, 15">
-	  <Label Name="lblCaption" Text="Close" />
-	</Button>
-    <Button Name="btnNew" OnClick="{Action NewLibrary}" Margins="0, 15, 0, 0" DesiredSize="70, 20">
-	  <Label Name="lblCaption" Text="New Library" />
-	</Button>
-  </StackLayout>
-</Window>
-
-

+ 0 - 45
samples/res/window_fractal.xml

@@ -1,45 +0,0 @@
-<Window Name="loaderWindow" Title="Fractal" DesiredSize="200, 176">
-  <StackLayout Margins="2, 2, 2, 2">
-	<Label Text="Interactions:" Height="25" />
-	<Button OnClick="{Action Generate}" Height="25">
-	  <Label Text="Generate" HorizontalTextAlign="Center" />
-	</Button>
-	
-	<StackLayout Orientation="Horizontal">
-	  <Button OnClick="{Action MoveLeft}" DesiredSize="25, 25">
-	    <Label Text="<" HorizontalTextAlign="Center" />
-	  </Button>
-	  
-	  <StackLayout Orientation="Vertical" FitToChildren="Both">
-	    <Button OnClick="{Action MoveUp}" DesiredSize="25, 25">
-	      <Label Text="^" HorizontalTextAlign="Center" />
-	    </Button>
-	    
-	    <Button OnClick="{Action MoveDown}" DesiredSize="25, 25">
-	      <Label Text="v" HorizontalTextAlign="Center" />
-	    </Button>
-	  </StackLayout>
-	
-	  <Button OnClick="{Action MoveRight}" DesiredSize="25, 25">
-	    <Label Text=">" HorizontalTextAlign="Center" />
-	  </Button>
-	  
-	  <StackLayout Orientation="Vertical" FitToChildren="Both" Margins="25,0,0,0">
-	    <Button OnClick="{Action ZoomPlus}" DesiredSize="25, 25">
-	      <Label Text="z+" HorizontalTextAlign="Center" />
-	    </Button>
-	    
-	    <Button OnClick="{Action ZoomMinus}" DesiredSize="25, 25">
-	      <Label Text="z-" HorizontalTextAlign="Center" />
-	    </Button>
-	  </StackLayout>
-	  
-	</StackLayout>
-	
-	<Button OnClick="{Action QuitApplication}" Height="25">
-	  <Label Text="Quit" HorizontalTextAlign="Center" />
-	</Button>
-  </StackLayout>
-</Window>
-
-

+ 0 - 30
samples/res/window_listview.xml

@@ -1,30 +0,0 @@
-<Window Name="listviewWindow" Title="List View Window" DesiredSize="300, 300">
-  <StackLayout Orientation="Horizontal">
-    <ListView Name="lwFruits" Items="{Bind FruitsList}">
-	  <ListView.ItemTemplate>
-	    <StackLayout Margins="4,4,4,4">
-		  <StackLayout Orientation="Horizontal">
-		    <Label Text="Name: " />
-			<Label Text="{Bind fruitName}" />
-		  </StackLayout>
-		  <StackLayout Orientation="Horizontal">
-		    <Label Text="Cost: " />
-			<Label Text="{Bind fruitPrice}" />
-			<Label Text="€" />
-		  </StackLayout>
-		</StackLayout>
-	  </ListView.ItemTemplate>
-	</ListView>
-    <StackLayout Margins="2, -1, 2, -1" Orientation="Horizontal" FitToChildren="Vertically">
-	  <Label Text="Price:" Width="0" />
-      <Button Height="20" Margins="4,0,0,0" OnClick="{Action IncreaseFruitPrice}" >
-		<Label Text="Increase" />
-	  </Button>
-	  <Button Height="20" Margins="4,0,0,0" OnClick="{Action DecreaseFruitPrice}" >
-		<Label Text="Decrease" />
-	  </Button>
-    </StackLayout>
-  </StackLayout>
-</Window>
-
-

+ 0 - 33
samples/res/window_loader.xml

@@ -1,33 +0,0 @@
-<Window Name="loaderWindow" Title="Load a XWML file" DesiredSize="200, 176">
-  <StackLayout Margins="2, 2, 2, 2">
-	<Label Text="Insert the XWML file:" />
-    <TextBox Name="tbXWMLFilepath" Text="<insert xwml filename>" />
-    <Button Name="btnLoad" OnClick="{Action LoadXWMLFromFilepath}" Margins="0, 4, 0, 0">
-	  <Label Name="lblCaption" Text="Load XWML" HorizontalTextAlign="Center" />
-	</Button>
-	<Label Text="Examples:" Margins="0, 5, 0, 0" />
-	<StackLayout Orientation="Horizontal" FitToChildren="Both">
-	  <Label Name="lblExample1" Text="res/window.xml" />
-	  <Button DesiredSize="10, 10" Margins="3,0,0,0" OnClick="{Action CopyProperty('lblExample1.Text','tbXWMLFilepath.Text')}">
-	    <Label Text="+" />
-	  </Button>
-	</StackLayout>
-	<StackLayout Orientation="Horizontal" FitToChildren="Both">
-	  <Label Name="lblExample2" Text="res/window_listview.xml" />
-	  <Button DesiredSize="10, 10" Margins="3,0,0,0" OnClick="{Action CopyProperty('lblExample2.Text','tbXWMLFilepath.Text')}">
-	    <Label Text="+" />
-	  </Button>
-	</StackLayout>
-	<StackLayout Orientation="Horizontal" FitToChildren="Both">
-	  <Label Name="lblExample3" Text="res/window_loader.xml" />
-	  <Button DesiredSize="10, 10" Margins="3,0,0,0" OnClick="{Action CopyProperty('lblExample3.Text','tbXWMLFilepath.Text')}">
-	    <Label Text="+" />
-	  </Button>
-	</StackLayout>
-	<Button OnClick="{Action QuitApplication}">
-	  <Label Text="Quit" HorizontalTextAlign="Center" />
-	</Button>
-  </StackLayout>
-</Window>
-
-

+ 13 - 6
samples/terrain/Terrain.cpp

@@ -148,6 +148,11 @@ void Terrain::CreateTerrain(uint32_t xSize, uint32_t zSize, uint32_t tilePerMete
 			iIndex += 6;
 		}
 	}
+
+	m_vertex_buffer = device()->renderer()->create_dynamic_vertex_buffer(mVertexCount, VF_XYZ_FLOAT_32, mVertices);
+	m_normal_buffer = device()->renderer()->create_dynamic_vertex_buffer(mNormalCount, VF_XYZ_NORMAL_FLOAT_32, mNormals);
+	m_tex_coord_buffer = device()->renderer()->create_vertex_buffer(mTexCoordCount, VF_UV_FLOAT_32, mTexCoords);
+	m_index_buffer = device()->renderer()->create_index_buffer(mIndexCount, mIndices);
 }
 
 void Terrain::UpdateVertexBuffer(bool recomputeNormals)
@@ -160,6 +165,8 @@ void Terrain::UpdateVertexBuffer(bool recomputeNormals)
 			mVertices[vIndex].y = mHeights[vIndex];
 			vIndex++;
 		}
+
+		device()->renderer()->update_vertex_buffer(m_vertex_buffer, 0, mVertexCount, mVertices);
 	}
 
 	if (recomputeNormals)
@@ -179,6 +186,8 @@ void Terrain::UpdateVertexBuffer(bool recomputeNormals)
 			mNormals[mIndices[i + 1]] = normal;
 			mNormals[mIndices[i + 2]] = normal;
 		}
+
+		device()->renderer()->update_vertex_buffer(m_normal_buffer, 0, mNormalCount, mNormals);
 	}
 }
 
@@ -278,12 +287,10 @@ void Terrain::Render()
 {
 	Renderer* renderer = device()->renderer();
 
-	renderer->draw_triangles(
-				mVertices[0].to_float_ptr(),
-				mNormals[0].to_float_ptr(),
-				mTexCoords[0].to_float_ptr(),
-				mIndices,
-				mTilesInSizeX * mTilesInSizeZ * 6);
+	renderer->bind_vertex_buffer(m_vertex_buffer);
+	renderer->bind_vertex_buffer(m_normal_buffer);
+	renderer->bind_vertex_buffer(m_tex_coord_buffer);
+	renderer->draw_triangles(m_index_buffer);
 }
 
 float Terrain::GaussDist(float x, float y, float sigma)

+ 6 - 0
samples/terrain/Terrain.h

@@ -29,6 +29,7 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include "Triangle.h"
 #include "Intersection.h"
 #include "Ray.h"
+#include "Renderer.h"
 
 #define MAX_BRUSH_SIZE 256
 
@@ -97,6 +98,11 @@ private:
 	uint32_t		mIndexCount;
 	uint16_t*		mIndices;
 
+	VertexBufferId	m_vertex_buffer;
+	VertexBufferId	m_normal_buffer;
+	VertexBufferId	m_tex_coord_buffer;
+	IndexBufferId	m_index_buffer;
+
 	uint32_t		mBrushWidth;
 	uint32_t		mBrushHeight;
 	float			mBrush[MAX_BRUSH_SIZE * MAX_BRUSH_SIZE];

+ 5 - 2
samples/terrain/terrain.cpp

@@ -130,7 +130,7 @@ public:
 		device()->resource_manager()->flush();
 
 		TextureResource* grass_texture = (TextureResource*)device()->data(grass);
-		grass_id = device()->renderer()->load_texture(grass_texture);
+		grass_id = device()->renderer()->create_texture(grass_texture->width(), grass_texture->height(), grass_texture->format(), grass_texture->data());
 
 		ScriptResource* script_resource = (ScriptResource*)device()->data(script);
 		device()->script_system()->load(script_resource);
@@ -145,6 +145,8 @@ public:
 		device()->unload(red_west);
 		device()->unload(red_up);
 		device()->unload(red_down);
+
+		//device()->renderer()->destroy_render_buffer(rb_id);
 	}
 
 	void update(float dt)
@@ -188,7 +190,7 @@ public:
 		if (device()->is_loaded(grass))
 		{
 			renderer->set_texturing(0, true);
-			renderer->set_texture(0, grass_id);
+			renderer->bind_texture(0, grass_id);
 		}
 		
 		//glColor3f(1, 1, 1);
@@ -233,6 +235,7 @@ private:
 	ResourceId red_up;
 	ResourceId red_down;
 	TextureId grass_id;
+	RenderBufferId rb_id;
 
 	ResourceId script;
 

BIN
samples/textrenderer/res/arial.tga


+ 0 - 95
samples/textrenderer/res/arial.tga.txt

@@ -1,95 +0,0 @@
-32 0.000000 0.050781 0.000000 0.066406 0.000000 0.000000 8.000000 0.000000
-33 0.056641 0.107422 0.000000 0.066406 4.000000 20.000000 8.000000 20.000000
-34 0.113281 0.164062 0.000000 0.066406 10.000000 7.000000 13.000000 20.000000
-35 0.169922 0.220703 0.000000 0.066406 15.000000 20.000000 15.000000 20.000000
-36 0.226562 0.277344 0.000000 0.066406 12.000000 23.000000 15.000000 21.000000
-37 0.283203 0.333984 0.000000 0.066406 22.000000 21.000000 24.000000 20.000000
-38 0.339844 0.390625 0.000000 0.066406 18.000000 20.000000 20.000000 20.000000
-39 0.396484 0.447266 0.000000 0.066406 4.000000 7.000000 6.000000 20.000000
-40 0.453125 0.503906 0.000000 0.066406 7.000000 25.000000 9.000000 20.000000
-41 0.509766 0.560547 0.000000 0.066406 7.000000 25.000000 9.000000 20.000000
-42 0.566406 0.617188 0.000000 0.066406 10.000000 9.000000 11.000000 20.000000
-43 0.623047 0.673828 0.000000 0.066406 14.000000 14.000000 16.000000 17.000000
-44 0.000000 0.050781 0.072266 0.138672 4.000000 8.000000 8.000000 4.000000
-45 0.056641 0.107422 0.072266 0.138672 8.000000 4.000000 9.000000 9.000000
-46 0.113281 0.164062 0.072266 0.138672 4.000000 4.000000 8.000000 4.000000
-47 0.169922 0.220703 0.072266 0.138672 9.000000 20.000000 8.000000 20.000000
-48 0.226562 0.277344 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-49 0.283203 0.333984 0.072266 0.138672 9.000000 20.000000 15.000000 20.000000
-50 0.339844 0.390625 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-51 0.396484 0.447266 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-52 0.453125 0.503906 0.072266 0.138672 14.000000 20.000000 15.000000 20.000000
-53 0.509766 0.560547 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-54 0.566406 0.617188 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-55 0.623047 0.673828 0.072266 0.138672 13.000000 20.000000 15.000000 20.000000
-56 0.000000 0.050781 0.144531 0.210938 13.000000 20.000000 15.000000 20.000000
-57 0.056641 0.107422 0.144531 0.210938 13.000000 20.000000 15.000000 20.000000
-58 0.113281 0.164062 0.144531 0.210938 4.000000 15.000000 10.000000 15.000000
-59 0.169922 0.220703 0.144531 0.210938 4.000000 19.000000 10.000000 15.000000
-60 0.226562 0.277344 0.144531 0.210938 13.000000 15.000000 16.000000 17.000000
-61 0.283203 0.333984 0.144531 0.210938 14.000000 10.000000 16.000000 15.000000
-62 0.339844 0.390625 0.144531 0.210938 13.000000 15.000000 16.000000 17.000000
-63 0.396484 0.447266 0.144531 0.210938 14.000000 20.000000 17.000000 20.000000
-64 0.453125 0.503906 0.144531 0.210938 25.000000 27.000000 26.000000 20.000000
-65 0.509766 0.560547 0.144531 0.210938 19.000000 20.000000 19.000000 20.000000
-66 0.566406 0.617188 0.144531 0.210938 17.000000 20.000000 20.000000 20.000000
-67 0.623047 0.673828 0.144531 0.210938 18.000000 20.000000 20.000000 20.000000
-68 0.000000 0.050781 0.216797 0.283203 17.000000 20.000000 20.000000 20.000000
-69 0.056641 0.107422 0.216797 0.283203 15.000000 20.000000 18.000000 20.000000
-70 0.113281 0.164062 0.216797 0.283203 14.000000 20.000000 17.000000 20.000000
-71 0.169922 0.220703 0.216797 0.283203 18.000000 20.000000 21.000000 20.000000
-72 0.226562 0.277344 0.216797 0.283203 16.000000 20.000000 20.000000 20.000000
-73 0.283203 0.333984 0.216797 0.283203 4.000000 20.000000 8.000000 20.000000
-74 0.339844 0.390625 0.216797 0.283203 13.000000 20.000000 15.000000 20.000000
-75 0.396484 0.447266 0.216797 0.283203 18.000000 20.000000 20.000000 20.000000
-76 0.453125 0.503906 0.216797 0.283203 14.000000 20.000000 17.000000 20.000000
-77 0.509766 0.560547 0.216797 0.283203 19.000000 20.000000 21.000000 20.000000
-78 0.566406 0.617188 0.216797 0.283203 16.000000 20.000000 20.000000 20.000000
-79 0.623047 0.673828 0.216797 0.283203 19.000000 20.000000 21.000000 20.000000
-80 0.000000 0.050781 0.289062 0.355469 15.000000 20.000000 18.000000 20.000000
-81 0.056641 0.107422 0.289062 0.355469 20.000000 22.000000 21.000000 20.000000
-82 0.113281 0.164062 0.289062 0.355469 18.000000 20.000000 20.000000 20.000000
-83 0.169922 0.220703 0.289062 0.355469 16.000000 20.000000 18.000000 20.000000
-84 0.226562 0.277344 0.289062 0.355469 16.000000 20.000000 18.000000 20.000000
-85 0.283203 0.333984 0.289062 0.355469 16.000000 20.000000 20.000000 20.000000
-86 0.339844 0.390625 0.289062 0.355469 17.000000 20.000000 18.000000 20.000000
-87 0.396484 0.447266 0.289062 0.355469 25.000000 20.000000 25.000000 20.000000
-88 0.453125 0.503906 0.289062 0.355469 18.000000 20.000000 18.000000 20.000000
-89 0.509766 0.560547 0.289062 0.355469 20.000000 20.000000 18.000000 20.000000
-90 0.566406 0.617188 0.289062 0.355469 16.000000 20.000000 17.000000 20.000000
-91 0.623047 0.673828 0.289062 0.355469 7.000000 25.000000 9.000000 20.000000
-92 0.000000 0.050781 0.361328 0.427734 9.000000 20.000000 8.000000 20.000000
-93 0.056641 0.107422 0.361328 0.427734 7.000000 25.000000 9.000000 20.000000
-94 0.113281 0.164062 0.361328 0.427734 12.000000 10.000000 16.000000 20.000000
-95 0.169922 0.220703 0.361328 0.427734 16.000000 3.000000 15.000000 -2.000000
-96 0.226562 0.277344 0.361328 0.427734 6.000000 4.000000 9.000000 20.000000
-97 0.283203 0.333984 0.361328 0.427734 13.000000 15.000000 15.000000 15.000000
-98 0.339844 0.390625 0.361328 0.427734 14.000000 20.000000 17.000000 20.000000
-99 0.396484 0.447266 0.361328 0.427734 13.000000 15.000000 15.000000 15.000000
-100 0.453125 0.503906 0.361328 0.427734 14.000000 20.000000 17.000000 20.000000
-101 0.509766 0.560547 0.361328 0.427734 14.000000 15.000000 15.000000 15.000000
-102 0.566406 0.617188 0.361328 0.427734 10.000000 20.000000 9.000000 20.000000
-103 0.623047 0.673828 0.361328 0.427734 15.000000 20.000000 17.000000 15.000000
-104 0.000000 0.050781 0.433594 0.500000 13.000000 20.000000 17.000000 20.000000
-105 0.056641 0.107422 0.433594 0.500000 4.000000 20.000000 8.000000 20.000000
-106 0.113281 0.164062 0.433594 0.500000 7.000000 25.000000 8.000000 20.000000
-107 0.169922 0.220703 0.433594 0.500000 13.000000 20.000000 15.000000 20.000000
-108 0.226562 0.277344 0.433594 0.500000 4.000000 20.000000 8.000000 20.000000
-109 0.283203 0.333984 0.433594 0.500000 22.000000 15.000000 26.000000 15.000000
-110 0.339844 0.390625 0.433594 0.500000 13.000000 15.000000 17.000000 15.000000
-111 0.396484 0.447266 0.433594 0.500000 15.000000 15.000000 17.000000 15.000000
-112 0.453125 0.503906 0.433594 0.500000 14.000000 20.000000 17.000000 15.000000
-113 0.509766 0.560547 0.433594 0.500000 14.000000 20.000000 17.000000 15.000000
-114 0.566406 0.617188 0.433594 0.500000 9.000000 15.000000 11.000000 15.000000
-115 0.623047 0.673828 0.433594 0.500000 13.000000 15.000000 15.000000 15.000000
-116 0.000000 0.050781 0.505859 0.572266 9.000000 20.000000 9.000000 20.000000
-117 0.056641 0.107422 0.505859 0.572266 13.000000 15.000000 17.000000 15.000000
-118 0.113281 0.164062 0.505859 0.572266 15.000000 15.000000 15.000000 15.000000
-119 0.169922 0.220703 0.505859 0.572266 21.000000 15.000000 21.000000 15.000000
-120 0.226562 0.277344 0.505859 0.572266 15.000000 15.000000 15.000000 15.000000
-121 0.283203 0.333984 0.505859 0.572266 17.000000 20.000000 15.000000 15.000000
-122 0.339844 0.390625 0.505859 0.572266 12.000000 15.000000 14.000000 15.000000
-123 0.396484 0.447266 0.505859 0.572266 9.000000 25.000000 11.000000 20.000000
-124 0.453125 0.503906 0.505859 0.572266 3.000000 25.000000 7.000000 20.000000
-125 0.509766 0.560547 0.505859 0.572266 9.000000 25.000000 11.000000 20.000000
-126 0.566406 0.617188 0.505859 0.572266 14.000000 6.000000 16.000000 13.000000

BIN
samples/textrenderer/res/arialbd.ttf


BIN
samples/textrenderer/res/times.ttf


+ 0 - 113
samples/textrenderer/textrenderer.cpp

@@ -1,113 +0,0 @@
-#include "Crown.h"
-#include <cstdlib>
-#include <GL/glew.h>
-
-using namespace Crown;
-
-class WndCtrl: public KeyboardListener
-{
-public:
-
-	WndCtrl()
-	{
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual void KeyReleased(const KeyboardEvent& event)
-	{
-		if (event.key == KC_ESCAPE)
-		{
-			GetDevice()->StopRunning();
-		}
-	}
-};
-
-class MainScene
-{
-
-public:
-
-	MainScene(uint windowWidth, uint windowHeight)
-	{
-	}
-
-	virtual ~MainScene()
-	{
-	}
-
-	virtual void OnLoad()
-	{
-		mOrtho.BuildProjectionOrtho2dRH(800, 600, 10, -10);
-
-		Crown::Renderer* renderer = Crown::GetDevice()->GetRenderer();
-
-		renderer->SetClearColor(Crown::Color4(0.8f, 0.8f, 0.8f, 0.8f));
-
-		// Load and select the font
-		mLargeFont = GetFontManager()->Load("res/arial.tga");
-
-		renderer->_SetLighting(false);
-	}
-
-	virtual void RenderScene()
-	{
-		Scene::RenderScene();
-
-		Renderer* renderer = GetDevice()->GetRenderer();
-
-		Scene::RenderScene();
-
-		renderer->SetMatrix(MT_PROJECTION, mOrtho);
-
-		//text.SetFont(mLargeFont);
-		//text.SetColor(Color4::SILVER);
-		text.Draw("abcdef ABCDEF .@#^?=()&%!", 100, 90, mLargeFont);
-		text.Draw("Hello world! This is the new TextRenderer.\n", 100, 120, mLargeFont);
-		text.Draw("It supports a lot of new features!", 100, 150, mLargeFont);
-	}
-
-private:
-
-	Mat4 mOrtho;
-	Crown::Font* mLargeFont;
-	Crown::Font* mSmallFont;
-	Crown::Font* mTimesFont;
-
-	TextRenderer text;
-};
-
-int main(int argc, char** argv)
-{
-	int wndW = 800;
-	int wndH = 600;
-
-	if (argc == 3)
-	{
-		wndW = atoi(argv[1]);
-		wndH = atoi(argv[2]);
-	}
-
-	Device* mDevice = GetDevice();
-
-	if (!mDevice->Init(wndW, wndH, 32, false))
-	{
-		return 0;
-	}
-
-	WndCtrl ctrl;
-
-	MainScene* mainScene = new MainScene(wndW, wndH);
-	GetDevice()->GetSceneManager()->SelectNextScene(mainScene);
-
-	mDevice->GetMainWindow()->SetTitle("Crown Engine v0.1 - TextRenderer Test");
-
-	while (mDevice->IsRunning())
-	{
-		mDevice->Frame();
-	}
-
-	mDevice->Shutdown();
-
-	return 0;
-}
-

BIN
samples/texturing/ress/crate.tga


BIN
samples/texturing/ress/grass.tga


BIN
samples/texturing/ress/red_down.tga


BIN
samples/texturing/ress/red_east.tga


BIN
samples/texturing/ress/red_north.tga


BIN
samples/texturing/ress/red_south.tga


BIN
samples/texturing/ress/red_up.tga


BIN
samples/texturing/ress/red_west.tga


+ 0 - 222
samples/texturing/texturing.cpp

@@ -1,222 +0,0 @@
-#include "Crown.h"
-#include <cstdlib>
-
-using namespace Crown;
-
-class WndCtrl: public KeyboardListener
-{
-public:
-
-	WndCtrl()
-	{
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual void KeyReleased(const KeyboardEvent& event)
-	{
-		if (event.key == KC_ESCAPE)
-		{
-			GetDevice()->StopRunning();
-		}
-	}
-};
-
-class MainScene: public Scene, public KeyboardListener
-{
-
-public:
-
-	MainScene() :
-		optShowSkybox(true),
-		optShowCrate(true),
-		optShowTerrain(true)
-	{
-		GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
-	}
-
-	virtual ~MainScene()
-	{
-	}
-
-	virtual void KeyReleased(const KeyboardEvent& event)
-	{
-		if (event.key == '1')
-		{
-			optShowSkybox = !optShowSkybox;
-		}
-
-		if (event.key == '2')
-		{
-			optShowCrate = !optShowCrate;
-		}
-
-		if (event.key == '3')
-		{
-			optShowTerrain = !optShowTerrain;
-		}
-
-		if (event.key == KC_F5)
-		{
-			GetTextureManager()->Unload("res/grass.tga", false);
-		}
-
-		if (event.key == KC_SPACE)
-		{
-			if (cam)
-			{
-				cam->SetActive(!cam->IsActive());
-			}
-		}
-	}
-		
-
-	virtual void OnLoad()
-	{
-		Crown::Renderer* renderer = Crown::GetDevice()->GetRenderer();
-		renderer->SetClearColor(Crown::Color4(0.0f, 0.0f, 0.0f, 1.0f));
-
-		// Add a movable camera
-		cam = AddMovableCamera();
-
-		if (cam)
-		{
-			cam->SetActive(true);
-			cam->SetSpeed(0.1);
-			cam->SetFarClipDistance(1000.0f);
-		}
-
-		// Add a skybox
-		skybox = AddSkybox();
-
-		if (skybox)
-		{
-			skybox->SetFace(SF_NORTH,	GetTextureManager()->Load("res/red_north.tga"));
-			skybox->SetFace(SF_SOUTH,	GetTextureManager()->Load("res/red_south.tga"));
-			skybox->SetFace(SF_EAST,	GetTextureManager()->Load("res/red_east.tga"));
-			skybox->SetFace(SF_WEST,	GetTextureManager()->Load("res/red_west.tga"));
-			skybox->SetFace(SF_UP,		GetTextureManager()->Load("res/red_up.tga"));
-			skybox->SetFace(SF_DOWN,	GetTextureManager()->Load("res/red_down.tga"));
-		}
-
-		crate = GetTextureManager()->Load("res/crate.tga");
-		grass = GetTextureManager()->Load("res/grass.tga");
-
-		crate->SetFilter(TF_BILINEAR);
-		grass->SetFilter(TF_BILINEAR);
-
-		cube = GetMeshManager()->LoadCube("cube", 1.0f);
-		grid = GetMeshManager()->LoadGrid("grid", 32);
-
-		font = GetFontManager()->Load("arial", "res/arialbd.ttf", 12);
-
-		renderer->GetTextRenderer()->SetFont(font);
-		renderer->GetTextRenderer()->SetColor(Color4::WHITE);
-
-		ortho.BuildProjectionOrtho2dRH(1000, 625, -1, 1);
-		crateModel.LoadIdentity();
-		crateModel.SetTranslation(Vec3(0, 2, 0));
-	}
-
-	virtual void RenderScene()
-	{
-		Renderer* renderer = GetDevice()->GetRenderer();
-
-		if (skybox)
-		{
-			skybox->SetVisible(optShowSkybox);
-		}
-
-		Scene::RenderScene();
-
-		renderer->_SetLighting(false);
-		renderer->_SetBlending(false);
-		renderer->_SetAlphaTest(false);
-
-		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-		renderer->_SetTexturing(0, false);
-		renderer->_SetTexturing(1, false);
-		renderer->_SetTexturing(2, false);
-
-		// Render crate
-		if (optShowCrate)
-		{
-			renderer->_SetTexture(0, crate);
-			renderer->_SetTexturing(0, true);
-			renderer->_SetTextureMode(0, crate->GetMode(), crate->GetBlendColor());
-			renderer->_SetTextureFilter(0, crate->GetFilter());
-
-			renderer->SetMatrix(MT_MODEL, crateModel);
-			renderer->RenderVertexIndexBuffer(cube->GetVertexBuffer(), cube->GetIndexBuffer());
-		}
-
-		// Render terrain
-		if (optShowTerrain)
-		{
-			renderer->_SetTexture(0, grass);
-			renderer->_SetTexturing(0, true);
-			renderer->_SetTextureMode(0, grass->GetMode(), grass->GetBlendColor());
-			renderer->_SetTextureFilter(0, grass->GetFilter());
-
-			renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-			renderer->RenderVertexIndexBuffer(grid->GetVertexBuffer(), grid->GetIndexBuffer());
-		}
-
-/*
-		renderer->SetMatrix(MT_MODEL,		Mat4::IDENTITY);
-		renderer->SetMatrix(MT_VIEW,		Mat4::IDENTITY);
-		renderer->SetMatrix(MT_PROJECTION,	mOrtho2dRH);
-
-		renderer->_SetDepthTest(false);
-		renderer->SetMatrix(MT_PROJECTION, ortho);
-		renderer->SetMatrix(MT_MODEL, Mat4::IDENTITY);
-		renderer->SetMatrix(MT_VIEW, Mat4::IDENTITY);
-		renderer->GetTextRenderer()->Draw("Show/Hide Skybox (1)", 10, 24);
-		renderer->GetTextRenderer()->Draw("Show/Hide Crate (2)", 10, 38);
-		renderer->GetTextRenderer()->Draw("Show/Hide Terrain (3)", 10, 52);
-		renderer->_SetDepthTest(true);
-*/
-	}
-
-private:
-
-	MovableCamera* cam;
-	Skybox* skybox;
-	Texture* crate;
-	Texture* grass;
-	Mesh* cube;
-	Mesh* grid;
-	Crown::Font* font;
-	Mat4 ortho;
-	Mat4 crateModel;
-
-	bool optShowSkybox;
-	bool optShowCrate;
-	bool optShowTerrain;
-};
-
-int main(int argc, char** argv)
-{
-	Device* mDevice = GetDevice();
-
-	if (!mDevice->Init(argc, argv))
-	{
-		return 0;
-	}
-
-	WndCtrl ctrl;
-
-	MainScene* mainScene = new MainScene();
-	GetDevice()->GetSceneManager()->SelectNextScene(mainScene);
-
-	mDevice->GetMainWindow()->SetTitle("Crown Engine v0.1 - Texturing Test");
-
-	while (mDevice->IsRunning())
-	{
-		mDevice->Frame();
-	}
-
-	mDevice->Shutdown();
-
-	return 0;
-}
-

+ 8 - 1
src/ArchiveResourceArchive.cpp

@@ -76,7 +76,7 @@ ArchiveResourceArchive::~ArchiveResourceArchive()
 }
 
 //-----------------------------------------------------------------------------
-FileStream* ArchiveResourceArchive::find(ResourceId name)
+FileStream* ArchiveResourceArchive::open(ResourceId name)
 {
 	// Search the resource in the archive
 	for (uint32_t i = 0; i < m_entries_count; i++)
@@ -93,4 +93,11 @@ FileStream* ArchiveResourceArchive::find(ResourceId name)
 	return NULL;
 }
 
+//-----------------------------------------------------------------------------
+void ArchiveResourceArchive::close(FileStream* resource)
+{
+	// Does nothing, the stream is automatically closed at exit.
+	(void)resource;
+}
+
 } // namespace crown

+ 5 - 1
src/ArchiveResourceArchive.h

@@ -61,7 +61,11 @@ public:
 					ArchiveResourceArchive(Filesystem& fs);
 					~ArchiveResourceArchive();
 
-	FileStream*		find(ResourceId name);
+	/// @copydoc ResourceArchive::open()
+	FileStream*		open(ResourceId name);
+
+	/// @copydoc ResourceArchive::close()
+	void			close(FileStream* resource);
 
 private:
 

+ 6 - 14
src/CMakeLists.txt

@@ -75,6 +75,7 @@ set (CONTAINERS_HEADERS
 	core/containers/Generic.h
 	core/containers/List.h
 	core/containers/RBTree.h
+	core/containers/IdTable.h
 )
 
 set (MATH_SRC
@@ -163,15 +164,6 @@ set (COMPRESSORS_HEADERS
 	core/compressors/ZipCompressor.h
 )
 
-set (THREADS_HEADERS
-	core/threads/Thread.h
-	core/threads/Mutex.h
-	core/threads/Cond.h
-)
-
-set (THREADS_SRC
-)
-
 set (SETTINGS_SRC
 	core/settings/IntSetting.cpp
 	core/settings/FloatSetting.cpp
@@ -202,22 +194,24 @@ set (INPUT_HEADERS
 
 set (RENDERERS_SRC
 	renderers/DebugRenderer.cpp
-	renderers/Pixel.cpp
+	renderers/PixelFormat.cpp
+	renderers/VertexFormat.cpp
 )
 
 set (RENDERERS_HEADERS
 	renderers/Renderer.h
 	renderers/IndexBuffer.h
 	renderers/VertexBuffer.h
-	renderers/OcclusionQuery.h
 	renderers/Material.h
 	renderers/Texture.h
 	renderers/DebugRenderer.h
-	renderers/Pixel.h
+	renderers/PixelFormat.h
+	renderers/VertexFormat.h
 )
 
 set (OS_HEADERS
 	os/OS.h
+	os/NetAddress.h
 )
 
 set (OS_SRC
@@ -257,7 +251,6 @@ set (CROWN_SOURCES
 	${STREAMS_SRC}
 	${MEM_SRC}
 	${COMPRESSORS_SRC}
-	${THREADS_SRC}
 	${SETTINGS_SRC}
 
 	${INPUT_SRC}
@@ -281,7 +274,6 @@ set (CROWN_HEADERS
 	${STREAMS_HEADERS}
 	${MEM_HEADERS}
 	${COMPRESSORS_HEADERS}
-	${THREADS_HEADERS}
 	${SETTINGS_HEADERS}
 
 	${INPUT_HEADERS}

+ 3 - 2
src/Crown.h

@@ -61,6 +61,7 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include "List.h"
 #include "Generic.h"
 #include "Queue.h"
+#include "IdTable.h"
 
 // Core/Strings
 #include "String.h"
@@ -124,9 +125,9 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include "VertexBuffer.h"
 #include "IndexBuffer.h"
 #include "Renderer.h"
-#include "OcclusionQuery.h"
 #include "Material.h"
 #include "Texture.h"
 #include "DebugRenderer.h"
-#include "Pixel.h"
+#include "PixelFormat.h"
+#include "VertexFormat.h"
 

+ 2 - 7
src/Device.cpp

@@ -119,6 +119,8 @@ bool Device::init(int argc, char** argv)
 
 	Log::d("Filesystem created.");
 
+	Log::d("Filesystem root path: %s", m_filesystem->root_path());
+
 	create_resource_manager();
 
 	Log::d("Resource manager created.");
@@ -143,8 +145,6 @@ bool Device::init(int argc, char** argv)
 
 	Log::i("Initializing Game...");
 
-	Log::d(m_filesystem->root_path());
-
 	// Try to locate the game library
 	if (!m_filesystem->exists(GAME_LIBRARY_NAME))
 	{
@@ -389,11 +389,6 @@ void Device::reload(ResourceId name)
 	m_resource_manager->reload(name);
 
 	const void* new_resource = m_resource_manager->data(name);
-
-	if (name.type == TEXTURE_TYPE)
-	{
-		m_renderer->reload_texture((TextureResource*)old_resource, (TextureResource*)new_resource);
-	}
 }
 
 //-----------------------------------------------------------------------------

+ 7 - 4
src/FileResourceArchive.cpp

@@ -46,7 +46,7 @@ FileResourceArchive::~FileResourceArchive()
 }
 
 //-----------------------------------------------------------------------------
-FileStream* FileResourceArchive::find(ResourceId name)
+FileStream* FileResourceArchive::open(ResourceId name)
 {
 	// Convert name/type into strings
 	char resource_name[512];
@@ -62,12 +62,15 @@ FileStream* FileResourceArchive::find(ResourceId name)
 
 	FileStream* file = (FileStream*)m_filesystem.open(resource_name, SOM_READ);
 
-	/// FIXME harcoded!!!
-	file->skip(sizeof(uint32_t) * 3);
+	file->skip(sizeof(ResourceHeader));
 
 	return file;
+}
 
-	// FIXME NEED TO RELEASE MEMORY FOR file
+//-----------------------------------------------------------------------------
+void FileResourceArchive::close(FileStream* resource)
+{
+	m_filesystem.close(resource);
 }
 
 } // namespace crown

+ 17 - 1
src/FileResourceArchive.h

@@ -34,6 +34,17 @@ namespace crown
 class Filesystem;
 class FileStream;
 
+// The header of every compiled resource file.
+// KEEP IN SYNC WITH CompiledResource struct in Compiler.h!
+struct ResourceHeader
+{
+	uint32_t	magic;		// Magic number used to identify the file
+	uint32_t	version;	// Version of the compiler used to compile the resource
+	uint32_t	name;		// Name of the resource (murmur2_32 hash)
+	uint32_t	type;		// Type of the resource (murmur2_32 hash)
+	uint32_t	size;		// Size of the resource data _not_ including header (in bytes)
+};
+
 /// Source of resources
 class FileResourceArchive : public ResourceArchive
 {
@@ -42,7 +53,12 @@ public:
 					FileResourceArchive(Filesystem& fs);
 					~FileResourceArchive();
 
-	FileStream*		find(ResourceId name);
+	/// @copydoc ResourceArchive::open()
+	FileStream*		open(ResourceId name);
+
+	/// @copydoc ResourceArchive::close()
+	void			close(FileStream* resource);
+
 
 private:
 

+ 1 - 1
src/Filesystem.h

@@ -143,7 +143,7 @@ public:
 
 	/// Closes a previously opened file @stream
 	void				close(FileStream* stream);
-	
+
 private:
 
 	// Builds the OS-dependent path from base_path and relative_path

+ 14 - 10
src/Resource.h

@@ -33,17 +33,21 @@ namespace crown
 {
 
 /// Hashed values for supported resource types
-const char* const TEXTURE_EXTENSION		= "tga";
-const char* const MESH_EXTENSION		= "dae";
-const char* const SCRIPT_EXTENSION		= "lua";
-const char* const TEXT_EXTENSION		= "txt";
-const char* const MATERIAL_EXTENSION	= "material";
+const char* const TEXTURE_EXTENSION			= "tga";
+const char* const MESH_EXTENSION			= "dae";
+const char* const SCRIPT_EXTENSION			= "lua";
+const char* const TEXT_EXTENSION			= "txt";
+const char* const MATERIAL_EXTENSION		= "material";
+const char* const VERTEX_SHADER_EXTENSION	= "vs";
+const char* const PIXEL_SHADER_EXTENSION	= "ps";
 
-const uint32_t TEXTURE_TYPE		= 0x1410A16A;
-const uint32_t MESH_TYPE		= 0xE8239EEC;
-const uint32_t SCRIPT_TYPE		= 0xD96E7C37;
-const uint32_t TEXT_TYPE		= 0x9000BF0B;
-const uint32_t MATERIAL_TYPE	= 0x46807A92;
+const uint32_t TEXTURE_TYPE					= 0x1410A16A;
+const uint32_t MESH_TYPE					= 0xE8239EEC;
+const uint32_t SCRIPT_TYPE					= 0xD96E7C37;
+const uint32_t TEXT_TYPE					= 0x9000BF0B;
+const uint32_t MATERIAL_TYPE				= 0x46807A92;
+const uint32_t VERTEX_SHADER_TYPE			= 0xDC7F061F;
+const uint32_t PIXEL_SHADER_TYPE			= 0x2A461B45;
 
 /// Enumerates the loading states of a resource
 enum ResourceState

+ 10 - 1
src/ResourceArchive.h

@@ -57,7 +57,16 @@ public:
 
 	virtual					~ResourceArchive() {}
 
-	virtual FileStream*		find(ResourceId name) = 0;
+	/// Opens the resource file containing @name resource
+	/// and returns a stream from which read the data from.
+	/// @note
+	/// The resource stream points exactly at the start
+	/// of the useful resource data, so you do not have to
+	/// care about skipping headers, metadatas and so on.
+	virtual FileStream*		open(ResourceId name) = 0;
+
+	/// Closes the resource file.
+	virtual void			close(FileStream* resource) = 0;
 };
 
 } // namespace crown

+ 25 - 5
src/ResourceManager.cpp

@@ -23,14 +23,19 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
+#include <algorithm>
+#include <cstdio>
+
 #include "Types.h"
 #include "ResourceManager.h"
 #include "String.h"
 #include "Hash.h"
 #include "Path.h"
 #include "Log.h"
-#include <algorithm>
-
+#include "Device.h"
+#include "Filesystem.h"
+#include "TextReader.h"
+#include "FileStream.h"
 #include "TextResource.h"
 #include "TextureResource.h"
 #include "ScriptResource.h"
@@ -45,13 +50,27 @@ ResourceManager::ResourceManager(ResourceArchive& archive, Allocator& allocator)
 	m_resources(m_allocator),
 	m_loading_queue(m_allocator),
 	m_loaded_queue(m_allocator),
+	m_seed(0),
+	m_background_thread_should_run(true),
 	m_thread(ResourceManager::background_thread, (void*)this, "resource-loader-thread")
 {
+	FileStream* seed_file = device()->filesystem()->open("seed.ini", SOM_READ);
+	TextReader reader(*seed_file);
+
+	char tmp_buf[32];
+	reader.read_string(tmp_buf, 32);
+
+	device()->filesystem()->close(seed_file);
+
+	sscanf(tmp_buf, "%u", &m_seed);
+
+	Log::d("Seed: %d", m_seed);
 }
 
 //-----------------------------------------------------------------------------
 ResourceManager::~ResourceManager()
 {
+	m_background_thread_should_run = false;
 }
 
 //-----------------------------------------------------------------------------
@@ -63,8 +82,7 @@ ResourceId ResourceManager::load(const char* name)
 	path::filename_without_extension(name, basename, 512);
 	path::extension(name, extension, 512);
 
-	// FIXME hardcoded seed
-	uint32_t name_hash = hash::murmur2_32(basename, string::strlen(basename), 0);
+	uint32_t name_hash = hash::murmur2_32(basename, string::strlen(basename), m_seed);
 	uint32_t type_hash = hash::murmur2_32(extension, string::strlen(extension), 0);
 
 	return load(name_hash, type_hash);
@@ -282,7 +300,7 @@ ResourceId ResourceManager::load(uint32_t name, uint32_t type)
 //-----------------------------------------------------------------------------
 void ResourceManager::background_load()
 {
-	while (true)
+	while (m_background_thread_should_run)
 	{
 		m_loading_mutex.lock();
 		while (m_loading_queue.size() == 0)
@@ -383,6 +401,8 @@ void* ResourceManager::background_thread(void* thiz)
 	ResourceManager* mgr = (ResourceManager*)thiz;
 
 	mgr->background_load();
+
+	return NULL;
 }
 
 } // namespace crown

+ 9 - 6
src/ResourceManager.h

@@ -157,15 +157,18 @@ private:
 	// Resources already loaded, ready to bring online
 	Queue<LoadedResource>	m_loaded_queue;
 
+	uint32_t				m_seed;
+
 	// Background loading thread
-	Thread					m_thread;
+	bool 					m_background_thread_should_run;
+	os::Thread				m_thread;
 
-	mutable Mutex			m_loading_mutex;
-	Cond 					m_loading_requests;
-	Cond 					m_all_loaded;
+	mutable os::Mutex		m_loading_mutex;
+	os::Cond 				m_loading_requests;
+	os::Cond 				m_all_loaded;
 
-	Mutex					m_loaded_mutex;
-	mutable Mutex			m_resources_mutex;
+	os::Mutex				m_loaded_mutex;
+	mutable os::Mutex		m_resources_mutex;
 
 	friend class			Device;
 };

+ 3 - 1
src/ScriptResource.cpp

@@ -12,7 +12,7 @@ namespace crown
 //-----------------------------------------------------------------------------
 void* ScriptResource::load(Allocator& allocator, ResourceArchive& archive, ResourceId id)
 {
-	FileStream* stream = archive.find(id);
+	FileStream* stream = archive.open(id);
 
 	if (stream != NULL)
 	{
@@ -26,6 +26,8 @@ void* ScriptResource::load(Allocator& allocator, ResourceArchive& archive, Resou
 
 		stream->read(resource->m_data, size);
 
+		archive.close(stream);
+
 		return resource;
 	}
 

+ 3 - 1
src/TextResource.cpp

@@ -10,7 +10,7 @@ namespace crown
 //-----------------------------------------------------------------------------
 void* TextResource::load(Allocator& allocator, ResourceArchive& archive, ResourceId id)
 {
-	FileStream* stream = archive.find(id);
+	FileStream* stream = archive.open(id);
 
 	if (stream != NULL)
 	{
@@ -24,6 +24,8 @@ void* TextResource::load(Allocator& allocator, ResourceArchive& archive, Resourc
 		
 		resource->data[resource->length] = '\0';
 
+		archive.close(stream);
+
 		return resource;
 	}
 

+ 3 - 1
src/TextureResource.cpp

@@ -13,7 +13,7 @@ namespace crown
 //-----------------------------------------------------------------------------
 void* TextureResource::load(Allocator& allocator, ResourceArchive& archive, ResourceId id)
 {
-	FileStream* stream = archive.find(id);
+	FileStream* stream = archive.open(id);
 
 	if (stream != NULL)
 	{
@@ -29,6 +29,8 @@ void* TextureResource::load(Allocator& allocator, ResourceArchive& archive, Reso
 
 		stream->read(resource->m_data, size);
 
+		archive.close(stream);
+
 		return resource;
 	}
 

+ 1 - 1
src/TextureResource.h

@@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #include "Types.h"
 #include "Resource.h"
-#include "Pixel.h"
+#include "PixelFormat.h"
 #include "Texture.h"
 
 namespace crown

+ 161 - 0
src/core/containers/IdTable.h

@@ -0,0 +1,161 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include "Allocator.h"
+#include "Types.h"
+
+namespace crown
+{
+
+struct Id
+{
+	union
+	{
+		uint16_t id;
+		uint16_t next;
+	};
+
+	uint16_t index;
+};
+
+/// Table of Ids.
+class IdTable
+{
+public:
+
+	/// Creates the table for tracking exactly @max_ids - 1 unique Ids.
+					IdTable(Allocator& allocator, uint16_t max_ids);
+					~IdTable();
+
+	/// Returns a new Id.
+	Id				create();
+
+	/// Destroys the specified @id.
+	void			destroy(Id id);
+
+	/// Returns whether the table has the specified @id
+	bool			has(Id id) const;
+
+private:
+
+	// Returns the next available unique id.
+	uint16_t		next_id();
+
+private:
+
+	Allocator&		m_allocator;
+
+	// The maximum number of Ids the table can track.
+	// The last valid id is reserved and cannot be used to
+	// refer to Ids from the outside.
+	const uint16_t	m_max_ids;
+
+	// The index of the first unused id.
+	uint16_t		m_freelist;
+
+	// The index of the last id in the id table.
+	uint16_t		m_last_index;
+
+	// Next available unique id.
+	uint16_t		m_next_id;
+
+	// Table of ids.
+	Id*				m_ids;
+};
+
+//-----------------------------------------------------------------------------
+inline IdTable::IdTable(Allocator& allocator, uint16_t max_ids) :
+	m_allocator(allocator),
+	m_max_ids(max_ids),
+	m_freelist(max_ids),
+	m_last_index(0),
+	m_next_id(0)
+{
+	m_ids = (Id*)m_allocator.allocate(m_max_ids * sizeof(Id));
+}
+
+//-----------------------------------------------------------------------------
+inline IdTable::~IdTable()
+{
+	if (m_ids)
+	{
+		m_allocator.deallocate(m_ids);
+	}
+}
+
+//-----------------------------------------------------------------------------
+inline Id IdTable::create()
+{
+	// We have reached maximum number of ids
+	assert(m_next_id != m_max_ids);
+
+	// Obtain a new id
+	Id id;
+	id.id = next_id();
+
+	// Recycle slot if there are any
+	if (m_freelist != m_max_ids)
+	{
+		id.index = m_freelist;
+		m_freelist = m_ids[m_freelist].next;
+	}
+	else
+	{
+		id.index = m_last_index++;
+	}
+
+	m_ids[id.index] = id;
+
+	return id;
+}
+
+//-----------------------------------------------------------------------------
+inline void IdTable::destroy(Id id)
+{
+	assert(has(id));
+
+	m_ids[id.index].next = m_freelist;
+	m_freelist = id.index;
+}
+
+//-----------------------------------------------------------------------------
+inline bool IdTable::has(Id id) const
+{
+	assert (id.index < m_max_ids);
+
+	return m_ids[id.index].id == id.id;
+}
+
+//-----------------------------------------------------------------------------
+inline uint16_t IdTable::next_id()
+{
+	assert(m_next_id < m_max_ids);
+
+	return m_next_id++;
+}
+
+} // namespace crown

+ 0 - 1
src/core/streams/BinaryReader.h

@@ -33,7 +33,6 @@ class Stream;
 /// A reader that offers a convenient way to read from a Stream
 class BinaryReader
 {
-
 public:
 
 						BinaryReader(Stream& s);

+ 0 - 1
src/core/streams/BinaryWriter.h

@@ -33,7 +33,6 @@ class Stream;
 /// A writer that offers a convenient way to write to a Stream
 class BinaryWriter
 {
-
 public:
 
 						BinaryWriter(Stream& s);

+ 29 - 58
src/core/streams/FileStream.cpp

@@ -33,26 +33,16 @@ namespace crown
 
 //-----------------------------------------------------------------------------
 FileStream::FileStream(StreamOpenMode mode, const char* filename) :
-	Stream(mode), m_file(NULL),
+	Stream(mode),
 	m_last_was_read(true)
 {
-	//Takes ownership
-	FileOpenMode file_open_mode = (FileOpenMode)0;
-
-	if (math::test_bitmask(mode, SOM_READ))
-		file_open_mode = (FileOpenMode)(file_open_mode | FOM_READ);
-	if (math::test_bitmask(mode, SOM_WRITE))
-		file_open_mode = (FileOpenMode)(file_open_mode | FOM_WRITE);
-
-	m_file = File::open(filename, file_open_mode);
+	m_file.open(filename, mode);
 }
 
 //-----------------------------------------------------------------------------
 FileStream::~FileStream()
 {
-	delete m_file;
-
-	m_file = 0;
+	//m_file.close();
 }
 
 //-----------------------------------------------------------------------------
@@ -60,7 +50,7 @@ void FileStream::seek(size_t position)
 {
 	check_valid();
 
-	m_file->seek(position, SEEK_SET);
+	m_file.seek(position);
 }
 
 //-----------------------------------------------------------------------------
@@ -68,7 +58,7 @@ void FileStream::seek_to_end()
 {
 	check_valid();
 
-	m_file->seek(0, SEEK_END);
+	m_file.seek_to_end();
 }
 
 //-----------------------------------------------------------------------------
@@ -76,7 +66,7 @@ void FileStream::skip(size_t bytes)
 {
 	check_valid();
 
-	m_file->seek(bytes, SEEK_CUR);
+	m_file.skip(bytes);
 }
 
 //-----------------------------------------------------------------------------
@@ -87,15 +77,12 @@ uint8_t FileStream::read_byte()
 	if (!m_last_was_read)
 	{
 		m_last_was_read = true;
-		m_file->seek(0, SEEK_CUR);
+		m_file.seek(0);
 	}
 
 	uint8_t buffer;
-	
-	if (m_file->read(&buffer, 1, 1) != 1)
-	{
-		Log::e("Could not read from file");
-	}
+
+	assert(m_file.read(&buffer, 1));
 
 	return buffer;
 }
@@ -108,13 +95,10 @@ void FileStream::read(void* buffer, size_t size)
 	if (!m_last_was_read)
 	{
 		m_last_was_read = true;
-		m_file->seek(0, SEEK_CUR);
+		m_file.seek(0);
 	}
 
-	if (m_file->read(buffer, size, 1) != 1)
-	{
-		Log::e("Could not read from file.");
-	}
+	assert(m_file.read(buffer, size));
 }
 
 //-----------------------------------------------------------------------------
@@ -131,22 +115,22 @@ bool FileStream::copy_to(Stream* stream, size_t size)
 
 	char* buff = new char[chunksize];
 
-	size_t totReadBytes = 0;
+	size_t tot_read_bytes = 0;
 
-	while (totReadBytes < size)
+	while (tot_read_bytes < size)
 	{
-		int32_t readBytes;
-		int32_t expectedReadBytes = math::min(size - totReadBytes, chunksize);
+		size_t read_bytes;
+		size_t expected_read_bytes = math::min(size - tot_read_bytes, chunksize);
 
-		readBytes = m_file->read(buff, 1, expectedReadBytes);
+		read_bytes = m_file.read(buff, expected_read_bytes);
 
-		if (readBytes < expectedReadBytes)
+		if (read_bytes < expected_read_bytes)
 		{
-			if (m_file->eof())
+			if (m_file.eof())
 			{
-				if (readBytes != 0)
+				if (read_bytes != 0)
 				{
-					stream->write(buff, readBytes);
+					stream->write(buff, read_bytes);
 				}
 			}
 
@@ -155,8 +139,8 @@ bool FileStream::copy_to(Stream* stream, size_t size)
 			return false;
 		}
 
-		stream->write(buff, readBytes);
-		totReadBytes += readBytes;
+		stream->write(buff, read_bytes);
+		tot_read_bytes += read_bytes;
 	}
 
 	delete [] buff;
@@ -172,14 +156,7 @@ bool FileStream::end_of_stream() const
 //-----------------------------------------------------------------------------
 bool FileStream::is_valid() const
 {
-	{
-		if (!m_file)
-		{
-			return false;
-		}
-
-		return m_file->is_valid();
-	}
+	return m_file.is_open();
 }
 
 //-----------------------------------------------------------------------------
@@ -190,13 +167,10 @@ void FileStream::write_byte(uint8_t val)
 	if (m_last_was_read)
 	{
 		m_last_was_read = false;
-		m_file->seek(0, SEEK_CUR);
+		m_file.seek(0);
 	}
 
-	if (m_file->write(&val, 1, 1) != 1)
-	{
-		Log::e("Could not write to file.");
-	}
+	assert(m_file.write(&val, 1) == 1);
 }
 
 //-----------------------------------------------------------------------------
@@ -207,13 +181,10 @@ void FileStream::write(const void* buffer, size_t size)
 	if (m_last_was_read)
 	{
 		m_last_was_read = false;
-		m_file->seek(0, SEEK_CUR);
+		m_file.seek(0);
 	}
 
-	if (m_file->write(buffer, size, 1) != 1)
-	{
-		Log::e("Could not write to file.");
-	}
+	assert(m_file.write(buffer, size) == size);
 }
 
 //-----------------------------------------------------------------------------
@@ -229,7 +200,7 @@ size_t FileStream::position() const
 {
 	check_valid();
 
-	return m_file->tell();
+	return m_file.position();
 }
 
 //-----------------------------------------------------------------------------
@@ -237,7 +208,7 @@ size_t FileStream::size() const
 {
 	check_valid();
 	
-	return m_file->size();
+	return m_file.size();
 }
 
 //-----------------------------------------------------------------------------

+ 4 - 4
src/core/streams/FileStream.h

@@ -25,9 +25,10 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
+#include <cassert>
+
 #include "Stream.h"
 #include "File.h"
-#include <cassert>
 
 namespace crown
 {
@@ -37,7 +38,6 @@ namespace crown
 /// Provides common facilities to access files on disk.
 class FileStream: public Stream
 {
-
 public:
 
 	/// Opens @filename with specified @mode
@@ -94,14 +94,14 @@ public:
 
 protected:
 
-	File*			m_file;
+	File			m_file;
 	bool			m_last_was_read;
 
 protected:
 
 	inline void		check_valid() const
 	{
-		assert(m_file != NULL);
+		assert(m_file.is_open());
 	}
 };
 

+ 0 - 3
src/core/streams/MemoryStream.h

@@ -35,7 +35,6 @@ namespace crown
 
 class MemoryBuffer
 {
-
 public:
 
 						MemoryBuffer();
@@ -53,7 +52,6 @@ public:
 
 class DynamicMemoryBuffer: public MemoryBuffer
 {
-
 public:
 
 						DynamicMemoryBuffer(Allocator& allocator, size_t initial_capacity);
@@ -84,7 +82,6 @@ protected:
 /// Access memory buffers.
 class MemoryStream: public Stream
 {
-
 public:
 
 	/// @copydoc Stream::Stream()

+ 0 - 1
src/core/streams/NullStream.h

@@ -35,7 +35,6 @@ namespace crown
 /// Discards all data written to it and provides null data reading from it; plain and simple.
 class NullStream: public Stream
 {
-
 public:
 
 	/// @copydoc Stream::Stream()

+ 0 - 1
src/core/streams/TextReader.h

@@ -33,7 +33,6 @@ class Stream;
 /// A reader that offers a convenient way to read text from a Stream
 class TextReader
 {
-
 public:
 
 						TextReader(Stream& s);

+ 0 - 1
src/core/streams/TextWriter.h

@@ -31,7 +31,6 @@ class Stream;
 /// A reader that offers a convenient way to write text to a Stream
 class TextWriter
 {
-
 public:
 
 						TextWriter(Stream& s);

+ 39 - 57
src/network/BitMessage.cpp

@@ -1,15 +1,42 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
 #include <cassert>
 #include <cstring>
 
+#include "NetAddress.h"
 #include "BitMessage.h"
 
 namespace crown
 {
 namespace network
 {
-  
+
+//---------------------------------------------------------------------------------------------
 BitMessage::BitMessage(Allocator& allocator) :
-	m_allocator(&allocator),
+	m_allocator(allocator),
 	m_header(NULL),
 	m_data(NULL),
 	m_write(NULL), 
@@ -25,20 +52,19 @@ BitMessage::BitMessage(Allocator& allocator) :
 }
 
 //---------------------------------------------------------------------------------------------
-
 BitMessage::~BitMessage()
 {
 	if (m_header)
 	{
-		m_allocator->deallocate((void*)m_header);
+		m_allocator.deallocate((void*)m_header);
 	}
 	if (m_data)
 	{
-		  m_allocator->deallocate((void*)m_data);
+		  m_allocator.deallocate((void*)m_data);
 	}
 }
-//---------------------------------------------------------------------------------------------
 
+//---------------------------------------------------------------------------------------------
 uint8_t* BitMessage::get_byte_space(int32_t len)
 {
 	uint8_t *ptr;
@@ -62,7 +88,6 @@ uint8_t* BitMessage::get_byte_space(int32_t len)
 }
 
 //---------------------------------------------------------------------------------------------
-
 bool BitMessage::check_overflow(int32_t num_bits)
 {
 	assert(num_bits >= 0);
@@ -78,15 +103,15 @@ bool BitMessage::check_overflow(int32_t num_bits)
 		m_overflowed = true;
 		return true;
 	}
-	return false;  
+	return false;
 }
 
 //---------------------------------------------------------------------------------------------
 void BitMessage::init(int32_t len)
 {
-	m_header = (uint8_t*)m_allocator->allocate(12);
+	m_header = (uint8_t*)m_allocator.allocate(12);
 	
-	m_data = (uint8_t*)m_allocator->allocate(len);
+	m_data = (uint8_t*)m_allocator.allocate(len);
 	
 	m_write = m_data;
 	m_read = m_data;
@@ -169,7 +194,6 @@ size_t BitMessage::get_size() const
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::set_size(size_t size)
 {
 	if (size > m_max_size)
@@ -183,14 +207,12 @@ void BitMessage::set_size(size_t size)
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_write_bit() const
 {
 	return m_write_bit;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::set_write_bit(int32_t bit)
 {
 	m_write_bit = bit & 7;
@@ -201,21 +223,18 @@ void BitMessage::set_write_bit(int32_t bit)
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_num_bits_written() const
 {
 	return ((m_cur_size << 3) - ((8 - m_write_bit) & 7));  
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_remaining_write_bits() const
 {
 	return (m_max_size << 3) - get_num_bits_written(); 
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::save_write_state(int32_t& s,int32_t& b) const
 {
 	s = m_cur_size;
@@ -223,7 +242,6 @@ void BitMessage::save_write_state(int32_t& s,int32_t& b) const
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::restore_write_state(int32_t s,int32_t b)
 {
 	m_cur_size = s;
@@ -236,49 +254,42 @@ void BitMessage::restore_write_state(int32_t s,int32_t b)
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_read_count() const
 {
 	return m_read_count;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::set_read_count(int32_t bytes)
 {
 	m_read_count = bytes;
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_read_bit() const
 {
 	return m_read_bit;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::set_read_bit(int32_t bit)
 {
 	m_read_bit = bit & 7;
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_num_bits_read() const
 {
 	return ((m_read_count << 3) - ((8 - m_read_bit) & 7));  
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_remaining_read_bits() const
 {
 	return (m_cur_size << 3) - get_num_bits_read();
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::save_read_state(int32_t& c, int32_t& b) const
 {
 	c = m_read_count;
@@ -286,7 +297,6 @@ void BitMessage::save_read_state(int32_t& c, int32_t& b) const
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::restore_read_state(int32_t c, int32_t b)
 {
 	m_read_count = c;
@@ -294,7 +304,6 @@ void BitMessage::restore_read_state(int32_t c, int32_t b)
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::begin_writing()
 {
 	m_cur_size = 0;
@@ -303,21 +312,18 @@ void BitMessage::begin_writing()
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_remaining_space() const
 {
 	return m_max_size - m_cur_size;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_byte_align()
 {
 	m_write_bit = 0;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_bits(int32_t value, int32_t num_bits)
 {
 	int32_t		put;
@@ -399,49 +405,42 @@ void BitMessage::write_bits(int32_t value, int32_t num_bits)
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_int8(int32_t c)
 {
 	write_bits(c, -8);
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_uint8(int32_t c)
 {
 	write_bits(c, 8);  
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_int16(int32_t c)
 {
 	write_bits(c, -16);  
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_uint16(int32_t c)
 {
 	write_bits(c, 16);
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_int32(int32_t c)
 {
 	write_bits(c, 32);
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_real(real f)
 {
 	write_bits(*reinterpret_cast<int32_t *>(&f), 32);  
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_vec3(const Vec3& v)
 {
 	write_real(v.x);
@@ -450,7 +449,6 @@ void BitMessage::write_vec3(const Vec3& v)
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_string(const char* s, int32_t max_len, bool make_7_bit)
 {
 	if (!s) 
@@ -501,25 +499,22 @@ void BitMessage::write_string(const char* s, int32_t max_len, bool make_7_bit)
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_data(const void* data, int32_t length)
 {
 	memcpy(get_byte_space(length), data, length);
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::write_netaddr(const os::NetAddress addr)
 {
 	uint8_t* ptr;
 	
 	ptr = get_byte_space(4);
-	memcpy(ptr, addr.address, 4);
-	write_uint16(addr.port);
+	memcpy(ptr, addr.m_address, 4);
+	write_uint16(addr.port());
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::begin_reading() const
 {
 	m_read_count = 0;
@@ -527,21 +522,18 @@ void BitMessage::begin_reading() const
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::get_remaing_data() const
 {
 	m_cur_size - m_read_count;
 }
 
 //---------------------------------------------------------------------------------------------
-
 void BitMessage::read_byte_align() const
 {
 	m_read_bit = 0;
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_bits(int32_t num_bits) const
 {
 	int32_t		value;
@@ -616,14 +608,12 @@ int32_t BitMessage::read_bits(int32_t num_bits) const
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_int8() const
 {
 	return (int32_t)read_bits(-8);
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_uint8() const
 {
   	return (int32_t)read_bits(8);
@@ -631,28 +621,24 @@ int32_t BitMessage::read_uint8() const
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_int16() const
 {
 	return (int32_t)read_bits(-16);  
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_uint16() const
 {
 	return (int32_t)read_bits(16);  
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_int32() const
 {
 	return (int32_t)read_bits(32);
 }
 
 //---------------------------------------------------------------------------------------------
-
 real BitMessage::read_real() const
 {
 	float value;
@@ -661,7 +647,6 @@ real BitMessage::read_real() const
 }
 
 //---------------------------------------------------------------------------------------------
-
 Vec3 BitMessage::read_vec3() const
 {
 	Vec3 v;
@@ -674,7 +659,6 @@ Vec3 BitMessage::read_vec3() const
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_string(char* buffer, int32_t buffer_size) const
 {
 	int	l = 0;
@@ -710,7 +694,6 @@ int32_t BitMessage::read_string(char* buffer, int32_t buffer_size) const
 }
 
 //---------------------------------------------------------------------------------------------
-
 int32_t BitMessage::read_data(void* data, int32_t length) const
 {
 	int count;
@@ -742,13 +725,12 @@ int32_t BitMessage::read_data(void* data, int32_t length) const
 //---------------------------------------------------------------------------------------------
 void BitMessage::read_netaddr(os::NetAddress* addr) const
 {
-
 	for (int i = 0; i < 4; i++) 
 	{
-		addr->address[i] = read_uint8();
+		addr->m_address[i] = read_uint8();
 	}
 	
-	addr->port = read_uint16();  
+	addr->m_port = read_uint16();  
 }
 
 //---------------------------------------------------------------------------------------------

+ 31 - 10
src/network/BitMessage.h

@@ -1,7 +1,31 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
 #pragma once
 
 #include "Types.h"
-#include "OS.h"
 #include "Allocator.h"
 #include "Vec3.h"
 
@@ -9,15 +33,12 @@ namespace crown
 {
 namespace network
 {
-	/**
-	* bit-packet reliable message.
-	* Usage: After every instantition, must be initialized with @init(len)
-	*	TODO: rework as POD is needed; this feature provides compatibility with queue
-	*/
 
+/// Bit-packet reliable message.
+/// Usage: After every instantition, must be initialized with @init(len)
+/// TODO: rework as POD is needed; this feature provides compatibility with queue
 class BitMessage
 {
-
 public:
 						BitMessage(Allocator& allocator);
 						~BitMessage();
@@ -91,7 +112,7 @@ private:
 	
 private:
 	
-	Allocator*			m_allocator;								// memory allocator
+	Allocator&			m_allocator;								// memory allocator
 	
 	uint8_t*			m_header;
 	uint8_t*			m_data;
@@ -106,9 +127,9 @@ private:
 	mutable int32_t		m_read_bit;									// number of bits read from the last read byte
 	
 	bool 				m_overflowed;								// overflow flag
-	bool				m_init;										// is init flag
-	
+	bool				m_init;										// is init flag	
 };
+
 } // namespace network
 } // namespace crown
 

+ 158 - 0
src/os/NetAddress.h

@@ -0,0 +1,158 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include "Types.h"
+#include "OS.h"
+
+namespace crown
+{
+namespace os
+{
+
+/// OS level network address.
+class NetAddress
+{
+public:
+
+	/// Initializes the address to 127.0.0.1 and port to 1000.
+					NetAddress();
+
+	/// Initializes the address from IP address (as single elemets)
+	/// and the port number.
+					NetAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port);
+
+	
+	/// Returns the IP address as packed 32-bit integer.
+	uint32_t		address() const;
+
+	/// Returns the port number bind to the address.
+	uint16_t		port() const;
+
+	/// Sets both the IP address (packed 32-bit integer) and the port number.
+	void			set(uint32_t address, uint16_t port);
+
+	/// Sets both the IP address (as single elements) and the port number.
+	void			set(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port);
+	
+	bool			operator==(const NetAddress& addr) const;
+	NetAddress&		operator=(const NetAddress& addr);
+	
+	void			print() const;
+
+public:
+
+	uint8_t 		m_address[4];
+	uint16_t 		m_port;
+};
+
+//-----------------------------------------------------------------------------
+NetAddress::NetAddress() :
+	m_port(1000)
+{
+	m_address[0] = 127;
+	m_address[1] = 0;
+	m_address[2] = 0;
+	m_address[3] = 1;
+}
+
+//-----------------------------------------------------------------------------
+NetAddress::NetAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) :
+	m_port(port)
+{
+	m_address[0] = a;
+	m_address[1] = b;
+	m_address[2] = c;
+	m_address[3] = d;
+}
+
+//-----------------------------------------------------------------------------
+uint32_t NetAddress::address() const
+{
+	uint32_t addr = (m_address[0] << 24) | (m_address[1] << 16) | (m_address[2] << 8) | (m_address[3]);
+
+	return addr;
+}
+
+//-----------------------------------------------------------------------------
+uint16_t NetAddress::port() const
+{
+	return m_port;
+}
+
+//-----------------------------------------------------------------------------
+void NetAddress::set(uint32_t address, uint16_t port)
+{
+	m_address[0] = address >> 24;
+	m_address[1] = address >> 16;
+	m_address[2] = address >> 8;
+	m_address[3] = address;
+
+	m_port = port;
+}
+
+//-----------------------------------------------------------------------------
+void NetAddress::set(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port)
+{
+	m_address[0] = a;
+	m_address[1] = b;
+	m_address[2] = c;
+	m_address[3] = d;
+	
+	m_port = port;
+}
+
+//-----------------------------------------------------------------------------
+bool NetAddress::operator==(const NetAddress& addr) const
+{
+	return m_address[0] == addr.m_address[0] &&
+		   m_address[1] == addr.m_address[1] &&
+		   m_address[2] == addr.m_address[2] &&
+		   m_address[3] == addr.m_address[3] &&
+		   m_port == addr.m_port;
+}
+
+//-----------------------------------------------------------------------------
+NetAddress& NetAddress::operator=(const NetAddress& addr)
+{
+	m_address[0] = addr.m_address[0];
+	m_address[1] = addr.m_address[1];
+	m_address[2] = addr.m_address[2];
+	m_address[3] = addr.m_address[3];
+	
+	m_port = addr.m_port;
+	
+	return *this;
+}
+
+//-----------------------------------------------------------------------------
+void NetAddress::print() const
+{
+	os::printf("NetAddress: %i.%i.%i.%i:%i\n", m_address[0], m_address[1], m_address[2], m_address[3], m_port);
+}
+
+} // namespace os
+} // namespace crown

+ 0 - 185
src/os/OS.h

@@ -30,10 +30,6 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include <cstdarg>
 #include "Types.h"
 
-#ifdef LINUX
-	#include <pthread.h>
-#endif
-
 namespace crown
 {
 
@@ -50,23 +46,6 @@ const size_t	MAX_EVENTS = 512;
 
 const size_t	MAX_THREADS = 16;
 const size_t	MAX_MUTEXES = 16;
-
-struct OSThread
-{
-	pthread_t	thread;
-	const char*	name;
-};
-
-struct OSMutex
-{
-	pthread_mutex_t mutex;
-};
-
-struct OSCond
-{
-	pthread_cond_t cond;
-};
-
 #endif
 
 #ifdef WINDOWS
@@ -191,170 +170,6 @@ void*			open_library(const char* path);
 void			close_library(void* library);
 void*			lookup_symbol(void* library, const char* name);
 
-//-----------------------------------------------------------------------------
-// Threads
-//-----------------------------------------------------------------------------
-typedef			void* (*ThreadFunction)(void*);
-
-void			thread_create(ThreadFunction f, void* params, OSThread* thread, const char* name);
-void			thread_join(OSThread* thread);
-void			thread_detach(OSThread* thread);
-
-void			mutex_create(OSMutex* mutex);
-void			mutex_destroy(OSMutex* mutex);
-void			mutex_lock(OSMutex* mutex);
-void			mutex_unlock(OSMutex* mutex);
-void			cond_create(OSCond* cond);
-void			cond_destroy(OSCond* cond);
-void			cond_signal(OSCond* cond);
-void			cond_wait(OSCond* cond, OSMutex* mutex);
-
-//-----------------------------------------------------------------------------
-// Networking
-//-----------------------------------------------------------------------------
-struct NetAddress
-{
-	uint8_t 	address[4];
-	uint16_t 	port;
-
-	NetAddress()
-	{
-		
-	}
-	
-	NetAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t p)
-	{
-		address[0] = a;
-		address[1] = b;
-		address[2] = c;
-		address[3] = d;
-		
-		port = p;
-	}
-	
-	uint32_t get_address()
-	{
-		uint32_t addr = (address[0] << 24) | (address[1] << 16) | (address[2] << 8) | (address[3]);
-		
-		return addr;
-	}
-	
-	uint16_t get_port() const
-	{
-		return port;
-	}
-	
-	void set(uint32_t a, uint16_t p)
-	{
-		address[0] = a >> 24;
-		address[1] = a >> 16;
-		address[2] = a >> 8;
-		address[3] = a;
-
-		port = p;
-	}
-	
-	void set(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t p)
-	{
-		address[0] = a;
-		address[1] = b;
-		address[2] = c;
-		address[3] = d;
-		
-		port = p;
-	}
-	
-	bool operator==(NetAddress& addr)
-	{
-		return address[0] == addr.address[0] &&
-			   address[1] == addr.address[1] &&
-			   address[2] == addr.address[2] &&
-			   address[3] == addr.address[3] &&
-			   port == addr.port;
-	}
-	
-	NetAddress& operator=(const NetAddress& addr)
-	{
-		address[0] = addr.address[0];
-		address[1] = addr.address[1];
-		address[2] = addr.address[2];
-		address[3] = addr.address[3];
-		
-		port = addr.port;
-		
-		return *this;
-	}
-	
-	void print()
-	{
-		printf("NetAddress: %i.%i.%i.%i:%i\n", address[0], address[1], address[2], address[3], port);
-	}
-};
-
-//-----------------------------------------------------------------------------
-class UDPSocket
-{
-public:
-
-				// Constructor
-				UDPSocket();
-				// Destructor
-				~UDPSocket();
-				// Open connection
-	bool 		open(uint16_t port);
-				 // Send data through socket
-	bool 		send(NetAddress &receiver, const void* data, size_t size );
-				// Receive data through socket
-	int32_t 	receive(NetAddress &sender, void* data, size_t size);
-				// Close connection
-	void 		close();
-				// Is connection open?
-	bool 		is_open();
-
-private:
-				// Socket descriptor
-	int32_t 	m_socket;
-};
-
-//-----------------------------------------------------------------------------
-class TCPSocket
-{
-public:
-
-				// Constructor
-				TCPSocket();
-				// Destructor
-				~TCPSocket();
-				// Open connection (server side)
-	bool 		open(uint16_t port);
-				// Connect (client side)
-	bool		connect(NetAddress& destination);
-				// Close connection
-	int32_t		close();
-				// Send data through socket
-	bool 		send(const void* data, size_t size);
-				// Receive data through socket
-	int32_t		receive(void* data, size_t size);
-				// Is connection open?
-	bool 		is_open();
-				// Getter method for socket descriptor
-	int32_t 	get_socket_id();
-				// Getter method for active socket descriptor
-	int32_t 	get_active_socket_id();
-				// Setter method for socket descriptor
-
-private:
-
-	void 		set_socket_id(int32_t socket);
-				// Setter method for ative socket descriptor
-	void 		set_active_socket_id(int32_t socket);
-	
-				// Generated by ::socket
-	int32_t 	m_socket;
-			  	// Generated by ::accept
-	int32_t 	m_active_socket;
-}; 
-
 } // namespace os
 } // namespace crown
 

+ 2 - 5
src/os/android/AndroidDevice.cpp

@@ -1,7 +1,6 @@
 #include <jni.h>
 #include "Device.h"
 
-
 namespace crown
 {
 
@@ -16,15 +15,13 @@ extern "C"
 //------------------------------------------------------------------------------------
 JNIEXPORT void JNICALL Java_crown_android_CrownLib_init(JNIEnv* env, jobject obj)
 {
-	Device* device = GetDevice();
-	device->Init(0, NULL);
+	device()->init(0, NULL);
 }
 
 //------------------------------------------------------------------------------------
 JNIEXPORT void JNICALL Java_crown_android_CrownLib_shutdown(JNIEnv* env, jobject obj)
 {
-	Device* device = GetDevice();
-	device->Shutdown();
+	device()->shutdown();
 }
 
 } // namespace crown

+ 0 - 67
src/os/android/AndroidOS.cpp

@@ -266,73 +266,6 @@ void swap_buffers()
 	// not necessary
 }
 
-//-----------------------------------------------------------------------------
-void thread_create(ThreadFunction f, void* params, OSThread& thread, const char* name)
-{
-	OSThread tid;
-	tid.name = name;
-
-	// Make thread joinable
-	pthread_attr_t attr;
-	pthread_attr_init(&attr);
-	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
-	// Create thread
-	int rc = pthread_create(&tid.thread, &attr, f, (void*)params);
-
-	if (rc != 0)
-	{
-		os::printf("OS: ERROR: Unable to create the thread '%s' Error code: %d\n", name, rc);
-		exit(-1);
-	}
-
-	// Free memory
-	pthread_attr_destroy(&attr);
-
-	thread = tid;
-}
-
-//-----------------------------------------------------------------------------
-void thread_join(OSThread thread)
-{
-	pthread_join(thread.thread, NULL);
-}
-
-//-----------------------------------------------------------------------------
-void thread_detach(OSThread thread)
-{
-	pthread_detach(thread.thread);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_create(OSMutex& mutex)
-{
-	OSMutex mut;
-
-	pthread_mutex_init(&mut.mutex, NULL);
-
-	mutex = mut;
-}
-
-//-----------------------------------------------------------------------------
-void mutex_destroy(OSMutex mutex)
-{
-	pthread_mutex_destroy(&mutex.mutex);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_lock(OSMutex mutex)
-{
-	pthread_mutex_lock(&mutex.mutex);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_unlock(OSMutex mutex)
-{
-	pthread_mutex_unlock(&mutex.mutex);
-}
-
-
 //-----------------------------------------------------------------------------
 JNIEXPORT void JNICALL Java_crown_android_CrownLib_initAssetManager(JNIEnv* env, jobject obj, jobject assetManager)
 {

+ 0 - 87
src/os/android/AndroidTimer.cpp

@@ -1,87 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#include "Types.h"
-#include "Timer.h"
-#include <sys/time.h>
-
-namespace crown
-{
-
-Timer::Timer()
-{
-	Reset();
-}
-
-Timer::~Timer()
-{
-}
-
-void Timer::Reset()
-{
-	clock_gettime(CLOCK_MONOTONIC, &mCreationTime);
-}
-
-uint64_t Timer::GetMilliseconds() const
-{
-	timespec tmp;
-	clock_gettime(CLOCK_MONOTONIC, &tmp);
-	return (tmp.tv_sec - mCreationTime.tv_sec) * 1000 + (tmp.tv_nsec - mCreationTime.tv_nsec) / 1000000;
-}
-
-uint64_t Timer::GetMicroseconds() const
-{
-	timespec tmp;
-	clock_gettime(CLOCK_MONOTONIC, &tmp);
-	return (tmp.tv_sec - mCreationTime.tv_sec) * 1000000 + (tmp.tv_nsec - mCreationTime.tv_nsec) / 1000;
-}
-
-
-void Timer::StartMilliseconds()
-{
-	clock_gettime(CLOCK_MONOTONIC, &mStartTime);
-}
-
-uint64_t Timer::StopMilliseconds() const
-{
-	timespec tmp;
-	clock_gettime(CLOCK_MONOTONIC, &tmp);
-	return (tmp.tv_sec - mStartTime.tv_sec) * 1000 + (tmp.tv_nsec - mStartTime.tv_nsec) / 1000000;
-}
-
-void Timer::StartMicroseconds()
-{
-	clock_gettime(CLOCK_MONOTONIC, &mStartTime);
-}
-
-uint64_t Timer::StopMicroseconds() const
-{
-	timespec tmp;
-	clock_gettime(CLOCK_MONOTONIC, &tmp);
-	return (tmp.tv_sec - mStartTime.tv_sec) * 1000000 + (tmp.tv_nsec - mStartTime.tv_nsec) / 1000;
-}
-
-} // namespace crown
-

+ 0 - 73
src/os/android/AndroidTimer.h

@@ -1,73 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#pragma once
-
-#include <sys/time.h>
-#include "Types.h"
-
-namespace crown
-{
-
-class Timer
-{
-
-public:
-
-	//! Constructor
-	Timer();
-
-	//! Destructor
-	~Timer();
-
-	//! Returns the time (in milliseconds) elapsed since the instantiation of this class
-	uint64_t GetMilliseconds() const;
-
-	//! Returns the time (in microseconds) elapsed since the instantiation of this class
-	uint64_t GetMicroseconds() const;
-
-	//! Records the current time
-	void StartMilliseconds();
-
-	//! Returns the time (in milliseconds) elapsed since the last call to StartMilliseconds()
-	uint64_t StopMilliseconds() const;
-
-	//! Records the current time
-	void StartMicroseconds();
-
-	//! Returns the time (in microseconds) elapsed since the last call to StartMicroseconds()
-	uint64_t StopMicroseconds() const;
-
-private:
-
-	// Records the initial reference time
-	void Reset();
-
-	timespec mCreationTime;		// Time at instantiation
-	timespec mStartTime;		// Time at Start* call
-};
-
-} // namespace crown
-

+ 61 - 28
src/os/android/File.cpp

@@ -23,105 +23,138 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
+#include <cassert>
+#include <stdio.h>
+
+#include "OS.h"
 #include "File.h"
-#include "Log.h"
-#include "MathUtils.h"
 #include "AndroidOS.h"
-#include <cassert>
 
 namespace crown
 {
 
 //-----------------------------------------------------------------------------
 File::File() :
-	m_asset(NULL), m_mode(FOM_READ)
+	m_asset(NULL),
+	m_mode(SOM_READ)
 {
 }
 
 //-----------------------------------------------------------------------------
 File::~File()
+{
+	close();
+}
+
+//-----------------------------------------------------------------------------
+void File::close()
 {
 	if (m_asset != NULL)
 	{
 		AAsset_close(m_asset);
+		m_asset = NULL;
 	}
 }
 
 //-----------------------------------------------------------------------------
-bool File::is_valid()
+bool File::is_open() const
 {
 	return m_asset != NULL;
 }
 
 //-----------------------------------------------------------------------------
-FileOpenMode File::mode()
+StreamOpenMode File::mode()
 {
 	return m_mode;
 }
 
 //-----------------------------------------------------------------------------
-File* File::open(const char* path, FileOpenMode mode)
+size_t File::size() const
+{
+	assert(m_asset != NULL);
+	
+	return AAsset_getLength(m_asset);
+}
+
+//-----------------------------------------------------------------------------
+bool File::open(const char* path, StreamOpenMode mode)
 {
-	File* f = new File();
+	assert(!is_open());
 
-	f->m_asset = AAssetManager_open(os::get_android_asset_manager(), path, AASSET_MODE_RANDOM);
+	// Android assets are always read-only
+	(void) mode;
+	m_mode = SOM_READ;
 
-	if (f->m_asset == NULL)
+	m_asset = AAssetManager_open(os::get_android_asset_manager(), path, AASSET_MODE_RANDOM);
+
+	if (m_asset == NULL)
 	{
-		Log::E("File::Open: Could not open file %s", path);
-		return NULL;
+		os::printf("Could not open asset %s", path);
+
+		return false;
 	}
 
-	f->m_mode = FOM_READ;
+	return true;
+}
+
+//-----------------------------------------------------------------------------
+size_t File::read(void* data, size_t size)
+{
+	assert(m_asset != NULL);
+	assert(data != NULL);
 
-	return f;
+	return (size_t)AAsset_read(m_asset, data, size);
 }
 
 //-----------------------------------------------------------------------------
-size_t File::read(void* ptr, size_t size, size_t nmemb)
+size_t File::write(const void* data, size_t size)
 {
 	assert(m_asset != NULL);
-	assert(ptr != NULL);
+	assert(data != NULL);
 
-	return (size_t)AAsset_read(m_asset, ptr, size * nmemb);
+	os::printf("Android asset directory is read-only!");
+
+	return 0;
 }
 
 //-----------------------------------------------------------------------------
-size_t File::write(const void* ptr, size_t size, size_t nmemb)
+void File::seek(size_t position)
 {
-	Log::W("Cannot write to Android asset directory!!!");
+	assert(m_asset != NULL);
+
+	assert(AAsset_seek(m_asset, (off_t)position, SEEK_SET) != (off_t) -1);
 }
 
 //-----------------------------------------------------------------------------
-int File::seek(int32_t offset, int whence)
+void File::seek_to_end()
 {
 	assert(m_asset != NULL);
 
-	return AAsset_seek(m_asset, (off_t)offset, whence);
+	assert(AAsset_seek(m_asset, 0, SEEK_END) != (off_t) -1);
 }
 
 //-----------------------------------------------------------------------------
-int32_t File::tell()
+void File::skip(size_t bytes)
 {
 	assert(m_asset != NULL);
-	
-	return (int32_t)(AAsset_getLength(m_asset) - AAsset_getRemainingLength(m_asset));
+
+	assert(AAsset_seek(m_asset, (off_t) bytes, SEEK_CUR) != (off_t) -1);
 }
 
 //-----------------------------------------------------------------------------
-int File::eof()
+size_t File::position() const
 {
 	assert(m_asset != NULL);
 	
-	return (int)(AAsset_getRemainingLength(m_asset) == 0);
+	return (size_t) (AAsset_getLength(m_asset) - AAsset_getRemainingLength(m_asset));
 }
 
 //-----------------------------------------------------------------------------
-size_t File::size()
+bool File::eof() const
 {
 	assert(m_asset != NULL);
 	
-	return AAsset_getLength(m_asset);
+	return AAsset_getRemainingLength(m_asset) == 0;
 }
 
 } // namespace crown

+ 41 - 29
src/os/android/File.h

@@ -25,54 +25,66 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
-#include "Types.h"
 #include <sys/types.h>
 #include <android/asset_manager.h>
 
-namespace crown
-{
+#include "Types.h"
+#include "Stream.h"
 
-/**
-	Enumerates file opening modes.
-*/
-enum FileOpenMode
+namespace crown
 {
-	FOM_READ	= 1,
-	FOM_WRITE	= 2
-};
 
-/**
-	Standard C file wrapper.
-*/
+/// Android assets wrapper
 class File
 {
-
 public:
 
-						~File();
+							File();
+							~File();
 
-	bool				is_valid();
+	/// Opens the file located at @path with the given @mode.
+	bool					open(const char* path, StreamOpenMode mode);
 
-	FileOpenMode		mode();
+	/// Closes the file.
+	void					close();
 
-	size_t				read(void* ptr, size_t size, size_t nmemb);
-	size_t				write(const void* ptr, size_t size, size_t nmemb);
-	int					seek(int32_t offset, int whence);
-	int32_t				tell();
+	bool					is_open() const;
 
-	int					eof();
+	/// Return the size of the file in bytes.
+	size_t					size() const;
 
-	size_t				size();
+	/// Returs the mode used to open the file.
+	StreamOpenMode			mode();
 
-	static File*		open(const char* path, FileOpenMode mode);
+	/// Reads @size bytes from the file and stores it into @data.
+	/// Returns the number of bytes read.
+	size_t					read(void* data, size_t size);
 
-private:
+	/// Writes @size bytes of data stored in @data and returns the
+	/// number of bytes written.
+	size_t					write(const void* data, size_t size);
+
+	/// Moves the file pointer to the given @position.
+	void					seek(size_t position);
+
+	/// Moves the file pointer to the end of the file.
+	void					seek_to_end();
+
+	/// Moves the file pointer @bytes bytes ahead the current
+	/// file pointer position.
+	void					skip(size_t bytes);
 
-	AAsset*				m_asset;
-	FileOpenMode		m_mode;
+	/// Returns the position of the file pointer from the
+	/// start of the file in bytes.
+	size_t					position() const;
 
-						File();
+	/// Returns whether the file pointer is at the end of the file.
+	bool					eof() const;
+
+private:
+
+	AAsset*					m_asset;
+	StreamOpenMode			m_mode;
 };
 
 } // namespace crown
-

+ 12 - 6
src/os/linux/CMakeLists.txt

@@ -3,18 +3,24 @@ cmake_minimum_required(VERSION 2.8)
 project(crown-linux)
 
 set (LINUX_SRC
-#	EGLRenderWindow.cpp
 	GLXRenderWindow.cpp
 	LinuxOS.cpp
 	Input.cpp
-	LinuxTCPSocket.cpp
-	LinuxUDPSocket.cpp	
-	File.cpp
+	../posix/TCPSocket.cpp
+	../posix/UDPSocket.cpp	
+	../posix/File.cpp
+	../posix/Thread.cpp
+	../posix/Mutex.cpp
+	../posix/Cond.cpp
 )
 
 set (LINUX_HEADERS
-	File.h
-#	EGLRenderWindow.h
+	../posix/TCPSocket.h
+	../posix/UDPSocket.h
+	../posix/File.h
+	../posix/Thread.h
+	../posix/Mutex.h
+	../posix/Cond.h
 )
 
 link_libraries(X11 Xrandr pthread)

+ 0 - 308
src/os/linux/EGLRenderWindow.cpp

@@ -1,308 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#include "Device.h"
-#include "GLESSupport.h"
-#include "EGLRenderWindow.h"
-#include "Log.h"
-#include "Types.h"
-#include "Config.h"
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-namespace crown
-{
-
-EGLRenderWindow::EGLRenderWindow() :
-	mEGLDisplay(EGL_NO_DISPLAY),
-	mEGLContext(EGL_NO_CONTEXT),
-	mEGLWindow(EGL_NO_SURFACE)
-{
-	mXDisplay = XOpenDisplay(NULL);
-	mEGLDisplay = eglGetDisplay((EGLNativeDisplayType) mXDisplay);
-
-	eglInitialize(mEGLDisplay, NULL, NULL);
-}
-
-EGLRenderWindow::~EGLRenderWindow()
-{
-	if (mEGLDisplay != EGL_NO_DISPLAY)
-	{
-		Log::d("EGLRenderWindow::Destroy: Releasing context...");
-		if (mEGLContext != EGL_NO_CONTEXT)
-		{
-			eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-			eglDestroyContext(mEGLDisplay, mEGLContext);
-		}
-		Log::d("EGLRenderWindow::Destroy: Context released.");
-
-		if (mEGLWindow != EGL_NO_SURFACE)
-		{
-			eglDestroySurface(mEGLDisplay, mEGLWindow);
-		}
-
-		mEGLWindow = EGL_NO_SURFACE;
-		Log::d("EGLRenderWindow::Destroy: Window Destroyed.");
-
-		eglTerminate(mEGLDisplay);
-	}
-
-	if (mXDisplay)
-	{
-		XCloseDisplay(mXDisplay);
-	}
-}
-
-bool EGLRenderWindow::Create(uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint32_t depth, bool /*fullscreen*/)
-{
-	Log::d("EGLRenderWindow::Create: Creating window...");
-	if (!width || !height)
-	{
-		Log::e("Width and height must differ from 0.");
-		return false;
-	}
-
-	if (!mEGLDisplay)
-	{
-		Log::e("Unable to open a display");
-		return false;
-	}
-
-	XSetWindowAttributes winAttribs;
-	winAttribs.event_mask = FocusChangeMask | StructureNotifyMask;
-
-	mXWindow = XCreateWindow(
-				   mXDisplay, DefaultRootWindow(mXDisplay),
-				   x, y, width, height, 0,
-				   CopyFromParent, InputOutput,
-				   CopyFromParent, CWEventMask,
-				   &winAttribs);
-
-	if (!mXWindow)
-	{
-		Log::e("Unable to create the X Window.");
-		return false;
-	}
-
-	XSetWindowAttributes  xattr;
-
-	xattr.override_redirect = False;
-	XChangeWindowAttributes (mXDisplay, mXWindow, CWOverrideRedirect, &xattr);
-
-	XWMHint32_ts hint32_ts;
-	hint32_ts.input = True;
-	hint32_ts.flags = InputHint32_t;
-	XSetWMHint32_ts(mXDisplay, mXWindow, &hint32_ts);
-
-	XMapRaised(mXDisplay, mXWindow);
-	XStoreName (mXDisplay, mXWindow, "GL test" );
-
-	uint32_t bpp			= depth / 4;
-
-	const EGLint attribs[] =
-	{
-		EGL_BUFFER_SIZE, 24,
-		EGL_DEPTH_SIZE, 24,
-		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
-		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
-		EGL_NONE
-	};
-
-	EGLConfig  ecfg;
-	EGLint     num_config;
-	if (!eglChooseConfig(mEGLDisplay, attribs, &ecfg, 1, &num_config))
-	{
-		Log::e("Unable to choose config.");
-		return false;
-	}
-
-	mEGLWindow = eglCreateWindowSurface(mEGLDisplay, ecfg, mXWindow, NULL);
-	if (mEGLWindow == EGL_NO_SURFACE)
-	{
-		Log::e("Unable to create window surface.");
-		return false;
-	}
-
-	EGLint ctxattr[] =
-	{
-		EGL_CONTEXT_CLIENT_VERSION, 1,
-		EGL_NONE
-	};
-
-	mEGLContext = eglCreateContext(mEGLDisplay, ecfg, EGL_NO_CONTEXT, ctxattr);
-	if (mEGLContext == EGL_NO_CONTEXT)
-	{
-		Log::e("Unable to create context: " + Str(eglGetError()));
-		return false;
-	}
-
-	eglMakeCurrent(mEGLDisplay, mEGLWindow, mEGLWindow, mEGLContext);
-
-	EGLint w, h;
-	eglQuerySurface(mEGLDisplay, mEGLWindow, EGL_WIDTH, &w);
-	eglQuerySurface(mEGLDisplay, mEGLWindow, EGL_HEIGHT, &h);
-
-	mX = x;
-	mY = y;
-	mWidth = w;
-	mHeight = h;
-
-	mCreated = true;
-
-	Log::d("EGLRenderWindow::Create: Window created.");
-
-	return true;
-}
-
-void EGLRenderWindow::Destroy()
-{
-	if (!mCreated)
-	{
-		return;
-	}
-
-	// Main window can not be destroyed
-	if (mMain)
-	{
-		return;
-	}
-
-	if (mFull)
-	{
-		SetFullscreen(false);
-	}
-
-	mCreated = false;
-}
-
-void EGLRenderWindow::SetVisible(bool visible)
-{
-	mVisible = visible;
-}
-
-void EGLRenderWindow::Move(uint32_t x, uint32_t y)
-{
-	if (x == mX && y == mY)
-	{
-		return;
-	}
-
-	XMoveWindow(mXDisplay, mXWindow, x, y);
-}
-
-void EGLRenderWindow::Resize(uint32_t width, uint32_t height)
-{
-	if (!width || !height)
-	{
-		return;
-	}
-
-	if (width == mWidth && height == mHeight)
-	{
-		return;
-	}
-
-	XResizeWindow(mXDisplay, mXWindow, width, height);
-}
-
-void EGLRenderWindow::SetFullscreen(bool full)
-{
-	/* No action */
-}
-
-void EGLRenderWindow::Bind()
-{
-	eglMakeCurrent(mEGLDisplay, mEGLWindow, mEGLWindow, mEGLContext);
-}
-
-void EGLRenderWindow::Unbind()
-{
-	eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-}
-
-void EGLRenderWindow::Update()
-{
-	eglSwapBuffers(mEGLDisplay, mEGLWindow);
-}
-
-void EGLRenderWindow::EventLoop()
-{
-	XEvent event;
-
-	while (XPending(mXDisplay))
-	{
-		XNextEvent(mXDisplay, &event);
-
-		switch (event.type)
-		{
-			case ConfigureNotify:
-			{
-				_NotifyMetricsChange(event.xconfigure.x, event.xconfigure.y,
-										event.xconfigure.width, event.xconfigure.height);
-				break;
-			}
-			default:
-			{
-				break;
-			}
-		}
-	}
-}
-
-void EGLRenderWindow::_NotifyMetricsChange(uint32_t x, uint32_t y, uint32_t width, uint32_t height)
-{
-	if (x == mX && y == mY && width == mWidth && height == mHeight)
-	{
-		return;
-	}
-
-	XWindowAttributes attribs;
-	XGetWindowAttributes(mXDisplay, mXWindow, &attribs);
-
-	if (attribs.x == (int32_t)x && attribs.y == (int32_t)y)
-	{
-		mX = x;
-		mY = y;
-	}
-
-	if (attribs.width == (int32_t)width && attribs.height == (int32_t)height)
-	{
-		mWidth = width;
-		mHeight = height;
-	}
-}
-
-void EGLRenderWindow::_SetTitleAndAdditionalTextToWindow()
-{
-	Str tmp = GetDisplayedTitle();
-	const char* ctitle = tmp.c_str();
-	XTextProperty textProperty;
-	XStringListToTextProperty((char**)&ctitle, 1, &textProperty);
-	XSetWMName(mXDisplay, mXWindow, &textProperty);
-	XFree(textProperty.value);
-}
-
-} // namespace crown
-

+ 0 - 101
src/os/linux/EGLRenderWindow.h

@@ -1,101 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#pragma once
-
-#include "RenderWindow.h"
-#include "Types.h"
-#include "Types.h"
-#include <EGL/egl.h>
-
-namespace crown
-{
-
-class EGLRenderWindow : public RenderWindow
-{
-
-public:
-
-	//! See RenderWindow
-	EGLRenderWindow();
-
-	//! See RenderWindow
-	~EGLRenderWindow();
-
-	//! See RenderWindow
-	virtual bool Create(uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint32_t depth, bool fullscreen);
-
-	//! See RenderWindow
-	virtual void Destroy();
-
-	//! See RenderWindow
-	virtual void SetVisible(bool visible);
-
-	//! See RenderWindow
-	virtual void Move(uint32_t x, uint32_t y);
-
-	//! See RenderWindow
-	virtual void Resize(uint32_t width, uint32_t height);
-
-	//! See RenderWindow
-	virtual void SetFullscreen(bool full);
-
-	virtual void Bind();
-
-	virtual void Unbind();
-
-	//! See RenderWindow
-	virtual void Update();
-
-	virtual void EventLoop();
-
-	inline Window GetXWindow() const
-	{
-		return mXWindow;
-	}
-
-	inline EGLSurface GetEGLWindow() const
-	{
-		return mEGLWindow;
-	}
-
-private:
-
-	//! See RenderWindow
-	void _NotifyMetricsChange(uint32_t x, uint32_t y, uint32_t width, uint32_t height);
-
-	//! Sets the window's title plus the additional title text in the window
-	virtual void _SetTitleAndAdditionalTextToWindow();
-
-	Display* mXDisplay;		// X Display connection
-	Window mXWindow;		// The native X11 Window
-
-	EGLDisplay mEGLDisplay;
-	EGLContext mEGLContext;
-	EGLSurface mEGLWindow;
-};
-
-} // namespace crown
-

+ 0 - 83
src/os/linux/LinuxOS.cpp

@@ -301,88 +301,5 @@ void* lookup_symbol(void* library, const char* name)
 	return symbol;
 }
 
-//-----------------------------------------------------------------------------
-void thread_create(ThreadFunction f, void* params, OSThread* thread, const char* name)
-{
-	thread->name = name;
-
-	// Make thread joinable
-	pthread_attr_t attr;
-	pthread_attr_init(&attr);
-	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
-	// Create thread
-	int rc = pthread_create(&(thread->thread), &attr, f, (void*)params);
-
-	if (rc != 0)
-	{
-		os::printf("OS: ERROR: Unable to create the thread '%s' Error code: %d\n", name, rc);
-		exit(-1);
-	}
-
-	// Free memory
-	pthread_attr_destroy(&attr);
-}
-
-//-----------------------------------------------------------------------------
-void thread_join(OSThread* thread)
-{
-	pthread_join(thread->thread, NULL);
-}
-
-//-----------------------------------------------------------------------------
-void thread_detach(OSThread* thread)
-{
-	pthread_detach(thread->thread);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_create(OSMutex* mutex)
-{
-	pthread_mutex_init(&mutex->mutex, NULL);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_destroy(OSMutex* mutex)
-{
-	pthread_mutex_destroy(&mutex->mutex);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_lock(OSMutex* mutex)
-{
-	pthread_mutex_lock(&mutex->mutex);
-}
-
-//-----------------------------------------------------------------------------
-void mutex_unlock(OSMutex* mutex)
-{
-	pthread_mutex_unlock(&mutex->mutex);
-}
-
-//-----------------------------------------------------------------------------
-void cond_create(OSCond* cond)
-{
-	pthread_cond_init(&cond->cond, NULL);
-}
-
-//-----------------------------------------------------------------------------
-void cond_destroy(OSCond* cond)
-{
-	pthread_cond_destroy(&cond->cond);
-}
-
-//-----------------------------------------------------------------------------
-void cond_signal(OSCond* cond)
-{
-	pthread_cond_signal(&cond->cond);
-}
-
-//-----------------------------------------------------------------------------
-void cond_wait(OSCond* cond, OSMutex* mutex)
-{
-	pthread_cond_wait(&cond->cond, &mutex->mutex);
-}
-
 } // namespace os
 } // namespace crown

+ 0 - 182
src/os/linux/LinuxTCPSocket.cpp

@@ -1,182 +0,0 @@
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <cassert>
-
-#include "Types.h"
-#include "OS.h"
-
-namespace crown
-{
-namespace os
-{
-
-TCPSocket::TCPSocket()
-{
-	set_socket_id(0);
-	set_active_socket_id(0);
-}
-
-TCPSocket::~TCPSocket()
-{
-	close();
-}
-
-bool TCPSocket::open(uint16_t port)
-{
-	int32_t sd = socket(AF_INET, SOCK_STREAM, 0);
-
-	if (sd <= 0)
-	{
-		os::printf("failed to open socket\n");
-		set_socket_id(0);
-		return false;
-	}
-
-	set_socket_id(sd);
-
-	// Bind socket
-	sockaddr_in address;
-	address.sin_family = AF_INET;
-	address.sin_addr.s_addr = htonl(INADDR_ANY);
-	address.sin_port = htons(port);
-
-	if (bind(sd, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
-	{
-		os::printf("failed to bind socket\n");
-		close();
-		return false;
-	}
-
-	listen(sd, 5);
-	os::printf("listening on port %d\n", port);
-
-	sockaddr_in client;
-	uint32_t client_length = sizeof(client);
-
-	int32_t asd = accept(sd, (sockaddr*)&client, &client_length);
-	if (asd < 0)
-	{
-		os::printf("failed to accept connection\n");
-	}
-
-	set_active_socket_id(asd);
-
-	return true;  
-}
-
-bool TCPSocket::connect(NetAddress& destination)
-{
-	int32_t sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-
-	if (sd <= 0)
-	{
-		os::printf("failed to open socket\n");
-		set_socket_id(0);
-		return false;
-	}
-
-	set_socket_id(sd);
-
-	sockaddr_in address;
-	address.sin_family = AF_INET;
-	address.sin_addr.s_addr =  htonl(destination.get_address());
-	address.sin_port = htons(destination.get_port());
-
-	if (::connect(sd, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
-	{
-		os::printf("failed to connect socket\n");
-		close();
-		return false;
-	}  
-}
-
-int32_t	TCPSocket::close()
-{
-	int32_t asd = get_active_socket_id();
-	if (asd != 0)
-	{
-		::close(asd);
-		set_active_socket_id(0);  
-	}
-	int32_t sd = get_socket_id();
-	if (sd != 0)
-	{
-		::close(sd);
-		set_socket_id(0);
-	}
-}
-
-bool TCPSocket::send(const void* data, size_t size)
-{
-	assert(data);
-	assert(size > 0);
-
-	int32_t sd = get_active_socket_id();
-	if (sd <= 0)
-	{
-		set_socket_id(0);
-		set_active_socket_id(0);
-		return false;
-	}
-
-	int32_t sent_bytes = ::send(sd, (const char*)data, size, 0);
-	if (sent_bytes <= 0)
-	{
-		os::printf("Unable to send data");
-		return false;
-	}
-
-	return true;  
-}
-
-int32_t TCPSocket::receive(void* data, size_t size)
-{
-	assert(data);
-	assert(size > 0);
-
-	int32_t sd = get_active_socket_id();
-
-	if ( sd <= 0 )
-	{
-		return false;
-	}
-
-	int32_t received_bytes = ::recv(sd, (char*)data, size, 0);
-	if ( received_bytes <= 0 )
-	{
-		return 0;
-	}
-
-	return received_bytes;
-}
-
-bool TCPSocket::is_open()
-{
-	return m_active_socket != 0 || m_socket != 0;
-}
-
-int32_t	TCPSocket::get_socket_id()
-{
-	return m_socket;
-}
-
-int32_t	TCPSocket::get_active_socket_id()
-{
-	return m_active_socket;
-}
-
-void TCPSocket::set_socket_id(int32_t socket)
-{
-	m_socket = socket;
-}
-
-void TCPSocket::set_active_socket_id(int32_t socket)
-{
-	m_active_socket = socket;
-}
-		
-}
-}

+ 0 - 127
src/os/linux/LinuxUDPSocket.cpp

@@ -1,127 +0,0 @@
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <cassert>
-
-#include "Types.h"
-#include "OS.h"
-
-namespace crown
-{ 
-namespace os
-{
-
-UDPSocket::UDPSocket()
-{
-	m_socket = 0;  
-}
-UDPSocket::~UDPSocket()
-{
-	close();
-}
-
-bool UDPSocket::open(uint16_t port)
-{
-  		assert(!is_open());
-
-		m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
-		if (m_socket <= 0)
-		{
-			os::printf("Failed to create socket.\n");;
-			m_socket = 0;
-			return false;
-		}
-
-		// bind to port
-		sockaddr_in address;
-		address.sin_family = AF_INET;
-		address.sin_addr.s_addr = INADDR_ANY;
-		address.sin_port = htons(port);
-
-		if ( bind( m_socket, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
-		{
-			os::printf("Failed to bind socket\n");
-			close();
-			return false;
-		}
-
-		int32_t non_blocking = 1;
-		if (fcntl( m_socket, F_SETFL, O_NONBLOCK, non_blocking ) == -1)
-		{
-			os::printf("Failed to set non-blocking socket\n");
-			close();
-			return false;
-		}
-		
-		return true;
-}
-
-bool UDPSocket::send(NetAddress &receiver, const void* data, size_t size)
-{
-	assert(data);
-	assert(size > 0);
-
-	if (m_socket == 0)
-	{
-		return false;
-	}
-	
-	assert(receiver.address);
-	assert(receiver.port);
-
-	sockaddr_in address;
-	address.sin_family = AF_INET;
-	address.sin_addr.s_addr = htonl(receiver.get_address());
-	address.sin_port = htons(receiver.get_port());
-
-	int32_t sent_bytes = sendto(m_socket, (const char*)data, size, 0, (sockaddr*)&address, sizeof(sockaddr_in));
-
-	return sent_bytes == size;
-}
-
-int32_t UDPSocket::receive(NetAddress& sender, void* data, size_t size)
-{
-	assert(data);
-	assert(size > 0);
-
-	if (m_socket == 0)
-	{
-		return false;
-	}
-
-	sockaddr_in from;
-	socklen_t from_length = sizeof(from);
-
-	int32_t received_bytes = recvfrom(m_socket, (char*)data, size, 0, (sockaddr*)&from, &from_length);
-
-	if (received_bytes <= 0)
-	{
-			return 0;
-	}
-
-	uint32_t address = ntohl(from.sin_addr.s_addr);
-	uint16_t port = ntohs(from.sin_port);
-	
-	sender.set(address, port);
-	
-	return received_bytes;	
-}
-
-void UDPSocket::close()
-{
-	if ( m_socket != 0 )
-	{
-		::close(m_socket);
-		m_socket = 0; 
-	}
-}
-
-bool UDPSocket::is_open()
-{
-	return m_socket != 0;
-}
-
-} // namespace os
-} // namespace crown

+ 12 - 31
src/core/threads/Mutex.h → src/os/posix/Cond.cpp

@@ -23,57 +23,38 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#pragma once
-
-#include "Types.h"
-#include "OS.h"
+#include "Cond.h"
 
 namespace crown
 {
-
-class Mutex
+namespace os
 {
-public:
-
-					Mutex();
-					~Mutex();
-
-	void			lock();
-	void			unlock();
-
-private:
-
-	os::OSMutex		m_mutex;
-
-private:
-
-	friend class	Cond;
-};
 
 //-----------------------------------------------------------------------------
-inline Mutex::Mutex()
+Cond::Cond()
 {
-	memset(&m_mutex, 0, sizeof(os::OSMutex));
+	memset(&m_cond, 0, sizeof(pthread_cond_t));
 
-	os::mutex_create(&m_mutex);
+	pthread_cond_init(&m_cond, NULL);
 }
 
 //-----------------------------------------------------------------------------
-inline Mutex::~Mutex()
+Cond::~Cond()
 {
-	os::mutex_destroy(&m_mutex);
+	pthread_cond_destroy(&m_cond);
 }
 
 //-----------------------------------------------------------------------------
-inline void Mutex::lock()
+void Cond::signal()
 {
-	os::mutex_lock(&m_mutex);
+	pthread_cond_signal(&m_cond);
 }
 
 //-----------------------------------------------------------------------------
-inline void Mutex::unlock()
+void Cond::wait(Mutex& mutex)
 {
-	os::mutex_unlock(&m_mutex);
+	pthread_cond_wait(&m_cond, &(mutex.m_mutex));
 }
 
+} // namespace os
 } // namespace crown

+ 15 - 18
src/renderers/gl/GLIndexBuffer.h → src/os/posix/Cond.h

@@ -25,34 +25,31 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
+#include <pthread.h>
+
 #include "Types.h"
-#include "IndexBuffer.h"
-#include <GL/glew.h>
+#include "Mutex.h"
+#include "OS.h"
 
 namespace crown
 {
-
-class GLIndexBuffer: public IndexBuffer
+namespace os
 {
 
+class Cond
+{
 public:
 
-				GLIndexBuffer();
-				~GLIndexBuffer();
-
-	void		SetIndexData(const uint16_t* indexData, uint32_t indexCount);
-	void		SetIndexSubData(const uint16_t* indexData, uint32_t indexOffset, uint32_t indexCount);
+					Cond();
+					~Cond();
 
-	uint32_t	GetIndexCount() const { return mCount; }
-
-	void		Bind() const;
-	void		Unbind() const;
+	void			signal();
+	void			wait(Mutex& mutex);
 
 private:
-	
-	GLuint			mBufferID;
-	uint32_t		mCount;
-};
 
-}
+	pthread_cond_t	m_cond;
+};
 
+} // namespace os
+} // namespace crown

+ 63 - 44
src/os/linux/File.cpp → src/os/posix/File.cpp

@@ -23,124 +23,143 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#include "File.h"
-#include "Log.h"
-#include "MathUtils.h"
 #include <cassert>
+#include <stdio.h>
+
+#include "OS.h"
+#include "File.h"
 
 namespace crown
 {
 
 //-----------------------------------------------------------------------------
 File::File() :
-	m_file_handle(NULL), m_mode(FOM_READ)
+	m_file_handle(NULL),
+	m_mode(SOM_READ)
 {
 }
 
 //-----------------------------------------------------------------------------
 File::~File()
+{
+	close();
+}
+
+//-----------------------------------------------------------------------------
+void File::close()
 {
 	if (m_file_handle != NULL)
 	{
 		fclose(m_file_handle);
+		m_file_handle = NULL;
 	}
 }
 
 //-----------------------------------------------------------------------------
-bool File::is_valid()
+bool File::is_open() const
 {
-	return m_file_handle != 0;
+	return m_file_handle != NULL;
 }
 
 //-----------------------------------------------------------------------------
-FileOpenMode File::mode()
+StreamOpenMode File::mode()
 {
 	return m_mode;
 }
 
 //-----------------------------------------------------------------------------
-FILE* File::get_handle()
+size_t File::size() const
 {
-	return m_file_handle;
+	long pos = ftell(m_file_handle);
+
+	fseek(m_file_handle, 0, SEEK_END);
+
+	long size = ftell(m_file_handle);
+
+	fseek(m_file_handle, pos, SEEK_SET);
+
+	return (size_t) size;
 }
 
 //-----------------------------------------------------------------------------
-File* File::open(const char* path, FileOpenMode mode)
+bool File::open(const char* path, StreamOpenMode mode)
 {
-	File* f = new File();
-	f->m_file_handle = fopen(path, 
+	assert(!is_open());
 
-	/*
-		TestFlag(mode, FOM_READ) ?
-			(TestFlag(mode, FOM_WRITE) ?
-				(TestFlag(mode, FOM_CREATENEW) ? "wb+" : "rb+") : "rb") : (TestFlag(mode, FOM_WRITE) ? "wb" : "rb"));
-	*/
+	const char* c_mode = mode == SOM_READ ? "rb" : SOM_WRITE ? "wb" : "x";
 
-	math::test_bitmask(mode, FOM_READ) ?
-		(math::test_bitmask(mode, FOM_WRITE) ? "rb+" : "rb") : (math::test_bitmask(mode, FOM_WRITE) ? "wb" : "rb")); 
+	assert(c_mode[0] != 'x');
 
-	if (f->m_file_handle == NULL)
+	m_file_handle = fopen(path, c_mode);
+
+	if (m_file_handle == NULL)
 	{
-		Log::e("File::Open: Could not open file %s", path);
-		return NULL;
+		os::printf("Could not open file %s", path);
+
+		return false;
 	}
 
-	f->m_mode = mode;
+	m_mode = mode;
 
-	return f;
+	return true;
 }
 
 //-----------------------------------------------------------------------------
-size_t File::read(void* ptr, size_t size, size_t nmemb)
+size_t File::read(void* data, size_t size)
 {
 	assert(m_file_handle != NULL);
-	assert(ptr != NULL);
+	assert(data != NULL);
 
-	return fread(ptr, size, nmemb, m_file_handle);
+	return fread(data, size, 1, m_file_handle);
 }
 
 //-----------------------------------------------------------------------------
-size_t File::write(const void* ptr, size_t size, size_t nmemb)
+size_t File::write(const void* data, size_t size)
 {
 	assert(m_file_handle != NULL);
-	assert(ptr != NULL);
+	assert(data != NULL);
 
-	return fwrite(ptr, size, nmemb, m_file_handle);
+	return fwrite(data, size, 1, m_file_handle);
 }
 
 //-----------------------------------------------------------------------------
-int File::seek(int32_t offset, int whence)
+void File::seek(size_t position)
 {
 	assert(m_file_handle != NULL);
 
-	return fseek(m_file_handle, offset, whence);
+	assert(fseek(m_file_handle, (long) position, SEEK_SET) == 0);
 }
 
 //-----------------------------------------------------------------------------
-int32_t File::tell()
+void File::seek_to_end()
 {
 	assert(m_file_handle != NULL);
-	
-	return ftell(m_file_handle);
+
+	assert(fseek(m_file_handle, 0, SEEK_END) == 0);
 }
 
 //-----------------------------------------------------------------------------
-int File::eof()
+void File::skip(size_t bytes)
 {
 	assert(m_file_handle != NULL);
-	
-	return feof(m_file_handle);
+
+	assert(fseek(m_file_handle, bytes, SEEK_CUR) == 0);
 }
 
 //-----------------------------------------------------------------------------
-size_t File::size()
+size_t File::position() const
 {
-	size_t pos = ftell(m_file_handle);
-	fseek(m_file_handle, 0, SEEK_END);
-	size_t size = ftell(m_file_handle);
-	fseek(m_file_handle, pos, SEEK_SET);
+	assert(m_file_handle != NULL);
+
+	return (size_t) ftell(m_file_handle);
+}
+
+//-----------------------------------------------------------------------------
+bool File::eof() const
+{
+	assert(m_file_handle != NULL);
 
-	return size;
+	return feof(m_file_handle) != 0;
 }
 
 } // namespace crown

+ 90 - 0
src/os/posix/File.h

@@ -0,0 +1,90 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include <cstdio>
+
+#include "Types.h"
+#include "Stream.h"
+
+namespace crown
+{
+
+/// Standard C file wrapper
+class File
+{
+public:
+
+							File();
+							~File();
+
+	/// Opens the file located at @path with the given @mode.
+	bool					open(const char* path, StreamOpenMode mode);
+
+	/// Closes the file.
+	void					close();
+
+	bool					is_open() const;
+
+	/// Return the size of the file in bytes.
+	size_t					size() const;
+
+	/// Returs the mode used to open the file.
+	StreamOpenMode			mode();
+
+	/// Reads @size bytes from the file and stores it into @data.
+	/// Returns the number of bytes read.
+	size_t					read(void* data, size_t size);
+
+	/// Writes @size bytes of data stored in @data and returns the
+	/// number of bytes written.
+	size_t					write(const void* data, size_t size);
+
+	/// Moves the file pointer to the given @position.
+	void					seek(size_t position);
+
+	/// Moves the file pointer to the end of the file.
+	void					seek_to_end();
+
+	/// Moves the file pointer @bytes bytes ahead the current
+	/// file pointer position.
+	void					skip(size_t bytes);
+
+	/// Returns the position of the file pointer from the
+	/// start of the file in bytes.
+	size_t					position() const;
+
+	/// Returns whether the file pointer is at the end of the file.
+	bool					eof() const;
+
+private:
+
+	FILE*					m_file_handle;
+	StreamOpenMode			m_mode;
+};
+
+} // namespace crown
+

+ 12 - 27
src/core/threads/Cond.h → src/os/posix/Mutex.cpp

@@ -23,54 +23,39 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#pragma once
-
-#include "Types.h"
 #include "Mutex.h"
-#include "OS.h"
 
 namespace crown
 {
-
-class Cond
+namespace os
 {
-public:
-
-					Cond();
-					~Cond();
-
-	void			signal();
-	void			wait(Mutex& mutex);
-
-private:
-
-	os::OSCond		m_cond;
-};
 
 //-----------------------------------------------------------------------------
-inline Cond::Cond()
+Mutex::Mutex()
 {
-	memset(&m_cond, 0, sizeof(os::OSCond));
+	memset(&m_mutex, 0, sizeof(pthread_mutex_t));
 
-	os::cond_create(&m_cond);
+	pthread_mutex_init(&m_mutex, NULL);
 }
 
 //-----------------------------------------------------------------------------
-inline Cond::~Cond()
+Mutex::~Mutex()
 {
-	os::cond_destroy(&m_cond);
+	pthread_mutex_destroy(&m_mutex);
 }
 
 //-----------------------------------------------------------------------------
-inline void Cond::signal()
+void Mutex::lock()
 {
-	os::cond_signal(&m_cond);
+	pthread_mutex_lock(&m_mutex);
 }
 
 //-----------------------------------------------------------------------------
-inline void Cond::wait(Mutex& mutex)
+void Mutex::unlock()
 {
-	os::cond_wait(&m_cond, &mutex.m_mutex);
+	pthread_mutex_unlock(&m_mutex);
 }
 
+} // namespace os
 } // namespace crown
+

+ 15 - 21
src/renderers/gl/GLOcclusionQuery.h → src/os/posix/Mutex.h

@@ -25,38 +25,32 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
-#include "OcclusionQuery.h"
+#include <pthread.h>
+
+#include "Types.h"
+#include "OS.h"
 
 namespace crown
 {
-
-class GLOcclusionQuery : public OcclusionQuery
+namespace os
 {
 
+class Mutex
+{
 public:
 
-	//! See OcclusionQuery
-	GLOcclusionQuery();
-
-	//! See OcclusionQuery
-	~GLOcclusionQuery();
-
-	//! See OcclusionQuery
-	virtual void BeginQuery();
+						Mutex();
+						~Mutex();
 
-	//! See OcclusionQuery
-	virtual void EndQuery();
-
-	//! See OcclusionQuery
-	virtual uint32_t GetQueryResult();
-
-	//! See OcclusionQuery
-	virtual bool IsResultAvailable();
+	void				lock();
+	void				unlock();
 
 private:
 
-	GLuint	mQueryObject;
+	pthread_mutex_t		m_mutex;
+
+	friend class		Cond;
 };
 
+} // namespace os
 } // namespace crown
-

+ 216 - 0
src/os/posix/TCPSocket.cpp

@@ -0,0 +1,216 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <cassert>
+
+#include "Types.h"
+#include "OS.h"
+#include "TCPSocket.h"
+#include "NetAddress.h"
+
+namespace crown
+{
+namespace os
+{
+
+//-----------------------------------------------------------------------------
+TCPSocket::TCPSocket() :
+	m_socket(0),
+	m_active_socket(0)
+
+{
+}
+
+//-----------------------------------------------------------------------------
+TCPSocket::~TCPSocket()
+{
+	close();
+}
+
+//-----------------------------------------------------------------------------
+bool TCPSocket::open(uint16_t port)
+{
+	int sd = socket(AF_INET, SOCK_STREAM, 0);
+
+	if (sd <= 0)
+	{
+		os::printf("failed to open socket\n");
+		m_socket = 0;
+
+		return false;
+	}
+
+	m_socket = sd;
+
+	// Bind socket
+	sockaddr_in address;
+	address.sin_family = AF_INET;
+	address.sin_addr.s_addr = htonl(INADDR_ANY);
+	address.sin_port = htons(port);
+
+	if (bind(sd, (const sockaddr*) &address, sizeof(sockaddr_in)) < 0)
+	{
+		os::printf("Failed to bind socket\n");
+		close();
+
+		return false;
+	}
+
+	listen(sd, 5);
+	os::printf("Listening on port %d\n", port);
+
+	sockaddr_in client;
+	size_t client_length = sizeof(client);
+
+	int asd = accept(sd, (sockaddr*)&client, (socklen_t*)&client_length);
+
+	if (asd < 0)
+	{
+		os::printf("failed to accept connection\n");
+
+		return false;
+	}
+
+	m_active_socket = asd;
+
+	return true;
+}
+
+//-----------------------------------------------------------------------------
+bool TCPSocket::connect(const NetAddress& destination)
+{
+	int sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+
+	if (sd <= 0)
+	{
+		os::printf("Failed to open socket\n");
+		m_socket = 0;
+
+		return false;
+	}
+
+	m_socket = sd;
+
+	sockaddr_in address;
+	address.sin_family = AF_INET;
+	address.sin_addr.s_addr =  htonl(destination.address());
+	address.sin_port = htons(destination.port());
+
+	if (::connect(sd, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
+	{
+		os::printf("Failed to connect socket\n");
+		close();
+
+		return false;
+	}
+
+	return true;
+}
+
+//-----------------------------------------------------------------------------
+void TCPSocket::close()
+{
+	if (m_active_socket != 0)
+	{
+		::close(m_active_socket);
+		m_active_socket = 0;  
+	}
+
+	if (m_socket != 0)
+	{
+		::close(m_socket);
+		m_socket = 0;
+	}
+}
+
+//-----------------------------------------------------------------------------
+bool TCPSocket::send(const void* data, size_t size)
+{
+	assert(data != NULL);
+	assert(size > 0);
+
+	if (m_active_socket <= 0)
+	{
+		m_socket = 0;
+		m_active_socket = 0;
+
+		return false;
+	}
+
+	ssize_t sent_bytes = ::send(m_active_socket, (const char*) data, size, 0);
+	if (sent_bytes <= 0)
+	{
+		os::printf("Unable to send data");
+		return false;
+	}
+
+	return true;
+}
+
+//-----------------------------------------------------------------------------
+size_t TCPSocket::receive(void* data, size_t size)
+{
+	assert(data);
+	assert(size > 0);
+
+	if (m_active_socket <= 0)
+	{
+		return false;
+	}
+
+	ssize_t received_bytes = ::recv(m_active_socket, (char*) data, size, 0);
+	if (received_bytes <= 0)
+	{
+		return 0;
+	}
+
+	return received_bytes;
+}
+
+//-----------------------------------------------------------------------------
+bool TCPSocket::is_open()
+{
+	return m_active_socket != 0 || m_socket != 0;
+}
+
+//-----------------------------------------------------------------------------
+int	TCPSocket::socket_id()
+{
+	return m_socket;
+}
+
+//-----------------------------------------------------------------------------
+int	TCPSocket::active_socket_id()
+{
+	return m_active_socket;
+}
+		
+} // namespace os
+} // namespace crown

+ 30 - 30
src/os/linux/File.h → src/os/posix/TCPSocket.h

@@ -25,55 +25,55 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
-#include <cstdio>
 #include "Types.h"
 
 namespace crown
 {
-
-/**
-	Enumerates file opening modes.
-*/
-enum FileOpenMode
+namespace os
 {
-	FOM_READ	= 1,
-	FOM_WRITE	= 2
-};
 
-/**
-	Standard C file wrapper.
-*/
-class File
-{
+class NetAddress;
 
+/// OS level TCP socket.
+class TCPSocket
+{
 public:
 
-						~File();
+				TCPSocket();
+				~TCPSocket();
 
-	bool				is_valid();
+	// Open connection (server side)
+	bool 		open(uint16_t port);
 
-	FileOpenMode		mode();
+	// Connect (client side)
+	bool		connect(const NetAddress& destination);
 
-	FILE*				get_handle();
+	// Close connection
+	void		close();
 
-	size_t				read(void* ptr, size_t size, size_t nmemb);
-	size_t				write(const void* ptr, size_t size, size_t nmemb);
-	int					seek(int32_t offset, int whence);
-	int32_t				tell();
+	// Send data through socket
+	bool 		send(const void* data, size_t size);
 
-	int					eof();
+	// Receive data through socket
+	size_t		receive(void* data, size_t size);
 
-	size_t				size();
+	// Is connection open?
+	bool 		is_open();
 
-	static File*		open(const char* path, FileOpenMode mode);
+	// Getter method for socket descriptor
+	int 		socket_id();
 
-private:
+	// Getter method for active socket descriptor
+	int 		active_socket_id();
 
-	FILE*				m_file_handle;
-	FileOpenMode		m_mode;
+private:
+	
+	// Generated by ::socket
+	int 		m_socket;
 
-						File();
+	// Generated by ::accept
+	int 		m_active_socket;
 };
 
+} // namespace os
 } // namespace crown
-

+ 27 - 25
src/core/threads/Thread.h → src/os/posix/Thread.cpp

@@ -23,52 +23,54 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#pragma once
-
-#include "Types.h"
-#include "OS.h"
+#include "Thread.h"
+#include <stdlib.h>
 
 namespace crown
 {
-
-class Thread
+namespace os
 {
-public:
 
-					Thread(os::ThreadFunction f, void* args, const char* name);
-					~Thread();
-
-	void			join();
-	void			detach();
+//-----------------------------------------------------------------------------
+Thread::Thread(os::ThreadFunction f, void* params, const char* name) :
+	m_name(name)
+{
+	memset(&m_thread, 0, sizeof(pthread_t));
 
-private:
+	// Make thread joinable
+	pthread_attr_t attr;
+	pthread_attr_init(&attr);
+	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
 
-	os::OSThread	m_thread;
-};
+	// Create thread
+	int rc = pthread_create(&m_thread, &attr, f, (void*)params);
 
-//-----------------------------------------------------------------------------
-inline Thread::Thread(os::ThreadFunction f, void* args, const char* name)
-{
-	memset(&m_thread, 0, sizeof(os::OSThread));
+	if (rc != 0)
+	{
+		os::printf("Unable to create the thread '%s' Error code: %d\n", name, rc);
+		exit(-1);
+	}
 
-	os::thread_create(f, args, &m_thread, name);
+	// Free attr memory
+	pthread_attr_destroy(&attr);
 }
 
 //-----------------------------------------------------------------------------
-inline Thread::~Thread()
+Thread::~Thread()
 {
 }
 
 //-----------------------------------------------------------------------------
-inline void Thread::join()
+void Thread::join()
 {
-	os::thread_join(&m_thread);
+	pthread_join(m_thread, NULL);
 }
 
 //-----------------------------------------------------------------------------
-inline void Thread::detach()
+void Thread::detach()
 {
-	os::thread_detach(&m_thread);
+	pthread_detach(m_thread);
 }
 
+} // namespace os
 } // namespace crown

+ 16 - 17
src/renderers/OcclusionQuery.h → src/os/posix/Thread.h

@@ -25,34 +25,33 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 #pragma once
 
+#include <pthread.h>
+
 #include "Types.h"
+#include "OS.h"
 
 namespace crown
 {
-
-class OcclusionQuery
+namespace os
 {
 
-public:
-
-	//! Constructor
-	OcclusionQuery() {}
+typedef void* (*ThreadFunction)(void*);
 
-	//! Destructor
-	virtual ~OcclusionQuery() {}
+class Thread
+{
+public:
 
-	//! Begins the query
-	virtual void BeginQuery() = 0;
+					Thread(os::ThreadFunction f, void* params, const char* name);
+					~Thread();
 
-	//! Ends the query
-	virtual void EndQuery() = 0;
+	void			join();
+	void			detach();
 
-	//! Returns the number of fragments visible from the last query operation
-	virtual uint32_t GetQueryResult() = 0;
+private:
 
-	//! Returns whether result for this query is available
-	virtual bool IsResultAvailable() = 0;
+	pthread_t		m_thread;
+	const char*		m_name;
 };
 
+} // namespace os
 } // namespace crown
-

+ 161 - 0
src/os/posix/UDPSocket.cpp

@@ -0,0 +1,161 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <cassert>
+
+#include "Types.h"
+#include "OS.h"
+#include "UDPSocket.h"
+#include "NetAddress.h"
+
+namespace crown
+{ 
+namespace os
+{
+
+//-----------------------------------------------------------------------------
+UDPSocket::UDPSocket() :
+	m_socket(0)
+{
+}
+
+//-----------------------------------------------------------------------------
+UDPSocket::~UDPSocket()
+{
+	close();
+}
+
+//-----------------------------------------------------------------------------
+bool UDPSocket::open(uint16_t port)
+{
+	assert(!is_open());
+
+	m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+
+	if (m_socket <= 0)
+	{
+		os::printf("Failed to create socket.\n");
+		m_socket = 0;
+
+		return false;
+	}
+
+	// Bind to port
+	sockaddr_in address;
+	address.sin_family = AF_INET;
+	address.sin_addr.s_addr = INADDR_ANY;
+	address.sin_port = htons(port);
+
+	if (bind(m_socket, (const sockaddr*) &address, sizeof(sockaddr_in)) < 0)
+	{
+		os::printf("Failed to bind socket\n");
+		close();
+
+		return false;
+	}
+
+	int non_blocking = 1;
+
+	if (fcntl(m_socket, F_SETFL, O_NONBLOCK, non_blocking) == -1)
+	{
+		os::printf("Failed to set non-blocking socket\n");
+		close();
+
+		return false;
+	}
+	
+	return true;
+}
+
+//-----------------------------------------------------------------------------
+bool UDPSocket::send(const NetAddress &receiver, const void* data, size_t size)
+{
+	assert(is_open());
+	assert(data != NULL);
+	assert(size > 0);
+
+	sockaddr_in address;
+	address.sin_family = AF_INET;
+	address.sin_addr.s_addr = htonl(receiver.address());
+	address.sin_port = htons(receiver.port());
+
+	ssize_t sent_bytes = sendto(m_socket, (const char*) data, size, 0, (sockaddr*) &address, sizeof(sockaddr_in));
+
+	if (sent_bytes < 0)
+	{
+		return false;
+	}
+
+	return (size_t) sent_bytes == size;
+}
+
+//-----------------------------------------------------------------------------
+size_t UDPSocket::receive(NetAddress& sender, void* data, size_t size)
+{
+	assert(is_open());
+	assert(data);
+	assert(size > 0);
+
+	sockaddr_in from;
+	socklen_t from_length = sizeof(from);
+
+	ssize_t received_bytes = recvfrom(m_socket, (char*)data, size, 0, (sockaddr*)&from, &from_length);
+
+	if (received_bytes <= 0)
+	{
+		return 0;
+	}
+
+	uint32_t address = ntohl(from.sin_addr.s_addr);
+	uint16_t port = ntohs(from.sin_port);
+
+	sender.set(address, port);
+
+	return (size_t) received_bytes;
+}
+
+//-----------------------------------------------------------------------------
+void UDPSocket::close()
+{
+	if (m_socket != 0)
+	{
+		::close(m_socket);
+		m_socket = 0;
+	}
+}
+
+//-----------------------------------------------------------------------------
+bool UDPSocket::is_open()
+{
+	return m_socket != 0;
+}
+
+} // namespace os
+} // namespace crown

+ 67 - 0
src/os/posix/UDPSocket.h

@@ -0,0 +1,67 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include "Types.h"
+
+namespace crown
+{
+namespace os
+{
+
+class NetAddress;
+
+/// OS level UDP socket.
+class UDPSocket
+{
+public:
+
+				UDPSocket();
+				~UDPSocket();
+
+	// Open connection
+	bool 		open(uint16_t port);
+
+	// Send data through socket
+	bool 		send(const NetAddress& receiver, const void* data, size_t size);
+
+	// Receive data through socket
+	size_t	 	receive(NetAddress& sender, void* data, size_t size);
+
+	// Close connection
+	void 		close();
+
+	// Is connection open?
+	bool 		is_open();
+
+private:
+	
+	// Socket descriptor
+	int 	m_socket;
+};
+
+} // namespace os
+} // namespace crown

+ 0 - 92
src/os/win/WinInputManager.h

@@ -1,92 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#pragma once
-
-#include "InputManager.h"
-#include <windows.h>
-
-namespace crown
-{
-
-class WinInputManager : public InputManager
-{
-
-	friend class WinMouse;
-	friend class WinKeyboard;
-
-public:
-
-	/** @copydoc InputManager::InputManager() */
-	WinInputManager();
-
-	/** @copydoc InputManager::~InputManager() */
-	virtual ~WinInputManager();
-
-	/** @copydoc InputManager::Init() */
-	virtual void Init(const EventSource& source);
-
-	/** @copydoc InputManager::IsMouseAvailable() */
-	virtual bool IsMouseAvailable()
-	{
-		return mIsMouseAvailable;
-	}
-
-	/** @copydoc InputManager::IsKeyboardAvailable() */
-	virtual bool IsKeyboardAvailable()
-	{
-		return mIsKeyboardAvailable;
-	}
-
-	/** @copydoc InputManager::IsTouchAvailable() */
-	virtual bool IsTouchAvailable()
-	{
-		return false;
-	}
-
-	/**
-		Returns the Window Handle "attached" to this manager.
-	@return
-		The Window Handle
-	*/
-	inline unsigned int64_t GetWindowHandle()
-	{
-		return (unsigned int64_t)mWindowHandle;
-	}
-
-private:
-
-	void SetMouseAvailable(bool available) { mIsMouseAvailable = available; }
-	void SetKeyboardAvailable(bool available) { mIsKeyboardAvailable = available; }
-
-	bool mIsMouseAvailable		: 1;
-	bool mIsKeyboardAvailable	: 1;
-
-	// Win related
-	HWND mWindowHandle;
-};
-
-} // namespace crown
-

+ 3 - 23
src/renderers/IndexBuffer.h

@@ -30,28 +30,8 @@ OTHER DEALINGS IN THE SOFTWARE.
 namespace crown
 {
 
-/**
-	Represents an index buffer to stream indexes to the GPU.
-*/
-class IndexBuffer
-{
-
-public:
-
-					IndexBuffer() {}
-	virtual			~IndexBuffer() {}
-
-					//! Set the index data
-	virtual void	SetIndexData(const uint16_t* indexData, uint32_t indexCount) = 0;
-					//! Replaces a subset of the index data
-	virtual void	SetIndexSubData(const uint16_t* indexData, uint32_t indexOffset, uint32_t indexCount) = 0;
-					//! Selects the index buffer as current index buffer
-
-	virtual uint32_t	GetIndexCount() const = 0;
-
-	virtual void	Bind() const = 0;
-	virtual void	Unbind() const = 0;
-};
+// Max number of index buffers a renderer can hold.
+const uint32_t MAX_INDEX_BUFFERS = 4096;
 
-}
+} // namespace crown
 

+ 0 - 118
src/renderers/Pixel.h

@@ -1,118 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#pragma once
-
-#include "Types.h"
-
-namespace crown
-{
-
-// [0 - 2]		-> 8-bit
-// [3 - 11] 	-> 16-bit
-// [12 - 13]	-> 24-bit
-// [14 - 23]	-> 32-bit
-// [24 - 25]	-> 48-bit
-// [26 - 31]	-> 64-bit
-// [32 - 35]	-> 96-bit
-// [36 - 39]	-> 128-bit
-// 40			-> Unknown (0-bit)
-
-
-/// Enumerates pixel formats.
-enum PixelFormat
-{
-	PF_L_8 = 0,				//!< Luminance only, 8-bit
-	PF_L_16 = 3,			//!< Luminance only, 16-bit
-	PF_L_32 = 14,			//!< Luminance only, 32-bit int32_teger
-	PF_L_FLOAT_32 = 15,		//!< Luminance only, 32-bit flaoting point32_t
-
-	PF_LA_8 = 4,			//!< Luminance and alpha, 8-bit each
-	PF_LA_16 = 16,			//!< Luminance and alpha, 16-bit each
-	PF_LA_32 = 26,			//!< Luminance and alpha, 32-bit int32_teger each
-	PF_LA_FLOAT_32 = 27,	//!< Luminance and alpha, 32-bit floating point32_t each
-
-	PF_AL_8 = 5,			//!< Luminance and alpha, 8-bit each
-	PF_AL_16 = 17,			//!< Luminance and alpha, 16-bit each
-	PF_AL_32 = 28,			//!< Luminance and alpha, 32-bit int32_teger each
-	PF_AL_FLOAT_32 = 29,	//!< Luminance and alpha, 32-bit floating point32_t each
-
-	PF_RGB_8 = 12,			//!< RGB values, 8-bit each
-	PF_RGB_16 = 24,			//!< RGB values, 16-bit each
-	PF_RGB_32 = 32,			//!< RGB values, 32-bit int32_teger each
-	PF_RGB_FLOAT_32 = 33,	//!< RGB values, 32-bit floating point32_t each
-
-	PF_RGB_3_3_2 = 1,		//!< Packed 8-bit RGB values
-	PF_RGB_5_6_5 = 6,		//!< Packed 16-bit RGB values
-
-	PF_BGR_8 = 13,			//!< BGR values, 8-bit each
-	PF_BGR_16 = 25,			//!< BGR values, 16-bit each
-	PF_BGR_32 = 34,			//!< BGR values, 32-bit int32_teger each
-	PF_BGR_FLOAT_32 = 35,	//!< BGR values, 32-bit floating point32_t each
-
-	PF_BGR_2_3_3 = 2,		//!< Packed 8-bit BGR values
-	PF_BGR_5_6_5 = 7,		//!< Packed 16-bit BGR values
-
-	PF_RGBA_8 = 18,			//!< RGBA values, 8-bit each
-	PF_RGBA_16 = 30,		//!< RGBA values, 16-bit each
-	PF_RGBA_32 = 36,		//!< RGBA values, 32-bit int32_teger each
-	PF_RGBA_FLOAT_32 = 37,	//!< RGBA values, 32-bit floating point32_t each
-
-	PF_RGBA_4_4_4_4 = 8,	//!< Packed 16-bit RGBA values
-	PF_RGBA_5_5_5_1 = 9,	//!< Packed 16-bit RGBA values
-	PF_RGBA_8_8_8_8 = 19,	//!< Packed 32-bit RGBA values
-	PF_RGBA_10_10_10_2 = 20,//!< Packed 32-bit RGBA values
-
-	PF_ABGR_8 = 21,			//!< ABGR values, 8-bit each
-	PF_ABGR_16 = 31,		//!< ABGR values, 16-bit each
-	PF_ABGR_32 = 38,		//!< ABGR values, 32-bit int32_teger each
-	PF_ABGR_FLOAT_32 = 39,	//!< ABGR values, 32-bit floating point32_t each
-
-	PF_ABGR_4_4_4_4 = 10,	//!< Packed 16-bit ABGR values
-	PF_ABGR_1_5_5_5 = 11,	//!< Packed 16-bit ABGR values
-	PF_ABGR_8_8_8_8 = 22,	//!< Packed 32-bit ABGR values
-	PF_ABGR_2_10_10_10 = 23,//!< Packed 32-bit ABGR values
-
-	PF_UNKNOWN = 40
-};
-
-class Pixel
-{
-public:
-
-	/// Returns the bytes per pixel necessary to @format pixel format
-	static uint32_t bytes_per_pixel(PixelFormat format);
-
-	/// Returns the bits per pixel necessary to @format pixel format
-	static uint32_t bits_per_pixel(PixelFormat format);
-
-private:
-
-	// Disable construction
-	Pixel();
-};
-
-} // namespace crown
-

+ 16 - 19
src/renderers/Pixel.cpp → src/renderers/PixelFormat.cpp

@@ -23,14 +23,20 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#include "Pixel.h"
 #include "Types.h"
+#include "PixelFormat.h"
 
 namespace crown
 {
 
 //-----------------------------------------------------------------------------
-uint32_t Pixel::bits_per_pixel(PixelFormat format)
+size_t Pixel::bits_per_pixel(PixelFormat format)
+{
+	return bytes_per_pixel(format) * 8;
+}
+
+//-----------------------------------------------------------------------------
+size_t Pixel::bytes_per_pixel(PixelFormat format)
 {
 	switch (format)
 	{
@@ -38,7 +44,7 @@ uint32_t Pixel::bits_per_pixel(PixelFormat format)
 		case PF_RGB_3_3_2:
 		case PF_BGR_2_3_3:
 		{
-			return 8;
+			return 1;
 		}
 		case PF_L_16:
 		case PF_LA_8:
@@ -50,12 +56,12 @@ uint32_t Pixel::bits_per_pixel(PixelFormat format)
 		case PF_ABGR_4_4_4_4:
 		case PF_ABGR_1_5_5_5:
 		{
-			return 16;
+			return 2;
 		}
 		case PF_RGB_8:
 		case PF_BGR_8:
 		{
-			return 24;
+			return 3;
 		}
 		case PF_L_32:
 		case PF_L_FLOAT_32:
@@ -68,12 +74,12 @@ uint32_t Pixel::bits_per_pixel(PixelFormat format)
 		case PF_ABGR_8_8_8_8:
 		case PF_ABGR_2_10_10_10:
 		{
-			return 32;
+			return 4;
 		}
 		case PF_RGB_16:
 		case PF_BGR_16:
 		{
-			return 48;
+			return 6;
 		}
 		case PF_LA_32:
 		case PF_LA_FLOAT_32:
@@ -82,26 +88,23 @@ uint32_t Pixel::bits_per_pixel(PixelFormat format)
 		case PF_RGBA_16:
 		case PF_ABGR_16:
 		{
-			return 64;
+			return 8;
 		}
 		case PF_RGB_32:
 		case PF_RGB_FLOAT_32:
 		case PF_BGR_32:
 		case PF_BGR_FLOAT_32:
 		{
-			return 96;
+			return 12;
 		}
 		case PF_RGBA_32:
 		case PF_RGBA_FLOAT_32:
 		case PF_ABGR_32:
 		case PF_ABGR_FLOAT_32:
 		{
-			return 128;
+			return 16;
 		}
 		case PF_UNKNOWN:
-		{
-			return 0;
-		}
 		default:
 		{
 			return 0;
@@ -109,11 +112,5 @@ uint32_t Pixel::bits_per_pixel(PixelFormat format)
 	}
 }
 
-//-----------------------------------------------------------------------------
-uint32_t Pixel::bytes_per_pixel(PixelFormat format)
-{
-	return bits_per_pixel(format) / 8;
-}
-
 } // namespace crown
 

+ 118 - 0
src/renderers/PixelFormat.h

@@ -0,0 +1,118 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include "Types.h"
+
+namespace crown
+{
+
+// [0 - 2]		-> 8-bit
+// [3 - 11] 	-> 16-bit
+// [12 - 13]	-> 24-bit
+// [14 - 23]	-> 32-bit
+// [24 - 25]	-> 48-bit
+// [26 - 31]	-> 64-bit
+// [32 - 35]	-> 96-bit
+// [36 - 39]	-> 128-bit
+// 40			-> Unknown (0-bit)
+
+
+/// Enumerates pixel formats.
+enum PixelFormat
+{
+	PF_L_8 = 0,				///< Luminance only, 8-bit
+	PF_L_16 = 3,			///< Luminance only, 16-bit
+	PF_L_32 = 14,			///< Luminance only, 32-bit integer
+	PF_L_FLOAT_32 = 15,		///< Luminance only, 32-bit flaoting point
+
+	PF_LA_8 = 4,			///< Luminance and alpha, 8-bit each
+	PF_LA_16 = 16,			///< Luminance and alpha, 16-bit each
+	PF_LA_32 = 26,			///< Luminance and alpha, 32-bit integer each
+	PF_LA_FLOAT_32 = 27,	///< Luminance and alpha, 32-bit floating point each
+
+	PF_AL_8 = 5,			///< Luminance and alpha, 8-bit each
+	PF_AL_16 = 17,			///< Luminance and alpha, 16-bit each
+	PF_AL_32 = 28,			///< Luminance and alpha, 32-bit integer each
+	PF_AL_FLOAT_32 = 29,	///< Luminance and alpha, 32-bit floating point each
+
+	PF_RGB_8 = 12,			///< RGB values, 8-bit each
+	PF_RGB_16 = 24,			///< RGB values, 16-bit each
+	PF_RGB_32 = 32,			///< RGB values, 32-bit integer each
+	PF_RGB_FLOAT_32 = 33,	///< RGB values, 32-bit floating point each
+
+	PF_RGB_3_3_2 = 1,		///< Packed 8-bit RGB values
+	PF_RGB_5_6_5 = 6,		///< Packed 16-bit RGB values
+
+	PF_BGR_8 = 13,			///< BGR values, 8-bit each
+	PF_BGR_16 = 25,			///< BGR values, 16-bit each
+	PF_BGR_32 = 34,			///< BGR values, 32-bit integer each
+	PF_BGR_FLOAT_32 = 35,	///< BGR values, 32-bit floating point each
+
+	PF_BGR_2_3_3 = 2,		///< Packed 8-bit BGR values
+	PF_BGR_5_6_5 = 7,		///< Packed 16-bit BGR values
+
+	PF_RGBA_8 = 18,			///< RGBA values, 8-bit each
+	PF_RGBA_16 = 30,		///< RGBA values, 16-bit each
+	PF_RGBA_32 = 36,		///< RGBA values, 32-bit integer each
+	PF_RGBA_FLOAT_32 = 37,	///< RGBA values, 32-bit floating point each
+
+	PF_RGBA_4_4_4_4 = 8,	///< Packed 16-bit RGBA values
+	PF_RGBA_5_5_5_1 = 9,	///< Packed 16-bit RGBA values
+	PF_RGBA_8_8_8_8 = 19,	///< Packed 32-bit RGBA values
+	PF_RGBA_10_10_10_2 = 20,///< Packed 32-bit RGBA values
+
+	PF_ABGR_8 = 21,			///< ABGR values, 8-bit each
+	PF_ABGR_16 = 31,		///< ABGR values, 16-bit each
+	PF_ABGR_32 = 38,		///< ABGR values, 32-bit integer each
+	PF_ABGR_FLOAT_32 = 39,	///< ABGR values, 32-bit floating point each
+
+	PF_ABGR_4_4_4_4 = 10,	///< Packed 16-bit ABGR values
+	PF_ABGR_1_5_5_5 = 11,	///< Packed 16-bit ABGR values
+	PF_ABGR_8_8_8_8 = 22,	///< Packed 32-bit ABGR values
+	PF_ABGR_2_10_10_10 = 23,///< Packed 32-bit ABGR values
+
+	PF_UNKNOWN = 40
+};
+
+class Pixel
+{
+public:
+
+	/// Returns the bytes occupied by @format
+	static size_t bytes_per_pixel(PixelFormat format);
+
+	/// Returns the bits occupied by @format
+	static size_t bits_per_pixel(PixelFormat format);
+
+private:
+
+	// Disable construction
+	Pixel();
+};
+
+} // namespace crown
+

+ 36 - 0
src/renderers/RenderBuffer.h

@@ -0,0 +1,36 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+#include "Types.h"
+
+namespace crown
+{
+
+// Max number of textures a renderer can hold.
+const uint32_t MAX_RENDER_BUFFERS = 32;
+
+} // namespace crown

+ 104 - 71
src/renderers/Renderer.h

@@ -28,9 +28,14 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include "Types.h"
 #include "Color4.h"
 #include "Mat4.h"
-#include "Point2.h"
-#include "Material.h"
+#include "VertexBuffer.h"
+#include "IndexBuffer.h"
+#include "RenderBuffer.h"
 #include "Texture.h"
+#include "Material.h"
+#include "PixelFormat.h"
+#include "VertexFormat.h"
+#include "IdTable.h"
 
 namespace crown
 {
@@ -58,12 +63,10 @@ enum LightType
 	LT_SPOT			= 2
 };
 
-enum DrawMode
-{
-	DM_NO_DRAW		= 0,
-	DM_BORDER		= 1,
-	DM_FILL			= 2
-};
+typedef Id VertexBufferId;
+typedef Id IndexBufferId;
+typedef Id RenderBufferId;
+typedef Id TextureId;
 
 class Renderer
 {
@@ -72,118 +75,148 @@ public:
 	Renderer() {}
 	virtual ~Renderer() {}
 
+	/// Creates a new vertex buffer optimized for rendering static vertex data.
+	/// @vertices is the array containig @count vertex data elements of the given @format.
+	virtual VertexBufferId	create_vertex_buffer(size_t count, VertexFormat format, const void* vertices) = 0;
+
+	/// Creates a new vertex buffer optimized for rendering dynamic vertex data.
+	/// @vertices is the array containig @count vertex data elements of the given @format.
+	virtual VertexBufferId	create_dynamic_vertex_buffer(size_t count, VertexFormat format, const void* vertices) = 0;
+
+	/// Updates the data associated with the given vertex buffer @id.
+	/// @vertices is the array containig @count vertex data elements of the format
+	/// specified at the creation of the buffer.
+	/// @note
+	/// @count and @offset together do not have to exceed the number of elements specified
+	/// at the creation of the buffer.	
+	virtual void			update_vertex_buffer(VertexBufferId id, size_t offset, size_t count, const void* vertices) = 0;
+
+	/// Destroys the @id vertex buffer.
+	virtual void			destroy_vertex_buffer(VertexBufferId id) = 0;
+
+	/// Creates a new index buffer optimized for rendering static index buffers.
+	/// @indices is the array containing @count index data elements.
+	virtual IndexBufferId	create_index_buffer(size_t count, const void* indices) = 0;
+
+	/// Destroys the @id index buffer.
+	virtual void			destroy_index_buffer(IndexBufferId id) = 0;
+
+	virtual TextureId		create_texture(uint32_t width, uint32_t height, PixelFormat format, const void* data) = 0;
+	virtual void			update_texture(TextureId id, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const void* data) = 0;
+	virtual void			destroy_texture(TextureId id) = 0;
+
+	//virtual RenderBufferId	create_render_buffer(uint32_t width, uint32_t height, PixelFormat format) = 0;
+	//virtual void			destroy_render_buffer(RenderBufferId id) = 0;
+
 	///	Tasks to perform before a frame is rendered.
-	virtual void begin_frame() = 0;
+	virtual void			begin_frame() = 0;
 
 	/// Tasks to perform after a frame is rendered.
-	virtual void end_frame() = 0;
+	virtual void			end_frame() = 0;
 
 	/// Sets the clearing color of the framebuffer.
-	virtual void set_clear_color(const Color4& color) = 0;
+	virtual void			set_clear_color(const Color4& color) = 0;
 
-	virtual void set_material_params(const Color4& ambient, const Color4& diffuse, const Color4& specular,
-					const Color4& emission, int32_t shininess) = 0;
+	virtual void			set_material_params(const Color4& ambient, const Color4& diffuse, const Color4& specular,
+												const Color4& emission, int32_t shininess) = 0;
 
 	
 	/// Sets whether lighting is enabled.
-	virtual void set_lighting(bool lighting) = 0;
+	virtual void			set_lighting(bool lighting) = 0;
 
 	/// Sets the global ambient light @color.
-	virtual void set_ambient_light(const Color4& color) = 0;
-
-	/// Set whether the given texture @unit is enabled.
-	virtual void set_texturing(uint32_t unit, bool texturing) = 0;
+	virtual void			set_ambient_light(const Color4& color) = 0;
 
 	//! Sets the texture to use in the specified layer
-	virtual void set_texture(uint32_t layer, TextureId texture) = 0;
+	virtual void			bind_texture(uint32_t layer, TextureId texture) = 0;
+
+	/// Set whether the given texture @unit is enabled.
+	virtual void			set_texturing(uint32_t unit, bool texturing) = 0;
 
 	/// Sets the texture @mode for the given texture @unit.
-	virtual void set_texture_mode(uint32_t unit, TextureMode mode, const Color4& blendColor) = 0;
+	virtual void			set_texture_mode(uint32_t unit, TextureMode mode, const Color4& blendColor) = 0;
 
 	/// Sets the texture @wrap parameter for the given texture @unit.
-	virtual void set_texture_wrap(uint32_t unit, TextureWrap wrap) = 0;
+	virtual void			set_texture_wrap(uint32_t unit, TextureWrap wrap) = 0;
 
 	/// Sets the @filter for the given texture @unit.
-	virtual void set_texture_filter(uint32_t unit, TextureFilter filter) = 0;
+	virtual void			set_texture_filter(uint32_t unit, TextureFilter filter) = 0;
 
-	virtual void set_light(uint32_t light, bool active) = 0;
-	virtual void set_light_params(uint32_t light, LightType type, const Vec3& position) = 0;
-	virtual void set_light_color(uint32_t light, const Color4& ambient, const Color4& diffuse, const Color4& specular) = 0;
-	virtual void set_light_attenuation(uint32_t light, float constant, float linear, float quadratic) = 0;
+	virtual void			set_light(uint32_t light, bool active) = 0;
+	virtual void			set_light_params(uint32_t light, LightType type, const Vec3& position) = 0;
+	virtual void			set_light_color(uint32_t light, const Color4& ambient, const Color4& diffuse, const Color4& specular) = 0;
+	virtual void			set_light_attenuation(uint32_t light, float constant, float linear, float quadratic) = 0;
 
 	/// Sets whether backface-culling is enabled.
-	virtual void set_backface_culling(bool culling) = 0;
+	virtual void			set_backface_culling(bool culling) = 0;
 
 	/// Sets whether separate specular color is enabled.	
-	virtual void set_separate_specular_color(bool separate) = 0;
+	virtual void			set_separate_specular_color(bool separate) = 0;
 
 	/// Sets whether depth test is enabled.
-	virtual void set_depth_test(bool test) = 0;
+	virtual void			set_depth_test(bool test) = 0;
 
 	/// Sets whether writing to depth buffer is enabled.
-	virtual void set_depth_write(bool write) = 0;
+	virtual void			set_depth_write(bool write) = 0;
 
 	/// Sets the depth function to use when testing depth values.
-	virtual void set_depth_func(CompareFunction func) = 0;
+	virtual void			set_depth_func(CompareFunction func) = 0;
 
 	///	Sets whether normal vectors are scaled after transformations
 	///	and before lighting.
 	/// @note
 	///	If the modelview matrix scales space uniformly, this
 	///	has the effect of restoring the trasformed normal to unit length.
-	virtual void set_rescale_normals(bool rescale) = 0;
+	virtual void			set_rescale_normals(bool rescale) = 0;
 
 	/// Sets whether blending is enabled.
-	virtual void set_blending(bool blending) = 0;
+	virtual void			set_blending(bool blending) = 0;
 
 	///	Specifies blending parameters.
 	/// @note
 	///	This method specifies the blend equation, the blend function
 	///	for source and destination pixel values and a const blend color.
-	virtual void set_blending_params(BlendEquation equation, BlendFunction src, BlendFunction dst, const Color4& color) = 0;
+	virtual void			set_blending_params(BlendEquation equation, BlendFunction src, BlendFunction dst, const Color4& color) = 0;
 
 	/// Sets whether writing to color buffer is enabled.
-	virtual void set_color_write(bool write) = 0;
+	virtual void			set_color_write(bool write) = 0;
 
 	/// Sets whether fog is enabled.
-	virtual void set_fog(bool fog) = 0;
+	virtual void			set_fog(bool fog) = 0;
 
 	/// Specifies fog parameters.
-	virtual void set_fog_params(FogMode mode, float density, float start, float end, const Color4& color) = 0;
-
-	virtual void set_alpha_test(bool test) = 0;
-
-	virtual void set_alpha_params(CompareFunction func, float ref) = 0;
-
-	virtual void set_shading_type(ShadingType type) = 0;
-
-	virtual void set_polygon_mode(PolygonMode mode) = 0;
-
-	virtual void set_front_face(FrontFace face) = 0;
-
-	virtual void set_viewport_params(int32_t x, int32_t y, int32_t width, int32_t height) = 0;
-	virtual void get_viewport_params(int32_t& x, int32_t& y, int32_t& width, int32_t& height) = 0;
-
-	virtual void set_scissor(bool scissor) = 0;
-	virtual void set_scissor_params(int32_t x, int32_t y, int32_t width, int32_t height) = 0;
-	virtual void get_scissor_params(int32_t& x, int32_t& y, int32_t& width, int32_t& height) = 0;
-
-	virtual void set_point_sprite(bool sprite) = 0;
-	virtual void set_point_size(float size) = 0;
-	virtual void set_point_params(float min, float max) = 0;
-
-	virtual Mat4 get_matrix(MatrixType type) const = 0;
-	virtual void set_matrix(MatrixType type, const Mat4& matrix) = 0;
-
-	virtual void draw_vertex_index_buffer(const VertexBuffer* vertices, const IndexBuffer* indices) = 0;
-	virtual void draw_point_buffer(const VertexBuffer* buffer) = 0;
-
-	virtual void draw_lines(const float* vertices, const float* colors, uint32_t count) = 0;
-	virtual void draw_triangles(const float* vertices, const float* normals, const float* uvs, const uint16_t* indices, uint32_t count) = 0;
-
-	virtual TextureId	load_texture(TextureResource* texture) = 0;
-	virtual void		unload_texture(TextureResource* texture) = 0;
-	virtual TextureId	reload_texture(TextureResource* old_texture, TextureResource* new_texture) = 0;
+	virtual void			set_fog_params(FogMode mode, float density, float start, float end, const Color4& color) = 0;
+
+	virtual void			set_alpha_test(bool test) = 0;
+
+	virtual void			set_alpha_params(CompareFunction func, float ref) = 0;
+
+	virtual void			set_shading_type(ShadingType type) = 0;
+
+	virtual void 			set_polygon_mode(PolygonMode mode) = 0;
+				
+	virtual void 			set_front_face(FrontFace face) = 0;
+				
+	virtual void 			set_viewport_params(int32_t x, int32_t y, int32_t width, int32_t height) = 0;
+	virtual void 			get_viewport_params(int32_t& x, int32_t& y, int32_t& width, int32_t& height) = 0;
+				
+	virtual void 			set_scissor(bool scissor) = 0;
+	virtual void 			set_scissor_params(int32_t x, int32_t y, int32_t width, int32_t height) = 0;
+	virtual void 			get_scissor_params(int32_t& x, int32_t& y, int32_t& width, int32_t& height) = 0;
+				
+	virtual void 			set_point_sprite(bool sprite) = 0;
+	virtual void 			set_point_size(float size) = 0;
+	virtual void 			set_point_params(float min, float max) = 0;
+				
+	virtual Mat4 			get_matrix(MatrixType type) const = 0;
+	virtual void 			set_matrix(MatrixType type, const Mat4& matrix) = 0;
+				
+	virtual void 			bind_vertex_buffer(VertexBufferId vb) const = 0;
+	//virtual void bind_render_buffer(RenderBufferId id) const = 0;
+				
+	virtual void 			draw_triangles(IndexBufferId id) const = 0;
+				
+	virtual void 			draw_lines(const float* vertices, const float* colors, uint32_t count) = 0;
 };
 
 } // namespace crown

+ 3 - 6
src/renderers/Texture.h

@@ -30,6 +30,9 @@ OTHER DEALINGS IN THE SOFTWARE.
 namespace crown
 {
 
+// Max number of textures a renderer can hold.
+const uint32_t MAX_TEXTURES = 4096;
+
 enum TextureMode
 {
 	TM_MODULATE	= 0,	// Multiplies texel color by the geometry color after lighting
@@ -61,10 +64,4 @@ enum TextureWrap
 	TW_COUNT
 };
 
-struct TextureId
-{
-	uint16_t	index;
-	uint16_t	id;
-};
-
 } // namespace crown

+ 4 - 32
src/renderers/VertexBuffer.h

@@ -30,6 +30,9 @@ OTHER DEALINGS IN THE SOFTWARE.
 namespace crown
 {
 
+// Max number of vertex buffers a renderer can hold.
+const uint32_t MAX_VERTEX_BUFFERS = 4096;
+
 enum VertexBufferMode
 {
 	VBM_VERTEX_ONLY		= 0,
@@ -38,36 +41,5 @@ enum VertexBufferMode
 	VBM_COLOR_COORDS	= 4
 };
 
-/**
-	Represents a vertex buffer to stream vertexes to the GPU.
-*/
-class VertexBuffer
-{
-
-public:
-
-						VertexBuffer() : mMode(VBM_VERTEX_ONLY) {}
-	virtual				~VertexBuffer() { }
-
-	inline bool			HasTextureCoords() const { return (mMode & VBM_TEXTURE_COORDS) != 0; }
-	inline bool			HasNormalCoords() const { return (mMode & VBM_NORMAL_COORDS) != 0; }
-	inline bool			HasColorCoords() const { return (mMode & VBM_COLOR_COORDS) != 0; }
-
-						//! Set the vertex data, the order of coordinates is Vertex, [Normals], [Texture], [Color]
-	virtual void		SetVertexData(VertexBufferMode mode, const void* vertexData, uint32_t vertexCount) = 0;
-						//! Replaces a subset of the vertex data, the order of coordinates is Vertex, [Normals], [Texture], [Color]
-	virtual void		SetVertexSubData(const void* vertexData, uint32_t vertexOffset, uint32_t vertexCount) = 0;
-
-	virtual uint32_t		GetSize() const = 0;			//!< Returns the size of the buffer
-	virtual uint32_t		GetVertexCount() const = 0;		//!< Returns the number of vertices in the buffer
-
-	virtual void		Bind() const = 0;
-	virtual void		Unbind() const = 0;
-
-protected:
-	
-	VertexBufferMode	mMode;
-};
-
-}
+} // namespace crown
 

+ 26 - 31
src/os/win/WinInputManager.cpp → src/renderers/VertexFormat.cpp

@@ -23,48 +23,43 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#include "WinInputManager.h"
-#include "WinMouse.h"
-#include "WinKeyboard.h"
+#include "Types.h"
+#include "VertexFormat.h"
 
 namespace crown
 {
 
 //-----------------------------------------------------------------------------
-WinInputManager::WinInputManager() :
-	mIsMouseAvailable(false),
-	mIsKeyboardAvailable(false),
-	mWindowHandle(0)
+size_t Vertex::bits_per_vertex(VertexFormat format)
 {
+	return bytes_per_vertex(format) * 8;
 }
 
 //-----------------------------------------------------------------------------
-WinInputManager::~WinInputManager()
+size_t Vertex::bytes_per_vertex(VertexFormat format)
 {
-	if (mMouse)
+	switch (format)
 	{
-		delete mMouse;
-	}
-
-	if (mKeyboard)
-	{
-		delete mKeyboard;
-	}
-}
-
-//-----------------------------------------------------------------------------
-void WinInputManager::Init(const EventSource& source)
-{
-	mWindowHandle = (HWND)source.WindowHandle;
-
-	if (!mMouse)
-	{
-		mMouse = new WinMouse(this);
-	}
-
-	if (!mKeyboard)
-	{
-		mKeyboard = new WinKeyboard(this);
+		case VF_XY_FLOAT_32:
+		case VF_UV_FLOAT_32:
+		{
+			return 8;
+		}
+		case VF_XYZ_FLOAT_32:
+		case VF_UVT_FLOAT_32:
+		case VF_XYZ_NORMAL_FLOAT_32:
+		{
+			return 12;
+		}
+		case VF_XYZ_UV_XYZ_NORMAL_FLOAT_32:
+		{
+			return 32;
+		}
+		case VF_UNKNOWN:
+		default:
+		{
+			return 0;
+		}
 	}
 }
 

+ 63 - 0
src/renderers/VertexFormat.h

@@ -0,0 +1,63 @@
+/*
+Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
+
+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.
+*/
+
+#pragma once
+
+namespace crown
+{
+
+/// Enumerates vertex formats.
+enum VertexFormat
+{
+	VF_XY_FLOAT_32,					///< XY coordinates, 32-bit floating point each
+	VF_XYZ_FLOAT_32,				///< XYZ coordinates, 32-bit floating point each
+
+	VF_UV_FLOAT_32,					///< UV coordinates, 32-bit floating point each
+	VF_UVT_FLOAT_32,				///< UVT coordinates, 32-bit floating point each
+
+	VF_XYZ_NORMAL_FLOAT_32,			///< XYZ normal coordinates, 32-bit floating point each
+
+	VF_XYZ_UV_XYZ_NORMAL_FLOAT_32,	///< XYZ coordinates, UV coordinates, XYZ normal coordinates, 32-bit floating point each
+
+	VF_UNKNOWN
+};
+
+class Vertex
+{
+public:
+
+	/// Returns the bytes occupied by @format
+	static size_t bytes_per_vertex(VertexFormat format);
+
+	/// Returns the bits occupied by @format
+	static size_t bits_per_vertex(VertexFormat format);
+
+private:
+
+	// Disable construction
+	Vertex();
+};
+
+} // namespace crown

+ 0 - 6
src/renderers/gl/CMakeLists.txt

@@ -3,19 +3,13 @@ cmake_minimum_required(VERSION 2.8)
 project(crown-gl)
 
 set (GL_SRC
-	GLIndexBuffer.cpp
-	GLOcclusionQuery.cpp
 	GLRenderer.cpp
 	GLUtils.cpp
-	GLVertexBuffer.cpp
 )
 
 set (GL_HEADERS
-	GLIndexBuffer.h
-	GLOcclusionQuery.h
 	GLRenderer.h
 	GLUtils.h
-	GLVertexBuffer.h
 )
 
 link_libraries(GL GLEW)

+ 0 - 67
src/renderers/gl/GLIndexBuffer.cpp

@@ -1,67 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#include "GLIndexBuffer.h"
-#include <GL/glew.h>
-#include "Types.h"
-
-namespace crown
-{
-
-GLIndexBuffer::GLIndexBuffer()
-{
-	glGenBuffers(1, &mBufferID);
-}
-
-GLIndexBuffer::~GLIndexBuffer()
-{
-	glDeleteBuffers(1, &mBufferID);
-}
-
-void GLIndexBuffer::SetIndexData(const uint16_t* indexData, uint32_t indexCount)
-{
-	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID);
-	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(uint16_t), indexData, GL_DYNAMIC_DRAW);
-	mCount = indexCount;
-}
-
-void GLIndexBuffer::SetIndexSubData(const uint16_t* indexData, uint32_t indexOffset, uint32_t indexCount)
-{
-	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID);
-	glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, indexOffset * sizeof(uint16_t), indexCount * sizeof(uint16_t), indexData);
-}
-
-void GLIndexBuffer::Bind() const
-{
-	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID);
-}
-
-void GLIndexBuffer::Unbind() const
-{
-	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
-}
-
-}
-

+ 0 - 72
src/renderers/gl/GLOcclusionQuery.cpp

@@ -1,72 +0,0 @@
-/*
-Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
-
-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.
-*/
-
-#include <GL/glew.h>
-#include "GLOcclusionQuery.h"
-
-namespace crown
-{
-
-GLOcclusionQuery::GLOcclusionQuery() :
-	mQueryObject(0)
-{
-	glGenQueries(1, &mQueryObject);
-}
-
-GLOcclusionQuery::~GLOcclusionQuery()
-{
-	glDeleteQueries(1, &mQueryObject);
-}
-
-void GLOcclusionQuery::BeginQuery()
-{
-	glBeginQuery(GL_SAMPLES_PASSED, mQueryObject);
-}
-
-void GLOcclusionQuery::EndQuery()
-{
-	glEndQuery(GL_SAMPLES_PASSED);
-}
-
-uint32_t GLOcclusionQuery::GetQueryResult()
-{
-	uint32_t passedCount;
-
-	glGetQueryObjectuiv(mQueryObject, GL_QUERY_RESULT, &passedCount);
-
-	return passedCount;
-}
-
-bool GLOcclusionQuery::IsResultAvailable()
-{
-	uint32_t available;
-
-	glGetQueryObjectuiv(mQueryObject, GL_QUERY_RESULT_AVAILABLE, &available);
-
-	return available != 0;
-}
-
-} // namespace crown
-

+ 264 - 120
src/renderers/gl/GLRenderer.cpp

@@ -28,16 +28,14 @@ OTHER DEALINGS IN THE SOFTWARE.
 #include <GL/glew.h>
 #include <cassert>
 #include <algorithm>
+
 #include "Types.h"
-#include "GLIndexBuffer.h"
-#include "GLOcclusionQuery.h"
 #include "GLRenderer.h"
 #include "GLUtils.h"
-#include "GLVertexBuffer.h"
 #include "Log.h"
 #include "Material.h"
-#include "Allocator.h"
 #include "TextureResource.h"
+#include "Vec3.h"
 
 #if defined(WINDOWS)
 	//Define the missing constants in vs' gl.h
@@ -61,8 +59,12 @@ GLRenderer::GLRenderer() :
 	m_max_vertex_vertices(0),
 	m_max_anisotropy(0.0f),
 
-	m_texture_count(0),
-	m_active_texture_unit(0)
+	m_textures_id_table(m_allocator, MAX_TEXTURES),
+	m_active_texture_unit(0),
+
+	m_vertex_buffers_id_table(m_allocator, MAX_VERTEX_BUFFERS),
+	m_index_buffers_id_table(m_allocator, MAX_INDEX_BUFFERS)
+	//m_render_buffers_id_table(m_allocator, MAX_RENDER_BUFFERS)
 {
 	m_min_max_point_size[0] = 0.0f;
 	m_min_max_point_size[1] = 0.0f;
@@ -185,6 +187,179 @@ GLRenderer::~GLRenderer()
 {
 }
 
+//-----------------------------------------------------------------------------
+VertexBufferId GLRenderer::create_vertex_buffer(size_t count, VertexFormat format, const void* vertices)
+{
+	const VertexBufferId id = m_vertex_buffers_id_table.create();
+
+	GLVertexBuffer& buffer = m_vertex_buffers[id.index];
+
+	glGenBuffers(1, &buffer.gl_object);
+
+	glBindBuffer(GL_ARRAY_BUFFER, buffer.gl_object);
+	glBufferData(GL_ARRAY_BUFFER, count * Vertex::bytes_per_vertex(format), vertices, GL_STATIC_DRAW);
+
+	buffer.count = count;
+	buffer.format = format;
+
+	return id;
+}
+
+//-----------------------------------------------------------------------------
+VertexBufferId GLRenderer::create_dynamic_vertex_buffer(size_t count, VertexFormat format, const void* vertices)
+{
+	const VertexBufferId id = m_vertex_buffers_id_table.create();
+
+	GLVertexBuffer& buffer = m_vertex_buffers[id.index];
+
+	glGenBuffers(1, &buffer.gl_object);
+
+	glBindBuffer(GL_ARRAY_BUFFER, buffer.gl_object);
+	glBufferData(GL_ARRAY_BUFFER, count * Vertex::bytes_per_vertex(format), vertices, GL_STREAM_DRAW);
+
+	buffer.count = count;
+	buffer.format = format;
+
+	return id;
+}
+
+//-----------------------------------------------------------------------------
+void GLRenderer::update_vertex_buffer(VertexBufferId id, size_t offset, size_t count, const void* vertices)
+{
+	assert(m_vertex_buffers_id_table.has(id));
+
+	GLVertexBuffer& buffer = m_vertex_buffers[id.index];
+
+	glBindBuffer(GL_ARRAY_BUFFER, buffer.gl_object);
+	glBufferSubData(GL_ARRAY_BUFFER, offset * Vertex::bytes_per_vertex(buffer.format),
+					count * Vertex::bytes_per_vertex(buffer.format), vertices);
+}
+
+//-----------------------------------------------------------------------------
+void GLRenderer::destroy_vertex_buffer(VertexBufferId id)
+{
+	assert(m_vertex_buffers_id_table.has(id));
+
+	GLVertexBuffer& buffer = m_vertex_buffers[id.index];
+
+	glDeleteBuffers(1, &buffer.gl_object);
+
+	m_vertex_buffers_id_table.destroy(id);
+}
+
+//-----------------------------------------------------------------------------
+IndexBufferId GLRenderer::create_index_buffer(size_t count, const void* indices)
+{
+	const IndexBufferId id = m_index_buffers_id_table.create();
+
+	GLIndexBuffer& buffer = m_index_buffers[id.index];
+
+	glGenBuffers(1, &buffer.gl_object);
+
+	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.gl_object);
+	glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(GLushort), indices, GL_STATIC_DRAW);
+
+	buffer.index_count = count;
+
+	return id;
+}
+
+//-----------------------------------------------------------------------------
+void GLRenderer::destroy_index_buffer(IndexBufferId id)
+{
+	assert(m_index_buffers_id_table.has(id));
+
+	GLIndexBuffer& buffer = m_index_buffers[id.index];
+
+	glDeleteBuffers(1, &buffer.gl_object);
+
+	m_index_buffers_id_table.destroy(id);
+}
+
+//-----------------------------------------------------------------------------
+TextureId GLRenderer::create_texture(uint32_t width, uint32_t height, PixelFormat format, const void* data)
+{
+	const TextureId id = m_textures_id_table.create();
+
+	GLTexture& gl_texture = m_textures[id.index];
+
+	glGenTextures(1, &gl_texture.gl_object);
+
+	glBindTexture(GL_TEXTURE_2D, gl_texture.gl_object);
+
+	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
+
+	// FIXME
+	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
+				 GL::pixel_format(format), GL_UNSIGNED_BYTE, data);
+
+	gl_texture.format = format;
+
+	return id;
+}
+
+//-----------------------------------------------------------------------------
+void GLRenderer::update_texture(TextureId id, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const void* data)
+{
+	assert(m_textures_id_table.has(id));
+
+	GLTexture& gl_texture = m_textures[id.index];
+
+	glBindTexture(GL_TEXTURE_2D, gl_texture.gl_object);
+
+	glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL::pixel_format(gl_texture.format),
+					GL_UNSIGNED_BYTE, data);
+}
+
+//-----------------------------------------------------------------------------
+void GLRenderer::destroy_texture(TextureId id)
+{
+	assert(m_textures_id_table.has(id));
+
+	GLTexture& gl_texture = m_textures[id.index];
+
+	glDeleteTextures(1, &gl_texture.gl_object);
+}
+
+//-----------------------------------------------------------------------------
+// RenderBufferId GLRenderer::create_render_buffer(uint32_t width, uint32_t height, PixelFormat format)
+// {
+// 	const RenderBufferId id = m_render_buffers_id_table.create();
+
+// 	GLRenderBuffer& buffer = m_render_buffers[id.index];
+
+// 	if (GLEW_EXT_framebuffer_object)
+// 	{
+// 		glGenFramebuffersEXT(1, &buffer.gl_frame_buffer);
+// 		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, buffer.gl_frame_buffer);
+
+// 		glGenRenderbuffersEXT(1, &buffer.gl_render_buffer);
+// 		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, buffer.gl_render_buffer);
+
+// 		glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, width, height);
+
+// 		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, buffer.gl_render_buffer);
+
+// 		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+// 	}
+
+// 	return id;
+// }
+
+//-----------------------------------------------------------------------------
+// void GLRenderer::destroy_render_buffer(RenderBufferId id)
+// {
+// 	GLRenderBuffer& buffer = m_render_buffers[id.index];
+
+// 	if (GLEW_EXT_framebuffer_object)
+// 	{
+// 		glDeleteFramebuffersEXT(1, &buffer.gl_frame_buffer);
+// 		glDeleteRenderbuffersEXT(1, &buffer.gl_render_buffer);
+// 	}
+
+// 	m_render_buffers_id_table.destroy(id);
+// }
+
 //-----------------------------------------------------------------------------
 void GLRenderer::set_clear_color(const Color4& color)
 {
@@ -221,6 +396,23 @@ void GLRenderer::set_lighting(bool lighting)
 	}
 }
 
+//-----------------------------------------------------------------------------
+void GLRenderer::bind_texture(uint32_t unit, TextureId texture)
+{
+	assert(m_textures_id_table.has(texture));
+
+	if (!activate_texture_unit(unit))
+	{
+		return;
+	}
+
+	m_texture_unit_target[unit] = GL_TEXTURE_2D;
+	m_texture_unit[unit] = m_textures[texture.index].gl_object;
+
+	glEnable(m_texture_unit_target[unit]);
+	glBindTexture(m_texture_unit_target[unit], m_texture_unit[unit]);
+}
+
 //-----------------------------------------------------------------------------
 void GLRenderer::set_texturing(uint32_t unit, bool texturing)
 {
@@ -237,21 +429,6 @@ void GLRenderer::set_texturing(uint32_t unit, bool texturing)
 	}
 }
 
-//-----------------------------------------------------------------------------
-void GLRenderer::set_texture(uint32_t unit, TextureId texture)
-{
-	if (!activate_texture_unit(unit))
-	{
-		return;
-	}
-
-	m_texture_unit_target[unit] = GL_TEXTURE_2D;
-	m_texture_unit[unit] = m_textures[texture.index].texture_object;
-
-	glEnable(m_texture_unit_target[unit]);
-	glBindTexture(m_texture_unit_target[unit], m_texture_unit[unit]);
-}
-
 //-----------------------------------------------------------------------------
 void GLRenderer::set_texture_mode(uint32_t unit, TextureMode mode, const Color4& blendColor)
 {
@@ -613,46 +790,84 @@ void GLRenderer::set_matrix(MatrixType type, const Mat4& matrix)
 }
 
 //-----------------------------------------------------------------------------
-void GLRenderer::draw_vertex_index_buffer(const VertexBuffer* vertices, const IndexBuffer* indices)
+void GLRenderer::bind_vertex_buffer(VertexBufferId vb) const
 {
-	assert(vertices != NULL);
-	assert(indices != NULL);
-
-	glEnableClientState(GL_VERTEX_ARRAY);
-	glEnableClientState(GL_NORMAL_ARRAY);
-	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-	glEnableClientState(GL_COLOR_ARRAY);
+	assert(m_vertex_buffers_id_table.has(vb));
 
-	vertices->Bind();
-	indices->Bind();
+	const GLVertexBuffer& vertex_buffer = m_vertex_buffers[vb.index];
 
-	glDrawElements(GL_TRIANGLES, indices->GetIndexCount(), GL_UNSIGNED_SHORT, 0);
+	glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer.gl_object);
 
-	glDisableClientState(GL_COLOR_ARRAY);
-	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-	glDisableClientState(GL_NORMAL_ARRAY);
-	glDisableClientState(GL_VERTEX_ARRAY);
+	switch (vertex_buffer.format)
+	{
+		case VF_XY_FLOAT_32:
+		{
+			glEnableClientState(GL_VERTEX_ARRAY);
+			glVertexPointer(2, GL_FLOAT, 0, 0);
+			break;
+		}
+		case VF_XYZ_FLOAT_32:
+		{
+			glEnableClientState(GL_VERTEX_ARRAY);
+			glVertexPointer(3, GL_FLOAT, 0, 0);
+			break;
+		}
+		case VF_UV_FLOAT_32:
+		{
+			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+			glTexCoordPointer(2, GL_FLOAT, 0, 0);
+			break;
+		}
+		case VF_UVT_FLOAT_32:
+		{
+			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+			glTexCoordPointer(3, GL_FLOAT, 0, 0);
+			break;
+		}
+		case VF_XYZ_NORMAL_FLOAT_32:
+		{
+			glEnableClientState(GL_NORMAL_ARRAY);
+			glNormalPointer(GL_FLOAT, 0, 0);
+			break;
+		}
+		case VF_XYZ_UV_XYZ_NORMAL_FLOAT_32:
+		{
+			glEnableClientState(GL_VERTEX_ARRAY);
+			glEnableClientState(GL_NORMAL_ARRAY);
+			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+			glVertexPointer(3, GL_FLOAT, 0, 0);
+			glTexCoordPointer(2, GL_FLOAT, 0, 0);
+			glNormalPointer(GL_FLOAT, 0, 0);
+			break;
+		}
+		default:
+		{
+			assert(0);
+			break;
+		}
+	}
 }
 
 //-----------------------------------------------------------------------------
-void GLRenderer::draw_point_buffer(const VertexBuffer* buffer)
+void GLRenderer::draw_triangles(IndexBufferId id) const
 {
-	if (buffer == NULL)
-		return;
-	glEnableClientState(GL_VERTEX_ARRAY);
-	glEnableClientState(GL_NORMAL_ARRAY);
-	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-	glEnableClientState(GL_COLOR_ARRAY);
+	assert(m_index_buffers_id_table.has(id));
 
-	buffer->Bind();
-	glDrawArrays(GL_POINTS, 0, buffer->GetVertexCount());
+	const GLIndexBuffer& index_buffer = m_index_buffers[id.index];
 
-	glDisableClientState(GL_COLOR_ARRAY);
-	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-	glDisableClientState(GL_NORMAL_ARRAY);
-	glDisableClientState(GL_VERTEX_ARRAY);
+	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer.gl_object);
+
+	glDrawElements(GL_TRIANGLES, index_buffer.index_count, GL_UNSIGNED_SHORT, 0);
 }
 
+//-----------------------------------------------------------------------------
+// void GLRenderer::bind_render_buffer(RenderBufferId id) const
+// {
+// 	assert(m_render_buffers_id_table.has(id));
+
+// 	const GLRenderBuffer& render_buffer = m_render_buffers[id.index];
+// }
+
 //-----------------------------------------------------------------------------
 bool GLRenderer::activate_texture_unit(uint32_t unit)
 {
@@ -738,77 +953,6 @@ void GLRenderer::draw_lines(const float* vertices, const float* colors, uint32_t
 	glDisableClientState(GL_VERTEX_ARRAY);
 }
 
-//-----------------------------------------------------------------------------
-void GLRenderer::draw_triangles(const float* vertices, const float* normals, const float* uvs, const uint16_t* indices, uint32_t count)
-{
-	glBindBuffer(GL_ARRAY_BUFFER, 0);
-	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
-
-	glEnableClientState(GL_VERTEX_ARRAY);
-	glEnableClientState(GL_NORMAL_ARRAY);
-	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-	glVertexPointer(3, GL_FLOAT, 0, vertices);
-	glNormalPointer(GL_FLOAT, 0, normals);
-	glTexCoordPointer(2, GL_FLOAT, 0, uvs);
-
-	glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, indices);
-
-	glDisableClientState(GL_VERTEX_ARRAY);
-	glDisableClientState(GL_NORMAL_ARRAY);
-	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-}
-
-//-----------------------------------------------------------------------------
-TextureId GLRenderer::load_texture(TextureResource* texture)
-{
-	// If texture not found, create a new one
-	GLuint gl_texture_object;
-
-	glGenTextures(1, &gl_texture_object);
-	glBindTexture(GL_TEXTURE_2D, gl_texture_object);
-	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
-
-	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width(), texture->height(), 0,
-				 GL::pixel_format(texture->format()), GL_UNSIGNED_BYTE, texture->data());
-
-	TextureId id;
-	id.index = m_texture_count;
-	id.id = 0;
-
-	m_textures[id.index].texture_object = gl_texture_object;
-	m_textures[id.index].texture_resource = texture;
-	m_textures[id.index].id = id;
-
-	m_texture_count++;
-
-	return id;
-}
-
-//-----------------------------------------------------------------------------
-void GLRenderer::unload_texture(TextureResource* texture)
-{
-	// FIXME
-	(void)texture;
-}
-
-//-----------------------------------------------------------------------------
-TextureId GLRenderer::reload_texture(TextureResource* old_texture, TextureResource* new_texture)
-{
-	for (uint32_t i = 0; i < m_texture_count; i++)
-	{
-		if (m_textures[i].texture_resource == old_texture)
-		{
-			// Reload texture
-			glBindTexture(GL_TEXTURE_2D, m_textures[i].texture_object);
-
-			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, new_texture->width(), new_texture->height(),
-				GL::pixel_format(new_texture->format()), GL_UNSIGNED_BYTE, new_texture->data());
-
-			m_textures[i].texture_resource = new_texture;
-		}
-	}
-}
-
 //-----------------------------------------------------------------------------
 void GLRenderer::check_gl_errors()
 {

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.