Explorar el Código

Started on bindings, set up old collision scene code as a module

Ivan Safrin hace 15 años
padre
commit
552195f8a8
Se han modificado 27 ficheros con 2330 adiciones y 60 borrados
  1. 1 0
      .gitignore
  2. 241 0
      Bindings/Build/Mac OS X/Bindings.xcodeproj/project.pbxproj
  3. 10 0
      Bindings/Contents/LUA/API/Polycode/Core.lua
  4. 10 0
      Bindings/Contents/LUA/API/Polycode/Screen.lua
  5. 412 0
      Bindings/Contents/LUA/API/class.lua
  6. 16 0
      Bindings/Contents/LUA/Include/PolycodeLUA.h
  7. 127 0
      Bindings/Contents/LUA/Include/PolycodeLUA2D.h
  8. 26 0
      Bindings/Contents/LUA/Source/PolycodeLUA.cpp
  9. 2 0
      Core/Contents/Include/PolySubstanceView.h
  10. 2 2
      Core/Contents/Source/PolyCocoaCore.cpp
  11. 10 0
      Core/Contents/Source/PolySubstanceView.m
  12. 126 0
      Modules/Build/Mac OS X/Modules.xcodeproj/project.pbxproj
  13. 121 0
      Modules/Contents/2DPhysics/Include/PolyPhysicsScreen.h
  14. 49 0
      Modules/Contents/2DPhysics/Include/PolyPhysicsScreenEntity.h
  15. 405 0
      Modules/Contents/2DPhysics/Source/PolyPhysicsScreen.cpp
  16. 107 0
      Modules/Contents/2DPhysics/Source/PolyPhysicsScreenEntity.cpp
  17. 72 0
      Modules/Contents/3DPhysics/Include/PolyCollisionScene.h
  18. 57 0
      Modules/Contents/3DPhysics/Include/PolyCollisionSceneEntity.h
  19. 4 0
      Modules/Contents/3DPhysics/Include/Polycode3DPhysics.h
  20. 335 0
      Modules/Contents/3DPhysics/Source/PolyCollisionScene.cpp
  21. 126 0
      Modules/Contents/3DPhysics/Source/PolyCollisionSceneEntity.cpp
  22. 1 1
      Modules/Contents/UI/Source/PolyUITextInput.cpp
  23. 9 28
      Player/Build/Mac OS X/English.lproj/MyDocument.xib
  24. 16 23
      Player/Build/Mac OS X/MyDocument.m
  25. 8 0
      Player/Build/Mac OS X/Polycode Player.xcodeproj/project.pbxproj
  26. 2 1
      Player/Contents/Include/PolycodePlayer.h
  27. 35 5
      Player/Contents/Source/PolycodePlayer.cpp

+ 1 - 0
.gitignore

@@ -14,6 +14,7 @@ IDE/Build/Mac\ OS\ X/build
 Modules/Build/Mac\ OS\ X/build
 Modules/Build/Mac\ OS\ X/build
 Tools/Build/Mac\ OS\ X/build
 Tools/Build/Mac\ OS\ X/build
 Player/Build/Mac\ OS\ X/build
 Player/Build/Mac\ OS\ X/build
+Bindings/Build/Mac\ OS\ X/build
 Core/Dependencies
 Core/Dependencies
 
 
 # OS generated files #
 # OS generated files #

+ 241 - 0
Bindings/Build/Mac OS X/Bindings.xcodeproj/project.pbxproj

@@ -0,0 +1,241 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 42;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		6D3415FA12B837080034FA9B /* PolycodeLUA.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D3415F712B837080034FA9B /* PolycodeLUA.h */; };
+		6D3415FB12B837080034FA9B /* PolycodeLUA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6D3415F912B837080034FA9B /* PolycodeLUA.cpp */; };
+		6D3418F712B91DBF0034FA9B /* PolycodeLUA2D.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D3418F612B91DBF0034FA9B /* PolycodeLUA2D.h */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+		6D3415EF12B836CE0034FA9B /* libPolycodeLUA.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPolycodeLUA.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6D3415F712B837080034FA9B /* PolycodeLUA.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PolycodeLUA.h; sourceTree = "<group>"; };
+		6D3415F912B837080034FA9B /* PolycodeLUA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PolycodeLUA.cpp; sourceTree = "<group>"; };
+		6D3418F612B91DBF0034FA9B /* PolycodeLUA2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PolycodeLUA2D.h; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		6D3415ED12B836CE0034FA9B /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		6D3415D712B8360B0034FA9B = {
+			isa = PBXGroup;
+			children = (
+				6D3415F512B837080034FA9B /* LUA */,
+				6D3415F012B836CE0034FA9B /* Products */,
+			);
+			sourceTree = "<group>";
+		};
+		6D3415F012B836CE0034FA9B /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				6D3415EF12B836CE0034FA9B /* libPolycodeLUA.a */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		6D3415F512B837080034FA9B /* LUA */ = {
+			isa = PBXGroup;
+			children = (
+				6D3415F612B837080034FA9B /* Include */,
+				6D3415F812B837080034FA9B /* Source */,
+			);
+			name = LUA;
+			path = ../../Contents/LUA;
+			sourceTree = SOURCE_ROOT;
+		};
+		6D3415F612B837080034FA9B /* Include */ = {
+			isa = PBXGroup;
+			children = (
+				6D3418F612B91DBF0034FA9B /* PolycodeLUA2D.h */,
+				6D3415F712B837080034FA9B /* PolycodeLUA.h */,
+			);
+			path = Include;
+			sourceTree = "<group>";
+		};
+		6D3415F812B837080034FA9B /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				6D3415F912B837080034FA9B /* PolycodeLUA.cpp */,
+			);
+			path = Source;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		6D3415EB12B836CE0034FA9B /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6D3415FA12B837080034FA9B /* PolycodeLUA.h in Headers */,
+				6D3418F712B91DBF0034FA9B /* PolycodeLUA2D.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXHeadersBuildPhase section */
+
+/* Begin PBXNativeTarget section */
+		6D3415EE12B836CE0034FA9B /* PolycodeLUA */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6D3415F312B836CE0034FA9B /* Build configuration list for PBXNativeTarget "PolycodeLUA" */;
+			buildPhases = (
+				6D3415EB12B836CE0034FA9B /* Headers */,
+				6D3415EC12B836CE0034FA9B /* Sources */,
+				6D3415ED12B836CE0034FA9B /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = PolycodeLUA;
+			productName = PolycodeLUA;
+			productReference = 6D3415EF12B836CE0034FA9B /* libPolycodeLUA.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		6D3415D912B8360B0034FA9B /* Project object */ = {
+			isa = PBXProject;
+			buildConfigurationList = 6D3415DC12B8360B0034FA9B /* Build configuration list for PBXProject "Bindings" */;
+			compatibilityVersion = "Xcode 2.4";
+			developmentRegion = English;
+			hasScannedForEncodings = 0;
+			knownRegions = (
+				English,
+				Japanese,
+				French,
+				German,
+			);
+			mainGroup = 6D3415D712B8360B0034FA9B;
+			productRefGroup = 6D3415F012B836CE0034FA9B /* Products */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				6D3415EE12B836CE0034FA9B /* PolycodeLUA */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		6D3415EC12B836CE0034FA9B /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6D3415FB12B837080034FA9B /* PolycodeLUA.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin XCBuildConfiguration section */
+		6D3415DA12B8360B0034FA9B /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ONLY_ACTIVE_ARCH_PRE_XCODE_3_1)";
+				COPY_PHASE_STRIP = NO;
+				HEADER_SEARCH_PATHS = (
+					../../../Core/Contents/Include,
+					../../../Core/Dependencies/luajit/src,
+					../../../Core/Dependencies/libvorbis/include,
+					../../../Core/Dependencies/libogg/include,
+					/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/OpenAL.framework/Versions/A/Headers,
+					../../../Core/Dependencies/freetype/include,
+					../../../Core/Dependencies/libpng,
+					../../../Core/Dependencies/physfs,
+					../../../Modules/Contents/UI/Include,
+				);
+				ONLY_ACTIVE_ARCH_PRE_XCODE_3_1 = "$(NATIVE_ARCH_ACTUAL)";
+			};
+			name = Debug;
+		};
+		6D3415DB12B8360B0034FA9B /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ONLY_ACTIVE_ARCH_PRE_XCODE_3_1)";
+				COPY_PHASE_STRIP = YES;
+				HEADER_SEARCH_PATHS = (
+					../../../Core/Contents/Include,
+					../../../Core/Dependencies/luajit/src,
+					../../../Core/Dependencies/libvorbis/include,
+					../../../Core/Dependencies/libogg/include,
+					/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/OpenAL.framework/Versions/A/Headers,
+					../../../Core/Dependencies/freetype/include,
+					../../../Core/Dependencies/libpng,
+					../../../Core/Dependencies/physfs,
+					../../../Modules/Contents/UI/Include,
+				);
+				ONLY_ACTIVE_ARCH_PRE_XCODE_3_1 = "$(NATIVE_ARCH_ACTUAL)";
+			};
+			name = Release;
+		};
+		6D3415F112B836CE0034FA9B /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				ONLY_ACTIVE_ARCH = YES;
+				PREBINDING = NO;
+				PRODUCT_NAME = PolycodeLUA;
+			};
+			name = Debug;
+		};
+		6D3415F212B836CE0034FA9B /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				ONLY_ACTIVE_ARCH = YES;
+				PREBINDING = NO;
+				PRODUCT_NAME = PolycodeLUA;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		6D3415DC12B8360B0034FA9B /* Build configuration list for PBXProject "Bindings" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6D3415DA12B8360B0034FA9B /* Debug */,
+				6D3415DB12B8360B0034FA9B /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6D3415F312B836CE0034FA9B /* Build configuration list for PBXNativeTarget "PolycodeLUA" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6D3415F112B836CE0034FA9B /* Debug */,
+				6D3415F212B836CE0034FA9B /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 6D3415D912B8360B0034FA9B /* Project object */;
+}

+ 10 - 0
Bindings/Contents/LUA/API/Polycode/Core.lua

@@ -0,0 +1,10 @@
+
+class "Core"
+	
+	function Core:Core()
+--		self.__ptr = Polycore.CoreServices()
+	end
+	
+	function Core:Update()
+--		self.__ptr
+	end

+ 10 - 0
Bindings/Contents/LUA/API/Polycode/Screen.lua

@@ -0,0 +1,10 @@
+
+class "Screen"
+
+function Screen:Screen()
+	self.__ptr = Polycore.Screen()
+end
+
+function addChild(child)
+	Polycore.Screen_addChild(self.__ptr, child.__ptr)
+end

+ 412 - 0
Bindings/Contents/LUA/API/class.lua

@@ -0,0 +1,412 @@
+local u = {}
+
+function u.wrongarg(n,expected,got)
+  return 'arg '..n..' expected to be '..expected..' (got '..tostring(got)..')'
+end
+
+local wrongarg = u.wrongarg
+
+function u.isname(name)
+  return type(name)=='string' and string.find(name,'^[_%a][_%w]*$')
+end
+
+local isname = u.isname
+
+function u.assert(value,errmsg,...)
+  if value then
+    return value
+  else
+    if type(errmsg)=='nil' then
+      error('assertion failed!',2)
+    elseif type(errmsg)=='string' then
+      error(errmsg,2)
+    else
+      error(errmsg(unpack(arg)),2)
+    end
+  end
+end
+
+local assert = u.assert
+
+function u.fwrongarg(...)
+  return function()
+    return wrongarg(unpack(arg))
+  end
+end
+
+local fwrongarg = u.fwrongarg
+
+
+
+
+local INFO = '__info'
+
+
+function u.isobject(o)
+  return type(o)=='table' and rawget(o,INFO)
+end
+
+local isobject = u.isobject
+
+
+local METAMETHODS = {
+  '__tostring',
+  '__add',
+  '__sub',
+  '__mul',
+  '__div',
+  '__pow',
+  '__lt',
+  '__le',
+  '__eq',
+  '__call',
+  '__unm',
+  '__concat',
+  '__newindex',
+}
+
+
+local metatable = {}
+
+for _, name in ipairs(METAMETHODS) do
+  local name = name
+  metatable[name] = function(...)
+    local a, b = unpack(arg)
+    local f
+    if isobject(a) then
+      f = a[name]
+    end
+    if not f and isobject(b) then
+      f = b[name]
+    end
+    if not f then
+    local name = name..'__'
+    if isobject(a) then
+      f = a[name]
+    end
+    if not f and isobject(b) then
+      f = b[name]
+    end
+    end
+    assert(f, function()
+                 local class = rawget(a,INFO).__class
+                 local cname = rawget(class,INFO).__name
+                 return 'meta-method not found: '..cname..':'..name
+               end)
+    return f(unpack(arg))
+  end
+end
+
+
+local
+function table2object(t)
+  assert(type(t)=='table', fwrongarg(1,'table',t))
+  local info = {}
+  rawset(t,INFO,info)
+  setmetatable(t,metatable)
+
+  local p = newproxy(true)
+  local mp = getmetatable(p)
+  function mp:__gc()
+    if rawget(t,INFO) == info then
+      t:finalize()
+    end
+  end
+  rawget(t,INFO).__proxy = p
+
+  return t
+end
+
+local
+function object2table(o)
+  assert(isobject(o), fwrongarg(1,'object',o))
+  setmetatable(o,nil)
+  rawset(o,INFO,nil)
+  return o
+end
+
+local
+function givename(o,name)
+  assert(isobject(o), fwrongarg(1,'object',o))
+  assert(isname(name), fwrongarg(2,'name',name))
+  rawget(o,INFO).__name = name
+  getfenv(2)[name] = o
+end
+
+local
+function setclass(o,class)
+  assert(isobject(o), fwrongarg(1,'object',o))
+  assert(isobject(class), fwrongarg(2,'object',class))
+  rawget(o,INFO).__class = class
+end
+
+local
+function setsuper(class,superclass)
+  assert(isobject(class), fwrongarg(1,'object',class))
+  assert(isobject(superclass), fwrongarg(2,'object',superclass))
+  rawget(class,INFO).__super = superclass
+end
+
+local
+function object2class(o,name)
+  assert(isobject(o), fwrongarg(1,'object',o))
+  assert(isname(name), fwrongarg(2,'name',name))
+  givename(o,name)
+  rawget(o,INFO).__methods = {}
+  rawget(o,INFO).__isclass = true
+  rawget(o,INFO).__cmethods = {}
+end
+
+local
+function findmethod(class,name,iscmethod)
+  local storage = iscmethod and '__cmethods' or '__methods'
+  while class do
+    local info = rawget(class,INFO)
+    value = info[storage][name]
+    if value ~= nil then
+      return value
+    end
+    class = info.__super
+  end
+end
+
+
+
+function metatable:__index(name)
+  local value
+
+  if rawget(self,INFO).__isclass then
+    value = findmethod(self,name,true)
+    if value ~= nil then
+      return value
+    end
+  end
+
+  local class = rawget(self,INFO).__class
+  value = findmethod(class,name)
+  if value ~= nil then
+    return value
+  end
+
+  if name ~= '__index' and name ~= '__index__' then
+    local index = self.__index or self.__index__ 
+    if index then
+      value = index(self,name)
+      if value ~= nil then
+        return value
+      end
+    end
+  end
+end
+
+
+local _Object = table2object{}
+object2class(_Object,"Object")
+
+
+
+local _Class = table2object{}
+object2class(_Class,"Class")
+
+
+setclass(Object,Class)
+setclass(Class,Class)
+setsuper(Class,Object)
+
+
+local
+function makesupermethod(self,name,iscmethod)
+  return function(...)
+    local method
+    local classinfo
+    if iscmethod then
+      classinfo = rawget(self,INFO)
+    else
+      local class = rawget(self,INFO).__class
+      classinfo = rawget(class,INFO)
+    end
+    local super = classinfo.__super
+    if super then
+      method = findmethod(super,name,iscmethod)
+    end
+    assert(method, "no super method for "..classinfo.__name..":"..name)
+    return method(self,unpack(arg))
+  end
+end
+
+local methodsmeta = {}
+
+function methodsmeta:__call(object,...)
+  local env = getfenv(self.__f)
+  local metafenv = {
+    __newindex = env,
+    __index = env,
+  }
+  local fenv = {
+    super = makesupermethod(object,self.__name,self.__iscmethod),
+  }
+  setmetatable(fenv,metafenv)
+  setfenv(self.__f,fenv)
+  local result = {self.__f(object,unpack(arg))}
+  setfenv(self.__f,env)
+  return unpack(result)
+end
+
+local
+function storemethod(storage,name,iscmethod,method)
+  if type(method) == 'function' then
+    local t = {
+      __name = name,
+      __f = method,
+      __iscmethod = iscmethod,
+    }
+    setmetatable(t,methodsmeta)
+    storage[name] = t
+  else
+    storage[name] = method
+  end
+end
+
+rawget(Class,INFO).__methods.__newindex =
+  function(self,name,method)	
+    storemethod(rawget(self,INFO).__methods,name,false,method)
+  end
+
+
+function Class:__call__(...)
+  local instance = self:new(unpack(arg))
+  instance:initialize(unpack(arg))
+  instance.__cbody = nil
+  local constructor = instance[rawget(self,INFO).__name]
+  if constructor ~= nil then
+  	constructor(instance, unpack(arg))
+  	constructor = nil
+  end
+  return instance
+end
+
+function Class:initialize(name,superclass)
+  assert(isname(name), fwrongarg(1,'name',name))
+  object2class(self,name)
+  superclass = superclass or Object
+  assert(isobject(superclass), fwrongarg(2,'object',superclass))
+  setsuper(self,superclass or Object)
+end
+
+function Class:name()
+  return rawget(self,INFO).__name
+end
+
+function Class:super()
+  return rawget(self,INFO).__super
+end
+
+function Class:classtable()
+  local t = {}
+  local mt = {}
+  function mt.__newindex(_,name,method)
+    storemethod(rawget(self,INFO).__cmethods,name,true,method)
+  end
+  setmetatable(t,mt)
+  return t
+end
+
+function Class:__tostring__()
+  return self:name()
+end
+
+function Class:derives(class)
+  local superclass = self:super()
+  if superclass then
+    return superclass == class or superclass:derives(class)
+  end
+end
+
+function Class:adopt(t,initialize,...)
+  assert(type(t)=='table', wrongarg(1,'table',t))
+  local o = table2object(t)
+  setclass(o,self)
+  if initialize then
+    o:initialize(unpack(arg))
+  end
+  return o
+end
+
+
+local Objectclass = Object:classtable()
+
+function Objectclass:new()
+  local o = table2object{}
+  setclass(o,self)
+  return o
+end
+
+
+function Object:initialize()
+end
+
+function Object:finalize()
+end
+
+function Object:class()
+  return rawget(self,INFO).__class
+end
+
+function Object:__eq__(other)
+  return rawequal(self,other)
+end
+
+function Object:__newindex__(name,value)
+  if self.__set_callback(self,name,value) == true then
+  	return
+  end
+  rawset(self,name,value)
+end
+
+function Object:instanceof(class)
+  return self:class() == class
+end
+
+function Object:__set_callback(name,value)
+	return false
+end
+
+function Object:inherits(class)
+  local _class = self:class()
+  return _class == class or _class:derives(class)
+end
+
+function Object:__tostring__()
+  return 'instance of '..self:class():name()
+end
+
+function Object:__concat__(other)
+  if isobject(self) then
+    self = tostring(self)
+  elseif isobject(other) then
+    other = tostring(other)
+  end
+  return self..other
+end
+
+function Object:totable(finalize)
+  if finalize then
+    self:finalize()
+  end
+  setmetatable(self,nil)
+  local info = rawget(self,INFO)
+  rawset(self,INFO,nil)
+  return self, info
+end
+
+
+function class(name)
+  assert(isname(name), fwrongarg(1,'name',name))
+  local _class = Class(name)
+  return function(superclass)
+    assert(isobject(superclass), fwrongarg(1,'object',superclass))
+    setsuper(_class,superclass)
+  end
+end
+
+classu = u

+ 16 - 0
Bindings/Contents/LUA/Include/PolycodeLUA.h

@@ -0,0 +1,16 @@
+
+#pragma once
+
+
+#include <Polycode.h>
+#include "PolycodeLUA2D.h"
+
+extern "C" {	
+#include <stdio.h>
+#include "lua.h"
+#include "lualib.h"
+#include "lauxlib.h"
+	
+int luaopen_Polycode(lua_State *L);	
+	
+}

+ 127 - 0
Bindings/Contents/LUA/Include/PolycodeLUA2D.h

@@ -0,0 +1,127 @@
+#pragma once
+
+
+#include <Polycode.h>
+#include "PolycodeLUA2D.h"
+
+
+extern "C" {	
+#include <stdio.h>
+#include "lua.h"
+#include "lualib.h"
+#include "lauxlib.h"
+	
+// Screen
+	
+	static int Polycore_Screen(lua_State *L) {
+		Screen *screen = new Screen();
+		lua_pushlightuserdata(L, (void*)screen);
+		return 1;
+	}
+	
+	static int Polycore_Screen_addChild(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		ScreenEntity *child = (ScreenEntity*)lua_topointer(L, 2);
+		screen->addChild(child);
+		return 0;
+	}	
+
+	static int Polycore_Screen_removeChild(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);
+		luaL_checktype(L, 2, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		ScreenEntity *child = (ScreenEntity*)lua_topointer(L, 2);
+		screen->removeChild(child);
+		return 0;
+	}
+	
+	static int Polycore_Screen_setScreenOffset(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);
+		luaL_checktype(L, 2, LUA_TNUMBER);
+		luaL_checktype(L, 3, LUA_TNUMBER);
+		Screen *screen = (Screen*)lua_topointer(L, 1);		
+		float x = lua_tonumber(L, 2);
+		float y = lua_tonumber(L, 3);
+		screen->setScreenOffset(x,y);
+		return 0;
+	}	
+	
+	static int Polycore_Screen_getScreenOffset(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		Vector2 offset = screen->getScreenOffset();
+		lua_pushnumber(L, offset.x);
+		lua_pushnumber(L, offset.y);		
+		return 2;
+	}	
+
+	static int Polycore_Screen_setScreenShader(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);
+		luaL_checktype(L, 2, LUA_TSTRING);
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		const char *str = lua_tostring(L, 2);
+		screen->setScreenShader(str);
+		return 0;
+	}		
+
+	static int Polycore_Screen_getHighestZIndex(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		lua_pushinteger(L, screen->getHighestZIndex());
+		return 1;
+	}	
+
+	static int Polycore_Screen_sortChildren(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		screen->sortChildren();
+		return 0;
+	}				
+
+	static int Polycore_Screen_hasFilterShader(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		lua_pushboolean(L, screen->hasFilterShader());
+		return 1;
+	}		
+	
+	static int Polycore_Screen_getRootEntity(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		lua_pushlightuserdata(L, (void*)screen->getRootEntity());
+		return 1;
+	}
+	
+	static int Polycore_Screen_setEnabled(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);
+		luaL_checktype(L, 2, LUA_TBOOLEAN);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		bool enabledVal = lua_toboolean(L, 2);
+		screen->enabled = enabledVal;
+		return 0;
+	}	
+
+	static int Polycore_Screen_getEnabled(lua_State *L) {
+		luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);		
+		Screen *screen = (Screen*)lua_topointer(L, 1);
+		lua_pushboolean(L, screen->enabled);
+		return 1;
+	}		
+		
+	
+	// Screen IMage
+	static int Polycore_ScreenImage(lua_State *L) {
+		ScreenImage *screenImage = new ScreenImage(lua_tostring(L, 1));
+		lua_pushlightuserdata(L, (void*)screenImage);
+		return 1;
+	}
+	
+	static int Polycore_ScreenImage_setRotation(lua_State *L) {
+		ScreenEntity *image = (ScreenEntity*)lua_topointer(L, 1);	
+		float rotation = lua_tonumber(L, 2);
+		image->setRotation(rotation);
+		return 1;
+	}
+	
+}

+ 26 - 0
Bindings/Contents/LUA/Source/PolycodeLUA.cpp

@@ -0,0 +1,26 @@
+
+#include "PolycodeLUA.h"
+#include "PolycodeLUA2D.h"
+
+int luaopen_Polycode(lua_State *L) {
+	static const struct luaL_reg polycodeLib [] = {
+		//Screen
+		{"Screen", Polycore_Screen},
+		{"Screen_addChild", Polycore_Screen_addChild},
+		{"Screen_removeChild", Polycore_Screen_removeChild},
+		{"Screen_setScreenOffset", Polycore_Screen_setScreenOffset},
+		{"Screen_getScreenOffset", Polycore_Screen_getScreenOffset},
+		{"Screen_setScreenShader", Polycore_Screen_setScreenShader},
+		{"Screen_getHighestZIndex", Polycore_Screen_getHighestZIndex},
+		{"Screen_sortChildren", Polycore_Screen_sortChildren},
+		{"Screen_hasFilterShader", Polycore_Screen_hasFilterShader},
+		{"Screen_setEnabled", Polycore_Screen_setEnabled},
+		{"Screen_getEnabled", Polycore_Screen_getEnabled},
+		
+		{"ScreenImage", Polycore_ScreenImage},
+		{"ScreenImage_setRotation", Polycore_ScreenImage_setRotation},				
+		{NULL, NULL}  /* sentinel */
+	};
+	luaL_openlib(L, "Polycore", polycodeLib, 0);
+	return 1;	
+}

+ 2 - 0
Core/Contents/Include/PolySubstanceView.h

@@ -29,8 +29,10 @@ using namespace Polycode;
 	
 	
 	NSCursor *currentCursor;
 	NSCursor *currentCursor;
 	bool contextReady;
 	bool contextReady;
+	
 }
 }
 
 
+@property BOOL viewReady;
 
 
 - (void) setCurrentCursor: (NSCursor*) newCursor;
 - (void) setCurrentCursor: (NSCursor*) newCursor;
 
 

+ 2 - 2
Core/Contents/Source/PolyCocoaCore.cpp

@@ -40,9 +40,9 @@ CocoaCore::CocoaCore(SubstanceView *view, int xRes, int yRes, bool fullScreen,in
 	
 	
 	initTime = mach_absolute_time();					
 	initTime = mach_absolute_time();					
 	
 	
-	while(![view isContextReady]) {
+//	while(![view isContextReady]) {
 		
 		
-	}
+//	}
 	
 	
 	renderer = new OpenGLRenderer();
 	renderer = new OpenGLRenderer();
 	services->setRenderer(renderer);	
 	services->setRenderer(renderer);	

+ 10 - 0
Core/Contents/Source/PolySubstanceView.m

@@ -11,10 +11,13 @@
 
 
 @implementation SubstanceView
 @implementation SubstanceView
 
 
+@synthesize viewReady;
+
 - (id)initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format 
 - (id)initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format 
 {
 {
 	self = [super initWithFrame:frameRect pixelFormat:format];
 	self = [super initWithFrame:frameRect pixelFormat:format];
 	if(self) {
 	if(self) {
+		viewReady = NO;
 		currentCursor = NULL;
 		currentCursor = NULL;
 		contextLock = [[NSLock alloc] init];
 		contextLock = [[NSLock alloc] init];
 	}
 	}
@@ -32,6 +35,13 @@
 	[self setAutoresizesSubviews: YES];
 	[self setAutoresizesSubviews: YES];
 }
 }
 
 
+-(void) viewDidMoveToWindow
+{
+	[super viewDidMoveToWindow];
+	viewReady = YES;
+	NSLog(@"VIEW READY!");	
+}
+
 
 
 - (void) initKeymap {	 
 - (void) initKeymap {	 
 	
 	

+ 126 - 0
Modules/Build/Mac OS X/Modules.xcodeproj/project.pbxproj

@@ -7,6 +7,11 @@
 	objects = {
 	objects = {
 
 
 /* Begin PBXBuildFile section */
 /* Begin PBXBuildFile section */
+		6D690D8412C1D99700C444B0 /* Polycode3DPhysics.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D690D7E12C1D99700C444B0 /* Polycode3DPhysics.h */; };
+		6D690D8512C1D99700C444B0 /* PolyCollisionScene.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D690D7F12C1D99700C444B0 /* PolyCollisionScene.h */; };
+		6D690D8612C1D99700C444B0 /* PolyCollisionSceneEntity.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D690D8012C1D99700C444B0 /* PolyCollisionSceneEntity.h */; };
+		6D690D8712C1D99700C444B0 /* PolyCollisionScene.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6D690D8212C1D99700C444B0 /* PolyCollisionScene.cpp */; };
+		6D690D8812C1D99700C444B0 /* PolyCollisionSceneEntity.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6D690D8312C1D99700C444B0 /* PolyCollisionSceneEntity.cpp */; };
 		6DFB01D112A741EB00C43A7D /* PolyCGProgram.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CA12A741EB00C43A7D /* PolyCGProgram.h */; };
 		6DFB01D112A741EB00C43A7D /* PolyCGProgram.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CA12A741EB00C43A7D /* PolyCGProgram.h */; };
 		6DFB01D212A741EB00C43A7D /* PolyCGShader.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CB12A741EB00C43A7D /* PolyCGShader.h */; };
 		6DFB01D212A741EB00C43A7D /* PolyCGShader.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CB12A741EB00C43A7D /* PolyCGShader.h */; };
 		6DFB01D312A741EB00C43A7D /* PolyCGShaderModule.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CC12A741EB00C43A7D /* PolyCGShaderModule.h */; };
 		6DFB01D312A741EB00C43A7D /* PolyCGShaderModule.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFB01CC12A741EB00C43A7D /* PolyCGShaderModule.h */; };
@@ -44,6 +49,12 @@
 /* End PBXBuildFile section */
 /* End PBXBuildFile section */
 
 
 /* Begin PBXFileReference section */
 /* Begin PBXFileReference section */
+		6D690D1B12C1D74A00C444B0 /* libPolycode3DPhysics.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPolycode3DPhysics.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6D690D7E12C1D99700C444B0 /* Polycode3DPhysics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Polycode3DPhysics.h; sourceTree = "<group>"; };
+		6D690D7F12C1D99700C444B0 /* PolyCollisionScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PolyCollisionScene.h; sourceTree = "<group>"; };
+		6D690D8012C1D99700C444B0 /* PolyCollisionSceneEntity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PolyCollisionSceneEntity.h; sourceTree = "<group>"; };
+		6D690D8212C1D99700C444B0 /* PolyCollisionScene.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PolyCollisionScene.cpp; sourceTree = "<group>"; };
+		6D690D8312C1D99700C444B0 /* PolyCollisionSceneEntity.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PolyCollisionSceneEntity.cpp; sourceTree = "<group>"; };
 		6DFB00FC12A736A900C43A7D /* libPolycodeCg.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPolycodeCg.a; sourceTree = BUILT_PRODUCTS_DIR; };
 		6DFB00FC12A736A900C43A7D /* libPolycodeCg.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPolycodeCg.a; sourceTree = BUILT_PRODUCTS_DIR; };
 		6DFB01CA12A741EB00C43A7D /* PolyCGProgram.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolyCGProgram.h; path = ../../Contents/CgShading/Include/PolyCGProgram.h; sourceTree = "<group>"; };
 		6DFB01CA12A741EB00C43A7D /* PolyCGProgram.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolyCGProgram.h; path = ../../Contents/CgShading/Include/PolyCGProgram.h; sourceTree = "<group>"; };
 		6DFB01CB12A741EB00C43A7D /* PolyCGShader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolyCGShader.h; path = ../../Contents/CgShading/Include/PolyCGShader.h; sourceTree = "<group>"; };
 		6DFB01CB12A741EB00C43A7D /* PolyCGShader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolyCGShader.h; path = ../../Contents/CgShading/Include/PolyCGShader.h; sourceTree = "<group>"; };
@@ -83,6 +94,13 @@
 /* End PBXFileReference section */
 /* End PBXFileReference section */
 
 
 /* Begin PBXFrameworksBuildPhase section */
 /* Begin PBXFrameworksBuildPhase section */
+		6D690D1912C1D74A00C444B0 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		6DFB00FA12A736A900C43A7D /* Frameworks */ = {
 		6DFB00FA12A736A900C43A7D /* Frameworks */ = {
 			isa = PBXFrameworksBuildPhase;
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
 			buildActionMask = 2147483647;
@@ -113,6 +131,7 @@
 		08FB7795FE84155DC02AAC07 /* Source */ = {
 		08FB7795FE84155DC02AAC07 /* Source */ = {
 			isa = PBXGroup;
 			isa = PBXGroup;
 			children = (
 			children = (
+				6D690D7C12C1D99700C444B0 /* 3DPhysics */,
 				6DFB00F012A7364300C43A7D /* PolycodeCg */,
 				6DFB00F012A7364300C43A7D /* PolycodeCg */,
 				6DFB00C012A71A5B00C43A7D /* PolycodeUI */,
 				6DFB00C012A71A5B00C43A7D /* PolycodeUI */,
 			);
 			);
@@ -124,10 +143,40 @@
 			children = (
 			children = (
 				6DFBF84712A3F24F00C43A7D /* libPolycodeUI.a */,
 				6DFBF84712A3F24F00C43A7D /* libPolycodeUI.a */,
 				6DFB00FC12A736A900C43A7D /* libPolycodeCg.a */,
 				6DFB00FC12A736A900C43A7D /* libPolycodeCg.a */,
+				6D690D1B12C1D74A00C444B0 /* libPolycode3DPhysics.a */,
 			);
 			);
 			name = Products;
 			name = Products;
 			sourceTree = "<group>";
 			sourceTree = "<group>";
 		};
 		};
+		6D690D7C12C1D99700C444B0 /* 3DPhysics */ = {
+			isa = PBXGroup;
+			children = (
+				6D690D7D12C1D99700C444B0 /* Include */,
+				6D690D8112C1D99700C444B0 /* Source */,
+			);
+			name = 3DPhysics;
+			path = ../../Contents/3DPhysics;
+			sourceTree = SOURCE_ROOT;
+		};
+		6D690D7D12C1D99700C444B0 /* Include */ = {
+			isa = PBXGroup;
+			children = (
+				6D690D7E12C1D99700C444B0 /* Polycode3DPhysics.h */,
+				6D690D7F12C1D99700C444B0 /* PolyCollisionScene.h */,
+				6D690D8012C1D99700C444B0 /* PolyCollisionSceneEntity.h */,
+			);
+			path = Include;
+			sourceTree = "<group>";
+		};
+		6D690D8112C1D99700C444B0 /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				6D690D8212C1D99700C444B0 /* PolyCollisionScene.cpp */,
+				6D690D8312C1D99700C444B0 /* PolyCollisionSceneEntity.cpp */,
+			);
+			path = Source;
+			sourceTree = "<group>";
+		};
 		6DFB00C012A71A5B00C43A7D /* PolycodeUI */ = {
 		6DFB00C012A71A5B00C43A7D /* PolycodeUI */ = {
 			isa = PBXGroup;
 			isa = PBXGroup;
 			children = (
 			children = (
@@ -186,6 +235,16 @@
 /* End PBXGroup section */
 /* End PBXGroup section */
 
 
 /* Begin PBXHeadersBuildPhase section */
 /* Begin PBXHeadersBuildPhase section */
+		6D690D1712C1D74A00C444B0 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6D690D8412C1D99700C444B0 /* Polycode3DPhysics.h in Headers */,
+				6D690D8512C1D99700C444B0 /* PolyCollisionScene.h in Headers */,
+				6D690D8612C1D99700C444B0 /* PolyCollisionSceneEntity.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		6DFB00F812A736A900C43A7D /* Headers */ = {
 		6DFB00F812A736A900C43A7D /* Headers */ = {
 			isa = PBXHeadersBuildPhase;
 			isa = PBXHeadersBuildPhase;
 			buildActionMask = 2147483647;
 			buildActionMask = 2147483647;
@@ -220,6 +279,23 @@
 /* End PBXHeadersBuildPhase section */
 /* End PBXHeadersBuildPhase section */
 
 
 /* Begin PBXNativeTarget section */
 /* Begin PBXNativeTarget section */
+		6D690D1A12C1D74A00C444B0 /* Polycode3DPhysics */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6D690D2012C1D76A00C444B0 /* Build configuration list for PBXNativeTarget "Polycode3DPhysics" */;
+			buildPhases = (
+				6D690D1712C1D74A00C444B0 /* Headers */,
+				6D690D1812C1D74A00C444B0 /* Sources */,
+				6D690D1912C1D74A00C444B0 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = Polycode3DPhysics;
+			productName = Polycode3DPhysics;
+			productReference = 6D690D1B12C1D74A00C444B0 /* libPolycode3DPhysics.a */;
+			productType = "com.apple.product-type.library.static";
+		};
 		6DFB00FB12A736A900C43A7D /* PolycodeCg */ = {
 		6DFB00FB12A736A900C43A7D /* PolycodeCg */ = {
 			isa = PBXNativeTarget;
 			isa = PBXNativeTarget;
 			buildConfigurationList = 6DFB010A12A736BE00C43A7D /* Build configuration list for PBXNativeTarget "PolycodeCg" */;
 			buildConfigurationList = 6DFB010A12A736BE00C43A7D /* Build configuration list for PBXNativeTarget "PolycodeCg" */;
@@ -275,11 +351,21 @@
 			targets = (
 			targets = (
 				6DFBF84612A3F24F00C43A7D /* PolycodeUI */,
 				6DFBF84612A3F24F00C43A7D /* PolycodeUI */,
 				6DFB00FB12A736A900C43A7D /* PolycodeCg */,
 				6DFB00FB12A736A900C43A7D /* PolycodeCg */,
+				6D690D1A12C1D74A00C444B0 /* Polycode3DPhysics */,
 			);
 			);
 		};
 		};
 /* End PBXProject section */
 /* End PBXProject section */
 
 
 /* Begin PBXSourcesBuildPhase section */
 /* Begin PBXSourcesBuildPhase section */
+		6D690D1812C1D74A00C444B0 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6D690D8712C1D99700C444B0 /* PolyCollisionScene.cpp in Sources */,
+				6D690D8812C1D99700C444B0 /* PolyCollisionSceneEntity.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		6DFB00F912A736A900C43A7D /* Sources */ = {
 		6DFB00F912A736A900C43A7D /* Sources */ = {
 			isa = PBXSourcesBuildPhase;
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			buildActionMask = 2147483647;
@@ -324,6 +410,7 @@
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				HEADER_SEARCH_PATHS = (
 				HEADER_SEARCH_PATHS = (
 					../../../Core/Contents/Include,
 					../../../Core/Contents/Include,
+					../../../Core/Dependencies/bullet/src,
 					../../../Core/Dependencies/libvorbis/include,
 					../../../Core/Dependencies/libvorbis/include,
 					../../../Core/Dependencies/libogg/include,
 					../../../Core/Dependencies/libogg/include,
 					/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/OpenAL.framework/Versions/A/Headers,
 					/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/OpenAL.framework/Versions/A/Headers,
@@ -350,6 +437,36 @@
 			};
 			};
 			name = Release;
 			name = Release;
 		};
 		};
+		6D690D1C12C1D74A00C444B0 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = Polycode3DPhysics;
+			};
+			name = Debug;
+		};
+		6D690D1D12C1D74A00C444B0 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = Polycode3DPhysics;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
 		6DFB00FD12A736AA00C43A7D /* Debug */ = {
 		6DFB00FD12A736AA00C43A7D /* Debug */ = {
 			isa = XCBuildConfiguration;
 			isa = XCBuildConfiguration;
 			buildSettings = {
 			buildSettings = {
@@ -431,6 +548,15 @@
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;
 			defaultConfigurationName = Release;
 		};
 		};
+		6D690D2012C1D76A00C444B0 /* Build configuration list for PBXNativeTarget "Polycode3DPhysics" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6D690D1C12C1D74A00C444B0 /* Debug */,
+				6D690D1D12C1D74A00C444B0 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
 		6DFB010A12A736BE00C43A7D /* Build configuration list for PBXNativeTarget "PolycodeCg" */ = {
 		6DFB010A12A736BE00C43A7D /* Build configuration list for PBXNativeTarget "PolycodeCg" */ = {
 			isa = XCConfigurationList;
 			isa = XCConfigurationList;
 			buildConfigurations = (
 			buildConfigurations = (

+ 121 - 0
Modules/Contents/2DPhysics/Include/PolyPhysicsScreen.h

@@ -0,0 +1,121 @@
+/*
+ *  PolyPhysicsScreen.h
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 5/8/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+// @package ScreenPhysics
+
+#pragma once
+#include "PolyGlobals.h"
+#include "PolyScreen.h"
+#include "Box2D.h"
+//#include "PolyCoreServices.h"
+#include "PolyScreenLine.h"
+#include "PolyPhysicsScreenEntity.h"
+#include "PolyTimer.h"
+#include <vector>
+
+#define MAX_B2DCONTACTPOINTS 2048
+
+namespace Polycode {
+	
+class _PolyExport PhysicsScreenEvent : public Event {
+	public:	
+		
+		PhysicsScreenEntity *entity1;	
+		PhysicsScreenEntity *entity2;	
+	
+		static const int EVENT_NEW_SHAPE_COLLISION = 0;
+		static const int EVENT_END_SHAPE_COLLISION = 1;
+		static const int EVENT_PERSIST_SHAPE_COLLISION = 2;	
+};		
+
+
+enum ContactState
+{
+	e_contactAdded = 0,
+	e_contactPersisted = 1,
+	e_contactRemoved = 2,
+};
+	
+struct ContactPoint
+{
+	b2Shape* shape1;
+	b2Shape* shape2;
+	b2Vec2 normal;
+	b2Vec2 position;
+	b2Vec2 velocity;
+	b2ContactID id;
+	ContactState state;
+};
+	
+	
+class _PolyExport PhysicsScreen : public Screen, b2ContactListener {
+
+public:
+	PhysicsScreen();
+	PhysicsScreen(float freq);
+	
+	PhysicsScreen(Vector2 physicsWorldLowerBound, Vector2 physicsWorldUpperBound);
+	~PhysicsScreen();
+	
+	void Update();
+	PhysicsScreenEntity *addPhysicsChild(ScreenEntity *newEntity, int entType, float friction, float density, float restitution = 0, bool isSensor = false);
+	void removePhysicsChild(PhysicsScreenEntity *entityToRemove);
+	
+	PhysicsScreenEntity *addCollisionChild(ScreenEntity *newEntity, int entType);
+	
+	void createDistanceJoint(ScreenEntity *ent1, ScreenEntity *ent2, bool collideConnected);
+	void createPrismaticJoint(ScreenEntity *ent1, ScreenEntity *ent2, bool collideConnected);
+	b2RevoluteJoint *createRevoluteJoint(ScreenEntity *ent1, ScreenEntity *ent2, float ax, float ay, bool enableLimit, float lowerLimit, float upperLimit, bool motorEnabled, float motorSpeed, float maxTorque);
+	b2MouseJoint *createMouseJoint(ScreenEntity *ent1, Vector2 *mp);
+	void applyForce(ScreenEntity *ent, float fx, float fy);
+	void applyImpulse(ScreenEntity *ent, float fx, float fy);
+	
+	PhysicsScreenEntity *getPhysicsEntityByShape(b2Shape *shape);
+	
+	void setVelocity(ScreenEntity *ent, float fx, float fy);	
+	void setVelocityX(ScreenEntity *ent, float fx);	
+	void setVelocityY(ScreenEntity *ent, float fy);	
+	
+	void Add(const b2ContactPoint* point);
+	void Persist(const b2ContactPoint* point);
+	void Remove(const b2ContactPoint* point);				
+	
+	void wakeUp(ScreenEntity *ent);
+	
+	void handleEvent(Event *event);
+	
+	Vector2 getEntityCollisionNormal(ScreenEntity *ent1, ScreenEntity *ent2);
+	
+	bool areEntitiesColliding(ScreenEntity *ent1, ScreenEntity *ent2);
+	ScreenEntity *getEntityAtPosition(float x, float y);
+	bool testEntityAtPosition(ScreenEntity *ent, float x, float y);
+	
+	void Shutdown();
+	
+	PhysicsScreenEntity *getPhysicsByScreenEntity(ScreenEntity *ent);
+	void destroyMouseJoint(b2MouseJoint *mJoint);
+
+
+protected:
+	
+	void init(Vector2 physicsWorldLowerBound, Vector2 physicsWorldUpperBound, float physicsTimeStep, int physicsIterations, Vector2 physicsGravity);
+
+	Timer *updateTimer;
+	vector <PhysicsScreenEntity*> physicsChildren;
+	
+	ContactPoint m_points[MAX_B2DCONTACTPOINTS];
+	int32 numContactPoints;
+	
+	b2World *world;
+	float32 timeStep;
+	int32 iterations;
+};
+
+
+}

+ 49 - 0
Modules/Contents/2DPhysics/Include/PolyPhysicsScreenEntity.h

@@ -0,0 +1,49 @@
+/*
+ *  PolyPhysicsScreenEntity.h
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 5/8/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+ 
+// @package ScreenPhysics
+
+#pragma once
+#include "PolyGlobals.h"
+#include "PolyScreenEntity.h"
+#include "Box2D.h"
+
+namespace Polycode {
+
+	class _PolyExport PhysicsScreenEntity {
+		public:
+			PhysicsScreenEntity(ScreenEntity *entity, b2World *world, int entType, float friction, float density, float restitution, bool isSensor);
+			~PhysicsScreenEntity();		
+			
+			ScreenEntity *getScreenEntity();
+			
+			void applyTorque(float torque);
+			void applyForce(Vector2 force);
+			
+			void Update();
+			
+			static const int ENTITY_RECT = 1;
+			static const int ENTITY_CIRCLE = 2;	
+			static const int ENTITY_STATICRECT = 3;
+		
+			b2Body* body;
+			b2BodyDef *bodyDef;
+			b2Shape *shape;
+			
+			bool collisionOnly;
+		
+		protected:
+		
+		Vector2 lastPosition;
+		float lastRotation;
+			
+		ScreenEntity *screenEntity;
+	};
+
+}

+ 405 - 0
Modules/Contents/2DPhysics/Source/PolyPhysicsScreen.cpp

@@ -0,0 +1,405 @@
+/*
+ *  PolyPhysicsScreen.cpp
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 5/8/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+
+#include "PolyPhysicsScreen.h"
+
+using namespace Polycode;
+
+
+void PhysicsScreen::Add(const b2ContactPoint* point) {
+	if (numContactPoints == MAX_B2DCONTACTPOINTS) {
+		return;
+	}
+	
+	ContactPoint* cp = m_points + numContactPoints;
+	cp->shape1 = point->shape1;
+	cp->shape2 = point->shape2;
+	cp->position = point->position;
+	cp->normal = point->normal;
+	cp->id = point->id;
+	cp->state = e_contactAdded;
+	
+	++numContactPoints;
+}
+
+void PhysicsScreen::Persist(const b2ContactPoint* point) {
+	if (numContactPoints == MAX_B2DCONTACTPOINTS) {
+		return;
+	}
+	
+	ContactPoint* cp = m_points + numContactPoints;
+	cp->shape1 = point->shape1;
+	cp->shape2 = point->shape2;
+	cp->position = point->position;
+	cp->normal = point->normal;
+	cp->id = point->id;
+	cp->state = e_contactPersisted;
+	
+	++numContactPoints;
+}
+
+void PhysicsScreen::Remove(const b2ContactPoint* point) {
+	if (numContactPoints == MAX_B2DCONTACTPOINTS) {
+		return;
+	}
+	
+	ContactPoint* cp = m_points + numContactPoints;
+	cp->shape1 = point->shape1;
+	cp->shape2 = point->shape2;
+	cp->position = point->position;
+	cp->normal = point->normal;
+	cp->id = point->id;
+	cp->state = e_contactRemoved;
+	
+	++numContactPoints;
+}
+
+PhysicsScreen::PhysicsScreen() : Screen() {
+	init(Vector2(-200.0f, -100.0f),Vector2(8500.0f, 1000.0f),1.0f/60.0f,10,Vector2(0.0f, 10.0f));
+}
+
+PhysicsScreen::PhysicsScreen(float freq) : Screen() {
+	init(Vector2(-200.0f, -100.0f),Vector2(8500.0f, 1000.0f),1.0f/freq,10,Vector2(0.0f, 10.0f));	
+}
+
+PhysicsScreen::PhysicsScreen(Vector2 physicsWorldLowerBound, Vector2 physicsWorldUpperBound)
+{
+	init(physicsWorldLowerBound,physicsWorldUpperBound,1.0f/60.0f,10,Vector2(0.0f, 10.0f));
+}
+
+void PhysicsScreen::init(Vector2 physicsWorldLowerBound, Vector2 physicsWorldUpperBound, float physicsTimeStep, int physicsIterations, Vector2 physicsGravity) {
+	numContactPoints = 0;	
+	timeStep = physicsTimeStep;
+	iterations = physicsIterations;
+	
+	b2AABB worldAABB;
+	worldAABB.lowerBound.Set(physicsWorldLowerBound.x/10.0,physicsWorldLowerBound.y/10.0);
+	worldAABB.upperBound.Set(physicsWorldUpperBound.x/10.0,physicsWorldUpperBound.y/10.0);
+	
+	b2Vec2 gravity(physicsGravity.x,physicsGravity.y);
+	bool doSleep = true;
+	world  = new b2World(worldAABB, gravity, doSleep);
+	
+	world->SetContactListener(this);
+
+	updateTimer = new Timer(true, 3);
+	updateTimer->addEventListener(this, Timer::EVENT_TRIGGER);
+}
+
+PhysicsScreenEntity *PhysicsScreen::getPhysicsByScreenEntity(ScreenEntity *ent) {
+	for(int i=0; i<physicsChildren.size();i++) {
+		if(physicsChildren[i]->getScreenEntity() == ent)
+			return physicsChildren[i];
+	}	
+	return NULL;
+}
+
+b2RevoluteJoint *PhysicsScreen::createRevoluteJoint(ScreenEntity *ent1, ScreenEntity *ent2, float ax, float ay, bool enableLimit, float lowerLimit, float upperLimit, bool motorEnabled, float motorSpeed, float maxTorque) {
+	PhysicsScreenEntity *pEnt1 = getPhysicsByScreenEntity(ent1);
+	PhysicsScreenEntity *pEnt2 = getPhysicsByScreenEntity(ent2);
+	if(pEnt1 == NULL || pEnt2 == NULL)
+		return NULL;
+	
+	b2Vec2 anchor((ent1->getPosition()->x+ax)/10.0f, (ent1->getPosition()->y+ay)/10.0f);
+	b2RevoluteJointDef *jointDef = new b2RevoluteJointDef();
+	jointDef->collideConnected = false;
+	jointDef->lowerAngle = lowerLimit * (PI/180.0f);
+	jointDef->upperAngle = upperLimit * (PI/180.0f);
+	jointDef->enableLimit = enableLimit;
+	jointDef->motorSpeed = motorSpeed;
+	jointDef->maxMotorTorque = maxTorque;
+	jointDef->enableMotor = motorEnabled;	
+	jointDef->Initialize(pEnt1->body, pEnt2->body, anchor);
+	b2RevoluteJoint *joint = (b2RevoluteJoint*)world->CreateJoint(jointDef);
+	return joint;
+}
+
+void PhysicsScreen::createPrismaticJoint(ScreenEntity *ent1, ScreenEntity *ent2, bool collideConnected) {
+
+}
+
+void PhysicsScreen::wakeUp(ScreenEntity *ent) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+		
+	pEnt->body->WakeUp();
+}
+
+void PhysicsScreen::setVelocity(ScreenEntity *ent, float fx, float fy) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+	
+	pEnt->body->WakeUp();
+	b2Vec2 f = pEnt->body->GetLinearVelocity();
+	if(fx != 0)
+		f.x = fx;
+	if(fy != 0)
+		f.y = fy;
+	
+	pEnt->body->SetLinearVelocity(f);
+}
+
+void PhysicsScreen::setVelocityX(ScreenEntity *ent, float fx) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+	
+	pEnt->body->WakeUp();
+	b2Vec2 f = pEnt->body->GetLinearVelocity();
+	f.x = fx;	
+	pEnt->body->SetLinearVelocity(f);
+	
+}
+
+void PhysicsScreen::setVelocityY(ScreenEntity *ent, float fy) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+	
+	pEnt->body->WakeUp();
+	b2Vec2 f = pEnt->body->GetLinearVelocity();
+	f.y = fy;	
+	pEnt->body->SetLinearVelocity(f);	
+}
+
+
+PhysicsScreenEntity *PhysicsScreen::addCollisionChild(ScreenEntity *newEntity, int entType) {
+	PhysicsScreenEntity *ret;
+	ret = addPhysicsChild(newEntity, entType, 0,0.1,0, true);
+	ret->collisionOnly = true; 
+	return ret;
+}
+
+void PhysicsScreen::applyForce(ScreenEntity *ent, float fx, float fy) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+
+	pEnt->body->WakeUp();
+	b2Vec2 f =  b2Vec2(fx,fy);
+	b2Vec2 p = pEnt->body->GetWorldPoint(b2Vec2(0.0f, 0.0f));
+		
+	pEnt->body->ApplyForce(f, p);
+}
+
+void PhysicsScreen::applyImpulse(ScreenEntity *ent, float fx, float fy) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);
+	if(pEnt == NULL)
+		return;
+	
+	pEnt->body->WakeUp();
+	b2Vec2 f =  b2Vec2(fx,fy);
+	b2Vec2 p = pEnt->body->GetWorldPoint(b2Vec2(0.0f, 0.0f));
+	
+	pEnt->body->ApplyImpulse(f, p);	
+}
+
+
+
+void PhysicsScreen::createDistanceJoint(ScreenEntity *ent1, ScreenEntity *ent2, bool collideConnected) {
+	PhysicsScreenEntity *pEnt1 = getPhysicsByScreenEntity(ent1);
+	PhysicsScreenEntity *pEnt2 = getPhysicsByScreenEntity(ent2);
+	if(pEnt1 == NULL || pEnt2 == NULL)
+		return;
+	
+	b2Vec2 a1(ent1->getPosition()->x/10.0f, ent1->getPosition()->y/10.0f);
+	b2Vec2 a2(ent2->getPosition()->x/10.0f, ent2->getPosition()->y/10.0f);
+	b2DistanceJointDef *jointDef = new b2DistanceJointDef();
+	jointDef->Initialize(pEnt1->body, pEnt2->body, a1, a2);
+	jointDef->collideConnected = collideConnected;
+	world->CreateJoint(jointDef);
+}
+
+b2MouseJoint *PhysicsScreen::createMouseJoint(ScreenEntity *ent1, Vector2 *mp) {
+	
+	PhysicsScreenEntity *pEnt1 = getPhysicsByScreenEntity(ent1);
+	if(pEnt1 == NULL)
+		return NULL;
+
+	b2MouseJointDef *mj = new b2MouseJointDef();
+	
+	mj->body1 = world->GetGroundBody();
+	mj->body2 = pEnt1->body;
+	b2Vec2 mpos(mp->x/10.0f, mp->y/10.0f);
+	mj->target = mpos;
+#ifdef TARGET_FLOAT32_IS_FIXED
+	mj->maxForce = (pEnt1->body->GetMass() < 16.0)? (1000.0f * pEnt1->body->GetMass()) : float32(16000.0);
+#else
+	mj->maxForce = 1000.0f * pEnt1->body->GetMass();
+#endif
+	b2MouseJoint *m_mouseJoint = (b2MouseJoint*)world->CreateJoint(mj);
+	pEnt1->body->WakeUp();
+	Logger::log("OK %d!\n", m_mouseJoint);
+	return m_mouseJoint;
+}
+
+Vector2 PhysicsScreen::getEntityCollisionNormal(ScreenEntity *ent1, ScreenEntity *ent2) {
+	PhysicsScreenEntity *pEnt1 = getPhysicsByScreenEntity(ent1);
+	PhysicsScreenEntity *pEnt2 = getPhysicsByScreenEntity(ent2);	
+	if(pEnt1 == NULL || pEnt2 == NULL)
+		return Vector2(0,0);	
+	
+	PhysicsScreenEntity *rEnt1;
+	PhysicsScreenEntity *rEnt2;
+	for (int32 i = 0; i < numContactPoints; ++i)
+	{
+		ContactPoint* point = m_points + i;		
+		if (point->state == 0 || point->state == 1) {	
+			rEnt1= getPhysicsEntityByShape(point->shape1);
+			rEnt2 = getPhysicsEntityByShape(point->shape2);						
+			if((rEnt1 == pEnt1 && rEnt2 == pEnt2) || 
+			   (rEnt1 == pEnt2 && rEnt2 == pEnt1)) {
+				return Vector2(point->normal.x,point->normal.y);
+			}
+		}
+	}
+	return Vector2(0,0);	
+}
+
+bool PhysicsScreen::areEntitiesColliding(ScreenEntity *ent1, ScreenEntity *ent2) {
+	PhysicsScreenEntity *pEnt1 = getPhysicsByScreenEntity(ent1);
+	PhysicsScreenEntity *pEnt2 = getPhysicsByScreenEntity(ent2);	
+	if(pEnt1 == NULL || pEnt2 == NULL)
+		return false;
+	
+	PhysicsScreenEntity *rEnt1;
+	PhysicsScreenEntity *rEnt2;
+	for (int32 i = 0; i < numContactPoints; ++i)
+	{
+		ContactPoint* point = m_points + i;		
+		if (point->state == 0 || point->state == 1) {	
+			rEnt1= getPhysicsEntityByShape(point->shape1);
+			rEnt2 = getPhysicsEntityByShape(point->shape2);						
+			if((rEnt1 == pEnt1 && rEnt2 == pEnt2) || 
+			   (rEnt1 == pEnt2 && rEnt2 == pEnt1)) {
+				return true;
+			}
+		}
+	}
+	return false;
+}
+
+ScreenEntity *PhysicsScreen::getEntityAtPosition(float x, float y) {
+	ScreenEntity *ret = NULL;
+	
+	b2Vec2 mousePosition;
+	mousePosition.x = x/10.0f;
+	mousePosition.y = y/10.0f;
+	
+	for(int i=0;i<physicsChildren.size();i++) {
+		PhysicsScreenEntity *ent = physicsChildren[i];
+		if(ent->shape->TestPoint(ent->body->GetXForm(), mousePosition))
+			return ent->getScreenEntity();
+	}	
+	return ret;
+}
+
+bool PhysicsScreen::testEntityAtPosition(ScreenEntity *ent, float x, float y) {
+	PhysicsScreenEntity *pEnt = getPhysicsByScreenEntity(ent);	
+	
+	if(pEnt == NULL)
+		return false;
+	
+	b2Vec2 mousePosition;
+	mousePosition.x = x/10.0f;
+	mousePosition.y = y/10.0f;
+	
+	if(pEnt->shape->TestPoint(pEnt->body->GetXForm(), mousePosition))
+		return true;
+	else
+		return false;
+	
+}
+
+void PhysicsScreen::destroyMouseJoint(b2MouseJoint *mJoint) {
+		world->DestroyJoint(mJoint);
+		mJoint = NULL;
+}
+
+PhysicsScreenEntity *PhysicsScreen::addPhysicsChild(ScreenEntity *newEntity, int entType, float friction, float density, float restitution, bool isSensor) {
+	addChild(newEntity);
+	newEntity->setPositionMode(ScreenEntity::POSITION_CENTER);
+	PhysicsScreenEntity *newPhysicsEntity = new PhysicsScreenEntity(newEntity, world, entType, friction, density, restitution, isSensor);
+	physicsChildren.push_back(newPhysicsEntity);
+	newPhysicsEntity->body->WakeUp();
+	return newPhysicsEntity;
+}
+
+void PhysicsScreen::removePhysicsChild(PhysicsScreenEntity *entityToRemove) {
+	world->DestroyBody(entityToRemove->body);
+	removeChild(entityToRemove->getScreenEntity());
+	for(int i=0;i<physicsChildren.size();i++) {
+		if(physicsChildren[i] == entityToRemove) {
+			physicsChildren.erase(physicsChildren.begin()+i);
+		}
+	}
+}
+
+
+void PhysicsScreen::Shutdown() {
+
+}
+
+PhysicsScreen::~PhysicsScreen() {
+	delete world;
+	for(int i=0; i<physicsChildren.size();i++) {
+			delete physicsChildren[i];
+	}
+}
+
+PhysicsScreenEntity *PhysicsScreen::getPhysicsEntityByShape(b2Shape *shape) {
+	for(int i=0; i < physicsChildren.size(); i++) {
+		if(physicsChildren[i]->shape == shape)
+			return physicsChildren[i];
+	}
+	return NULL;
+}
+	
+void PhysicsScreen::handleEvent(Event *event) {
+	
+	numContactPoints = 0;
+	
+	if(event->getDispatcher() == updateTimer) {		
+		world->Step(timeStep, iterations);
+	}
+	
+	for (int32 i = 0; i < numContactPoints; ++i)
+	{
+		ContactPoint* point = m_points + i;		
+		if (point->state == 0) {	
+			PhysicsScreenEvent *newEvent = new PhysicsScreenEvent();
+			newEvent->entity1 = getPhysicsEntityByShape(point->shape1);
+			newEvent->entity2 = getPhysicsEntityByShape(point->shape2);			
+	
+			dispatchEvent(newEvent, PhysicsScreenEvent::EVENT_NEW_SHAPE_COLLISION);
+		} else if (point->state == 1) {
+			// Persist
+//			DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f));
+		} else {
+			// Remove
+//			DrawPoint(point->position, 10.0f, b2Color(0.95f, 0.3f, 0.3f));
+			dispatchEvent(new PhysicsScreenEvent(), PhysicsScreenEvent::EVENT_END_SHAPE_COLLISION);			
+		}
+	}
+	
+	Screen::handleEvent(event);
+}
+
+void PhysicsScreen::Update() {
+//	unsigned int elapsed = updateTimer->getTicks();	
+//	if(updateTimer->hasElapsed()) {
+//		world->Step(timeStep, iterations);
+		for(int i=0; i<physicsChildren.size();i++) {
+			physicsChildren[i]->Update();
+		}
+//	}
+}

+ 107 - 0
Modules/Contents/2DPhysics/Source/PolyPhysicsScreenEntity.cpp

@@ -0,0 +1,107 @@
+/*
+ *  PolyPhysicsScreenEntity.cpp
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 5/8/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+#define PI 3.14159265
+
+#include "PolyPhysicsScreenEntity.h"
+
+using namespace Polycode;
+
+PhysicsScreenEntity::PhysicsScreenEntity(ScreenEntity *entity, b2World *world, int entType, float friction, float density, float restitution, bool isSensor) {
+	screenEntity = entity;
+	
+	bodyDef = new b2BodyDef();
+	bodyDef->position.Set(screenEntity->getPosition()->x/10.0f, screenEntity->getPosition()->y/10.0f);
+	bodyDef->angle = screenEntity->getRotation()*(PI/180.0f);
+	body = world->CreateBody(bodyDef);
+	bodyDef->isBullet = isSensor;
+	
+	switch(entType) {
+		case ENTITY_STATICRECT:{
+			b2PolygonDef *groundShapeDef = new b2PolygonDef();
+			groundShapeDef->isSensor = isSensor;
+			groundShapeDef->SetAsBox(screenEntity->getWidth()/20.0f, screenEntity->getHeight()/20.0f);
+			shape = body->CreateShape(groundShapeDef);
+		}
+		break;
+		case ENTITY_RECT: {
+			b2PolygonDef *shapeDef;
+			shapeDef = new b2PolygonDef();
+			shapeDef->SetAsBox(screenEntity->getWidth()/20.0f, screenEntity->getHeight()/20.0f);
+			shapeDef->density = density;
+			shapeDef->friction = friction;
+			shapeDef->restitution = restitution;
+			shapeDef->isSensor = isSensor;			
+			shape = body->CreateShape(shapeDef);
+			}
+		break;			
+		case ENTITY_CIRCLE: {
+			b2CircleDef *shapeDef = new b2CircleDef();
+			shapeDef->radius = screenEntity->getWidth()/20.0f;
+			shapeDef->density = density;
+//			shapeDef->SetAsBox(screenEntity->getWidth()/20.0f, screenEntity->getHeight()/20.0f);
+			shapeDef->friction = friction;
+			shapeDef->restitution = restitution;
+			shapeDef->isSensor = isSensor;				
+			shape = body->CreateShape(shapeDef);
+			}
+		break;
+	}
+	
+	lastPosition.x = screenEntity->getPosition2D().x;
+	lastPosition.y = screenEntity->getPosition2D().y;
+
+	body->SetMassFromShapes();
+
+	collisionOnly = false;
+}
+
+void PhysicsScreenEntity::applyTorque(float torque) {
+	body->ApplyTorque(torque);
+}
+
+void PhysicsScreenEntity::applyForce(Vector2 force){
+	body->WakeUp();
+	body->ApplyForce(b2Vec2(force.x,force.y), b2Vec2(body->GetPosition().x,body->GetPosition().y));
+}
+
+ScreenEntity *PhysicsScreenEntity::getScreenEntity() {
+	return screenEntity;
+}
+			
+void PhysicsScreenEntity::Update() {
+	b2Vec2 position = body->GetPosition();
+	float32 angle = body->GetAngle();
+
+	if(lastRotation != screenEntity->getRotation() || collisionOnly) {
+		body->SetXForm(position, screenEntity->getRotation()*(PI/180.0f));		
+	} else {
+		screenEntity->setRotation(angle*(180.0f/PI));	
+	}
+	
+	if(lastPosition != screenEntity->getPosition2D() || collisionOnly) {
+		b2Vec2 newPos;
+		newPos.x = screenEntity->getPosition2D().x/10.0f; 
+		newPos.y = screenEntity->getPosition2D().y/10.0f;				
+		body->SetXForm(newPos, screenEntity->getRotation()*(PI/180.0f));
+		position.x = screenEntity->getPosition2D().x/10.0f; 
+		position.y = screenEntity->getPosition2D().y/10.0f; 				
+	} else {
+		screenEntity->setPosition(position.x*10.0f, position.y*10.0f);
+	}
+	
+	lastPosition.x = position.x*10.0f;
+	lastPosition.y = position.y*10.0f;	
+	
+	lastRotation = angle * (180.0f/PI);
+}
+
+PhysicsScreenEntity::~PhysicsScreenEntity() {
+
+}

+ 72 - 0
Modules/Contents/3DPhysics/Include/PolyCollisionScene.h

@@ -0,0 +1,72 @@
+/*
+ *  PolyCollisionScene.h
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 6/16/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+// @package SceneDynamics
+
+#pragma once
+#include "PolyLogger.h"
+#include "PolyGlobals.h"
+#include "PolyGenericScene.h"
+#include "PolyCollisionSceneEntity.h"
+#include "btBulletCollisionCommon.h"
+#include "PolyVector3.h"
+#include <vector>
+
+using std::vector;
+
+namespace Polycode {
+
+struct CollisionResult {
+	bool collided;
+	Vector3 colNormal;
+	float colDist;
+	bool setOldPosition;
+	Vector3 newPos;
+};
+
+	struct RayTestResult {
+		SceneEntity *entity;
+		Vector3 normal;
+		Vector3 position;
+	};
+
+	class _PolyExport CollisionScene : public GenericScene {
+		public:
+			CollisionScene();
+			CollisionScene(bool virtualScene);		
+			~CollisionScene();
+		
+			void initCollisionScene();
+		
+			void Update();		
+			void enableCollision(SceneEntity *entity, bool val);		
+			CollisionSceneEntity *getCollisionEntityByObject(btCollisionObject *collisionObject);		
+			RayTestResult getFirstEntityInRay(const Vector3 &origin,  const Vector3 &dest);
+			
+			CollisionSceneEntity *getCollisionByScreenEntity(SceneEntity *ent);
+			CollisionResult testCollision(SceneEntity *ent1, SceneEntity *ent2);
+			CollisionResult testCollisionOnCollisionChild(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2);				
+			CollisionResult testCollisionOnCollisionChild_Convex(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2);		
+			CollisionResult testCollisionOnCollisionChild_RayTest(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2);					
+			Vector3 getCollisionNormalFromCollisionEnts(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2);			
+			Vector3 getCollisionNormal(SceneEntity *ent1, SceneEntity *ent2);			
+			void applyVelocity(SceneEntity *entity, float x, float y, float z);			
+			void loadCollisionChild(SceneEntity *entity, bool autoCollide=false, int type=0);
+			void enableGravity(SceneEntity *entity);
+			
+			CollisionSceneEntity *addCollisionChild(SceneEntity *newEntity, bool autoCollide=false, int type=0);
+			CollisionSceneEntity *trackCollision(SceneEntity *newEntity, bool autoCollide, int type=0);
+			void adjustForCollision(CollisionSceneEntity *collisionEntity);
+		private:
+		
+			vector<CollisionSceneEntity*> collisionChildren;
+			btCollisionWorld *world;
+	};
+
+}

+ 57 - 0
Modules/Contents/3DPhysics/Include/PolyCollisionSceneEntity.h

@@ -0,0 +1,57 @@
+/*
+ *  PolyCollisionSceneEntity.h
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 6/17/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+// @package SceneDynamics
+
+#pragma once
+#include "PolyLogger.h"
+#include "PolyGlobals.h"
+#include "PolySceneEntity.h"
+#include "btBulletCollisionCommon.h"
+#include "PolyCoreServices.h"
+#include "PolySceneMesh.h"
+
+namespace Polycode {
+
+	class _PolyExport CollisionSceneEntity {
+		public:
+			CollisionSceneEntity(SceneEntity *entity, bool autoCollide, int type);
+			~CollisionSceneEntity();
+			
+			SceneEntity *getSceneEntity();
+			void Update();
+		
+			int getType() { return type; }
+			btConvexShape *getShape(){ return shape; }
+		
+			btCollisionObject *collisionObject;
+			bool gravityEnabled;
+			bool autoCollide;
+			Vector3 gravityVector;
+			Vector3 gVelocity;
+			float gravityStrength;
+		
+			Vector3 lastPosition;
+		
+			static const int SHAPE_BOX = 0;
+			static const int SHAPE_TERRAIN = 1;
+			static const int SHAPE_SPHERE = 2;	
+			static const int SHAPE_MESH = 3;			
+		
+			bool enabled;
+		
+		private:
+		
+			
+			btConvexShape *shape;
+		
+			int type;
+			SceneEntity *sceneEntity;
+	
+	};
+}

+ 4 - 0
Modules/Contents/3DPhysics/Include/Polycode3DPhysics.h

@@ -0,0 +1,4 @@
+
+#pragma once
+#include "PolyCollisionScene.h"
+#include "PolyCollisionSceneEntity.h"

+ 335 - 0
Modules/Contents/3DPhysics/Source/PolyCollisionScene.cpp

@@ -0,0 +1,335 @@
+/*
+ *  PolyCollisionScene.cpp
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 6/16/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+
+#include "PolyCollisionScene.h"
+
+using namespace Polycode;
+
+CollisionScene::CollisionScene() : GenericScene() {
+	initCollisionScene();
+}
+
+CollisionScene::CollisionScene(bool virtualScene) : GenericScene(virtualScene) { 
+	initCollisionScene();
+}
+
+void CollisionScene::initCollisionScene() {
+	
+	btVector3	worldAabbMin(-1000,-1000,-1000);
+	btVector3	worldAabbMax(1000,1000,1000);
+	
+	btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
+	btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
+	//	dispatcher->setNearCallback(customNearCallback);
+	btAxisSweep3*	broadphase = new btAxisSweep3(worldAabbMin,worldAabbMax);
+	world = new btCollisionWorld(dispatcher,broadphase,collisionConfiguration);	
+}
+
+void CollisionScene::Update() {
+	
+	for(int i=0; i < collisionChildren.size(); i++) {
+		if(collisionChildren[i]->enabled)
+			collisionChildren[i]->Update();
+	}
+	
+	world->performDiscreteCollisionDetection();	
+	for(int i=0; i < collisionChildren.size(); i++) {
+		if(collisionChildren[i]->enabled) {		
+			if(collisionChildren[i]->autoCollide) {
+				adjustForCollision(collisionChildren[i]);
+			}	
+		}
+	}
+	
+	for(int i=0; i < collisionChildren.size(); i++) {
+		if(collisionChildren[i]->enabled)		
+			collisionChildren[i]->lastPosition = *collisionChildren[i]->getSceneEntity()->getPosition();
+	}	
+}
+
+void CollisionScene::enableCollision(SceneEntity *entity, bool val) {
+	// what the fuck?? rename that
+	CollisionSceneEntity *cEnt = getCollisionByScreenEntity(entity);
+	if(cEnt) {
+		cEnt->enabled = val;
+	}
+}
+
+void CollisionScene::adjustForCollision(CollisionSceneEntity *collisionEntity) {
+	CollisionResult result;
+//	float elapsed = CoreServices::getInstance()->getCore()->getElapsed();
+	result.collided = false;
+	for(int i=0; i < collisionChildren.size(); i++) {
+		if(collisionChildren[i] != collisionEntity) {
+			result = testCollisionOnCollisionChild(collisionEntity, collisionChildren[i]);
+			if(result.collided) {
+				if(result.setOldPosition) {
+					collisionEntity->getSceneEntity()->setPosition(result.newPos);
+					collisionEntity->gVelocity.set(0,0,0);					
+				} else {
+//				printf("colnormal: %f %f %f %f\n", result.colNormal.x, result.colNormal.y, result.colNormal.z,result.colDist);
+				collisionEntity->getSceneEntity()->Translate(result.colNormal.x*result.colDist, result.colNormal.y*result.colDist, result.colNormal.z*result.colDist);
+//				Logger::log("colnormal: %f,%f,%f\n",result.colNormal.x,result.colNormal.y,result.colNormal.z);
+				if(result.colNormal.x > 0 && collisionEntity->gVelocity.x > 0)
+					collisionEntity->gVelocity.x = 0;
+				if(result.colNormal.x < 0 && collisionEntity->gVelocity.x < 0)
+					collisionEntity->gVelocity.x = 0;
+				if(result.colNormal.y > 0 && collisionEntity->gVelocity.y > 0)
+					collisionEntity->gVelocity.y = 0;
+				if(result.colNormal.y < 0 && collisionEntity->gVelocity.y < 0)
+					collisionEntity->gVelocity.y = 0;
+				if(result.colNormal.z > 0 && collisionEntity->gVelocity.z > 0)
+					collisionEntity->gVelocity.z = 0;
+				if(result.colNormal.z < 0 && collisionEntity->gVelocity.z < 0)
+					collisionEntity->gVelocity.z = 0;
+				collisionEntity->gVelocity.set(0,0,0);
+				}
+			}
+		}
+	}
+}	
+
+CollisionSceneEntity *CollisionScene::getCollisionByScreenEntity(SceneEntity *ent) {
+	for(int i=0; i<collisionChildren.size();i++) {
+		if(collisionChildren[i]->getSceneEntity() == ent)
+			return collisionChildren[i];
+	}	
+	return NULL;
+
+}
+
+void CollisionScene::applyVelocity(SceneEntity *entity, float x, float y, float z) {
+	CollisionSceneEntity *cEnt1 = getCollisionByScreenEntity(entity);
+	if(!cEnt1)
+		return;
+	cEnt1->gVelocity.x += x;
+	cEnt1->gVelocity.y += y;
+	cEnt1->gVelocity.z += z;	
+}
+
+Vector3 CollisionScene::getCollisionNormalFromCollisionEnts(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2) {
+
+	int numManifolds = world->getDispatcher()->getNumManifolds();
+	for (int i=0;i<numManifolds;i++)
+	{
+		btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
+		btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
+		btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
+ 		if((obA == cEnt1->collisionObject && obB == cEnt2->collisionObject) ||
+		 (obA == cEnt2->collisionObject && obB == cEnt1->collisionObject)) {
+			if(contactManifold->getNumContacts() > 0) {
+				btVector3 vec = contactManifold->getContactPoint(0).m_normalWorldOnB;
+				return Vector3(vec.getX(), vec.getY(), vec.getZ());
+			}
+		}
+	}
+	return Vector3(0,0,0);
+}
+
+Vector3 CollisionScene::getCollisionNormal(SceneEntity *ent1, SceneEntity *ent2) {
+	CollisionSceneEntity *cEnt1 = getCollisionByScreenEntity(ent1);
+	CollisionSceneEntity *cEnt2 = getCollisionByScreenEntity(ent2);
+	if(cEnt1 == NULL || cEnt2 == NULL)
+		return Vector3(0,0,0);
+
+	return getCollisionNormalFromCollisionEnts(cEnt1, cEnt2);
+}
+
+CollisionResult CollisionScene::testCollisionOnCollisionChild_Convex(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2) {
+	CollisionResult result;
+	result.collided = false;
+	result.setOldPosition = false;
+	
+	Vector3 collNormal;
+	result.colNormal.set(0,0,0);									
+	result.colDist = 0; 	
+	
+	int numAdds = 0;
+	
+	int numManifolds = world->getDispatcher()->getNumManifolds();
+	for (int i=0;i<numManifolds;i++)
+	{
+		btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
+		btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
+		btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
+ 		if((obA == cEnt1->collisionObject && obB == cEnt2->collisionObject) ||
+		   (obA == cEnt2->collisionObject && obB == cEnt1->collisionObject)) {
+//			contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform());
+			if(contactManifold->getNumContacts() > 0) {
+				for(int j=0; j < contactManifold->getNumContacts(); j++) {
+					if(contactManifold->getContactPoint(j).getDistance() <= btScalar(0.0)) {
+						btVector3 vec = contactManifold->getContactPoint(j).m_normalWorldOnB;
+						result.colNormal += Vector3(vec.getX(), vec.getY(), vec.getZ());	
+						result.colDist += contactManifold->getContactPoint(j).getDistance(); 
+						numAdds++;
+					}
+				}
+				
+				//				btVector3 vec = contactManifold->getContactPoint(0).m_normalWorldOnB;
+				//				result.colNormal.set(vec.getX(), vec.getY(), vec.getZ());
+				//				result.colDist = contactManifold->getContactPoint(0).getDistance(); 
+				
+				result.collided = true;
+				//				return result;
+			}
+		}
+	}
+	
+	if(numAdds > 0) {
+		result.colNormal = result.colNormal / (float)numAdds;
+		//		result.colNormal = Vector3(0,1,0);
+		//		result.colNormal.Normalize();
+		result.colDist  = result.colDist / (float)numAdds;
+	}
+	
+	return result;
+	//	return cEnt1->collisionObject->checkCollideWith(cEnt2->collisionObject);
+}
+
+RayTestResult CollisionScene::getFirstEntityInRay(const Vector3 &origin,  const Vector3 &dest) {
+
+	RayTestResult ret;
+	ret.entity = NULL;
+	
+	btVector3 fromVec(origin.x, origin.y, origin.z);
+	btVector3 toVec(dest.x, dest.y, dest.z);
+	
+	btCollisionWorld::ClosestRayResultCallback cb(fromVec, toVec);
+	world->rayTest (fromVec, toVec, cb);
+	
+	if (cb.hasHit ()) {
+		CollisionSceneEntity *retEnt = getCollisionEntityByObject(cb.m_collisionObject);
+		if(retEnt) {
+			ret.entity = retEnt->getSceneEntity();
+			ret.position = Vector3(cb.m_hitPointWorld.getX(), cb.m_hitPointWorld.getY(), cb.m_hitPointWorld.getZ());
+			ret.normal = Vector3(cb.m_hitNormalWorld.getX(), cb.m_hitNormalWorld.getY(), cb.m_hitNormalWorld.getZ());			
+			return ret;
+		}
+	}
+	
+	return ret;
+}
+
+CollisionSceneEntity *CollisionScene::getCollisionEntityByObject(btCollisionObject *collisionObject) {
+	for(int i=0; i <collisionChildren.size(); i++) {
+		if(collisionChildren[i]->collisionObject == collisionObject) {
+			return collisionChildren[i];
+		}
+	}
+	return NULL;
+}
+
+CollisionResult CollisionScene::testCollisionOnCollisionChild_RayTest(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2) {
+	CollisionResult result;
+	result.collided = false;
+	result.setOldPosition = false;
+	btConvexShape *shape = cEnt1->getShape();
+	if(!shape)
+		return result;
+	
+//	shape->setMargin(1.0f);
+	
+	// hack to not collide with itself
+	world->removeCollisionObject(cEnt1->collisionObject);	
+
+	btVector3 fVec(cEnt1->lastPosition.x, cEnt1->lastPosition.y, cEnt1->lastPosition.z);
+	btVector3 toVec(cEnt1->getSceneEntity()->getPosition()->x, cEnt1->getSceneEntity()->getPosition()->y, cEnt1->getSceneEntity()->getPosition()->z);
+	
+	btCollisionWorld::ClosestConvexResultCallback cb(toVec, fVec);
+	btQuaternion qFrom;	
+	btQuaternion qTo;
+	qFrom.setRotation (btVector3(1.0, 0.0, 0.0), 0.0);
+	qTo.setRotation (btVector3(1.0, 0.0, 0.0), 0.0);
+	btTransform from(qFrom, fVec);
+	btTransform to(qTo, toVec);
+		
+	world->convexSweepTest(shape, from, to, cb);
+	
+	if (cb.hasHit()) {
+		result.collided = true;
+		
+		btVector3 newVec = toVec;
+		newVec.setInterpolate3(fVec, toVec, cb.m_closestHitFraction);		
+		result.colDist = newVec.distance(toVec);// + 0.001f;
+
+//		result.colDist = fVec.distance(toVec);// - cb.m_closestHitFraction;
+//		cb.m_hitPointWorld
+		
+//		result.colDist = shape->
+//		result.colDist = cb.m_hitPointWorld.distance(fVec) - shape->;
+
+		/*
+		btVector3 linVel, angVel;
+		btTransformUtil::calculateVelocity (from, to, 1.0, linVel, angVel);
+		btTransform T;
+		btTransformUtil::integrateTransform (from, linVel, angVel, cb.m_closestHitFraction, T);
+		btVector3 newVec;
+		newVec = T.getOrigin(); // * newVec;
+		result.colDist = toVec.distance(newVec);	
+		
+		Logger::log("dist: %f\n", result.colDist);
+		*/
+		
+//		result.colNormal = cEnt1->getSceneEntity()->getPosition()->(cEnt1->lastPosition);		
+		result.colNormal = Vector3(cb.m_hitNormalWorld.getX(), cb.m_hitNormalWorld.getY(), cb.m_hitNormalWorld.getZ());
+		result.colNormal.Normalize();
+	}
+	
+	world->addCollisionObject(cEnt1->collisionObject);
+	
+	return result;
+}
+
+CollisionResult CollisionScene::testCollisionOnCollisionChild(CollisionSceneEntity *cEnt1, CollisionSceneEntity *cEnt2) {
+	if(cEnt2->getType() == CollisionSceneEntity::SHAPE_TERRAIN || cEnt2->getType() == CollisionSceneEntity::SHAPE_MESH) {
+		return testCollisionOnCollisionChild_RayTest(cEnt1, cEnt2);		
+	} else {
+		return testCollisionOnCollisionChild_Convex(cEnt1, cEnt2);
+	}
+}
+
+CollisionResult CollisionScene::testCollision(SceneEntity *ent1, SceneEntity *ent2) {
+	CollisionSceneEntity *cEnt1 = getCollisionByScreenEntity(ent1);
+	CollisionSceneEntity *cEnt2 = getCollisionByScreenEntity(ent2);
+	CollisionResult result;
+	result.collided = false;
+	if(cEnt1 == NULL || cEnt2 == NULL)
+		return result;
+	return testCollisionOnCollisionChild(cEnt1, cEnt2);
+}
+
+CollisionScene::~CollisionScene() {
+
+}
+
+void CollisionScene::enableGravity(SceneEntity *entity) {
+	CollisionSceneEntity *cEnt1 = getCollisionByScreenEntity(entity);
+	if(!cEnt1)
+		return;
+	cEnt1->gravityEnabled = true;
+}
+
+void CollisionScene::loadCollisionChild(SceneEntity *entity, bool autoCollide, int type) {
+	addCollisionChild(entity, autoCollide, type);
+}
+
+CollisionSceneEntity *CollisionScene::trackCollision(SceneEntity *newEntity, bool autoCollide, int type) {
+	CollisionSceneEntity *newCollisionEntity = new CollisionSceneEntity(newEntity,autoCollide, type);
+	world->addCollisionObject(newCollisionEntity->collisionObject);
+	collisionChildren.push_back(newCollisionEntity);
+//	newCollisionEntity->Update();
+	return newCollisionEntity;
+}
+
+CollisionSceneEntity *CollisionScene::addCollisionChild(SceneEntity *newEntity, bool autoCollide, int type) {
+	addEntity(newEntity);
+	return trackCollision(newEntity, autoCollide, type);
+
+}

+ 126 - 0
Modules/Contents/3DPhysics/Source/PolyCollisionSceneEntity.cpp

@@ -0,0 +1,126 @@
+/*
+ *  PolyCollisionSceneEntity.cpp
+ *  Poly
+ *
+ *  Created by Ivan Safrin on 6/17/08.
+ *  Copyright 2008 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+#include "PolyCollisionSceneEntity.h"
+
+using namespace Polycode;
+
+CollisionSceneEntity::CollisionSceneEntity(SceneEntity *entity, bool autoCollide, int type) {
+	gravityEnabled = false;
+	this->autoCollide = autoCollide;
+	sceneEntity = entity;
+	gravityVector.y = -1.0f;
+	
+	this->type = type;
+	enabled = true;
+	
+	gravityStrength = 5.0f;
+	
+	btMatrix3x3 basisA;
+	basisA.setIdentity();
+	collisionObject = new btCollisionObject();
+	collisionObject->getWorldTransform().setBasis(basisA);
+	
+	lastPosition = *entity->getPosition();
+	
+	shape = NULL;
+	
+	btBoxShape* box;
+	btSphereShape* sphere;	
+	SceneMesh *sceneMesh;
+
+	switch(type) {
+		case SHAPE_BOX:
+			box = new btBoxShape(btVector3(entity->bBox.x/2.0f, entity->bBox.y/2.0f,entity->bBox.z/2.0f));
+			collisionObject->setCollisionShape(box);
+			shape = box;
+		break;
+		case SHAPE_SPHERE:
+			sphere = new btSphereShape(entity->bBox.x/2.0f);
+			collisionObject->setCollisionShape(sphere);
+			shape = sphere;			
+		break;
+		case SHAPE_MESH:
+			sceneMesh = dynamic_cast<SceneMesh*>(entity);
+			if(sceneMesh != NULL) {
+				btTriangleMesh *btMesh = new btTriangleMesh();
+				for(int i=0; i < sceneMesh->getMesh()->getPolygonCount(); i++) {
+					Polygon *poly = sceneMesh->getMesh()->getPolygon(i);
+					btVector3 v0 = btVector3(btScalar(poly->getVertex(0)->x),btScalar(poly->getVertex(0)->y),btScalar(poly->getVertex(0)->z));
+					btVector3 v1= btVector3(btScalar(poly->getVertex(1)->x),btScalar(poly->getVertex(1)->y),btScalar(poly->getVertex(1)->z));
+					btVector3 v2= btVector3(btScalar(poly->getVertex(2)->x),btScalar(poly->getVertex(2)->y),btScalar(poly->getVertex(2)->z));					
+					btMesh->addTriangle(v2,v1,v0);
+				}
+				btBvhTriangleMeshShape *concaveShape = new btBvhTriangleMeshShape(btMesh, true);
+				collisionObject->setCollisionShape(concaveShape);
+			} else {
+				Logger::log("Tried to make a mesh collision object from a non-mesh\n");
+				box = new btBoxShape(btVector3(entity->bBox.x/2.0f, entity->bBox.y/2.0f,entity->bBox.z/2.0f));			
+				collisionObject->setCollisionShape(box);	
+				shape = box;				
+			}			
+		break;
+		case SHAPE_TERRAIN:			
+			/*
+			Terrain *terrain = dynamic_cast<Terrain*>(entity);
+			if(terrain != NULL) {
+//				btHeightfieldTerrainShape *hf = new btHeightfieldTerrainShape(ter
+				btTriangleMesh *btMesh = new btTriangleMesh();
+				for(int i=0; i < terrain->getMesh()->getPolygonCount(); i++) {
+					Polygon *poly = terrain->getMesh()->getPolygon(i);
+					btVector3 v0 = btVector3(btScalar(poly->getVertex(0)->x),btScalar(poly->getVertex(0)->y),btScalar(poly->getVertex(0)->z));
+					btVector3 v1= btVector3(btScalar(poly->getVertex(1)->x),btScalar(poly->getVertex(1)->y),btScalar(poly->getVertex(1)->z));
+					btVector3 v2= btVector3(btScalar(poly->getVertex(2)->x),btScalar(poly->getVertex(2)->y),btScalar(poly->getVertex(2)->z));					
+					btMesh->addTriangle(v2,v1,v0);
+				}
+				btBvhTriangleMeshShape *concaveShape = new btBvhTriangleMeshShape(btMesh, true);
+				collisionObject->setCollisionShape(concaveShape);
+			} else {
+				Logger::log("Tried to make a terrain collision object from a non-terrain\n");
+				box = new btBoxShape(btVector3(entity->bBox.x/2.0f, entity->bBox.y/2.0f,entity->bBox.z/2.0f));			
+				collisionObject->setCollisionShape(box);	
+				shape = box;				
+			}
+			 */
+		break;
+	}
+	gVelocity.set(0,0,0);
+}
+
+void CollisionSceneEntity::Update() {
+	
+//	lastPosition = *getSceneEntity()->getPosition();	
+	if(gravityEnabled) {	
+		float elapsed = CoreServices::getInstance()->getCore()->getElapsed();
+		Vector3 elapsedGrav = gravityVector;
+		elapsedGrav * elapsed * gravityStrength;
+		gVelocity = gVelocity+(elapsedGrav);
+		sceneEntity->Translate(gVelocity.x * elapsed, gVelocity.y * elapsed,gVelocity.z * elapsed);
+		sceneEntity->rebuildTransformMatrix();
+	}
+
+	btQuaternion orn;
+//	collisionObject->getCollisionShape()->setLocalScaling
+	collisionObject->getWorldTransform().setFromOpenGLMatrix(sceneEntity->getConcatenatedMatrix().ml);
+
+/*	
+	float rads = PI/180.0f;
+	orn.setEuler(sceneEntity->getCombinedYaw()*rads,sceneEntity->getCombinedPitch()*rads,sceneEntity->getCombinedRoll()*rads);
+	collisionObject->getWorldTransform().setRotation(orn);
+	collisionObject->getWorldTransform().setOrigin(btVector3(sceneEntity->getCombinedPosition().x, sceneEntity->getCombinedPosition().y, sceneEntity->getCombinedPosition().z));
+*/	
+}
+
+SceneEntity *CollisionSceneEntity::getSceneEntity() {
+	return sceneEntity;
+}
+
+CollisionSceneEntity::~CollisionSceneEntity() {
+
+}

+ 1 - 1
Modules/Contents/UI/Source/PolyUITextInput.cpp

@@ -493,7 +493,7 @@ void UITextInput::insertText(String text) {
 		if(i < numLines) {
 		if(i < numLines) {
 			lines[i]->setText(strings[i]);
 			lines[i]->setText(strings[i]);
 		} else {
 		} else {
-			numLines++;	
+			numLines++;		
 			ScreenLabel *newLine = new ScreenLabel(fontName, L"", fontSize, Label::ANTIALIAS_FULL);
 			ScreenLabel *newLine = new ScreenLabel(fontName, L"", fontSize, Label::ANTIALIAS_FULL);
 			newLine->setColor(0,0,0,1);
 			newLine->setColor(0,0,0,1);
 			addChild(newLine);			
 			addChild(newLine);			

+ 9 - 28
Player/Build/Mac OS X/English.lproj/MyDocument.xib

@@ -34,7 +34,7 @@
 				<int key="NSWindowStyleMask">15</int>
 				<int key="NSWindowStyleMask">15</int>
 				<int key="NSWindowBacking">2</int>
 				<int key="NSWindowBacking">2</int>
 				<string key="NSWindowRect">{{133, 235}, {507, 413}}</string>
 				<string key="NSWindowRect">{{133, 235}, {507, 413}}</string>
-				<int key="NSWTFlags">1886912512</int>
+				<int key="NSWTFlags">1350041600</int>
 				<string key="NSWindowTitle">Window</string>
 				<string key="NSWindowTitle">Window</string>
 				<string key="NSWindowClass">NSWindow</string>
 				<string key="NSWindowClass">NSWindow</string>
 				<string key="NSViewClass">View</string>
 				<string key="NSViewClass">View</string>
@@ -165,6 +165,7 @@
 					<string>5.IBViewEditorWindowController.showingLayoutRectangles</string>
 					<string>5.IBViewEditorWindowController.showingLayoutRectangles</string>
 					<string>5.IBWindowTemplateEditedContentRect</string>
 					<string>5.IBWindowTemplateEditedContentRect</string>
 					<string>5.ImportedFromIB2</string>
 					<string>5.ImportedFromIB2</string>
+					<string>5.NSWindowTemplate.visibleAtLaunch</string>
 					<string>5.editorWindowContentRectSynchronizationRect</string>
 					<string>5.editorWindowContentRectSynchronizationRect</string>
 					<string>5.windowTemplate.hasMinSize</string>
 					<string>5.windowTemplate.hasMinSize</string>
 					<string>5.windowTemplate.minSize</string>
 					<string>5.windowTemplate.minSize</string>
@@ -184,6 +185,7 @@
 					<boolean value="YES"/>
 					<boolean value="YES"/>
 					<string>{{553, 417}, {507, 413}}</string>
 					<string>{{553, 417}, {507, 413}}</string>
 					<integer value="1"/>
 					<integer value="1"/>
+					<boolean value="YES"/>
 					<string>{{201, 387}, {507, 413}}</string>
 					<string>{{201, 387}, {507, 413}}</string>
 					<integer value="1"/>
 					<integer value="1"/>
 					<string>{94, 86}</string>
 					<string>{94, 86}</string>
@@ -216,35 +218,14 @@
 					<string key="className">MyDocument</string>
 					<string key="className">MyDocument</string>
 					<string key="superclassName">NSDocument</string>
 					<string key="superclassName">NSDocument</string>
 					<object class="NSMutableDictionary" key="outlets">
 					<object class="NSMutableDictionary" key="outlets">
-						<bool key="EncodedWithXMLCoder">YES</bool>
-						<object class="NSArray" key="dict.sortedKeys">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<string>substanceView</string>
-							<string>window</string>
-						</object>
-						<object class="NSMutableArray" key="dict.values">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<string>SubstanceView</string>
-							<string>NSWindow</string>
-						</object>
+						<string key="NS.key.0">substanceView</string>
+						<string key="NS.object.0">SubstanceView</string>
 					</object>
 					</object>
 					<object class="NSMutableDictionary" key="toOneOutletInfosByName">
 					<object class="NSMutableDictionary" key="toOneOutletInfosByName">
-						<bool key="EncodedWithXMLCoder">YES</bool>
-						<object class="NSArray" key="dict.sortedKeys">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<string>substanceView</string>
-							<string>window</string>
-						</object>
-						<object class="NSMutableArray" key="dict.values">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<object class="IBToOneOutletInfo">
-								<string key="name">substanceView</string>
-								<string key="candidateClassName">SubstanceView</string>
-							</object>
-							<object class="IBToOneOutletInfo">
-								<string key="name">window</string>
-								<string key="candidateClassName">NSWindow</string>
-							</object>
+						<string key="NS.key.0">substanceView</string>
+						<object class="IBToOneOutletInfo" key="NS.object.0">
+							<string key="name">substanceView</string>
+							<string key="candidateClassName">SubstanceView</string>
 						</object>
 						</object>
 					</object>
 					</object>
 					<object class="IBClassDescriptionSource" key="sourceIdentifier">
 					<object class="IBClassDescriptionSource" key="sourceIdentifier">

+ 16 - 23
Player/Build/Mac OS X/MyDocument.m

@@ -13,24 +13,6 @@
 @synthesize substanceView;
 @synthesize substanceView;
 
 
 
 
-void *threadFunc(void *data) {
-	NSAutoreleasePool *pool;
-    pool = [[NSAutoreleasePool alloc] init];
-	
-	CocoaPolycodePlayer *player = (CocoaPolycodePlayer*)data;
-	player->runThread();	
-
-	NSDocument *doc = (NSDocument*)player->windowData;
-	@synchronized(doc) {	
-		[doc close];
-	}
-	
-	[pool drain];		
-	
-	return NULL;
-}
-
-
 - (id)init
 - (id)init
 {
 {
     self = [super init];
     self = [super init];
@@ -53,17 +35,28 @@ void *threadFunc(void *data) {
 - (void)windowControllerDidLoadNib:(NSWindowController *) aController
 - (void)windowControllerDidLoadNib:(NSWindowController *) aController
 {
 {
     [super windowControllerDidLoadNib:aController];
     [super windowControllerDidLoadNib:aController];
-    // Add any code here that needs to be executed once the windowController has loaded the document's window.
-	
-		
+    // Add any code here that needs to be executed once the windowController has loaded the document's window.		
+
 	player =  new CocoaPolycodePlayer(substanceView, [docFileName cStringUsingEncoding:NSASCIIStringEncoding], false);
 	player =  new CocoaPolycodePlayer(substanceView, [docFileName cStringUsingEncoding:NSASCIIStringEncoding], false);
 	playerProxy = new PolycodeProxy();
 	playerProxy = new PolycodeProxy();
 	playerProxy->playerDocument = self;
 	playerProxy->playerDocument = self;
 	player->addEventListener(playerProxy, PolycodeDebugEvent::EVENT_RESIZE);
 	player->addEventListener(playerProxy, PolycodeDebugEvent::EVENT_RESIZE);
 	player->windowData = self;
 	player->windowData = self;
-	pthread_t thread;
-	pthread_create( &thread, NULL, threadFunc, (void*)player);	
 	
 	
+	player->runPlayer();
+
+	
+	timer = [NSTimer timerWithTimeInterval:(1.0f/90.0f) target:self selector:@selector(animationTimer:) userInfo:nil repeats:YES];
+	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
+	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode]; // ensure timer fires during resize		
+}
+
+- (void)animationTimer:(NSTimer *)timer
+{
+
+	if(!player->Update()) {
+		[self close];
+	}
 }
 }
 
 
 - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
 - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError

+ 8 - 0
Player/Build/Mac OS X/Polycode Player.xcodeproj/project.pbxproj

@@ -13,6 +13,7 @@
 		6D34133512B7FC760034FA9B /* libphysfs.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34133412B7FC760034FA9B /* libphysfs.a */; };
 		6D34133512B7FC760034FA9B /* libphysfs.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34133412B7FC760034FA9B /* libphysfs.a */; };
 		6D34134112B7FCD00034FA9B /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34134012B7FCD00034FA9B /* IOKit.framework */; };
 		6D34134112B7FCD00034FA9B /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34134012B7FCD00034FA9B /* IOKit.framework */; };
 		6D34153C12B82C7A0034FA9B /* liblua.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34153B12B82C7A0034FA9B /* liblua.a */; };
 		6D34153C12B82C7A0034FA9B /* liblua.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34153B12B82C7A0034FA9B /* liblua.a */; };
+		6D34160612B837250034FA9B /* libPolycodeLUA.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D34160512B837250034FA9B /* libPolycodeLUA.a */; };
 		6DBAB04B12B6EA4300986D01 /* PolySubstanceView.m in Sources */ = {isa = PBXBuildFile; fileRef = 6DBAB04912B6EA4300986D01 /* PolySubstanceView.m */; };
 		6DBAB04B12B6EA4300986D01 /* PolySubstanceView.m in Sources */ = {isa = PBXBuildFile; fileRef = 6DBAB04912B6EA4300986D01 /* PolySubstanceView.m */; };
 		6DBAB07E12B6EAAD00986D01 /* libfreetype.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DBAB07712B6EAAD00986D01 /* libfreetype.a */; };
 		6DBAB07E12B6EAAD00986D01 /* libfreetype.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DBAB07712B6EAAD00986D01 /* libfreetype.a */; };
 		6DBAB07F12B6EAAD00986D01 /* libz.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DBAB07812B6EAAD00986D01 /* libz.a */; };
 		6DBAB07F12B6EAAD00986D01 /* libz.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DBAB07812B6EAAD00986D01 /* libz.a */; };
@@ -48,6 +49,7 @@
 		6D34133412B7FC760034FA9B /* libphysfs.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libphysfs.a; path = ../../../Core/Dependencies/physfs/Debug/libphysfs.a; sourceTree = SOURCE_ROOT; };
 		6D34133412B7FC760034FA9B /* libphysfs.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libphysfs.a; path = ../../../Core/Dependencies/physfs/Debug/libphysfs.a; sourceTree = SOURCE_ROOT; };
 		6D34134012B7FCD00034FA9B /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
 		6D34134012B7FCD00034FA9B /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
 		6D34153B12B82C7A0034FA9B /* liblua.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = liblua.a; path = ../../../Core/Dependencies/lua/src/liblua.a; sourceTree = SOURCE_ROOT; };
 		6D34153B12B82C7A0034FA9B /* liblua.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = liblua.a; path = ../../../Core/Dependencies/lua/src/liblua.a; sourceTree = SOURCE_ROOT; };
+		6D34160512B837250034FA9B /* libPolycodeLUA.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libPolycodeLUA.a; path = "../../../Bindings/Build/Mac OS X/build/Debug/libPolycodeLUA.a"; sourceTree = SOURCE_ROOT; };
 		6DBAB04912B6EA4300986D01 /* PolySubstanceView.m */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; name = PolySubstanceView.m; path = ../../../Core/Contents/Source/PolySubstanceView.m; sourceTree = SOURCE_ROOT; };
 		6DBAB04912B6EA4300986D01 /* PolySubstanceView.m */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; name = PolySubstanceView.m; path = ../../../Core/Contents/Source/PolySubstanceView.m; sourceTree = SOURCE_ROOT; };
 		6DBAB04A12B6EA4300986D01 /* PolySubstanceView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolySubstanceView.h; path = ../../../Core/Contents/Include/PolySubstanceView.h; sourceTree = SOURCE_ROOT; };
 		6DBAB04A12B6EA4300986D01 /* PolySubstanceView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PolySubstanceView.h; path = ../../../Core/Contents/Include/PolySubstanceView.h; sourceTree = SOURCE_ROOT; };
 		6DBAB07712B6EAAD00986D01 /* libfreetype.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libfreetype.a; path = ../../../Core/Dependencies/freetype/libfreetype.a; sourceTree = SOURCE_ROOT; };
 		6DBAB07712B6EAAD00986D01 /* libfreetype.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libfreetype.a; path = ../../../Core/Dependencies/freetype/libfreetype.a; sourceTree = SOURCE_ROOT; };
@@ -81,6 +83,7 @@
 				6D34133512B7FC760034FA9B /* libphysfs.a in Frameworks */,
 				6D34133512B7FC760034FA9B /* libphysfs.a in Frameworks */,
 				6D34134112B7FCD00034FA9B /* IOKit.framework in Frameworks */,
 				6D34134112B7FCD00034FA9B /* IOKit.framework in Frameworks */,
 				6D34153C12B82C7A0034FA9B /* liblua.a in Frameworks */,
 				6D34153C12B82C7A0034FA9B /* liblua.a in Frameworks */,
+				6D34160612B837250034FA9B /* libPolycodeLUA.a in Frameworks */,
 			);
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			runOnlyForDeploymentPostprocessing = 0;
 		};
 		};
@@ -90,6 +93,7 @@
 		1058C7A6FEA54F5311CA2CBB /* Linked Frameworks */ = {
 		1058C7A6FEA54F5311CA2CBB /* Linked Frameworks */ = {
 			isa = PBXGroup;
 			isa = PBXGroup;
 			children = (
 			children = (
+				6D34160512B837250034FA9B /* libPolycodeLUA.a */,
 				6D34153B12B82C7A0034FA9B /* liblua.a */,
 				6D34153B12B82C7A0034FA9B /* liblua.a */,
 				6D34134012B7FCD00034FA9B /* IOKit.framework */,
 				6D34134012B7FCD00034FA9B /* IOKit.framework */,
 				6D34133412B7FC760034FA9B /* libphysfs.a */,
 				6D34133412B7FC760034FA9B /* libphysfs.a */,
@@ -333,6 +337,7 @@
 					"\"$(SRCROOT)/../../../Core/Dependencies/luajit/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/luajit/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/physfs/Debug\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/physfs/Debug\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/lua/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/lua/src\"",
+					"\"$(SRCROOT)/../../../Bindings/Build/Mac OS X/build/Debug\"",
 				);
 				);
 				PRODUCT_NAME = "Polycode Player";
 				PRODUCT_NAME = "Polycode Player";
 			};
 			};
@@ -358,6 +363,7 @@
 					"\"$(SRCROOT)/../../../Core/Dependencies/luajit/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/luajit/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/physfs/Debug\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/physfs/Debug\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/lua/src\"",
 					"\"$(SRCROOT)/../../../Core/Dependencies/lua/src\"",
+					"\"$(SRCROOT)/../../../Bindings/Build/Mac OS X/build/Debug\"",
 				);
 				);
 				PRODUCT_NAME = "Polycode Player";
 				PRODUCT_NAME = "Polycode Player";
 			};
 			};
@@ -372,6 +378,7 @@
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				HEADER_SEARCH_PATHS = (
 				HEADER_SEARCH_PATHS = (
+					../../../Bindings/Contents/LUA/Include,
 					../../../Core/Contents/Include,
 					../../../Core/Contents/Include,
 					../../../Core/Dependencies/luajit/src,
 					../../../Core/Dependencies/luajit/src,
 					../../../Core/Dependencies/libvorbis/include,
 					../../../Core/Dependencies/libvorbis/include,
@@ -396,6 +403,7 @@
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				HEADER_SEARCH_PATHS = (
 				HEADER_SEARCH_PATHS = (
+					../../../Bindings/Contents/LUA/Include,
 					../../../Core/Contents/Include,
 					../../../Core/Contents/Include,
 					../../../Core/Dependencies/luajit/src,
 					../../../Core/Dependencies/luajit/src,
 					../../../Core/Dependencies/libvorbis/include,
 					../../../Core/Dependencies/libvorbis/include,

+ 2 - 1
Player/Contents/Include/PolycodePlayer.h

@@ -13,6 +13,7 @@
 #include <fstream>
 #include <fstream>
 
 
 #include "Polycode.h"
 #include "Polycode.h"
+#include "PolycodeLUA.h"
 
 
 extern "C" {	
 extern "C" {	
 #include <stdio.h>
 #include <stdio.h>
@@ -48,7 +49,7 @@ public:
 	PolycodePlayer(String fileName, bool knownArchive);
 	PolycodePlayer(String fileName, bool knownArchive);
 	virtual ~PolycodePlayer();
 	virtual ~PolycodePlayer();
 	
 	
-	void runThread();
+	void runPlayer();
 	
 	
 	void loadFile(const char *fileName);
 	void loadFile(const char *fileName);
 	void runFile(String fileName);
 	void runFile(String fileName);

+ 35 - 5
Player/Contents/Source/PolycodePlayer.cpp

@@ -18,6 +18,7 @@ extern "C" {
 		module += ".lua";
 		module += ".lua";
 		
 		
 		const char* fullPath = module.c_str();		
 		const char* fullPath = module.c_str();		
+		printf("Loading custom class: %s\n", module.c_str());
 		OSFILE *inFile = OSBasics::open(module, "r");	
 		OSFILE *inFile = OSBasics::open(module, "r");	
 		if(inFile) {
 		if(inFile) {
 			OSBasics::seek(inFile, 0, SEEK_END);	
 			OSBasics::seek(inFile, 0, SEEK_END);	
@@ -93,6 +94,7 @@ extern "C" {
 		 */
 		 */
 		luaL_openlibs(L);
 		luaL_openlibs(L);
 		
 		
+		luaopen_Polycode(L);
 		//luaopen_Tau(L);	// load the wrappered module
 		//luaopen_Tau(L);	// load the wrappered module
 		
 		
 		
 		
@@ -118,7 +120,16 @@ extern "C" {
 		// Table is still on the stack.  Get rid of it now.
 		// Table is still on the stack.  Get rid of it now.
 		lua_pop(L, 1);
 		lua_pop(L, 1);
 		
 		
+		lua_getfield(L, LUA_GLOBALSINDEX, "require");
+		lua_pushstring(L, "class");		
+		lua_call(L, 1, 0);
+
+		lua_getfield(L, LUA_GLOBALSINDEX, "require");
+		lua_pushstring(L, "defaults");		
+		lua_call(L, 1, 0);
+		
 		
 		
+//		String prepend = "";
 		//string prepend = "for k,v in pairs(Tau) do _G[k]=v end for k,v in pairs(math) do _G[k]=v end for k,v in pairs(table) do _G[k]=v end _G[\"count\"]=_G[\"getn\"] RESOURCE_MANAGER = CoreServices_getInstance():getResourceManager() CORE = CoreServices_getInstance():getCore() INPUT = CORE:getInput() RENDERER = CoreServices_getInstance():getRenderer() listener = EventHandler() listener.onEvent = function(e) inputEvent = CoreInput_createEvent(e) if e:getEventCode() == EVENT_MOUSEUP then if onMouseUp ~= nil then onMouseUp(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == EVENT_MOUSEDOWN then if onMouseDown ~= nil then onMouseDown(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == EVENT_MOUSEMOVE then if onMouseMove ~= nil then onMouseMove(inputEvent.mousePosition.x, inputEvent.mousePosition.y) end end if e:getEventCode() == EVENT_KEYDOWN then if onKeyDown ~= nil then onKeyDown(inputEvent:keyCode()) end end if e:getEventCode() == EVENT_KEYUP then if onKeyUp ~= nil then onKeyUp(inputEvent:keyCode()) end end end INPUT:addEventListener(listener, EVENT_KEYDOWN) INPUT:addEventListener(listener, EVENT_KEYUP) INPUT:addEventListener(listener, EVENT_MOUSEDOWN) INPUT:addEventListener(listener, EVENT_MOUSEMOVE) INPUT:addEventListener(listener, EVENT_MOUSEUP)";
 		//string prepend = "for k,v in pairs(Tau) do _G[k]=v end for k,v in pairs(math) do _G[k]=v end for k,v in pairs(table) do _G[k]=v end _G[\"count\"]=_G[\"getn\"] RESOURCE_MANAGER = CoreServices_getInstance():getResourceManager() CORE = CoreServices_getInstance():getCore() INPUT = CORE:getInput() RENDERER = CoreServices_getInstance():getRenderer() listener = EventHandler() listener.onEvent = function(e) inputEvent = CoreInput_createEvent(e) if e:getEventCode() == EVENT_MOUSEUP then if onMouseUp ~= nil then onMouseUp(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == EVENT_MOUSEDOWN then if onMouseDown ~= nil then onMouseDown(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == EVENT_MOUSEMOVE then if onMouseMove ~= nil then onMouseMove(inputEvent.mousePosition.x, inputEvent.mousePosition.y) end end if e:getEventCode() == EVENT_KEYDOWN then if onKeyDown ~= nil then onKeyDown(inputEvent:keyCode()) end end if e:getEventCode() == EVENT_KEYUP then if onKeyUp ~= nil then onKeyUp(inputEvent:keyCode()) end end end INPUT:addEventListener(listener, EVENT_KEYDOWN) INPUT:addEventListener(listener, EVENT_KEYUP) INPUT:addEventListener(listener, EVENT_MOUSEDOWN) INPUT:addEventListener(listener, EVENT_MOUSEMOVE) INPUT:addEventListener(listener, EVENT_MOUSEUP)";
 //		String prepend = "for k,v in pairs(math) do _G[k]=v end for k,v in pairs(table) do _G[k]=v end _G[\"count\"]=_G[\"getn\"] RESOURCE_MANAGER = Tau.CoreServices_getInstance():getResourceManager() CORE = Tau.CoreServices_getInstance():getCore() FONT_MANAGER = Tau.CoreServices_getInstance():getFontManager() INPUT = CORE:getInput() RENDERER = Tau.CoreServices_getInstance():getRenderer() listener = Tau.EventHandler() listener.onEvent = function(e) inputEvent = Tau.CoreInput_createEvent(e) if e:getEventCode() == Tau.EVENT_MOUSEUP then if onMouseUp ~= nil then onMouseUp(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == Tau.EVENT_MOUSEDOWN then if onMouseDown ~= nil then onMouseDown(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == Tau.EVENT_MOUSEMOVE then if onMouseMove ~= nil then onMouseMove(inputEvent.mousePosition.x, inputEvent.mousePosition.y) end end if e:getEventCode() == Tau.EVENT_KEYDOWN then if onKeyDown ~= nil then onKeyDown(inputEvent:keyCode()) end end if e:getEventCode() == Tau.EVENT_KEYUP then if onKeyUp ~= nil then onKeyUp(inputEvent:keyCode()) end end end INPUT:addEventListener(listener, Tau.EVENT_KEYDOWN) INPUT:addEventListener(listener, Tau.EVENT_KEYUP) INPUT:addEventListener(listener, Tau.EVENT_MOUSEDOWN) INPUT:addEventListener(listener, Tau.EVENT_MOUSEMOVE) INPUT:addEventListener(listener, Tau.EVENT_MOUSEUP) ";
 //		String prepend = "for k,v in pairs(math) do _G[k]=v end for k,v in pairs(table) do _G[k]=v end _G[\"count\"]=_G[\"getn\"] RESOURCE_MANAGER = Tau.CoreServices_getInstance():getResourceManager() CORE = Tau.CoreServices_getInstance():getCore() FONT_MANAGER = Tau.CoreServices_getInstance():getFontManager() INPUT = CORE:getInput() RENDERER = Tau.CoreServices_getInstance():getRenderer() listener = Tau.EventHandler() listener.onEvent = function(e) inputEvent = Tau.CoreInput_createEvent(e) if e:getEventCode() == Tau.EVENT_MOUSEUP then if onMouseUp ~= nil then onMouseUp(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == Tau.EVENT_MOUSEDOWN then if onMouseDown ~= nil then onMouseDown(inputEvent.mousePosition.x, inputEvent.mousePosition.y, inputEvent.mouseButton) end end if e:getEventCode() == Tau.EVENT_MOUSEMOVE then if onMouseMove ~= nil then onMouseMove(inputEvent.mousePosition.x, inputEvent.mousePosition.y) end end if e:getEventCode() == Tau.EVENT_KEYDOWN then if onKeyDown ~= nil then onKeyDown(inputEvent:keyCode()) end end if e:getEventCode() == Tau.EVENT_KEYUP then if onKeyUp ~= nil then onKeyUp(inputEvent:keyCode()) end end end INPUT:addEventListener(listener, Tau.EVENT_KEYDOWN) INPUT:addEventListener(listener, Tau.EVENT_KEYUP) INPUT:addEventListener(listener, Tau.EVENT_MOUSEDOWN) INPUT:addEventListener(listener, Tau.EVENT_MOUSEMOVE) INPUT:addEventListener(listener, Tau.EVENT_MOUSEUP) ";
 		
 		
@@ -161,8 +172,8 @@ extern "C" {
 		String postpend = ""; //" \nif update == nil then\nfunction update(e)\nend\nend\nwhile CORE:Update() do\nupdate(CORE:getElapsed())\nend";
 		String postpend = ""; //" \nif update == nil then\nfunction update(e)\nend\nend\nwhile CORE:Update() do\nupdate(CORE:getElapsed())\nend";
 		
 		
 		//String fullScript = prepend + prepend2 + prepend3 + fileData;// + postpend;
 		//String fullScript = prepend + prepend2 + prepend3 + fileData;// + postpend;
-		
-		String fullScript = fileData;// + postpend;
+		String fullScript = fileData;
+		//String fullScript = fileData;// + postpend;
 		
 		
 		doneLoading = true;
 		doneLoading = true;
 		
 		
@@ -235,6 +246,16 @@ void PolycodePlayer::loadFile(const char *fileName) {
 		loadingArchive = true;
 		loadingArchive = true;
 		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
 		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
 	} else {
 	} else {
+		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
+		
+		String fileDir = "";
+		vector<String> bits = String(fileName).split("/");
+		for(int i=0; i < bits.size()-1; i++) {
+			fileDir += "/"+bits[i];
+		}
+		
+		rman->addArchive(fileDir);
+		
 		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
 		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
 		TiXmlDocument doc1(fileName);	
 		TiXmlDocument doc1(fileName);	
 		doc = doc1;
 		doc = doc1;
@@ -289,7 +310,7 @@ void PolycodePlayer::loadFile(const char *fileName) {
 		}
 		}
 	}
 	}
 	
 	
-	Logger::log(mainFile.c_str());
+	Logger::log("Mainfile: %s\n", mainFile.c_str());
 	
 	
 	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
 	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
 	event->xRes = xRes;
 	event->xRes = xRes;
@@ -297,13 +318,16 @@ void PolycodePlayer::loadFile(const char *fileName) {
 	
 	
 	createCore();
 	createCore();
 	
 	
+	Logger::log("Core created...\n");
+	
 	core->setUserPointer(this);
 	core->setUserPointer(this);
-	core->addEventListener(this, Core::EVENT_CORE_RESIZE);
+	//core->addEventListener(this, Core::EVENT_CORE_RESIZE);
 	core->setVideoMode(xRes, yRes, fullScreen, aaLevel);
 	core->setVideoMode(xRes, yRes, fullScreen, aaLevel);
 		
 		
 //	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
 //	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
 	
 	
 	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
 	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
+//	CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
 	srand(core->getTicks());
 	srand(core->getTicks());
 	
 	
 	string fullPath;
 	string fullPath;
@@ -320,7 +344,8 @@ void PolycodePlayer::loadFile(const char *fileName) {
 	runFile(fullPath);
 	runFile(fullPath);
 }
 }
 
 
-void PolycodePlayer::runThread() {
+void PolycodePlayer::runPlayer() {
+	Logger::log("Running player\n");	
 	loadFile(fileToRun.c_str());
 	loadFile(fileToRun.c_str());
 	Logger::log("Done running player...\n");
 	Logger::log("Done running player...\n");
 }
 }
@@ -348,5 +373,10 @@ void PolycodePlayer::handleEvent(Event *event) {
 
 
 
 
 bool PolycodePlayer::Update() {
 bool PolycodePlayer::Update() {
+	
+	lua_getfield(L, LUA_GLOBALSINDEX, "Update");
+	lua_pushnumber(L, core->getElapsed());
+	lua_call(L, 1, 0);
+	
 	return core->Update();
 	return core->Update();
 }
 }