From 646bbbc84b8010e0dacbeed5342cdb045f46cc49 Mon Sep 17 00:00:00 2001 From: MW Date: Wed, 27 Jun 2007 15:28:52 +0000 Subject: Some work on restructuring the namespaces / project names. Note this doesn't compile yet as not all the code has been changed to use the new namespaces. Am committing it now for feedback on the namespaces. --- .../Communications.OGS1/GridCommsManager.cs | 18 + .../Communications.OGS1/OGS1GridServices.cs | 248 ++++++ .../Communications.OGS1/OGSInterSimComms.cs | 70 ++ .../Communications.OGS1/OGSUserServices.cs | 25 + .../OpenSim.Framework.Communications.OGS1.csproj | 142 +++ ...enSim.Framework.Communications.OGS1.csproj.user | 12 + .../Communications.OGS1/Properties/AssemblyInfo.cs | 35 + .../Communications/CommunicationsManager.cs | 51 ++ OpenSim/Framework/Communications/IGridServices.cs | 51 ++ .../Communications/IInterRegionCommunications.cs | 41 + OpenSim/Framework/Communications/IUserServices.cs | 44 + .../OpenSim.Framework.Communications.csproj | 112 +++ .../OpenSim.Framework.Communications.csproj.user | 12 + .../Communications/Properties/AssemblyInfo.cs | 62 ++ OpenSim/Framework/Console/AssemblyInfo.cs | 58 ++ OpenSim/Framework/Console/ConsoleCallbacksBase.cs | 39 + OpenSim/Framework/Console/LogBase.cs | 238 +++++ OpenSim/Framework/Console/MainLog.cs | 49 ++ .../Console/OpenSim.Framework.Console.csproj | 89 ++ .../Console/OpenSim.Framework.Console.csproj.user | 12 + OpenSim/Framework/Data.DB4o/DB4oGridData.cs | 166 ++++ OpenSim/Framework/Data.DB4o/DB4oManager.cs | 165 ++++ OpenSim/Framework/Data.DB4o/DB4oUserData.cs | 205 +++++ .../Data.DB4o/OpenSim.Framework.Data.DB4o.csproj | 111 +++ .../OpenSim.Framework.Data.DB4o.csproj.user | 12 + .../Framework/Data.DB4o/Properties/AssemblyInfo.cs | 35 + OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs | 192 ++++ OpenSim/Framework/Data.MSSQL/MSSQLManager.cs | 214 +++++ .../Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj | 104 +++ .../OpenSim.Framework.Data.MSSQL.csproj.user | 12 + .../Data.MSSQL/Properties/AssemblyInfo.cs | 35 + OpenSim/Framework/Data.MySQL/MySQLGridData.cs | 285 ++++++ OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs | 309 +++++++ OpenSim/Framework/Data.MySQL/MySQLLogData.cs | 107 +++ OpenSim/Framework/Data.MySQL/MySQLManager.cs | 609 +++++++++++++ OpenSim/Framework/Data.MySQL/MySQLUserData.cs | 257 ++++++ .../Data.MySQL/OpenSim.Framework.Data.MySQL.csproj | 117 +++ .../OpenSim.Framework.Data.MySQL.csproj.user | 12 + .../Data.MySQL/Properties/AssemblyInfo.cs | 35 + .../OpenSim.Framework.Data.SQLite.csproj | 108 +++ .../OpenSim.Framework.Data.SQLite.csproj.user | 12 + .../Data.SQLite/Properties/AssemblyInfo.cs | 35 + OpenSim/Framework/Data.SQLite/SQLiteGridData.cs | 195 +++++ OpenSim/Framework/Data.SQLite/SQLiteManager.cs | 209 +++++ OpenSim/Framework/Data/GridData.cs | 113 +++ OpenSim/Framework/Data/ILogData.cs | 94 ++ OpenSim/Framework/Data/IniConfig.cs | 100 +++ OpenSim/Framework/Data/InventoryData.cs | 187 ++++ .../Framework/Data/OpenSim.Framework.Data.csproj | 116 +++ .../Data/OpenSim.Framework.Data.csproj.user | 12 + OpenSim/Framework/Data/Properties/AssemblyInfo.cs | 35 + OpenSim/Framework/Data/ReservationData.cs | 51 ++ OpenSim/Framework/Data/SimProfileData.cs | 114 +++ OpenSim/Framework/Data/UserData.cs | 131 +++ OpenSim/Framework/Data/UserProfileData.cs | 182 ++++ OpenSim/Framework/General/AgentInventory.cs | 267 ++++++ .../Framework/General/AuthenticateSessionBase.cs | 132 +++ OpenSim/Framework/General/BlockingQueue.cs | 60 ++ OpenSim/Framework/General/IRegionCommsListener.cs | 47 + .../General/Interfaces/AuthenticateResponse.cs | 51 ++ .../General/Interfaces/Config/IGenericConfig.cs | 42 + .../General/Interfaces/Config/IGridConfig.cs | 63 ++ .../General/Interfaces/Config/IUserConfig.cs | 57 ++ .../Framework/General/Interfaces/IAssetServer.cs | 69 ++ OpenSim/Framework/General/Interfaces/IClientAPI.cs | 160 ++++ .../Framework/General/Interfaces/ILocalStorage.cs | 69 ++ .../Framework/General/Interfaces/IUserServer.cs | 42 + OpenSim/Framework/General/Interfaces/IWorld.cs | 45 + .../General/Interfaces/Scripting/IScriptAPI.cs | 42 + .../General/Interfaces/Scripting/IScriptEngine.cs | 41 + OpenSim/Framework/General/LLSDHelpers.cs | 246 ++++++ OpenSim/Framework/General/Logger.cs | 85 ++ OpenSim/Framework/General/LoginService.cs | 41 + OpenSim/Framework/General/OpenSim.Framework.csproj | 213 +++++ .../General/OpenSim.Framework.csproj.user | 12 + .../Framework/General/Properties/AssemblyInfo.cs | 33 + OpenSim/Framework/General/RegionCommsListener.cs | 69 ++ OpenSim/Framework/General/Remoting.cs | 136 +++ OpenSim/Framework/General/SimProfile.cs | 122 +++ OpenSim/Framework/General/Types/AgentCiruitData.cs | 50 ++ OpenSim/Framework/General/Types/AgentWearable.cs | 60 ++ OpenSim/Framework/General/Types/AssetBase.cs | 49 ++ OpenSim/Framework/General/Types/AssetLandmark.cs | 61 ++ OpenSim/Framework/General/Types/AssetStorage.cs | 50 ++ OpenSim/Framework/General/Types/EstateSettings.cs | 97 ++ OpenSim/Framework/General/Types/Login.cs | 52 ++ OpenSim/Framework/General/Types/MapBlockData.cs | 25 + OpenSim/Framework/General/Types/NeighbourInfo.cs | 50 ++ .../Framework/General/Types/NetworkServersInfo.cs | 181 ++++ OpenSim/Framework/General/Types/ParcelData.cs | 115 +++ OpenSim/Framework/General/Types/PrimData.cs | 230 +++++ OpenSim/Framework/General/Types/RegionHandle.cs | 120 +++ OpenSim/Framework/General/Types/RegionInfo.cs | 304 +++++++ OpenSim/Framework/General/UserProfile.cs | 89 ++ OpenSim/Framework/General/Util.cs | 186 ++++ .../Xml/OpenSim.Framework.GenericConfig.Xml.csproj | 93 ++ ...OpenSim.Framework.GenericConfig.Xml.csproj.user | 12 + .../GenericConfig/Xml/Properties/AssemblyInfo.cs | 35 + OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs | 123 +++ OpenSim/Framework/Servers/BaseHttpServer.cs | 312 +++++++ OpenSim/Framework/Servers/CheckSumServer.cs | 141 +++ OpenSim/Framework/Servers/IRestHandler.cs | 35 + .../Servers/OpenSim.Framework.Servers.csproj | 116 +++ .../Servers/OpenSim.Framework.Servers.csproj.user | 12 + OpenSim/Framework/Servers/UDPServerBase.cs | 95 ++ OpenSim/Framework/Servers/XmlRpcMethod.cs | 34 + OpenSim/Framework/UserManager/LoginResponse.cs | 645 ++++++++++++++ .../OpenSim.Framework.UserManagement.csproj | 125 +++ .../OpenSim.Framework.UserManagement.csproj.user | 12 + OpenSim/Framework/UserManager/UserManagerBase.cs | 641 ++++++++++++++ OpenSim/Grid/AssetServer/AssetHttpServer.cs | 130 +++ OpenSim/Grid/AssetServer/Main.cs | 337 +++++++ .../AssetServer/OpenSim.Grid.AssetServer.csproj | 118 +++ .../OpenSim.Grid.AssetServer.csproj.user | 12 + .../Grid/AssetServer/Properties/AssemblyInfo.cs | 60 ++ .../Grid/Framework.Manager/GridManagementAgent.cs | 140 +++ .../Grid/Framework.Manager/GridServerManager.cs | 94 ++ .../OpenSim.Grid.Framework.Manager.csproj | 99 +++ .../OpenSim.Grid.Framework.Manager.csproj.user | 12 + OpenSim/Grid/GridServer.Config/AssemblyInfo.cs | 58 ++ OpenSim/Grid/GridServer.Config/DbGridConfig.cs | 161 ++++ .../OpenSim.Grid.GridServer.Config.csproj | 107 +++ .../OpenSim.Grid.GridServer.Config.csproj.user | 12 + OpenSim/Grid/GridServer/GridManager.cs | 599 +++++++++++++ OpenSim/Grid/GridServer/Main.cs | 271 ++++++ .../Grid/GridServer/OpenSim.Grid.GridServer.csproj | 134 +++ .../GridServer/OpenSim.Grid.GridServer.csproj.user | 12 + OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs | 60 ++ OpenSim/Grid/InventoryServer/InventoryManager.cs | 125 +++ OpenSim/Grid/InventoryServer/Main.cs | 87 ++ OpenSim/Grid/Manager/OpenGridServices.Manager.mds | 16 + .../Manager/OpenGridServices.Manager.userprefs | 39 + .../Manager/OpenGridServices.Manager.usertasks | 2 + .../OpenGridServices.Manager/AssemblyInfo.cs | 32 + .../OpenGridServices.Manager/BlockingQueue.cs | 33 + .../Connect to grid server.cs | 16 + .../ConnectToGridServerDialog.cs | 29 + .../GridServerConnectionManager.cs | 106 +++ .../Grid/Manager/OpenGridServices.Manager/Main.cs | 96 ++ .../Manager/OpenGridServices.Manager/MainWindow.cs | 76 ++ .../OpenGridServices.Manager.mdp | 43 + .../OpenGridServices.Manager.pidb | Bin 0 -> 12308 bytes .../OpenGridServices.Manager/RegionBlock.cs | 37 + .../Grid/Manager/OpenGridServices.Manager/Util.cs | 133 +++ ...idServices.Manager.ConnectToGridServerDialog.cs | 226 +++++ .../gtk-gui/OpenGridServices.Manager.MainWindow.cs | 256 ++++++ .../OpenGridServices.Manager/gtk-gui/generated.cs | 35 + .../OpenGridServices.Manager/gtk-gui/gui.stetic | 502 +++++++++++ OpenSim/Grid/UserServer.Config/AssemblyInfo.cs | 58 ++ OpenSim/Grid/UserServer.Config/DbUserConfig.cs | 96 ++ .../OpenSim.Grid.UserServer.Config.csproj | 107 +++ .../OpenSim.Grid.UserServer.Config.csproj.user | 12 + OpenSim/Grid/UserServer/Main.cs | 219 +++++ .../Grid/UserServer/OpenSim.Grid.UserServer.csproj | 132 +++ .../UserServer/OpenSim.Grid.UserServer.csproj.user | 12 + OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs | 33 + OpenSim/Grid/UserServer/UserManager.cs | 103 +++ OpenSim/Region/Application/Application.cs | 121 +++ OpenSim/Region/Application/OpenSim.csproj | 181 ++++ OpenSim/Region/Application/OpenSim.csproj.user | 13 + OpenSim/Region/Application/OpenSimMain.cs | 476 ++++++++++ OpenSim/Region/Caches/AssetCache.cs | 670 ++++++++++++++ OpenSim/Region/Caches/OpenSim.Region.Caches.csproj | 97 ++ .../Caches/OpenSim.Region.Caches.csproj.user | 12 + OpenSim/Region/Caches/Properties/AssemblyInfo.cs | 35 + OpenSim/Region/Caps/Caps.cs | 258 ++++++ OpenSim/Region/Caps/LLSDHelpers.cs | 246 ++++++ .../Region/ClientStack/Assets/InventoryCache.cs | 337 +++++++ .../ClientStack/ClientStackNetworkHandler.cs | 46 + OpenSim/Region/ClientStack/ClientView.API.cs | 975 +++++++++++++++++++++ .../ClientStack/ClientView.AgentAssetUpload.cs | 358 ++++++++ .../ClientStack/ClientView.PacketHandlers.cs | 198 +++++ .../ClientStack/ClientView.ProcessPackets.cs | 550 ++++++++++++ OpenSim/Region/ClientStack/ClientView.cs | 273 ++++++ OpenSim/Region/ClientStack/ClientViewBase.cs | 327 +++++++ .../ClientStack/OpenSim.Region.ClientStack.csproj | 173 ++++ .../OpenSim.Region.ClientStack.csproj.user | 12 + OpenSim/Region/ClientStack/PacketServer.cs | 183 ++++ .../Region/ClientStack/RegionApplicationBase.cs | 129 +++ OpenSim/Region/ClientStack/UDPServer.cs | 208 +++++ OpenSim/Region/ClientStack/VersionInfo.cs | 38 + OpenSim/Region/Examples/SimpleApp/MyWorld.cs | 113 +++ OpenSim/Region/Examples/SimpleApp/Program.cs | 128 +++ .../Examples/SimpleApp/Properties/AssemblyInfo.cs | 33 + OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj | 154 ++++ .../Examples/SimpleApp/SimpleApp.csproj.user | 12 + .../Region/GridInterfaces/Local/AssemblyInfo.cs | 58 ++ .../GridInterfaces/Local/LocalAssetServer.cs | 312 +++++++ .../OpenSim.Region.GridInterfaces.Local.csproj | 107 +++ ...OpenSim.Region.GridInterfaces.Local.csproj.user | 12 + .../Region/GridInterfaces/Remote/AssemblyInfo.cs | 58 ++ .../OpenSim.Region.GridInterfaces.Remote.csproj | 107 +++ ...penSim.Region.GridInterfaces.Remote.csproj.user | 12 + .../GridInterfaces/Remote/RemoteAssetServer.cs | 135 +++ .../LocalCommunications/CommunicationsLocal.cs | 61 ++ .../LocalCommunications/LocalBackEndServices.cs | 209 +++++ .../LocalCommunications/LocalUserServices.cs | 118 +++ .../OpenSim.Region.LocalCommunications.csproj | 121 +++ .../OpenSim.Region.LocalCommunications.csproj.user | 12 + .../LocalCommunications/Properties/AssemblyInfo.cs | 35 + .../Physics/BasicPhysicsPlugin/AssemblyInfo.cs | 58 ++ .../BasicPhysicsPlugin/BasicPhysicsPlugin.cs | 294 +++++++ ...penSim.Region.Physics.BasicPhysicsPlugin.csproj | 93 ++ ...m.Region.Physics.BasicPhysicsPlugin.csproj.user | 12 + OpenSim/Region/Physics/Manager/AssemblyInfo.cs | 58 ++ .../Manager/OpenSim.Region.Physics.Manager.csproj | 112 +++ .../OpenSim.Region.Physics.Manager.csproj.user | 12 + OpenSim/Region/Physics/Manager/PhysicsActor.cs | 161 ++++ OpenSim/Region/Physics/Manager/PhysicsManager.cs | 117 +++ OpenSim/Region/Physics/Manager/PhysicsScene.cs | 113 +++ OpenSim/Region/Physics/Manager/PhysicsVector.cs | 54 ++ OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs | 58 ++ OpenSim/Region/Physics/OdePlugin/OdePlugin.cs | 456 ++++++++++ .../OpenSim.Region.Physics.OdePlugin.csproj | 97 ++ .../OpenSim.Region.Physics.OdePlugin.csproj.user | 12 + OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs | 58 ++ .../OpenSim.Region.Physics.PhysXPlugin.csproj | 97 ++ .../OpenSim.Region.Physics.PhysXPlugin.csproj.user | 12 + OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs | 424 +++++++++ .../Region/Scripting/Properties/AssemblyInfo.cs | 35 + OpenSim/Region/Scripting/Script.cs | 32 + OpenSim/Region/Scripting/ScriptAccess.cs | 31 + OpenSim/Region/Simulation/Caps.cs | 258 ++++++ OpenSim/Region/Simulation/EstateManager.cs | 301 +++++++ .../Simulation/OpenSim.Region.Simulation.csproj | 211 +++++ .../OpenSim.Region.Simulation.csproj.user | 12 + OpenSim/Region/Simulation/ParcelManager.cs | 892 +++++++++++++++++++ OpenSim/Region/Simulation/RegionManager.cs | 30 + OpenSim/Region/Simulation/Scenes/Entity.cs | 194 ++++ .../Region/Simulation/Scenes/IScenePresenceBody.cs | 19 + OpenSim/Region/Simulation/Scenes/Primitive.cs | 582 ++++++++++++ .../Simulation/Scenes/Scene.PacketHandlers.cs | 305 +++++++ .../Region/Simulation/Scenes/Scene.Scripting.cs | 184 ++++ OpenSim/Region/Simulation/Scenes/Scene.cs | 795 +++++++++++++++++ OpenSim/Region/Simulation/Scenes/SceneBase.cs | 201 +++++ OpenSim/Region/Simulation/Scenes/SceneEvents.cs | 52 ++ OpenSim/Region/Simulation/Scenes/SceneObject.cs | 128 +++ .../Simulation/Scenes/ScenePresence.Animations.cs | 76 ++ .../Region/Simulation/Scenes/ScenePresence.Body.cs | 90 ++ OpenSim/Region/Simulation/Scenes/ScenePresence.cs | 525 +++++++++++ .../Simulation/Scenes/scripting/IScriptContext.cs | 40 + .../Simulation/Scenes/scripting/IScriptEntity.cs | 46 + .../Simulation/Scenes/scripting/IScriptHandler.cs | 126 +++ .../Region/Simulation/Scenes/scripting/Script.cs | 53 ++ .../Simulation/Scenes/scripting/ScriptFactory.cs | 35 + .../Scenes/scripting/Scripts/FollowRandomAvatar.cs | 64 ++ .../LocalStorageBerkeleyDB/BDBLocalStorage.cs | 117 +++ ...im.Region.Storage.LocalStorageBerkeleyDB.csproj | 112 +++ ...gion.Storage.LocalStorageBerkeleyDB.csproj.user | 12 + ...penSim.Storage.LocalStorageBerkeleyDB.dll.build | 46 + .../Storage/LocalStorageDb4o/AssemblyInfo.cs | 58 ++ .../Storage/LocalStorageDb4o/Db4LocalStorage.cs | 271 ++++++ .../Region/Storage/LocalStorageDb4o/MapStorage.cs | 43 + .../OpenSim.Region.Storage.LocalStorageDb4o.csproj | 116 +++ ...Sim.Region.Storage.LocalStorageDb4o.csproj.user | 12 + .../Storage/LocalStorageDb4o/UUIDParcelQuery.cs | 52 ++ .../Storage/LocalStorageDb4o/UUIDPrimQuery.cs | 52 ++ ...penSim.Region.Storage.LocalStorageSQLite.csproj | 111 +++ ...m.Region.Storage.LocalStorageSQLite.csproj.user | 12 + .../OpenSim.Storage.LocalStorageSQLite.dll.build | 46 + .../LocalStorageSQLite/Properties/AssemblyInfo.cs | 62 ++ .../LocalStorageSQLite/SQLiteLocalStorage.cs | 198 +++++ .../OpenSim.Region.Terrain.BasicTerrain.csproj | 110 +++ ...OpenSim.Region.Terrain.BasicTerrain.csproj.user | 12 + .../Properties/AssemblyInfo.cs | 62 ++ .../Region/Terrain.BasicTerrain/TerrainEngine.cs | 786 +++++++++++++++++ .../Region/Terrain.BasicTerrain/TerrainFilter.cs | 103 +++ 267 files changed, 35176 insertions(+) create mode 100644 OpenSim/Framework/Communications.OGS1/GridCommsManager.cs create mode 100644 OpenSim/Framework/Communications.OGS1/OGS1GridServices.cs create mode 100644 OpenSim/Framework/Communications.OGS1/OGSInterSimComms.cs create mode 100644 OpenSim/Framework/Communications.OGS1/OGSUserServices.cs create mode 100644 OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj create mode 100644 OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj.user create mode 100644 OpenSim/Framework/Communications.OGS1/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Communications/CommunicationsManager.cs create mode 100644 OpenSim/Framework/Communications/IGridServices.cs create mode 100644 OpenSim/Framework/Communications/IInterRegionCommunications.cs create mode 100644 OpenSim/Framework/Communications/IUserServices.cs create mode 100644 OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj create mode 100644 OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj.user create mode 100644 OpenSim/Framework/Communications/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Console/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Console/ConsoleCallbacksBase.cs create mode 100644 OpenSim/Framework/Console/LogBase.cs create mode 100644 OpenSim/Framework/Console/MainLog.cs create mode 100644 OpenSim/Framework/Console/OpenSim.Framework.Console.csproj create mode 100644 OpenSim/Framework/Console/OpenSim.Framework.Console.csproj.user create mode 100644 OpenSim/Framework/Data.DB4o/DB4oGridData.cs create mode 100644 OpenSim/Framework/Data.DB4o/DB4oManager.cs create mode 100644 OpenSim/Framework/Data.DB4o/DB4oUserData.cs create mode 100644 OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj create mode 100644 OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj.user create mode 100644 OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs create mode 100644 OpenSim/Framework/Data.MSSQL/MSSQLManager.cs create mode 100644 OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj create mode 100644 OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj.user create mode 100644 OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Data.MySQL/MySQLGridData.cs create mode 100644 OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs create mode 100644 OpenSim/Framework/Data.MySQL/MySQLLogData.cs create mode 100644 OpenSim/Framework/Data.MySQL/MySQLManager.cs create mode 100644 OpenSim/Framework/Data.MySQL/MySQLUserData.cs create mode 100644 OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj create mode 100644 OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj.user create mode 100644 OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj create mode 100644 OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj.user create mode 100644 OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Data.SQLite/SQLiteGridData.cs create mode 100644 OpenSim/Framework/Data.SQLite/SQLiteManager.cs create mode 100644 OpenSim/Framework/Data/GridData.cs create mode 100644 OpenSim/Framework/Data/ILogData.cs create mode 100644 OpenSim/Framework/Data/IniConfig.cs create mode 100644 OpenSim/Framework/Data/InventoryData.cs create mode 100644 OpenSim/Framework/Data/OpenSim.Framework.Data.csproj create mode 100644 OpenSim/Framework/Data/OpenSim.Framework.Data.csproj.user create mode 100644 OpenSim/Framework/Data/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/Data/ReservationData.cs create mode 100644 OpenSim/Framework/Data/SimProfileData.cs create mode 100644 OpenSim/Framework/Data/UserData.cs create mode 100644 OpenSim/Framework/Data/UserProfileData.cs create mode 100644 OpenSim/Framework/General/AgentInventory.cs create mode 100644 OpenSim/Framework/General/AuthenticateSessionBase.cs create mode 100644 OpenSim/Framework/General/BlockingQueue.cs create mode 100644 OpenSim/Framework/General/IRegionCommsListener.cs create mode 100644 OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs create mode 100644 OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs create mode 100644 OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs create mode 100644 OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs create mode 100644 OpenSim/Framework/General/Interfaces/IAssetServer.cs create mode 100644 OpenSim/Framework/General/Interfaces/IClientAPI.cs create mode 100644 OpenSim/Framework/General/Interfaces/ILocalStorage.cs create mode 100644 OpenSim/Framework/General/Interfaces/IUserServer.cs create mode 100644 OpenSim/Framework/General/Interfaces/IWorld.cs create mode 100644 OpenSim/Framework/General/Interfaces/Scripting/IScriptAPI.cs create mode 100644 OpenSim/Framework/General/Interfaces/Scripting/IScriptEngine.cs create mode 100644 OpenSim/Framework/General/LLSDHelpers.cs create mode 100644 OpenSim/Framework/General/Logger.cs create mode 100644 OpenSim/Framework/General/LoginService.cs create mode 100644 OpenSim/Framework/General/OpenSim.Framework.csproj create mode 100644 OpenSim/Framework/General/OpenSim.Framework.csproj.user create mode 100644 OpenSim/Framework/General/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/General/RegionCommsListener.cs create mode 100644 OpenSim/Framework/General/Remoting.cs create mode 100644 OpenSim/Framework/General/SimProfile.cs create mode 100644 OpenSim/Framework/General/Types/AgentCiruitData.cs create mode 100644 OpenSim/Framework/General/Types/AgentWearable.cs create mode 100644 OpenSim/Framework/General/Types/AssetBase.cs create mode 100644 OpenSim/Framework/General/Types/AssetLandmark.cs create mode 100644 OpenSim/Framework/General/Types/AssetStorage.cs create mode 100644 OpenSim/Framework/General/Types/EstateSettings.cs create mode 100644 OpenSim/Framework/General/Types/Login.cs create mode 100644 OpenSim/Framework/General/Types/MapBlockData.cs create mode 100644 OpenSim/Framework/General/Types/NeighbourInfo.cs create mode 100644 OpenSim/Framework/General/Types/NetworkServersInfo.cs create mode 100644 OpenSim/Framework/General/Types/ParcelData.cs create mode 100644 OpenSim/Framework/General/Types/PrimData.cs create mode 100644 OpenSim/Framework/General/Types/RegionHandle.cs create mode 100644 OpenSim/Framework/General/Types/RegionInfo.cs create mode 100644 OpenSim/Framework/General/UserProfile.cs create mode 100644 OpenSim/Framework/General/Util.cs create mode 100644 OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj create mode 100644 OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj.user create mode 100644 OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs create mode 100644 OpenSim/Framework/Servers/BaseHttpServer.cs create mode 100644 OpenSim/Framework/Servers/CheckSumServer.cs create mode 100644 OpenSim/Framework/Servers/IRestHandler.cs create mode 100644 OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj create mode 100644 OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj.user create mode 100644 OpenSim/Framework/Servers/UDPServerBase.cs create mode 100644 OpenSim/Framework/Servers/XmlRpcMethod.cs create mode 100644 OpenSim/Framework/UserManager/LoginResponse.cs create mode 100644 OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj create mode 100644 OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj.user create mode 100644 OpenSim/Framework/UserManager/UserManagerBase.cs create mode 100644 OpenSim/Grid/AssetServer/AssetHttpServer.cs create mode 100644 OpenSim/Grid/AssetServer/Main.cs create mode 100644 OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj create mode 100644 OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj.user create mode 100644 OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Grid/Framework.Manager/GridManagementAgent.cs create mode 100644 OpenSim/Grid/Framework.Manager/GridServerManager.cs create mode 100644 OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj create mode 100644 OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj.user create mode 100644 OpenSim/Grid/GridServer.Config/AssemblyInfo.cs create mode 100644 OpenSim/Grid/GridServer.Config/DbGridConfig.cs create mode 100644 OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj create mode 100644 OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj.user create mode 100644 OpenSim/Grid/GridServer/GridManager.cs create mode 100644 OpenSim/Grid/GridServer/Main.cs create mode 100644 OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj create mode 100644 OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj.user create mode 100644 OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Grid/InventoryServer/InventoryManager.cs create mode 100644 OpenSim/Grid/InventoryServer/Main.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager.mds create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager.userprefs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager.usertasks create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/AssemblyInfo.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/Connect to grid server.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/ConnectToGridServerDialog.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/GridServerConnectionManager.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/Main.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/MainWindow.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.mdp create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.pidb create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/RegionBlock.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.ConnectToGridServerDialog.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.MainWindow.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/generated.cs create mode 100644 OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/gui.stetic create mode 100644 OpenSim/Grid/UserServer.Config/AssemblyInfo.cs create mode 100644 OpenSim/Grid/UserServer.Config/DbUserConfig.cs create mode 100644 OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj create mode 100644 OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj.user create mode 100644 OpenSim/Grid/UserServer/Main.cs create mode 100644 OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj create mode 100644 OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj.user create mode 100644 OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Grid/UserServer/UserManager.cs create mode 100644 OpenSim/Region/Application/Application.cs create mode 100644 OpenSim/Region/Application/OpenSim.csproj create mode 100644 OpenSim/Region/Application/OpenSim.csproj.user create mode 100644 OpenSim/Region/Application/OpenSimMain.cs create mode 100644 OpenSim/Region/Caches/AssetCache.cs create mode 100644 OpenSim/Region/Caches/OpenSim.Region.Caches.csproj create mode 100644 OpenSim/Region/Caches/OpenSim.Region.Caches.csproj.user create mode 100644 OpenSim/Region/Caches/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Caps/Caps.cs create mode 100644 OpenSim/Region/Caps/LLSDHelpers.cs create mode 100644 OpenSim/Region/ClientStack/Assets/InventoryCache.cs create mode 100644 OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs create mode 100644 OpenSim/Region/ClientStack/ClientView.API.cs create mode 100644 OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs create mode 100644 OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs create mode 100644 OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs create mode 100644 OpenSim/Region/ClientStack/ClientView.cs create mode 100644 OpenSim/Region/ClientStack/ClientViewBase.cs create mode 100644 OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj create mode 100644 OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj.user create mode 100644 OpenSim/Region/ClientStack/PacketServer.cs create mode 100644 OpenSim/Region/ClientStack/RegionApplicationBase.cs create mode 100644 OpenSim/Region/ClientStack/UDPServer.cs create mode 100644 OpenSim/Region/ClientStack/VersionInfo.cs create mode 100644 OpenSim/Region/Examples/SimpleApp/MyWorld.cs create mode 100644 OpenSim/Region/Examples/SimpleApp/Program.cs create mode 100644 OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj create mode 100644 OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj.user create mode 100644 OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs create mode 100644 OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs create mode 100644 OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj create mode 100644 OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj.user create mode 100644 OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs create mode 100644 OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj create mode 100644 OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj.user create mode 100644 OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs create mode 100644 OpenSim/Region/LocalCommunications/CommunicationsLocal.cs create mode 100644 OpenSim/Region/LocalCommunications/LocalBackEndServices.cs create mode 100644 OpenSim/Region/LocalCommunications/LocalUserServices.cs create mode 100644 OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj create mode 100644 OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj.user create mode 100644 OpenSim/Region/LocalCommunications/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs create mode 100644 OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj create mode 100644 OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj.user create mode 100644 OpenSim/Region/Physics/Manager/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj create mode 100644 OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj.user create mode 100644 OpenSim/Region/Physics/Manager/PhysicsActor.cs create mode 100644 OpenSim/Region/Physics/Manager/PhysicsManager.cs create mode 100644 OpenSim/Region/Physics/Manager/PhysicsScene.cs create mode 100644 OpenSim/Region/Physics/Manager/PhysicsVector.cs create mode 100644 OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/OdePlugin/OdePlugin.cs create mode 100644 OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj create mode 100644 OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj.user create mode 100644 OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj create mode 100644 OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj.user create mode 100644 OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs create mode 100644 OpenSim/Region/Scripting/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Scripting/Script.cs create mode 100644 OpenSim/Region/Scripting/ScriptAccess.cs create mode 100644 OpenSim/Region/Simulation/Caps.cs create mode 100644 OpenSim/Region/Simulation/EstateManager.cs create mode 100644 OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj create mode 100644 OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj.user create mode 100644 OpenSim/Region/Simulation/ParcelManager.cs create mode 100644 OpenSim/Region/Simulation/RegionManager.cs create mode 100644 OpenSim/Region/Simulation/Scenes/Entity.cs create mode 100644 OpenSim/Region/Simulation/Scenes/IScenePresenceBody.cs create mode 100644 OpenSim/Region/Simulation/Scenes/Primitive.cs create mode 100644 OpenSim/Region/Simulation/Scenes/Scene.PacketHandlers.cs create mode 100644 OpenSim/Region/Simulation/Scenes/Scene.Scripting.cs create mode 100644 OpenSim/Region/Simulation/Scenes/Scene.cs create mode 100644 OpenSim/Region/Simulation/Scenes/SceneBase.cs create mode 100644 OpenSim/Region/Simulation/Scenes/SceneEvents.cs create mode 100644 OpenSim/Region/Simulation/Scenes/SceneObject.cs create mode 100644 OpenSim/Region/Simulation/Scenes/ScenePresence.Animations.cs create mode 100644 OpenSim/Region/Simulation/Scenes/ScenePresence.Body.cs create mode 100644 OpenSim/Region/Simulation/Scenes/ScenePresence.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/IScriptContext.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/IScriptEntity.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/IScriptHandler.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/Script.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/ScriptFactory.cs create mode 100644 OpenSim/Region/Simulation/Scenes/scripting/Scripts/FollowRandomAvatar.cs create mode 100644 OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs create mode 100644 OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj create mode 100644 OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj.user create mode 100644 OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj.user create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs create mode 100644 OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs create mode 100644 OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj create mode 100644 OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj.user create mode 100644 OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build create mode 100644 OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs create mode 100644 OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj create mode 100644 OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj.user create mode 100644 OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs create mode 100644 OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs (limited to 'OpenSim') diff --git a/OpenSim/Framework/Communications.OGS1/GridCommsManager.cs b/OpenSim/Framework/Communications.OGS1/GridCommsManager.cs new file mode 100644 index 0000000..6687380 --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/GridCommsManager.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; +using OpenSim.Framework.Communications; +namespace OpenSim.Framework.Communications.OGS1 +{ + public class GridCommsManager : CommunicationsManager + { + private OGS1GridServices gridInterComms = new OGS1GridServices(); + public GridCommsManager(NetworkServersInfo serversInfo) :base(serversInfo) + { + GridServer = gridInterComms; + InterRegion = gridInterComms; + UserServer = new OGSUserServices(); + } + } +} diff --git a/OpenSim/Framework/Communications.OGS1/OGS1GridServices.cs b/OpenSim/Framework/Communications.OGS1/OGS1GridServices.cs new file mode 100644 index 0000000..408643f --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/OGS1GridServices.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections.Generic; +using System.Collections; +using System.Text; +using System.Runtime.Remoting; +using System.Runtime.Remoting.Channels; +using System.Runtime.Remoting.Channels.Tcp; + +using OpenSim.Servers; +using OpenSim.Framework; +using OpenSim.Framework.Types; +using OpenSim.Framework.Communications; + +using Nwc.XmlRpc; +using libsecondlife; + +namespace OpenSim.Framework.Communications.OGS1 +{ + public class OGS1GridServices : IGridServices, IInterRegionCommunications + { + public Dictionary listeners = new Dictionary(); + public GridInfo grid; + public BaseHttpServer httpListener; + private bool initialised = false; + + public RegionCommsListener RegisterRegion(RegionInfo regionInfo, GridInfo gridInfo) + { + Hashtable GridParams = new Hashtable(); + + grid = gridInfo; + + // Login / Authentication + GridParams["authkey"] = gridInfo.GridServerSendKey; + GridParams["UUID"] = regionInfo.SimUUID.ToStringHyphenated(); + GridParams["sim_ip"] = regionInfo.CommsExternalAddress; + GridParams["sim_port"] = regionInfo.CommsIPListenPort.ToString(); + + // Package into an XMLRPC Request + ArrayList SendParams = new ArrayList(); + SendParams.Add(GridParams); + + // Send Request + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams); + XmlRpcResponse GridResp = GridReq.Send(gridInfo.GridServerURI, 3000); + Hashtable GridRespData = (Hashtable)GridResp.Value; + Hashtable griddatahash = GridRespData; + + // Process Response + if (GridRespData.ContainsKey("error")) + { + string errorstring = (string)GridRespData["error"]; + OpenSim.Framework.Console.MainLog.Instance.Error("Unable to connect to grid: " + errorstring); + return null; + } + + if (!this.listeners.ContainsKey(regionInfo.RegionHandle)) + { + // initialised = true; + httpListener = new BaseHttpServer(regionInfo.CommsIPListenPort); + httpListener.AddXmlRPCHandler("expect_user", this.ExpectUser); + httpListener.Start(); + } + + // Initialise the background listeners + listeners[regionInfo.RegionHandle] = new RegionCommsListener(); + + return listeners[regionInfo.RegionHandle]; + } + + public List RequestNeighbours(RegionInfo regionInfo) + { + Hashtable respData = MapBlockQuery((int)regionInfo.RegionLocX - 1, (int)regionInfo.RegionLocY - 1, (int)regionInfo.RegionLocX + 1, (int)regionInfo.RegionLocY + 1); + + List neighbours = new List(); + + foreach (Hashtable n in (Hashtable)respData.Values) + { + RegionInfo neighbour = new RegionInfo(); + + //OGS1 + neighbour.RegionHandle = (ulong)n["regionhandle"]; + neighbour.RegionLocX = (uint)n["x"]; + neighbour.RegionLocY = (uint)n["y"]; + neighbour.RegionName = (string)n["name"]; + + //OGS1+ + neighbour.CommsIPListenAddr = (string)n["sim_ip"]; + neighbour.CommsIPListenPort = (int)n["sim_port"]; + neighbour.CommsExternalAddress = (string)n["sim_uri"]; + neighbour.SimUUID = (string)n["uuid"]; + + neighbours.Add(neighbour); + } + + return neighbours; + } + + public RegionInfo RequestNeighbourInfo(ulong regionHandle) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Unimplemented - RequestNeighbourInfo()"); + return null; + } + + public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) + { + Hashtable respData = MapBlockQuery(minX, minY, maxX, maxY); + + List neighbours = new List(); + + foreach (Hashtable n in (Hashtable)respData.Values) + { + MapBlockData neighbour = new MapBlockData(); + + neighbour.X = (ushort)n["x"]; + neighbour.Y = (ushort)n["y"]; + + neighbour.Name = (string)n["name"]; + neighbour.Access = (byte)n["access"]; + neighbour.RegionFlags = (uint)n["region-flags"]; + neighbour.WaterHeight = (byte)n["water-height"]; + neighbour.MapImageId = (string)n["map-image-id"]; + + neighbours.Add(neighbour); + } + + return neighbours; + } + + /// + /// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates + /// + /// REDUNDANT - OGS1 is to be phased out in favour of OGS2 + /// Minimum X value + /// Minimum Y value + /// Maximum X value + /// Maximum Y value + /// Hashtable of hashtables containing map data elements + private Hashtable MapBlockQuery(int minX, int minY, int maxX, int maxY) + { + Hashtable param = new Hashtable(); + param["xmin"] = minX; + param["ymin"] = minY; + param["xmax"] = maxX; + param["ymax"] = maxY; + IList parameters = new ArrayList(); + parameters.Add(param); + XmlRpcRequest req = new XmlRpcRequest("map_block", parameters); + XmlRpcResponse resp = req.Send(grid.GridServerURI, 3000); + Hashtable respData = (Hashtable)resp.Value; + return respData; + } + + // Grid Request Processing + public XmlRpcResponse ExpectUser(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + AgentCircuitData agentData = new AgentCircuitData(); + agentData.SessionID = new LLUUID((string)requestData["session_id"]); + agentData.SecureSessionID = new LLUUID((string)requestData["secure_session_id"]); + agentData.firstname = (string)requestData["firstname"]; + agentData.lastname = (string)requestData["lastname"]; + agentData.AgentID = new LLUUID((string)requestData["agent_id"]); + agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); + if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1")) + { + agentData.child = true; + } + else + { + agentData.startpos = new LLVector3(Convert.ToUInt32(requestData["startpos_x"]), Convert.ToUInt32(requestData["startpos_y"]), Convert.ToUInt32(requestData["startpos_z"])); + agentData.child = false; + + } + + if (listeners.ContainsKey((ulong)requestData["regionhandle"])) + { + this.listeners[(ulong)requestData["regionhandle"]].TriggerExpectUser((ulong)requestData["regionhandle"], agentData); + } + else + { + OpenSim.Framework.Console.MainLog.Instance.Error("ExpectUser() - Unknown region " + ((ulong)requestData["regionhandle"]).ToString()); + } + + return new XmlRpcResponse(); + } + + #region InterRegion Comms + private void StartRemoting() + { + TcpChannel ch = new TcpChannel(8895); + ChannelServices.RegisterChannel(ch); + + WellKnownServiceTypeEntry wellType = new WellKnownServiceTypeEntry( Type.GetType("OGS1InterRegionRemoting"), "InterRegions", WellKnownObjectMode.Singleton); + RemotingConfiguration.RegisterWellKnownServiceType(wellType); + InterRegionSingleton.Instance.OnArrival += this.IncomingArrival; + InterRegionSingleton.Instance.OnChildAgent += this.IncomingChildAgent; + } + + #region Methods called by regions in this instance + public bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectUser(regionHandle, agentData); + return true; + } + //TODO need to see if we know about where this region is and use .net remoting + // to inform it. + return false; + } + + public bool ExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); + return true; + } + //TODO need to see if we know about where this region is and use .net remoting + // to inform it. + return false; + } + #endregion + + #region Methods triggered by calls from external instances + public bool IncomingChildAgent(ulong regionHandle, AgentCircuitData agentData) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectUser(regionHandle, agentData); + return true; + } + return false; + } + + public bool IncomingArrival(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); + return true; + } + return false; + } + #endregion + #endregion + } +} diff --git a/OpenSim/Framework/Communications.OGS1/OGSInterSimComms.cs b/OpenSim/Framework/Communications.OGS1/OGSInterSimComms.cs new file mode 100644 index 0000000..8ba257e --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/OGSInterSimComms.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; +using OpenSim.Framework.Communications; +namespace OpenSim.Framework.Communications.OGS1 +{ + public delegate bool InformRegionChild(ulong regionHandle, AgentCircuitData agentData); + public delegate bool ExpectArrival(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position); + + public sealed class InterRegionSingleton + { + static readonly InterRegionSingleton instance = new InterRegionSingleton(); + + public event InformRegionChild OnChildAgent; + public event ExpectArrival OnArrival; + + static InterRegionSingleton() + { + } + + InterRegionSingleton() + { + } + + public static InterRegionSingleton Instance + { + get + { + return instance; + } + } + + public bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData) + { + if (OnChildAgent != null) + { + return OnChildAgent(regionHandle, agentData); + } + return false; + } + + public bool ExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (OnArrival != null) + { + return OnArrival(regionHandle, agentID, position); + } + return false; + } + } + + public class OGS1InterRegionRemoting : MarshalByRefObject + { + + public OGS1InterRegionRemoting() + { + } + + public bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData) + { + return InterRegionSingleton.Instance.InformRegionOfChildAgent(regionHandle, agentData); + } + + public bool ExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + return InterRegionSingleton.Instance.ExpectAvatarCrossing(regionHandle, agentID, position); + } + } +} diff --git a/OpenSim/Framework/Communications.OGS1/OGSUserServices.cs b/OpenSim/Framework/Communications.OGS1/OGSUserServices.cs new file mode 100644 index 0000000..ff5fbbb --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/OGSUserServices.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Data; +using libsecondlife; + +namespace OpenSim.Framework.Communications.OGS1 +{ + public class OGSUserServices :IUserServices + { + public UserProfileData GetUserProfile(string firstName, string lastName) + { + return null; + } + public UserProfileData GetUserProfile(string name) + { + return null; + } + public UserProfileData GetUserProfile(LLUUID avatarID) + { + return null; + } + } +} diff --git a/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj b/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj new file mode 100644 index 0000000..3985ee5 --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj @@ -0,0 +1,142 @@ + + + Local + 8.0.50727 + 2.0 + {6109024D-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Communications.OGS1 + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Communications.OGS1 + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Runtime.Remoting.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications + {CB52B7E7-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Servers + {2CC71860-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj.user b/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/OpenSim.Framework.Communications.OGS1.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Communications.OGS1/Properties/AssemblyInfo.cs b/OpenSim/Framework/Communications.OGS1/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0c6f965 --- /dev/null +++ b/OpenSim/Framework/Communications.OGS1/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Communications.OGS1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Communications.OGS1")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a8b2b39b-c83b-41e2-b0b5-7ccfc1fddae7")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Communications/CommunicationsManager.cs b/OpenSim/Framework/Communications/CommunicationsManager.cs new file mode 100644 index 0000000..74d12d2 --- /dev/null +++ b/OpenSim/Framework/Communications/CommunicationsManager.cs @@ -0,0 +1,51 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using libsecondlife; + +namespace OpenSim.Framework.Communications +{ + + public class CommunicationsManager + { + public IUserServices UserServer; + public IGridServices GridServer; + public IInterRegionCommunications InterRegion; + + public CommunicationsManager(NetworkServersInfo serversInfo) + { + + } + } +} diff --git a/OpenSim/Framework/Communications/IGridServices.cs b/OpenSim/Framework/Communications/IGridServices.cs new file mode 100644 index 0000000..a4812fb --- /dev/null +++ b/OpenSim/Framework/Communications/IGridServices.cs @@ -0,0 +1,51 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; +using OpenSim.Framework; + +namespace OpenSim.Framework.Communications +{ + public class GridInfo + { + public string GridServerURI = "http://grid.deepgrid.com:8001/"; // Temporarily hardcoded. + public string GridServerSendKey = "badger"; + public string GridServerRecvKey = "badger"; + } + + public interface IGridServices + { + RegionCommsListener RegisterRegion(RegionInfo regionInfo, GridInfo gridInfo); + List RequestNeighbours(RegionInfo regionInfo); + RegionInfo RequestNeighbourInfo(ulong regionHandle); + List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY); + } +} diff --git a/OpenSim/Framework/Communications/IInterRegionCommunications.cs b/OpenSim/Framework/Communications/IInterRegionCommunications.cs new file mode 100644 index 0000000..7b0d340 --- /dev/null +++ b/OpenSim/Framework/Communications/IInterRegionCommunications.cs @@ -0,0 +1,41 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; +using OpenSim.Framework; + +namespace OpenSim.Framework.Communications +{ + public interface IInterRegionCommunications + { + bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData); + bool ExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position); + } +} diff --git a/OpenSim/Framework/Communications/IUserServices.cs b/OpenSim/Framework/Communications/IUserServices.cs new file mode 100644 index 0000000..6790651 --- /dev/null +++ b/OpenSim/Framework/Communications/IUserServices.cs @@ -0,0 +1,44 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +using OpenSim.Framework.Data; + +namespace OpenSim.Framework.Communications +{ + public interface IUserServices + { + UserProfileData GetUserProfile(string firstName, string lastName); + UserProfileData GetUserProfile(string name); + UserProfileData GetUserProfile(LLUUID avatarID); + + } +} diff --git a/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj b/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj new file mode 100644 index 0000000..31ab172 --- /dev/null +++ b/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {CB52B7E7-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Communications + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Communications + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj.user b/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Communications/OpenSim.Framework.Communications.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs b/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..83e7dd4 --- /dev/null +++ b/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs @@ -0,0 +1,62 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Communications")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Communications")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("13e7c396-78a9-4a5c-baf2-6f980ea75d95")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Console/AssemblyInfo.cs b/OpenSim/Framework/Console/AssemblyInfo.cs new file mode 100644 index 0000000..8f715d2 --- /dev/null +++ b/OpenSim/Framework/Console/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("ServerConsole")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ServerConsole")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Framework/Console/ConsoleCallbacksBase.cs b/OpenSim/Framework/Console/ConsoleCallbacksBase.cs new file mode 100644 index 0000000..e3847be --- /dev/null +++ b/OpenSim/Framework/Console/ConsoleCallbacksBase.cs @@ -0,0 +1,39 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Console +{ + public interface conscmd_callback + { + void RunCmd(string cmd, string[] cmdparams); + void Show(string ShowWhat); + } +} diff --git a/OpenSim/Framework/Console/LogBase.cs b/OpenSim/Framework/Console/LogBase.cs new file mode 100644 index 0000000..1a92d8e --- /dev/null +++ b/OpenSim/Framework/Console/LogBase.cs @@ -0,0 +1,238 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.IO; + +namespace OpenSim.Framework.Console +{ + public enum LogPriority : int + { + CRITICAL, + HIGH, + MEDIUM, + NORMAL, + LOW, + VERBOSE, + EXTRAVERBOSE + } + + public class LogBase + { + StreamWriter Log; + public conscmd_callback cmdparser; + public string componentname; + private bool m_silent; + + public LogBase(string LogFile, string componentname, conscmd_callback cmdparser, bool silent ) + { + this.componentname = componentname; + this.cmdparser = cmdparser; + this.m_silent = silent; + System.Console.WriteLine("ServerConsole.cs - creating new local console"); + + if( String.IsNullOrEmpty( LogFile ) ) + { + LogFile = componentname + ".log"; + } + + System.Console.WriteLine("Logs will be saved to current directory in " + LogFile); + Log = File.AppendText(LogFile); + Log.WriteLine("========================================================================"); + Log.WriteLine(componentname + " Started at " + DateTime.Now.ToString()); + } + + public void Close() + { + Log.WriteLine("Shutdown at " + DateTime.Now.ToString()); + Log.Close(); + } + + public void Write(string format, params object[] args) + { + Notice(format,args); + return; + } + + public void WriteLine(LogPriority importance, string format, params object[] args) + { + Log.WriteLine(format, args); + Log.Flush(); + if (!m_silent) + { + System.Console.WriteLine(format, args); + } + return; + } + + public void Warn(string format, params object[] args) + { + WriteNewLine(ConsoleColor.Yellow, format, args); + return; + } + + public void Notice(string format, params object[] args) + { + WriteNewLine(ConsoleColor.White, format, args); + return; + } + + public void Error(string format, params object[] args) + { + WriteNewLine(ConsoleColor.Red, format, args); + return; + } + + public void Verbose(string format, params object[] args) + { + WriteNewLine(ConsoleColor.Gray, format, args); + return; + } + + public void Status(string format, params object[] args) + { + WriteNewLine(ConsoleColor.Blue, format, args); + return; + } + + private void WriteNewLine(System.ConsoleColor color, string format, params object[] args) + { + Log.WriteLine(format, args); + Log.Flush(); + if (!m_silent) + { + try + { + System.Console.ForegroundColor = color; + System.Console.WriteLine(format, args); + System.Console.ResetColor(); + } + catch (System.ArgumentNullException) + { + // Some older systems dont support coloured text. + System.Console.WriteLine(format, args); + } + } + return; + } + + public string ReadLine() + { + string TempStr = System.Console.ReadLine(); + Log.WriteLine(TempStr); + return TempStr; + } + + public int Read() + { + int TempInt = System.Console.Read(); + Log.Write((char)TempInt); + return TempInt; + } + + // Displays a prompt and waits for the user to enter a string, then returns that string + // Done with no echo and suitable for passwords + public string PasswdPrompt(string prompt) + { + // FIXME: Needs to be better abstracted + Log.WriteLine(prompt); + this.Write(prompt); + ConsoleColor oldfg = System.Console.ForegroundColor; + System.Console.ForegroundColor = System.Console.BackgroundColor; + string temp = System.Console.ReadLine(); + System.Console.ForegroundColor = oldfg; + return temp; + } + + // Displays a command prompt and waits for the user to enter a string, then returns that string + public string CmdPrompt(string prompt) + { + this.Write(String.Format("{0}: ", prompt)); + return this.ReadLine(); + } + + // Displays a command prompt and returns a default value if the user simply presses enter + public string CmdPrompt(string prompt, string defaultresponse) + { + string temp = CmdPrompt(String.Format( "{0} [{1}]", prompt, defaultresponse )); + if (temp == "") + { + return defaultresponse; + } + else + { + return temp; + } + } + + // Displays a command prompt and returns a default value, user may only enter 1 of 2 options + public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB) + { + bool itisdone = false; + string temp = CmdPrompt(prompt, defaultresponse); + while (itisdone == false) + { + if ((temp == OptionA) || (temp == OptionB)) + { + itisdone = true; + } + else + { + Notice("Valid options are " + OptionA + " or " + OptionB); + temp = CmdPrompt(prompt, defaultresponse); + } + } + return temp; + } + + // Runs a command with a number of parameters + public Object RunCmd(string Cmd, string[] cmdparams) + { + cmdparser.RunCmd(Cmd, cmdparams); + return null; + } + + // Shows data about something + public void ShowCommands(string ShowWhat) + { + cmdparser.Show(ShowWhat); + } + + public void MainLogPrompt() + { + string[] tempstrarray; + string tempstr = this.CmdPrompt(this.componentname + "# "); + tempstrarray = tempstr.Split(' '); + string cmd = tempstrarray[0]; + Array.Reverse(tempstrarray); + Array.Resize(ref tempstrarray, tempstrarray.Length - 1); + Array.Reverse(tempstrarray); + string[] cmdparams = (string[])tempstrarray; + RunCmd(cmd, cmdparams); + } + } +} diff --git a/OpenSim/Framework/Console/MainLog.cs b/OpenSim/Framework/Console/MainLog.cs new file mode 100644 index 0000000..d7f945e --- /dev/null +++ b/OpenSim/Framework/Console/MainLog.cs @@ -0,0 +1,49 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; + +namespace OpenSim.Framework.Console +{ + public class MainLog { + + private static LogBase instance; + + public static LogBase Instance + { + get + { + return instance; + } + set + { + instance = value; + } + } + } + +} diff --git a/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj new file mode 100644 index 0000000..f3dcec5 --- /dev/null +++ b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj @@ -0,0 +1,89 @@ + + + Local + 8.0.50727 + 2.0 + {A7CD0630-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Console + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Console + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + + + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj.user b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data.DB4o/DB4oGridData.cs b/OpenSim/Framework/Data.DB4o/DB4oGridData.cs new file mode 100644 index 0000000..dc8488e --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/DB4oGridData.cs @@ -0,0 +1,166 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Data; +using libsecondlife; + + +namespace OpenSim.Framework.Data.DB4o +{ + /// + /// A grid server storage mechanism employing the DB4o database system + /// + class DB4oGridData : IGridData + { + /// + /// The database manager object + /// + DB4oGridManager manager; + + /// + /// Called when the plugin is first loaded (as constructors are not called) + /// + public void Initialise() { + manager = new DB4oGridManager("gridserver.yap"); + } + + /// + /// Returns a list of regions within the specified ranges + /// + /// minimum X coordinate + /// minimum Y coordinate + /// maximum X coordinate + /// maximum Y coordinate + /// An array of region profiles + public SimProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) + { + return null; + } + + /// + /// Returns a region located at the specified regionHandle (warning multiple regions may occupy the one spot, first found is returned) + /// + /// The handle to search for + /// A region profile + public SimProfileData GetProfileByHandle(ulong handle) { + lock (manager.simProfiles) + { + foreach (LLUUID UUID in manager.simProfiles.Keys) + { + if (manager.simProfiles[UUID].regionHandle == handle) + { + return manager.simProfiles[UUID]; + } + } + } + throw new Exception("Unable to find profile with handle (" + handle.ToString() + ")"); + } + + /// + /// Returns a specific region + /// + /// The region ID code + /// A region profile + public SimProfileData GetProfileByLLUUID(LLUUID uuid) + { + lock (manager.simProfiles) + { + if (manager.simProfiles.ContainsKey(uuid)) + return manager.simProfiles[uuid]; + } + throw new Exception("Unable to find profile with UUID (" + uuid.ToStringHyphenated() + ")"); + } + + /// + /// Adds a new specified region to the database + /// + /// The profile to add + /// A dataresponse enum indicating success + public DataResponse AddProfile(SimProfileData profile) + { + lock (manager.simProfiles) + { + if (manager.AddRow(profile)) + { + return DataResponse.RESPONSE_OK; + } + else + { + return DataResponse.RESPONSE_ERROR; + } + } + } + + /// + /// Authenticates a new region using the shared secrets. NOT SECURE. + /// + /// The UUID the region is authenticating with + /// The location the region is logging into (unused in Db4o) + /// The shared secret + /// Authenticated? + public bool AuthenticateSim(LLUUID uuid, ulong handle, string key) { + if (manager.simProfiles[uuid].regionRecvKey == key) + return true; + return false; + } + + /// + /// Shuts down the database + /// + public void Close() + { + manager = null; + } + + /// + /// Returns the providers name + /// + /// The name of the storage system + public string getName() + { + return "DB4o Grid Provider"; + } + + /// + /// Returns the providers version + /// + /// The version of the storage system + public string getVersion() + { + return "0.1"; + } + + public ReservationData GetReservationAtPoint(uint x, uint y) + { + return null; + } + } +} diff --git a/OpenSim/Framework/Data.DB4o/DB4oManager.cs b/OpenSim/Framework/Data.DB4o/DB4oManager.cs new file mode 100644 index 0000000..3870a8c --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/DB4oManager.cs @@ -0,0 +1,165 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using Db4objects.Db4o; +using OpenSim.Framework.Data; +using libsecondlife; + +namespace OpenSim.Framework.Data.DB4o +{ + /// + /// A Database manager for Db4o + /// + class DB4oGridManager + { + /// + /// A list of the current regions connected (in-memory cache) + /// + public Dictionary simProfiles = new Dictionary(); + /// + /// Database File Name + /// + string dbfl; + + /// + /// Creates a new grid storage manager + /// + /// Filename to the database file + public DB4oGridManager(string db4odb) + { + dbfl = db4odb; + IObjectContainer database; + database = Db4oFactory.OpenFile(dbfl); + IObjectSet result = database.Get(typeof(SimProfileData)); + // Loads the file into the in-memory cache + foreach(SimProfileData row in result) { + simProfiles.Add(row.UUID, row); + } + database.Close(); + } + + /// + /// Adds a new profile to the database (Warning: Probably slow.) + /// + /// The profile to add + /// Successful? + public bool AddRow(SimProfileData row) + { + if (simProfiles.ContainsKey(row.UUID)) + { + simProfiles[row.UUID] = row; + } + else + { + simProfiles.Add(row.UUID, row); + } + + try + { + IObjectContainer database; + database = Db4oFactory.OpenFile(dbfl); + database.Set(row); + database.Close(); + return true; + } + catch (Exception e) + { + return false; + } + } + + + } + + /// + /// A manager for the DB4o database (user profiles) + /// + class DB4oUserManager + { + /// + /// A list of the user profiles (in memory cache) + /// + public Dictionary userProfiles = new Dictionary(); + /// + /// Database filename + /// + string dbfl; + + /// + /// Initialises a new DB manager + /// + /// The filename to the database + public DB4oUserManager(string db4odb) + { + dbfl = db4odb; + IObjectContainer database; + database = Db4oFactory.OpenFile(dbfl); + // Load to cache + IObjectSet result = database.Get(typeof(UserProfileData)); + foreach (UserProfileData row in result) + { + userProfiles.Add(row.UUID, row); + } + database.Close(); + } + + /// + /// Adds a new profile to the database (Warning: Probably slow.) + /// + /// The profile to add + /// Successful? + public bool AddRow(UserProfileData row) + { + if (userProfiles.ContainsKey(row.UUID)) + { + userProfiles[row.UUID] = row; + } + else + { + userProfiles.Add(row.UUID, row); + } + + try + { + IObjectContainer database; + database = Db4oFactory.OpenFile(dbfl); + database.Set(row); + database.Close(); + return true; + } + catch (Exception e) + { + return false; + } + } + + + } +} diff --git a/OpenSim/Framework/Data.DB4o/DB4oUserData.cs b/OpenSim/Framework/Data.DB4o/DB4oUserData.cs new file mode 100644 index 0000000..8caa75d --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/DB4oUserData.cs @@ -0,0 +1,205 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Data; +using libsecondlife; + +namespace OpenSim.Framework.Data.DB4o +{ + /// + /// A User storage interface for the DB4o database system + /// + public class DB4oUserData : IUserData + { + /// + /// The database manager + /// + DB4oUserManager manager; + + /// + /// Artificial constructor called upon plugin load + /// + public void Initialise() + { + manager = new DB4oUserManager("userprofiles.yap"); + } + + /// + /// Loads a specified user profile from a UUID + /// + /// The users UUID + /// A user profile + public UserProfileData getUserByUUID(LLUUID uuid) + { + if(manager.userProfiles.ContainsKey(uuid)) + return manager.userProfiles[uuid]; + return null; + } + + /// + /// Returns a user by searching for its name + /// + /// The users account name + /// A matching users profile + public UserProfileData getUserByName(string name) + { + return getUserByName(name.Split(' ')[0], name.Split(' ')[1]); + } + + /// + /// Returns a user by searching for its name + /// + /// The first part of the users account name + /// The second part of the users account name + /// A matching users profile + public UserProfileData getUserByName(string fname, string lname) + { + foreach (UserProfileData profile in manager.userProfiles.Values) + { + if (profile.username == fname && profile.surname == lname) + return profile; + } + return null; + } + + /// + /// Returns a user by UUID direct + /// + /// The users account ID + /// A matching users profile + public UserAgentData getAgentByUUID(LLUUID uuid) + { + try + { + return getUserByUUID(uuid).currentAgent; + } + catch (Exception e) + { + return null; + } + } + + /// + /// Returns a session by account name + /// + /// The account name + /// The users session agent + public UserAgentData getAgentByName(string name) + { + return getAgentByName(name.Split(' ')[0], name.Split(' ')[1]); + } + + /// + /// Returns a session by account name + /// + /// The first part of the users account name + /// The second part of the users account name + /// A user agent + public UserAgentData getAgentByName(string fname, string lname) + { + try + { + return getUserByName(fname,lname).currentAgent; + } + catch (Exception e) + { + return null; + } + } + + /// + /// Creates a new user profile + /// + /// The profile to add to the database + public void addNewUserProfile(UserProfileData user) + { + try + { + manager.AddRow(user); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } + + /// + /// Creates a new user agent + /// + /// The agent to add to the database + public void addNewUserAgent(UserAgentData agent) + { + // Do nothing. yet. + } + + /// + /// Transfers money between two user accounts + /// + /// Starting account + /// End account + /// The amount to move + /// Success? + public bool moneyTransferRequest(LLUUID from, LLUUID to, uint amount) + { + return true; + } + + /// + /// Transfers inventory between two accounts + /// + /// Move to inventory server + /// Senders account + /// Recievers account + /// Inventory item + /// Success? + public bool inventoryTransferRequest(LLUUID from, LLUUID to, LLUUID item) + { + return true; + } + + /// + /// Returns the name of the storage provider + /// + /// Storage provider name + public string getName() + { + return "DB4o Userdata"; + } + + /// + /// Returns the version of the storage provider + /// + /// Storage provider version + public string getVersion() + { + return "0.1"; + } + } +} diff --git a/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj b/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj new file mode 100644 index 0000000..b09cecf --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj @@ -0,0 +1,111 @@ + + + Local + 8.0.50727 + 2.0 + {FD2D303D-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Data.DB4o + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Data.DB4o + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj.user b/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/OpenSim.Framework.Data.DB4o.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..dc4a9a1 --- /dev/null +++ b/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Data.DB4o")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Data.DB4o")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("57991e15-79da-41b7-aa06-2e6b49165a63")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs b/OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs new file mode 100644 index 0000000..1dac4bd --- /dev/null +++ b/OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs @@ -0,0 +1,192 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.MSSQL +{ + /// + /// A grid data interface for Microsoft SQL Server + /// + public class SqlGridData : IGridData + { + /// + /// Database manager + /// + private MSSqlManager database; + + /// + /// Initialises the Grid Interface + /// + public void Initialise() + { + database = new MSSqlManager("localhost", "db", "user", "password", "false"); + } + + /// + /// Shuts down the grid interface + /// + public void Close() + { + database.Close(); + } + + /// + /// Returns the storage system name + /// + /// A string containing the storage system name + public string getName() + { + return "Sql OpenGridData"; + } + + /// + /// Returns the storage system version + /// + /// A string containing the storage system version + public string getVersion() + { + return "0.1"; + } + + /// + /// Returns a list of regions within the specified ranges + /// + /// minimum X coordinate + /// minimum Y coordinate + /// maximum X coordinate + /// maximum Y coordinate + /// An array of region profiles + public SimProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) + { + return null; + } + + /// + /// Returns a sim profile from it's location + /// + /// Region location handle + /// Sim profile + public SimProfileData GetProfileByHandle(ulong handle) + { + Dictionary param = new Dictionary(); + param["handle"] = handle.ToString(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.getRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + + /// + /// Returns a sim profile from it's UUID + /// + /// The region UUID + /// The sim profile + public SimProfileData GetProfileByLLUUID(libsecondlife.LLUUID uuid) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.getRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + + /// + /// Adds a new specified region to the database + /// + /// The profile to add + /// A dataresponse enum indicating success + public DataResponse AddProfile(SimProfileData profile) + { + if (database.insertRow(profile)) + { + return DataResponse.RESPONSE_OK; + } + else + { + return DataResponse.RESPONSE_ERROR; + } + } + + /// + /// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret. + /// + /// The UUID of the challenger + /// The attempted regionHandle of the challenger + /// The secret + /// Whether the secret and regionhandle match the database entry for UUID + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authkey) + { + bool throwHissyFit = false; // Should be true by 1.0 + + if (throwHissyFit) + throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); + + SimProfileData data = GetProfileByLLUUID(uuid); + + return (handle == data.regionHandle && authkey == data.regionSecret); + } + + /// + /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region + /// + /// This requires a security audit. + /// + /// + /// + /// + /// + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authhash, string challenge) + { + System.Security.Cryptography.SHA512Managed HashProvider = new System.Security.Cryptography.SHA512Managed(); + System.Text.ASCIIEncoding TextProvider = new ASCIIEncoding(); + + byte[] stream = TextProvider.GetBytes(uuid.ToStringHyphenated() + ":" + handle.ToString() + ":" + challenge); + byte[] hash = HashProvider.ComputeHash(stream); + return false; + } + public ReservationData GetReservationAtPoint(uint x, uint y) + { + return null; + } + } + +} diff --git a/OpenSim/Framework/Data.MSSQL/MSSQLManager.cs b/OpenSim/Framework/Data.MSSQL/MSSQLManager.cs new file mode 100644 index 0000000..475a3e7 --- /dev/null +++ b/OpenSim/Framework/Data.MSSQL/MSSQLManager.cs @@ -0,0 +1,214 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; + +using System.Data.SqlClient; + +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.MSSQL +{ + /// + /// A management class for the MS SQL Storage Engine + /// + class MSSqlManager + { + /// + /// The database connection object + /// + IDbConnection dbcon; + + /// + /// Initialises and creates a new Sql connection and maintains it. + /// + /// The Sql server being connected to + /// The name of the Sql database being used + /// The username logging into the database + /// The password for the user logging in + /// Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'. + public MSSqlManager(string hostname, string database, string username, string password, string cpooling) + { + try + { + string connectionString = "Server=" + hostname + ";Database=" + database + ";User ID=" + username + ";Password=" + password + ";Pooling=" + cpooling + ";"; + dbcon = new SqlConnection(connectionString); + + dbcon.Open(); + } + catch (Exception e) + { + throw new Exception("Error initialising Sql Database: " + e.ToString()); + } + } + + /// + /// Shuts down the database connection + /// + public void Close() + { + dbcon.Close(); + dbcon = null; + } + + /// + /// Runs a query with protection against SQL Injection by using parameterised input. + /// + /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y + /// The parameters - index so that @y is indexed as 'y' + /// A Sql DB Command + public IDbCommand Query(string sql, Dictionary parameters) + { + SqlCommand dbcommand = (SqlCommand)dbcon.CreateCommand(); + dbcommand.CommandText = sql; + foreach (KeyValuePair param in parameters) + { + dbcommand.Parameters.AddWithValue(param.Key, param.Value); + } + + return (IDbCommand)dbcommand; + } + + /// + /// Runs a database reader object and returns a region row + /// + /// An active database reader + /// A region row + public SimProfileData getRow(IDataReader reader) + { + SimProfileData regionprofile = new SimProfileData(); + + if (reader.Read()) + { + // Region Main + regionprofile.regionHandle = (ulong)reader["regionHandle"]; + regionprofile.regionName = (string)reader["regionName"]; + regionprofile.UUID = new libsecondlife.LLUUID((string)reader["uuid"]); + + // Secrets + regionprofile.regionRecvKey = (string)reader["regionRecvKey"]; + regionprofile.regionSecret = (string)reader["regionSecret"]; + regionprofile.regionSendKey = (string)reader["regionSendKey"]; + + // Region Server + regionprofile.regionDataURI = (string)reader["regionDataURI"]; + regionprofile.regionOnline = false; // Needs to be pinged before this can be set. + regionprofile.serverIP = (string)reader["serverIP"]; + regionprofile.serverPort = (uint)reader["serverPort"]; + regionprofile.serverURI = (string)reader["serverURI"]; + + // Location + regionprofile.regionLocX = (uint)((int)reader["locX"]); + regionprofile.regionLocY = (uint)((int)reader["locY"]); + regionprofile.regionLocZ = (uint)((int)reader["locZ"]); + + // Neighbours - 0 = No Override + regionprofile.regionEastOverrideHandle = (ulong)reader["eastOverrideHandle"]; + regionprofile.regionWestOverrideHandle = (ulong)reader["westOverrideHandle"]; + regionprofile.regionSouthOverrideHandle = (ulong)reader["southOverrideHandle"]; + regionprofile.regionNorthOverrideHandle = (ulong)reader["northOverrideHandle"]; + + // Assets + regionprofile.regionAssetURI = (string)reader["regionAssetURI"]; + regionprofile.regionAssetRecvKey = (string)reader["regionAssetRecvKey"]; + regionprofile.regionAssetSendKey = (string)reader["regionAssetSendKey"]; + + // Userserver + regionprofile.regionUserURI = (string)reader["regionUserURI"]; + regionprofile.regionUserRecvKey = (string)reader["regionUserRecvKey"]; + regionprofile.regionUserSendKey = (string)reader["regionUserSendKey"]; + } + else + { + throw new Exception("No rows to return"); + } + return regionprofile; + } + + /// + /// Creates a new region in the database + /// + /// The region profile to insert + /// Successful? + public bool insertRow(SimProfileData profile) + { + string sql = "REPLACE INTO regions VALUES (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; + sql += "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; + sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey) VALUES "; + + sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; + sql += "@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; + sql += "@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey);"; + + Dictionary parameters = new Dictionary(); + + parameters["regionHandle"] = profile.regionHandle.ToString(); + parameters["regionName"] = profile.regionName; + parameters["uuid"] = profile.UUID.ToString(); + parameters["regionRecvKey"] = profile.regionRecvKey; + parameters["regionSendKey"] = profile.regionSendKey; + parameters["regionDataURI"] = profile.regionDataURI; + parameters["serverIP"] = profile.serverIP; + parameters["serverPort"] = profile.serverPort.ToString(); + parameters["serverURI"] = profile.serverURI; + parameters["locX"] = profile.regionLocX.ToString(); + parameters["locY"] = profile.regionLocY.ToString(); + parameters["locZ"] = profile.regionLocZ.ToString(); + parameters["eastOverrideHandle"] = profile.regionEastOverrideHandle.ToString(); + parameters["westOverrideHandle"] = profile.regionWestOverrideHandle.ToString(); + parameters["northOverrideHandle"] = profile.regionNorthOverrideHandle.ToString(); + parameters["southOverrideHandle"] = profile.regionSouthOverrideHandle.ToString(); + parameters["regionAssetURI"] = profile.regionAssetURI; + parameters["regionAssetRecvKey"] = profile.regionAssetRecvKey; + parameters["regionAssetSendKey"] = profile.regionAssetSendKey; + parameters["regionUserURI"] = profile.regionUserURI; + parameters["regionUserRecvKey"] = profile.regionUserRecvKey; + parameters["regionUserSendKey"] = profile.regionUserSendKey; + + bool returnval = false; + + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + return false; + } + + return returnval; + } + } +} diff --git a/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj b/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj new file mode 100644 index 0000000..4c41a4f --- /dev/null +++ b/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj @@ -0,0 +1,104 @@ + + + Local + 8.0.50727 + 2.0 + {17F7F694-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Data.MSSQL + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Data.MSSQL + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj.user b/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Data.MSSQL/OpenSim.Framework.Data.MSSQL.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bbe3cdf --- /dev/null +++ b/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Data.MSSQL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Data.MSSQL")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0e1c1ca4-2cf2-4315-b0e7-432c02feea8a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Data.MySQL/MySQLGridData.cs b/OpenSim/Framework/Data.MySQL/MySQLGridData.cs new file mode 100644 index 0000000..4d6cf63 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/MySQLGridData.cs @@ -0,0 +1,285 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.MySQL +{ + /// + /// A MySQL Interface for the Grid Server + /// + public class MySQLGridData : IGridData + { + /// + /// MySQL Database Manager + /// + private MySQLManager database; + + /// + /// Initialises the Grid Interface + /// + public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); + string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); + string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); + string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); + string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); + + database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); + } + + /// + /// Shuts down the grid interface + /// + public void Close() + { + database.Close(); + } + + /// + /// Returns the plugin name + /// + /// Plugin name + public string getName() + { + return "MySql OpenGridData"; + } + + /// + /// Returns the plugin version + /// + /// Plugin version + public string getVersion() + { + return "0.1"; + } + + /// + /// Returns all the specified region profiles within coordates -- coordinates are inclusive + /// + /// Minimum X coordinate + /// Minimum Y coordinate + /// Maximum X coordinate + /// Maximum Y coordinate + /// + public SimProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?xmin"] = xmin.ToString(); + param["?ymin"] = ymin.ToString(); + param["?xmax"] = xmax.ToString(); + param["?ymax"] = ymax.ToString(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row; + + List rows = new List(); + + while ((row = database.readSimRow(reader)) != null) + { + rows.Add(row); + } + reader.Close(); + result.Dispose(); + + return rows.ToArray(); + + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a sim profile from it's location + /// + /// Region location handle + /// Sim profile + public SimProfileData GetProfileByHandle(ulong handle) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?handle"] = handle.ToString(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.readSimRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a sim profile from it's UUID + /// + /// The region UUID + /// The sim profile + public SimProfileData GetProfileByLLUUID(libsecondlife.LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = uuid.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.readSimRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Adds a new profile to the database + /// + /// The profile to add + /// Successful? + public DataResponse AddProfile(SimProfileData profile) + { + lock (database) + { + if (database.insertRegion(profile)) + { + return DataResponse.RESPONSE_OK; + } + else + { + return DataResponse.RESPONSE_ERROR; + } + } + } + + /// + /// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret. + /// + /// The UUID of the challenger + /// The attempted regionHandle of the challenger + /// The secret + /// Whether the secret and regionhandle match the database entry for UUID + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authkey) + { + bool throwHissyFit = false; // Should be true by 1.0 + + if (throwHissyFit) + throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); + + SimProfileData data = GetProfileByLLUUID(uuid); + + return (handle == data.regionHandle && authkey == data.regionSecret); + } + + /// + /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region + /// + /// This requires a security audit. + /// + /// + /// + /// + /// + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authhash, string challenge) + { + System.Security.Cryptography.SHA512Managed HashProvider = new System.Security.Cryptography.SHA512Managed(); + System.Text.ASCIIEncoding TextProvider = new ASCIIEncoding(); + + byte[] stream = TextProvider.GetBytes(uuid.ToStringHyphenated() + ":" + handle.ToString() + ":" + challenge); + byte[] hash = HashProvider.ComputeHash(stream); + + return false; + } + + public ReservationData GetReservationAtPoint(uint x, uint y) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?x"] = x.ToString(); + param["?y"] = y.ToString(); + System.Data.IDbCommand result = database.Query("SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + ReservationData row = database.readReservationRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + } + + +} diff --git a/OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs b/OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs new file mode 100644 index 0000000..fb429e4 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs @@ -0,0 +1,309 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenGrid.Framework.Data.MySQL +{ + /// + /// A MySQL interface for the inventory server + /// + class MySQLInventoryData : IInventoryData + { + /// + /// The database manager + /// + public MySQLManager database; + + /// + /// Loads and initialises this database plugin + /// + public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); + string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); + string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); + string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); + string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); + + database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); + } + + /// + /// The name of this DB provider + /// + /// Name of DB provider + public string getName() + { + return "MySQL Inventory Data Interface"; + } + + /// + /// Closes this DB provider + /// + public void Close() + { + // Do nothing. + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the DB provider + public string getVersion() + { + return "0.1"; + } + + /// + /// Returns a list of items in a specified folder + /// + /// The folder to search + /// A list containing inventory items + public List getInventoryInFolder(LLUUID folderID) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = folderID.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + List items = database.readInventoryItems(reader); + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a list of the root folders within a users inventory + /// + /// The user whos inventory is to be searched + /// A list of folder objects + public List getUserRootFolders(LLUUID user) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = user.ToStringHyphenated(); + param["?zero"] = LLUUID.Zero.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + List items = database.readInventoryFolders(reader); + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a list of folders in a users inventory contained within the specified folder + /// + /// The folder to search + /// A list of inventory folders + public List getInventoryFolders(LLUUID parentID) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = parentID.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + List items = database.readInventoryFolders(reader); + + reader.Close(); + result.Dispose(); + + return items; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a specified inventory item + /// + /// The item to return + /// An inventory item + public InventoryItemBase getInventoryItem(LLUUID item) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = item.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + List items = database.readInventoryItems(reader); + + reader.Close(); + result.Dispose(); + + if (items.Count > 0) + { + return items[0]; + } + else + { + return null; + } + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a specified inventory folder + /// + /// The folder to return + /// A folder class + public InventoryFolderBase getInventoryFolder(LLUUID folder) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = folder.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + List items = database.readInventoryFolders(reader); + + reader.Close(); + result.Dispose(); + + if (items.Count > 0) + { + return items[0]; + } + else + { + return null; + } + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Adds a specified item to the database + /// + /// The inventory item + public void addInventoryItem(InventoryItemBase item) + { + lock (database) + { + database.insertItem(item); + } + } + + /// + /// Updates the specified inventory item + /// + /// Inventory item to update + public void updateInventoryItem(InventoryItemBase item) + { + addInventoryItem(item); + } + + /// + /// Creates a new inventory folder + /// + /// Folder to create + public void addInventoryFolder(InventoryFolderBase folder) + { + lock (database) + { + database.insertFolder(folder); + } + } + + /// + /// Updates an inventory folder + /// + /// Folder to update + public void updateInventoryFolder(InventoryFolderBase folder) + { + addInventoryFolder(folder); + } + } +} diff --git a/OpenSim/Framework/Data.MySQL/MySQLLogData.cs b/OpenSim/Framework/Data.MySQL/MySQLLogData.cs new file mode 100644 index 0000000..c88b39f --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/MySQLLogData.cs @@ -0,0 +1,107 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenGrid.Framework.Data.MySQL +{ + /// + /// An interface to the log database for MySQL + /// + class MySQLLogData : ILogData + { + /// + /// The database manager + /// + public MySQLManager database; + + /// + /// Artificial constructor called when the plugin is loaded + /// + public void Initialise() + { + IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); + string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); + string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); + string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); + string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); + + database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); + } + + /// + /// Saves a log item to the database + /// + /// The daemon triggering the event + /// The target of the action (region / agent UUID, etc) + /// The method call where the problem occured + /// The arguments passed to the method + /// How critical is this? + /// The message to log + public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, string logMessage) + { + try + { + database.insertLogRow(serverDaemon, target, methodCall, arguments, priority, logMessage); + } + catch (Exception e) + { + database.Reconnect(); + } + } + + /// + /// Returns the name of this DB provider + /// + /// A string containing the DB provider name + public string getName() + { + return "MySQL Logdata Interface"; + } + + /// + /// Closes the database provider + /// + public void Close() + { + // Do nothing. + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the provider version + public string getVersion() + { + return "0.1"; + } + } +} diff --git a/OpenSim/Framework/Data.MySQL/MySQLManager.cs b/OpenSim/Framework/Data.MySQL/MySQLManager.cs new file mode 100644 index 0000000..53b3bdd --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/MySQLManager.cs @@ -0,0 +1,609 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; + +// MySQL Native +using MySql; +using MySql.Data; +using MySql.Data.Types; +using MySql.Data.MySqlClient; + +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.MySQL +{ + /// + /// A MySQL Database manager + /// + class MySQLManager + { + /// + /// The database connection object + /// + IDbConnection dbcon; + /// + /// Connection string for ADO.net + /// + string connectionString; + + /// + /// Initialises and creates a new MySQL connection and maintains it. + /// + /// The MySQL server being connected to + /// The name of the MySQL database being used + /// The username logging into the database + /// The password for the user logging in + /// Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'. + public MySQLManager(string hostname, string database, string username, string password, string cpooling, string port) + { + try + { + connectionString = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" + username + ";Password=" + password + ";Pooling=" + cpooling + ";"; + dbcon = new MySqlConnection(connectionString); + + dbcon.Open(); + + System.Console.WriteLine("MySQL connection established"); + } + catch (Exception e) + { + throw new Exception("Error initialising MySql Database: " + e.ToString()); + } + } + + /// + /// Shuts down the database connection + /// + public void Close() + { + dbcon.Close(); + dbcon = null; + } + + /// + /// Reconnects to the database + /// + public void Reconnect() + { + lock (dbcon) + { + try + { + // Close the DB connection + dbcon.Close(); + // Try reopen it + dbcon = new MySqlConnection(connectionString); + dbcon.Open(); + } + catch (Exception e) + { + Console.WriteLine("Unable to reconnect to database " + e.ToString()); + } + } + } + + /// + /// Runs a query with protection against SQL Injection by using parameterised input. + /// + /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y + /// The parameters - index so that @y is indexed as 'y' + /// A MySQL DB Command + public IDbCommand Query(string sql, Dictionary parameters) + { + try + { + MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand(); + dbcommand.CommandText = sql; + foreach (KeyValuePair param in parameters) + { + dbcommand.Parameters.Add(param.Key, param.Value); + } + + return (IDbCommand)dbcommand; + } + catch + { + lock (dbcon) + { + // Close the DB connection + try + { + dbcon.Close(); + } + catch { } + + // Try reopen it + try + { + dbcon = new MySqlConnection(connectionString); + dbcon.Open(); + } + catch (Exception e) + { + Console.WriteLine("Unable to reconnect to database " + e.ToString()); + } + + // Run the query again + try + { + MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand(); + dbcommand.CommandText = sql; + foreach (KeyValuePair param in parameters) + { + dbcommand.Parameters.Add(param.Key, param.Value); + } + + return (IDbCommand)dbcommand; + } + catch (Exception e) + { + // Return null if it fails. + Console.WriteLine("Failed during Query generation: " + e.ToString()); + return null; + } + } + } + } + + /// + /// Reads a region row from a database reader + /// + /// An active database reader + /// A region profile + public SimProfileData readSimRow(IDataReader reader) + { + SimProfileData retval = new SimProfileData(); + + if (reader.Read()) + { + // Region Main + retval.regionHandle = Convert.ToUInt64(reader["regionHandle"].ToString()); + retval.regionName = (string)reader["regionName"]; + retval.UUID = new libsecondlife.LLUUID((string)reader["uuid"]); + + // Secrets + retval.regionRecvKey = (string)reader["regionRecvKey"]; + retval.regionSecret = (string)reader["regionSecret"]; + retval.regionSendKey = (string)reader["regionSendKey"]; + + // Region Server + retval.regionDataURI = (string)reader["regionDataURI"]; + retval.regionOnline = false; // Needs to be pinged before this can be set. + retval.serverIP = (string)reader["serverIP"]; + retval.serverPort = (uint)reader["serverPort"]; + retval.serverURI = (string)reader["serverURI"]; + + // Location + retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); + retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); + retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); + + // Neighbours - 0 = No Override + retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); + retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); + retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); + retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); + + // Assets + retval.regionAssetURI = (string)reader["regionAssetURI"]; + retval.regionAssetRecvKey = (string)reader["regionAssetRecvKey"]; + retval.regionAssetSendKey = (string)reader["regionAssetSendKey"]; + + // Userserver + retval.regionUserURI = (string)reader["regionUserURI"]; + retval.regionUserRecvKey = (string)reader["regionUserRecvKey"]; + retval.regionUserSendKey = (string)reader["regionUserSendKey"]; + + // World Map Addition + string tempRegionMap = reader["regionMapTexture"].ToString(); + if (tempRegionMap != "") + { + retval.regionMapTextureID = new libsecondlife.LLUUID(tempRegionMap); + } + else + { + retval.regionMapTextureID = new libsecondlife.LLUUID(); + } + } + else + { + return null; + } + return retval; + } + + /// + /// Reads a reservation row from a database reader + /// + /// An active database reader + /// A reservation data object + public ReservationData readReservationRow(IDataReader reader) + { + ReservationData retval = new ReservationData(); + if (reader.Read()) + { + retval.gridRecvKey = (string)reader["gridRecvKey"]; + retval.gridSendKey = (string)reader["gridSendKey"]; + retval.reservationCompany = (string)reader["resCompany"]; + retval.reservationMaxX = (int)reader["resXMax"]; + retval.reservationMaxY = (int)reader["resYMax"]; + retval.reservationMinX = (int)reader["resXMin"]; + retval.reservationMinY = (int)reader["resYMin"]; + retval.reservationName = (string)reader["resName"]; + retval.status = (bool)reader["status"]; + retval.userUUID = new libsecondlife.LLUUID((string)reader["userUUID"]); + + } + else + { + return null; + } + return retval; + } + /// + /// Reads an agent row from a database reader + /// + /// An active database reader + /// A user session agent + public UserAgentData readAgentRow(IDataReader reader) + { + UserAgentData retval = new UserAgentData(); + + if (reader.Read()) + { + // Agent IDs + retval.UUID = new libsecondlife.LLUUID((string)reader["UUID"]); + retval.sessionID = new libsecondlife.LLUUID((string)reader["sessionID"]); + retval.secureSessionID = new libsecondlife.LLUUID((string)reader["secureSessionID"]); + + // Agent Who? + retval.agentIP = (string)reader["agentIP"]; + retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString()); + retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString()); + + // Login/Logout times (UNIX Epoch) + retval.loginTime = Convert.ToInt32(reader["loginTime"].ToString()); + retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); + + // Current position + retval.currentRegion = (string)reader["currentRegion"]; + retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); + libsecondlife.LLVector3.TryParse((string)reader["currentPos"], out retval.currentPos); + } + else + { + return null; + } + return retval; + } + + /// + /// Reads a user profile from an active data reader + /// + /// An active database reader + /// A user profile + public UserProfileData readUserRow(IDataReader reader) + { + UserProfileData retval = new UserProfileData(); + + if (reader.Read()) + { + retval.UUID = new libsecondlife.LLUUID((string)reader["UUID"]); + retval.username = (string)reader["username"]; + retval.surname = (string)reader["lastname"]; + + retval.passwordHash = (string)reader["passwordHash"]; + retval.passwordSalt = (string)reader["passwordSalt"]; + + retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); + retval.homeLocation = new libsecondlife.LLVector3( + Convert.ToSingle(reader["homeLocationX"].ToString()), + Convert.ToSingle(reader["homeLocationY"].ToString()), + Convert.ToSingle(reader["homeLocationZ"].ToString())); + retval.homeLookAt = new libsecondlife.LLVector3( + Convert.ToSingle(reader["homeLookAtX"].ToString()), + Convert.ToSingle(reader["homeLookAtY"].ToString()), + Convert.ToSingle(reader["homeLookAtZ"].ToString())); + + retval.created = Convert.ToInt32(reader["created"].ToString()); + retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); + + retval.userInventoryURI = (string)reader["userInventoryURI"]; + retval.userAssetURI = (string)reader["userAssetURI"]; + + retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); + retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); + + retval.profileAboutText = (string)reader["profileAboutText"]; + retval.profileFirstText = (string)reader["profileFirstText"]; + + retval.profileImage = new libsecondlife.LLUUID((string)reader["profileImage"]); + retval.profileFirstImage = new libsecondlife.LLUUID((string)reader["profileFirstImage"]); + + } + else + { + return null; + } + return retval; + } + + /// + /// Reads a list of inventory folders returned by a query. + /// + /// A MySQL Data Reader + /// A List containing inventory folders + public List readInventoryFolders(IDataReader reader) + { + List rows = new List(); + + while(reader.Read()) + { + try + { + InventoryFolderBase folder = new InventoryFolderBase(); + + folder.agentID = new libsecondlife.LLUUID((string)reader["agentID"]); + folder.parentID = new libsecondlife.LLUUID((string)reader["parentFolderID"]); + folder.folderID = new libsecondlife.LLUUID((string)reader["folderID"]); + folder.name = (string)reader["folderName"]; + + rows.Add(folder); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } + + return rows; + } + + /// + /// Reads a collection of items from an SQL result + /// + /// The SQL Result + /// A List containing Inventory Items + public List readInventoryItems(IDataReader reader) + { + List rows = new List(); + + while (reader.Read()) + { + try + { + InventoryItemBase item = new InventoryItemBase(); + + item.assetID = new libsecondlife.LLUUID((string)reader["assetID"]); + item.avatarID = new libsecondlife.LLUUID((string)reader["avatarID"]); + item.inventoryCurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"].ToString()); + item.inventoryDescription = (string)reader["inventoryDescription"]; + item.inventoryID = new libsecondlife.LLUUID((string)reader["inventoryID"]); + item.inventoryName = (string)reader["inventoryName"]; + item.inventoryNextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"].ToString()); + item.parentFolderID = new libsecondlife.LLUUID((string)reader["parentFolderID"]); + item.type = Convert.ToInt32(reader["type"].ToString()); + + rows.Add(item); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } + + return rows; + } + + /// + /// Inserts a new row into the log database + /// + /// The daemon which triggered this event + /// Who were we operating on when this occured (region UUID, user UUID, etc) + /// The method call where the problem occured + /// The arguments passed to the method + /// How critical is this? + /// Extra message info + /// Saved successfully? + public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, string logMessage) + { + string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES "; + sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)"; + + Dictionary parameters = new Dictionary(); + parameters["?server"] = serverDaemon; + parameters["?target"] = target; + parameters["?method"] = methodCall; + parameters["?arguments"] = arguments; + parameters["?priority"] = priority.ToString(); + parameters["?message"] = logMessage; + + bool returnval = false; + + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + return false; + } + + return returnval; + } + + /// + /// Inserts a new item into the database + /// + /// The item + /// Success? + public bool insertItem(InventoryItemBase item) + { + string sql = "REPLACE INTO inventoryitems (inventoryID, assetID, type, parentFolderID, avatarID, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions) VALUES "; + sql += "(?inventoryID, ?assetID, ?type, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription, ?inventoryNextPermissions, ?inventoryCurrentPermissions)"; + + Dictionary parameters = new Dictionary(); + parameters["?inventoryID"] = item.inventoryID.ToStringHyphenated(); + parameters["?assetID"] = item.assetID.ToStringHyphenated(); + parameters["?type"] = item.type.ToString(); + parameters["?parentFolderID"] = item.parentFolderID.ToStringHyphenated(); + parameters["?avatarID"] = item.avatarID.ToStringHyphenated(); + parameters["?inventoryName"] = item.inventoryName; + parameters["?inventoryDescription"] = item.inventoryDescription; + parameters["?inventoryNextPermissions"] = item.inventoryNextPermissions.ToString(); + parameters["?inventoryCurrentPermissions"] = item.inventoryCurrentPermissions.ToString(); + + bool returnval = false; + + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + return false; + } + + return returnval; + } + + /// + /// Inserts a new folder into the database + /// + /// The folder + /// Success? + public bool insertFolder(InventoryFolderBase folder) + { + string sql = "REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName) VALUES "; + sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName)"; + + Dictionary parameters = new Dictionary(); + parameters["?folderID"] = folder.folderID.ToStringHyphenated(); + parameters["?agentID"] = folder.agentID.ToStringHyphenated(); + parameters["?parentFolderID"] = folder.parentID.ToStringHyphenated(); + parameters["?folderName"] = folder.name; + + bool returnval = false; + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + return false; + } + return returnval; + } + + /// + /// Inserts a new region into the database + /// + /// The region to insert + /// Success? + public bool insertRegion(SimProfileData regiondata) + { + string sql = "REPLACE INTO regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; + sql += "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; + sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture) VALUES "; + + sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, "; + sql += "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, "; + sql += "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture);"; + + Dictionary parameters = new Dictionary(); + + parameters["?regionHandle"] = regiondata.regionHandle.ToString(); + parameters["?regionName"] = regiondata.regionName.ToString(); + parameters["?uuid"] = regiondata.UUID.ToStringHyphenated(); + parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString(); + parameters["?regionSecret"] = regiondata.regionSecret.ToString(); + parameters["?regionSendKey"] = regiondata.regionSendKey.ToString(); + parameters["?regionDataURI"] = regiondata.regionDataURI.ToString(); + parameters["?serverIP"] = regiondata.serverIP.ToString(); + parameters["?serverPort"] = regiondata.serverPort.ToString(); + parameters["?serverURI"] = regiondata.serverURI.ToString(); + parameters["?locX"] = regiondata.regionLocX.ToString(); + parameters["?locY"] = regiondata.regionLocY.ToString(); + parameters["?locZ"] = regiondata.regionLocZ.ToString(); + parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString(); + parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString(); + parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString(); + parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString(); + parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString(); + parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString(); + parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString(); + parameters["?regionUserURI"] = regiondata.regionUserURI.ToString(); + parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString(); + parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString(); + parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToStringHyphenated(); + + bool returnval = false; + + try + { + + IDbCommand result = Query(sql, parameters); + + //Console.WriteLine(result.CommandText); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + return false; + } + + return returnval; + } + } +} diff --git a/OpenSim/Framework/Data.MySQL/MySQLUserData.cs b/OpenSim/Framework/Data.MySQL/MySQLUserData.cs new file mode 100644 index 0000000..032a0e6 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/MySQLUserData.cs @@ -0,0 +1,257 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; +using libsecondlife; + +namespace OpenGrid.Framework.Data.MySQL +{ + /// + /// A database interface class to a user profile storage system + /// + class MySQLUserData : IUserData + { + /// + /// Database manager for MySQL + /// + public MySQLManager database; + + /// + /// Loads and initialises the MySQL storage plugin + /// + public void Initialise() + { + // Load from an INI file connection details + // TODO: move this to XML? + IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); + string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); + string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); + string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); + string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); + string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); + string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); + + database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); + } + + /// + /// Searches the database for a specified user profile + /// + /// The account name of the user + /// A user profile + public UserProfileData getUserByName(string name) + { + return getUserByName(name.Split(' ')[0], name.Split(' ')[1]); + } + + /// + /// Searches the database for a specified user profile by name components + /// + /// The first part of the account name + /// The second part of the account name + /// A user profile + public UserProfileData getUserByName(string user, string last) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?first"] = user; + param["?second"] = last; + + System.Data.IDbCommand result = database.Query("SELECT * FROM users WHERE username = ?first AND lastname = ?second", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + UserProfileData row = database.readUserRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Searches the database for a specified user profile by UUID + /// + /// The account ID + /// The users profile + public UserProfileData getUserByUUID(LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = uuid.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM users WHERE UUID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + UserProfileData row = database.readUserRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Returns a user session searching by name + /// + /// The account name + /// The users session + public UserAgentData getAgentByName(string name) + { + return getAgentByName(name.Split(' ')[0], name.Split(' ')[1]); + } + + /// + /// Returns a user session by account name + /// + /// First part of the users account name + /// Second part of the users account name + /// The users session + public UserAgentData getAgentByName(string user, string last) + { + UserProfileData profile = getUserByName(user, last); + return getAgentByUUID(profile.UUID); + } + + /// + /// Returns an agent session by account UUID + /// + /// The accounts UUID + /// The users session + public UserAgentData getAgentByUUID(LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = uuid.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM agents WHERE UUID = ?uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + UserAgentData row = database.readAgentRow(reader); + + reader.Close(); + result.Dispose(); + + return row; + } + } + catch (Exception e) + { + database.Reconnect(); + Console.WriteLine(e.ToString()); + return null; + } + } + + /// + /// Creates a new users profile + /// + /// The user profile to create + public void addNewUserProfile(UserProfileData user) + { + } + + /// + /// Creates a new agent + /// + /// The agent to create + public void addNewUserAgent(UserAgentData agent) + { + // Do nothing. + } + + /// + /// Performs a money transfer request between two accounts + /// + /// The senders account ID + /// The recievers account ID + /// The amount to transfer + /// Success? + public bool moneyTransferRequest(LLUUID from, LLUUID to, uint amount) + { + return false; + } + + /// + /// Performs an inventory transfer request between two accounts + /// + /// TODO: Move to inventory server + /// The senders account ID + /// The recievers account ID + /// The item to transfer + /// Success? + public bool inventoryTransferRequest(LLUUID from, LLUUID to, LLUUID item) + { + return false; + } + + /// + /// Database provider name + /// + /// Provider name + public string getName() + { + return "MySQL Userdata Interface"; + } + + /// + /// Database provider version + /// + /// provider version + public string getVersion() + { + return "0.1"; + } + } +} diff --git a/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj b/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj new file mode 100644 index 0000000..62e3887 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj @@ -0,0 +1,117 @@ + + + Local + 8.0.50727 + 2.0 + {17F7F6BE-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Data.MySQL + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Data.MySQL + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + ..\..\..\bin\MySql.Data.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj.user b/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/OpenSim.Framework.Data.MySQL.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bfd1d6 --- /dev/null +++ b/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Data.MySQL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Data.MySQL")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e49826b2-dcef-41be-a5bd-596733fa3304")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj b/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj new file mode 100644 index 0000000..4ba24f1 --- /dev/null +++ b/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj @@ -0,0 +1,108 @@ + + + Local + 8.0.50727 + 2.0 + {6ECC56A9-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Data.SQLite + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Data.SQLite + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + ..\..\..\bin\System.Data.SQLite.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj.user b/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Data.SQLite/OpenSim.Framework.Data.SQLite.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..57c4bae --- /dev/null +++ b/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Data.SQLite")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Data.SQLite")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Data.SQLite/SQLiteGridData.cs b/OpenSim/Framework/Data.SQLite/SQLiteGridData.cs new file mode 100644 index 0000000..d7a5a69 --- /dev/null +++ b/OpenSim/Framework/Data.SQLite/SQLiteGridData.cs @@ -0,0 +1,195 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.SQLite +{ + /// + /// A Grid Interface to the SQLite database + /// + public class SQLiteGridData : IGridData + { + /// + /// A database manager + /// + private SQLiteManager database; + + /// + /// Initialises the Grid Interface + /// + public void Initialise() + { + database = new SQLiteManager("localhost", "db", "user", "password", "false"); + } + + /// + /// Shuts down the grid interface + /// + public void Close() + { + database.Close(); + } + + /// + /// Returns the name of this grid interface + /// + /// A string containing the grid interface + public string getName() + { + return "SQLite OpenGridData"; + } + + /// + /// Returns the version of this grid interface + /// + /// A string containing the version + public string getVersion() + { + return "0.1"; + } + + /// + /// Returns a list of regions within the specified ranges + /// + /// minimum X coordinate + /// minimum Y coordinate + /// maximum X coordinate + /// maximum Y coordinate + /// An array of region profiles + public SimProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) + { + return null; + } + + /// + /// Returns a sim profile from it's location + /// + /// Region location handle + /// Sim profile + public SimProfileData GetProfileByHandle(ulong handle) + { + Dictionary param = new Dictionary(); + param["handle"] = handle.ToString(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.getRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + + /// + /// Returns a sim profile from it's UUID + /// + /// The region UUID + /// The sim profile + public SimProfileData GetProfileByLLUUID(libsecondlife.LLUUID uuid) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToStringHyphenated(); + + System.Data.IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); + System.Data.IDataReader reader = result.ExecuteReader(); + + SimProfileData row = database.getRow(reader); + reader.Close(); + result.Dispose(); + + return row; + } + + /// + /// Adds a new specified region to the database + /// + /// The profile to add + /// A dataresponse enum indicating success + public DataResponse AddProfile(SimProfileData profile) + { + if (database.insertRow(profile)) + { + return DataResponse.RESPONSE_OK; + } + else + { + return DataResponse.RESPONSE_ERROR; + } + } + + /// + /// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret. + /// + /// The UUID of the challenger + /// The attempted regionHandle of the challenger + /// The secret + /// Whether the secret and regionhandle match the database entry for UUID + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authkey) + { + bool throwHissyFit = false; // Should be true by 1.0 + + if (throwHissyFit) + throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); + + SimProfileData data = GetProfileByLLUUID(uuid); + + return (handle == data.regionHandle && authkey == data.regionSecret); + } + + /// + /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region + /// + /// This requires a security audit. + /// + /// + /// + /// + /// + public bool AuthenticateSim(libsecondlife.LLUUID uuid, ulong handle, string authhash, string challenge) + { + System.Security.Cryptography.SHA512Managed HashProvider = new System.Security.Cryptography.SHA512Managed(); + System.Text.ASCIIEncoding TextProvider = new ASCIIEncoding(); + + byte[] stream = TextProvider.GetBytes(uuid.ToStringHyphenated() + ":" + handle.ToString() + ":" + challenge); + byte[] hash = HashProvider.ComputeHash(stream); + + return false; + } + + public ReservationData GetReservationAtPoint(uint x, uint y) + { + return null; + } + } + + +} diff --git a/OpenSim/Framework/Data.SQLite/SQLiteManager.cs b/OpenSim/Framework/Data.SQLite/SQLiteManager.cs new file mode 100644 index 0000000..9689356 --- /dev/null +++ b/OpenSim/Framework/Data.SQLite/SQLiteManager.cs @@ -0,0 +1,209 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; + +using System.Data.SQLite; + +using OpenGrid.Framework.Data; + +namespace OpenGrid.Framework.Data.SQLite +{ + class SQLiteManager + { + IDbConnection dbcon; + + /// + /// Initialises and creates a new SQLite connection and maintains it. + /// + /// The SQLite server being connected to + /// The name of the SQLite database being used + /// The username logging into the database + /// The password for the user logging in + /// Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'. + public SQLiteManager(string hostname, string database, string username, string password, string cpooling) + { + try + { + string connectionString = "URI=file:GridServerSqlite.db;"; + dbcon = new SQLiteConnection(connectionString); + + dbcon.Open(); + } + catch (Exception e) + { + throw new Exception("Error initialising SQLite Database: " + e.ToString()); + } + } + + /// + /// Shuts down the database connection + /// + public void Close() + { + dbcon.Close(); + dbcon = null; + } + + /// + /// Runs a query with protection against SQL Injection by using parameterised input. + /// + /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y + /// The parameters - index so that @y is indexed as 'y' + /// A SQLite DB Command + public IDbCommand Query(string sql, Dictionary parameters) + { + SQLiteCommand dbcommand = (SQLiteCommand)dbcon.CreateCommand(); + dbcommand.CommandText = sql; + foreach (KeyValuePair param in parameters) + { + SQLiteParameter paramx = new SQLiteParameter(param.Key,param.Value); + dbcommand.Parameters.Add(paramx); + } + + return (IDbCommand)dbcommand; + } + + /// + /// Reads a region row from a database reader + /// + /// An active database reader + /// A region profile + public SimProfileData getRow(IDataReader reader) + { + SimProfileData retval = new SimProfileData(); + + if (reader.Read()) + { + // Region Main + retval.regionHandle = (ulong)reader["regionHandle"]; + retval.regionName = (string)reader["regionName"]; + retval.UUID = new libsecondlife.LLUUID((string)reader["uuid"]); + + // Secrets + retval.regionRecvKey = (string)reader["regionRecvKey"]; + retval.regionSecret = (string)reader["regionSecret"]; + retval.regionSendKey = (string)reader["regionSendKey"]; + + // Region Server + retval.regionDataURI = (string)reader["regionDataURI"]; + retval.regionOnline = false; // Needs to be pinged before this can be set. + retval.serverIP = (string)reader["serverIP"]; + retval.serverPort = (uint)reader["serverPort"]; + retval.serverURI = (string)reader["serverURI"]; + + // Location + retval.regionLocX = (uint)((int)reader["locX"]); + retval.regionLocY = (uint)((int)reader["locY"]); + retval.regionLocZ = (uint)((int)reader["locZ"]); + + // Neighbours - 0 = No Override + retval.regionEastOverrideHandle = (ulong)reader["eastOverrideHandle"]; + retval.regionWestOverrideHandle = (ulong)reader["westOverrideHandle"]; + retval.regionSouthOverrideHandle = (ulong)reader["southOverrideHandle"]; + retval.regionNorthOverrideHandle = (ulong)reader["northOverrideHandle"]; + + // Assets + retval.regionAssetURI = (string)reader["regionAssetURI"]; + retval.regionAssetRecvKey = (string)reader["regionAssetRecvKey"]; + retval.regionAssetSendKey = (string)reader["regionAssetSendKey"]; + + // Userserver + retval.regionUserURI = (string)reader["regionUserURI"]; + retval.regionUserRecvKey = (string)reader["regionUserRecvKey"]; + retval.regionUserSendKey = (string)reader["regionUserSendKey"]; + } + else + { + throw new Exception("No rows to return"); + } + return retval; + } + + /// + /// Inserts a new region into the database + /// + /// The region to insert + /// Success? + public bool insertRow(SimProfileData profile) + { + string sql = "REPLACE INTO regions VALUES (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; + sql += "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; + sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey) VALUES "; + + sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; + sql += "@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; + sql += "@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey);"; + + Dictionary parameters = new Dictionary(); + + parameters["regionHandle"] = profile.regionHandle.ToString(); + parameters["regionName"] = profile.regionName; + parameters["uuid"] = profile.UUID.ToString(); + parameters["regionRecvKey"] = profile.regionRecvKey; + parameters["regionSendKey"] = profile.regionSendKey; + parameters["regionDataURI"] = profile.regionDataURI; + parameters["serverIP"] = profile.serverIP; + parameters["serverPort"] = profile.serverPort.ToString(); + parameters["serverURI"] = profile.serverURI; + parameters["locX"] = profile.regionLocX.ToString(); + parameters["locY"] = profile.regionLocY.ToString(); + parameters["locZ"] = profile.regionLocZ.ToString(); + parameters["eastOverrideHandle"] = profile.regionEastOverrideHandle.ToString(); + parameters["westOverrideHandle"] = profile.regionWestOverrideHandle.ToString(); + parameters["northOverrideHandle"] = profile.regionNorthOverrideHandle.ToString(); + parameters["southOverrideHandle"] = profile.regionSouthOverrideHandle.ToString(); + parameters["regionAssetURI"] = profile.regionAssetURI; + parameters["regionAssetRecvKey"] = profile.regionAssetRecvKey; + parameters["regionAssetSendKey"] = profile.regionAssetSendKey; + parameters["regionUserURI"] = profile.regionUserURI; + parameters["regionUserRecvKey"] = profile.regionUserRecvKey; + parameters["regionUserSendKey"] = profile.regionUserSendKey; + + bool returnval = false; + + try + { + IDbCommand result = Query(sql, parameters); + + if (result.ExecuteNonQuery() == 1) + returnval = true; + + result.Dispose(); + } + catch (Exception e) + { + return false; + } + + return returnval; + } + } +} diff --git a/OpenSim/Framework/Data/GridData.cs b/OpenSim/Framework/Data/GridData.cs new file mode 100644 index 0000000..7f8fdaf --- /dev/null +++ b/OpenSim/Framework/Data/GridData.cs @@ -0,0 +1,113 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Data +{ + public enum DataResponse + { + RESPONSE_OK, + RESPONSE_AUTHREQUIRED, + RESPONSE_INVALIDCREDENTIALS, + RESPONSE_ERROR + } + + /// + /// A standard grid interface + /// + public interface IGridData + { + /// + /// Returns a sim profile from a regionHandle + /// + /// A 64bit Region Handle + /// A simprofile + SimProfileData GetProfileByHandle(ulong regionHandle); + + /// + /// Returns a sim profile from a UUID + /// + /// A 128bit UUID + /// A sim profile + SimProfileData GetProfileByLLUUID(libsecondlife.LLUUID UUID); + + /// + /// Returns all profiles within the specified range + /// + /// Minimum sim coordinate (X) + /// Minimum sim coordinate (Y) + /// Maximum sim coordinate (X) + /// Maximum sim coordinate (Y) + /// An array containing all the sim profiles in the specified range + SimProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); + + /// + /// Authenticates a sim by use of it's recv key. + /// WARNING: Insecure + /// + /// The UUID sent by the sim + /// The regionhandle sent by the sim + /// The recieving key sent by the sim + /// Whether the sim has been authenticated + bool AuthenticateSim(libsecondlife.LLUUID UUID, ulong regionHandle, string simrecvkey); + + /// + /// Initialises the interface + /// + void Initialise(); + + /// + /// Closes the interface + /// + void Close(); + + /// + /// The plugin being loaded + /// + /// A string containing the plugin name + string getName(); + + /// + /// The plugins version + /// + /// A string containing the plugin version + string getVersion(); + + /// + /// Adds a new profile to the database + /// + /// The profile to add + /// RESPONSE_OK if successful, error if not. + DataResponse AddProfile(SimProfileData profile); + + ReservationData GetReservationAtPoint(uint x, uint y); + + } +} diff --git a/OpenSim/Framework/Data/ILogData.cs b/OpenSim/Framework/Data/ILogData.cs new file mode 100644 index 0000000..ccb3b84 --- /dev/null +++ b/OpenSim/Framework/Data/ILogData.cs @@ -0,0 +1,94 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Data +{ + /// + /// The severity of an individual log message + /// + public enum LogSeverity : int + { + /// + /// Critical: systems failure + /// + CRITICAL = 1, + /// + /// Major: warning prior to systems failure + /// + MAJOR = 2, + /// + /// Medium: an individual non-critical task failed + /// + MEDIUM = 3, + /// + /// Low: Informational warning + /// + LOW = 4, + /// + /// Info: Information + /// + INFO = 5, + /// + /// Verbose: Debug Information + /// + VERBOSE = 6 + } + + /// + /// An interface to a LogData storage system + /// + public interface ILogData + { + void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority,string logMessage); + /// + /// Initialises the interface + /// + void Initialise(); + + /// + /// Closes the interface + /// + void Close(); + + /// + /// The plugin being loaded + /// + /// A string containing the plugin name + string getName(); + + /// + /// The plugins version + /// + /// A string containing the plugin version + string getVersion(); + } + +} diff --git a/OpenSim/Framework/Data/IniConfig.cs b/OpenSim/Framework/Data/IniConfig.cs new file mode 100644 index 0000000..2f002c1 --- /dev/null +++ b/OpenSim/Framework/Data/IniConfig.cs @@ -0,0 +1,100 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Text.RegularExpressions; + +/* + Taken from public code listing at by Alex Pinsker + http://alexpinsker.blogspot.com/2005/12/reading-ini-file-from-c_113432097333021549.html + */ + +namespace OpenSim.Framework.Data +{ + /// + /// Parse settings from ini-like files + /// + public class IniFile + { + static IniFile() + { + _iniKeyValuePatternRegex = new Regex( + @"((\s)*(?([^\=^\s^\n]+))[\s^\n]* + # key part (surrounding whitespace stripped) + \= + (\s)*(?([^\n^\s]+(\n){0,1}))) + # value part (surrounding whitespace stripped) + ", + RegexOptions.IgnorePatternWhitespace | + RegexOptions.Compiled | + RegexOptions.CultureInvariant); + } + static private Regex _iniKeyValuePatternRegex; + + public IniFile(string iniFileName) + { + _iniFileName = iniFileName; + } + + public string ParseFileReadValue(string key) + { + using (StreamReader reader = + new StreamReader(_iniFileName)) + { + do + { + string line = reader.ReadLine(); + Match match = + _iniKeyValuePatternRegex.Match(line); + if (match.Success) + { + string currentKey = + match.Groups["Key"].Value as string; + if (currentKey != null && + currentKey.Trim().CompareTo(key) == 0) + { + string value = + match.Groups["Value"].Value as string; + return value; + } + } + + } + while (reader.Peek() != -1); + } + return null; + } + + public string IniFileName + { + get { return _iniFileName; } + } private string _iniFileName; + } +} diff --git a/OpenSim/Framework/Data/InventoryData.cs b/OpenSim/Framework/Data/InventoryData.cs new file mode 100644 index 0000000..8a3a664 --- /dev/null +++ b/OpenSim/Framework/Data/InventoryData.cs @@ -0,0 +1,187 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Data +{ + /// + /// Inventory Item - contains all the properties associated with an individual inventory piece. + /// + public class InventoryItemBase + { + /// + /// A UUID containing the ID for the inventory item itself + /// + public LLUUID inventoryID; + /// + /// The UUID of the associated asset on the asset server + /// + public LLUUID assetID; + /// + /// This is an enumerated value determining the type of asset (eg Notecard, Sound, Object, etc) + /// + public int type; + /// + /// The folder this item is contained in (NULL_KEY = Inventory Root) + /// + public LLUUID parentFolderID; + /// + /// The owner of this inventory item + /// + public LLUUID avatarID; + /// + /// The name of the inventory item (must be less than 64 characters) + /// + public string inventoryName; + /// + /// The description of the inventory item (must be less than 64 characters) + /// + public string inventoryDescription; + /// + /// A mask containing the permissions for the next owner (cannot be enforced) + /// + public uint inventoryNextPermissions; + /// + /// A mask containing permissions for the current owner (cannot be enforced) + /// + public uint inventoryCurrentPermissions; + } + + /// + /// A Class for folders which contain users inventory + /// + public class InventoryFolderBase + { + /// + /// The name of the folder (64 characters or less) + /// + public string name; + /// + /// The agent who's inventory this is contained by + /// + public LLUUID agentID; + /// + /// The folder this folder is contained in (NULL_KEY for root) + /// + public LLUUID parentID; + /// + /// The UUID for this folder + /// + public LLUUID folderID; + } + + /// + /// An interface for accessing inventory data from a storage server + /// + public interface IInventoryData + { + /// + /// Initialises the interface + /// + void Initialise(); + + /// + /// Closes the interface + /// + void Close(); + + /// + /// The plugin being loaded + /// + /// A string containing the plugin name + string getName(); + + /// + /// The plugins version + /// + /// A string containing the plugin version + string getVersion(); + + /// + /// Returns a list of inventory items contained within the specified folder + /// + /// The UUID of the target folder + /// A List of InventoryItemBase items + List getInventoryInFolder(LLUUID folderID); + + /// + /// Returns a list of folders in the users inventory root. + /// + /// The UUID of the user who is having inventory being returned + /// A list of folders + List getUserRootFolders(LLUUID user); + + /// + /// Returns a list of inventory folders contained in the folder 'parentID' + /// + /// The folder to get subfolders for + /// A list of inventory folders + List getInventoryFolders(LLUUID parentID); + + /// + /// Returns an inventory item by its UUID + /// + /// The UUID of the item to be returned + /// A class containing item information + InventoryItemBase getInventoryItem(LLUUID item); + + /// + /// Returns a specified inventory folder by its UUID + /// + /// The UUID of the folder to be returned + /// A class containing folder information + InventoryFolderBase getInventoryFolder(LLUUID folder); + + /// + /// Creates a new inventory item based on item + /// + /// The item to be created + void addInventoryItem(InventoryItemBase item); + + /// + /// Updates an inventory item with item (updates based on ID) + /// + /// The updated item + void updateInventoryItem(InventoryItemBase item); + + /// + /// Adds a new folder specified by folder + /// + /// The inventory folder + void addInventoryFolder(InventoryFolderBase folder); + + /// + /// Updates a folder based on its ID with folder + /// + /// The inventory folder + void updateInventoryFolder(InventoryFolderBase folder); + } +} diff --git a/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj b/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj new file mode 100644 index 0000000..dcafbcd --- /dev/null +++ b/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj @@ -0,0 +1,116 @@ + + + Local + 8.0.50727 + 2.0 + {36B72A9B-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Data + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Data + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj.user b/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Data/OpenSim.Framework.Data.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Data/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1446673 --- /dev/null +++ b/OpenSim/Framework/Data/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenGrid.Framework.Data")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenGrid.Framework.Data")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3a711c34-b0c0-4264-b0fe-f366eabf9d7b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/Data/ReservationData.cs b/OpenSim/Framework/Data/ReservationData.cs new file mode 100644 index 0000000..f404ebd --- /dev/null +++ b/OpenSim/Framework/Data/ReservationData.cs @@ -0,0 +1,51 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +using libsecondlife; + +namespace OpenSim.Framework.Data +{ + public class ReservationData + { + public LLUUID userUUID = new LLUUID(); + public int reservationMinX = 0; + public int reservationMinY = 0; + public int reservationMaxX = 65536; + public int reservationMaxY = 65536; + + public string reservationName = ""; + public string reservationCompany = ""; + public bool status = true; + + public string gridSendKey = ""; + public string gridRecvKey = ""; + } +} diff --git a/OpenSim/Framework/Data/SimProfileData.cs b/OpenSim/Framework/Data/SimProfileData.cs new file mode 100644 index 0000000..201aa01 --- /dev/null +++ b/OpenSim/Framework/Data/SimProfileData.cs @@ -0,0 +1,114 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Data +{ + /// + /// A class which contains information known to the grid server about a region + /// + public class SimProfileData + { + /// + /// The name of the region + /// + public string regionName = ""; + + /// + /// A 64-bit number combining map position into a (mostly) unique ID + /// + public ulong regionHandle; + + /// + /// OGS/OpenSim Specific ID for a region + /// + public libsecondlife.LLUUID UUID; + + /// + /// Coordinates of the region + /// + public uint regionLocX; + public uint regionLocY; + public uint regionLocZ; // Reserved (round-robin, layers, etc) + + /// + /// Authentication secrets + /// + /// Not very secure, needs improvement. + public string regionSendKey = ""; + public string regionRecvKey = ""; + public string regionSecret = ""; + + /// + /// Whether the region is online + /// + public bool regionOnline; + + /// + /// Information about the server that the region is currently hosted on + /// + public string serverIP = ""; + public uint serverPort; + public string serverURI = ""; + + /// + /// Set of optional overrides. Can be used to create non-eulicidean spaces. + /// + public ulong regionNorthOverrideHandle; + public ulong regionSouthOverrideHandle; + public ulong regionEastOverrideHandle; + public ulong regionWestOverrideHandle; + + /// + /// Optional: URI Location of the region database + /// + /// Used for floating sim pools where the region data is not nessecarily coupled to a specific server + public string regionDataURI = ""; + + /// + /// Region Asset Details + /// + public string regionAssetURI = ""; + public string regionAssetSendKey = ""; + public string regionAssetRecvKey = ""; + + /// + /// Region Userserver Details + /// + public string regionUserURI = ""; + public string regionUserSendKey = ""; + public string regionUserRecvKey = ""; + + /// + /// Region Map Texture Asset + /// + public libsecondlife.LLUUID regionMapTextureID = new libsecondlife.LLUUID("00000000-0000-0000-9999-000000000006"); + } +} diff --git a/OpenSim/Framework/Data/UserData.cs b/OpenSim/Framework/Data/UserData.cs new file mode 100644 index 0000000..2e15b47 --- /dev/null +++ b/OpenSim/Framework/Data/UserData.cs @@ -0,0 +1,131 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Data +{ + /// + /// An interface for connecting to user storage servers. + /// + public interface IUserData + { + /// + /// Returns a user profile from a database via their UUID + /// + /// The accounts UUID + /// The user data profile + UserProfileData getUserByUUID(LLUUID user); + + /// + /// Returns a users profile by searching their username + /// + /// The users username + /// The user data profile + UserProfileData getUserByName(string name); + + /// + /// Returns a users profile by searching their username parts + /// + /// Account firstname + /// Account lastname + /// The user data profile + UserProfileData getUserByName(string fname, string lname); + + /// + /// Returns the current agent for a user searching by it's UUID + /// + /// The users UUID + /// The current agent session + UserAgentData getAgentByUUID(LLUUID user); + + /// + /// Returns the current session agent for a user searching by username + /// + /// The users account name + /// The current agent session + UserAgentData getAgentByName(string name); + + /// + /// Returns the current session agent for a user searching by username parts + /// + /// The users first account name + /// The users account surname + /// The current agent session + UserAgentData getAgentByName(string fname, string lname); + + /// + /// Adds a new User profile to the database + /// + /// UserProfile to add + void addNewUserProfile(UserProfileData user); + + /// + /// Adds a new agent to the database + /// + /// The agent to add + void addNewUserAgent(UserAgentData agent); + + /// + /// Attempts to move currency units between accounts (NOT RELIABLE / TRUSTWORTHY. DONT TRY RUN YOUR OWN CURRENCY EXCHANGE WITH REAL VALUES) + /// + /// The account to transfer from + /// The account to transfer to + /// The amount to transfer + /// Successful? + bool moneyTransferRequest(LLUUID from, LLUUID to, uint amount); + + /// + /// Attempts to move inventory between accounts, if inventory is copyable it will be copied into the target account. + /// + /// User to transfer from + /// User to transfer to + /// Specified inventory item + /// Successful? + bool inventoryTransferRequest(LLUUID from, LLUUID to, LLUUID inventory); + + /// + /// Returns the plugin version + /// + /// Plugin version in MAJOR.MINOR.REVISION.BUILD format + string getVersion(); + + /// + /// Returns the plugin name + /// + /// Plugin name, eg MySQL User Provider + string getName(); + + /// + /// Initialises the plugin (artificial constructor) + /// + void Initialise(); + } +} diff --git a/OpenSim/Framework/Data/UserProfileData.cs b/OpenSim/Framework/Data/UserProfileData.cs new file mode 100644 index 0000000..00d422d --- /dev/null +++ b/OpenSim/Framework/Data/UserProfileData.cs @@ -0,0 +1,182 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Data +{ + /// + /// Information about a particular user known to the userserver + /// + public class UserProfileData + { + /// + /// The ID value for this user + /// + public LLUUID UUID; + + /// + /// The first component of a users account name + /// + public string username; + /// + /// The second component of a users account name + /// + public string surname; + + /// + /// A salted hash containing the users password, in the format md5(md5(password) + ":" + salt) + /// + /// This is double MD5'd because the client sends an unsalted MD5 to the loginserver + public string passwordHash; + /// + /// The salt used for the users hash, should be 32 bytes or longer + /// + public string passwordSalt; + + /// + /// The regionhandle of the users preffered home region. If multiple sims occupy the same spot, the grid may decide which region the user logs into + /// + public ulong homeRegion; + /// + /// The coordinates inside the region of the home location + /// + public LLVector3 homeLocation; + /// + /// Where the user will be looking when they rez. + /// + public LLVector3 homeLookAt; + + /// + /// A UNIX Timestamp (seconds since epoch) for the users creation + /// + public int created; + /// + /// A UNIX Timestamp for the users last login date / time + /// + public int lastLogin; + + /// + /// A URI to the users inventory server, used for foreigners and large grids + /// + public string userInventoryURI; + /// + /// A URI to the users asset server, used for foreigners and large grids. + /// + public string userAssetURI; + + /// + /// A uint mask containing the "I can do" fields of the users profile + /// + public uint profileCanDoMask; + /// + /// A uint mask containing the "I want to do" part of the users profile + /// + public uint profileWantDoMask; // Profile window "I want to" mask + + /// + /// The about text listed in a users profile. + /// + public string profileAboutText; + /// + /// The first life about text listed in a users profile + /// + public string profileFirstText; + + /// + /// The profile image for an avatar stored on the asset server + /// + public LLUUID profileImage; + /// + /// The profile image for the users first life tab + /// + public LLUUID profileFirstImage; + /// + /// The users last registered agent (filled in on the user server) + /// + public UserAgentData currentAgent; + } + + /// + /// Information about a users session + /// + public class UserAgentData + { + /// + /// The UUID of the users avatar (not the agent!) + /// + public LLUUID UUID; + /// + /// The IP address of the user + /// + public string agentIP; + /// + /// The port of the user + /// + public uint agentPort; + /// + /// Is the user online? + /// + public bool agentOnline; + /// + /// The session ID for the user (also the agent ID) + /// + public LLUUID sessionID; + /// + /// The "secure" session ID for the user + /// + /// Not very secure. Dont rely on it for anything more than Linden Lab does. + public LLUUID secureSessionID; + /// + /// The region the user logged into initially + /// + public LLUUID regionID; + /// + /// A unix timestamp from when the user logged in + /// + public int loginTime; + /// + /// When this agent expired and logged out, 0 if still online + /// + public int logoutTime; + /// + /// Current region the user is logged into + /// + public LLUUID currentRegion; + /// + /// Region handle of the current region the user is in + /// + public ulong currentHandle; + /// + /// The position of the user within the region + /// + public LLVector3 currentPos; + } +} diff --git a/OpenSim/Framework/General/AgentInventory.cs b/OpenSim/Framework/General/AgentInventory.cs new file mode 100644 index 0000000..fbf4d23 --- /dev/null +++ b/OpenSim/Framework/General/AgentInventory.cs @@ -0,0 +1,267 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Framework.Inventory +{ + public class AgentInventory + { + //Holds the local copy of Inventory info for a agent + public Dictionary InventoryFolders; + public Dictionary InventoryItems; + public InventoryFolder InventoryRoot; + public int LastCached; //maybe used by opensim app, time this was last stored/compared to user server + public LLUUID AgentID; + public AvatarWearable[] Wearables; + + public AgentInventory() + { + InventoryFolders = new Dictionary(); + InventoryItems = new Dictionary(); + this.Initialise(); + } + + public virtual void Initialise() + { + Wearables = new AvatarWearable[13]; //should be 12 of these + for (int i = 0; i < 13; i++) + { + Wearables[i] = new AvatarWearable(); + } + + } + + public bool CreateNewFolder(LLUUID folderID, ushort type) + { + InventoryFolder Folder = new InventoryFolder(); + Folder.FolderID = folderID; + Folder.OwnerID = this.AgentID; + Folder.DefaultType = type; + this.InventoryFolders.Add(Folder.FolderID, Folder); + return (true); + } + + public void CreateRootFolder(LLUUID newAgentID, bool createTextures) + { + this.AgentID = newAgentID; + InventoryRoot = new InventoryFolder(); + InventoryRoot.FolderID = LLUUID.Random(); + InventoryRoot.ParentID = new LLUUID(); + InventoryRoot.Version = 1; + InventoryRoot.DefaultType = 8; + InventoryRoot.OwnerID = this.AgentID; + InventoryRoot.FolderName = "My Inventory"; + InventoryFolders.Add(InventoryRoot.FolderID, InventoryRoot); + InventoryRoot.OwnerID = this.AgentID; + if (createTextures) + { + this.CreateNewFolder(LLUUID.Random(), 0, "Textures", InventoryRoot.FolderID); + } + } + + public bool CreateNewFolder(LLUUID folderID, ushort type, string folderName) + { + InventoryFolder Folder = new InventoryFolder(); + Folder.FolderID = folderID; + Folder.OwnerID = this.AgentID; + Folder.DefaultType = type; + Folder.FolderName = folderName; + this.InventoryFolders.Add(Folder.FolderID, Folder); + + return (true); + } + + public bool CreateNewFolder(LLUUID folderID, ushort type, string folderName, LLUUID parent) + { + if (!this.InventoryFolders.ContainsKey(folderID)) + { + System.Console.WriteLine("creating new folder called " + folderName + " in agents inventory"); + InventoryFolder Folder = new InventoryFolder(); + Folder.FolderID = folderID; + Folder.OwnerID = this.AgentID; + Folder.DefaultType = type; + Folder.FolderName = folderName; + Folder.ParentID = parent; + this.InventoryFolders.Add(Folder.FolderID, Folder); + } + + return (true); + } + + public bool HasFolder(LLUUID folderID) + { + if (this.InventoryFolders.ContainsKey(folderID)) + { + return true; + } + return false; + } + + public LLUUID GetFolderID(string folderName) + { + foreach (InventoryFolder inv in this.InventoryFolders.Values) + { + if (inv.FolderName == folderName) + { + return inv.FolderID; + } + } + + return LLUUID.Zero; + } + + public bool UpdateItemAsset(LLUUID itemID, AssetBase asset) + { + if(this.InventoryItems.ContainsKey(itemID)) + { + InventoryItem Item = this.InventoryItems[itemID]; + Item.AssetID = asset.FullID; + System.Console.WriteLine("updated inventory item " + itemID.ToStringHyphenated() + " so it now is set to asset " + asset.FullID.ToStringHyphenated()); + //TODO need to update the rest of the info + } + return true; + } + + public bool UpdateItemDetails(LLUUID itemID, UpdateInventoryItemPacket.InventoryDataBlock packet) + { + System.Console.WriteLine("updating inventory item details"); + if (this.InventoryItems.ContainsKey(itemID)) + { + System.Console.WriteLine("changing name to "+ Util.FieldToString(packet.Name)); + InventoryItem Item = this.InventoryItems[itemID]; + Item.Name = Util.FieldToString(packet.Name); + System.Console.WriteLine("updated inventory item " + itemID.ToStringHyphenated()); + //TODO need to update the rest of the info + } + return true; + } + + public LLUUID AddToInventory(LLUUID folderID, AssetBase asset) + { + if (this.InventoryFolders.ContainsKey(folderID)) + { + LLUUID NewItemID = LLUUID.Random(); + + InventoryItem Item = new InventoryItem(); + Item.FolderID = folderID; + Item.OwnerID = AgentID; + Item.AssetID = asset.FullID; + Item.ItemID = NewItemID; + Item.Type = asset.Type; + Item.Name = asset.Name; + Item.Description = asset.Description; + Item.InvType = asset.InvType; + this.InventoryItems.Add(Item.ItemID, Item); + InventoryFolder Folder = InventoryFolders[Item.FolderID]; + Folder.Items.Add(Item); + return (Item.ItemID); + } + else + { + return (null); + } + } + + public bool DeleteFromInventory(LLUUID itemID) + { + bool res = false; + if (this.InventoryItems.ContainsKey(itemID)) + { + InventoryItem item = this.InventoryItems[itemID]; + this.InventoryItems.Remove(itemID); + foreach (InventoryFolder fold in InventoryFolders.Values) + { + if (fold.Items.Contains(item)) + { + fold.Items.Remove(item); + break; + } + } + res = true; + + } + return res; + } + } + + public class InventoryFolder + { + public List Items; + //public List Subfolders; + public LLUUID FolderID; + public LLUUID OwnerID; + public LLUUID ParentID = LLUUID.Zero; + public string FolderName; + public ushort DefaultType; + public ushort Version; + + public InventoryFolder() + { + Items = new List(); + //Subfolders = new List(); + } + + } + + public class InventoryItem + { + public LLUUID FolderID; + public LLUUID OwnerID; + public LLUUID ItemID; + public LLUUID AssetID; + public LLUUID CreatorID; + public sbyte InvType; + public sbyte Type; + public string Name =""; + public string Description; + + public InventoryItem() + { + this.CreatorID = LLUUID.Zero; + } + + public string ExportString() + { + string typ = "notecard"; + string result = ""; + result += "\tinv_object\t0\n\t{\n"; + result += "\t\tobj_id\t%s\n"; + result += "\t\tparent_id\t"+ ItemID.ToString() +"\n"; + result += "\t\ttype\t"+ typ +"\n"; + result += "\t\tname\t" + Name+"|\n"; + result += "\t}\n"; + return result; + } + } +} diff --git a/OpenSim/Framework/General/AuthenticateSessionBase.cs b/OpenSim/Framework/General/AuthenticateSessionBase.cs new file mode 100644 index 0000000..73dd3e2 --- /dev/null +++ b/OpenSim/Framework/General/AuthenticateSessionBase.cs @@ -0,0 +1,132 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework +{ + public class AuthenticateSessionsBase + { + public Dictionary AgentCircuits = new Dictionary(); + + public AuthenticateSessionsBase() + { + + } + + public virtual AuthenticateResponse AuthenticateSession(LLUUID sessionID, LLUUID agentID, uint circuitcode) + { + AgentCircuitData validcircuit = null; + if (this.AgentCircuits.ContainsKey(circuitcode)) + { + validcircuit = this.AgentCircuits[circuitcode]; + } + AuthenticateResponse user = new AuthenticateResponse(); + if (validcircuit == null) + { + //don't have this circuit code in our list + user.Authorised = false; + return (user); + } + + if ((sessionID == validcircuit.SessionID) && (agentID == validcircuit.AgentID)) + { + user.Authorised = true; + user.LoginInfo = new Login(); + user.LoginInfo.Agent = agentID; + user.LoginInfo.Session = sessionID; + user.LoginInfo.SecureSession = validcircuit.SecureSessionID; + user.LoginInfo.First = validcircuit.firstname; + user.LoginInfo.Last = validcircuit.lastname; + user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder; + user.LoginInfo.BaseFolder = validcircuit.BaseFolder; + } + else + { + // Invalid + user.Authorised = false; + } + + return (user); + } + + public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData) + { + if (this.AgentCircuits.ContainsKey(circuitCode)) + { + this.AgentCircuits[circuitCode] = agentData; + } + else + { + this.AgentCircuits.Add(circuitCode, agentData); + } + } + + public LLVector3 GetPosition(uint circuitCode) + { + LLVector3 vec = new LLVector3(); + if (this.AgentCircuits.ContainsKey(circuitCode)) + { + vec = this.AgentCircuits[circuitCode].startpos; + } + return vec; + } + + public void UpdateAgentData(AgentCircuitData agentData) + { + if (this.AgentCircuits.ContainsKey((uint)agentData.circuitcode)) + { + this.AgentCircuits[(uint)agentData.circuitcode].firstname = agentData.firstname; + this.AgentCircuits[(uint)agentData.circuitcode].lastname = agentData.lastname; + this.AgentCircuits[(uint)agentData.circuitcode].startpos = agentData.startpos; + // Console.WriteLine("update user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z); + } + } + + public void UpdateAgentChildStatus(uint circuitcode, bool childstatus) + { + if (this.AgentCircuits.ContainsKey(circuitcode)) + { + this.AgentCircuits[circuitcode].child = childstatus; + } + } + + public bool GetAgentChildStatus(uint circuitcode) + { + if (this.AgentCircuits.ContainsKey(circuitcode)) + { + return this.AgentCircuits[circuitcode].child; + } + return false; + } + } +} \ No newline at end of file diff --git a/OpenSim/Framework/General/BlockingQueue.cs b/OpenSim/Framework/General/BlockingQueue.cs new file mode 100644 index 0000000..667b8d8 --- /dev/null +++ b/OpenSim/Framework/General/BlockingQueue.cs @@ -0,0 +1,60 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Threading; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Utilities +{ + public class BlockingQueue + { + private Queue _queue = new Queue(); + private object _queueSync = new object(); + + public void Enqueue(T value) + { + lock (_queueSync) + { + _queue.Enqueue(value); + Monitor.Pulse(_queueSync); + } + } + + public T Dequeue() + { + lock (_queueSync) + { + if (_queue.Count < 1) + Monitor.Wait(_queueSync); + + return _queue.Dequeue(); + } + } + } +} diff --git a/OpenSim/Framework/General/IRegionCommsListener.cs b/OpenSim/Framework/General/IRegionCommsListener.cs new file mode 100644 index 0000000..0e80941 --- /dev/null +++ b/OpenSim/Framework/General/IRegionCommsListener.cs @@ -0,0 +1,47 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework +{ + public delegate void ExpectUserDelegate(ulong regionHandle, AgentCircuitData agent); + public delegate void UpdateNeighbours(List neighbours); + public delegate void AgentCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position); + + public interface IRegionCommsListener + { + event ExpectUserDelegate OnExpectUser; + event GenericCall2 OnExpectChildAgent; + event AgentCrossing OnAvatarCrossingIntoRegion; + event UpdateNeighbours OnNeighboursUpdate; + } +} diff --git a/OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs b/OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs new file mode 100644 index 0000000..462e2c5 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs @@ -0,0 +1,51 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.IO; +using libsecondlife; +using OpenSim; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + public class AuthenticateResponse + { + public bool Authorised; + public Login LoginInfo; + + public AuthenticateResponse() + { + + } + + } +} diff --git a/OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs b/OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs new file mode 100644 index 0000000..13980fe --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs @@ -0,0 +1,42 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Interfaces +{ + public interface IGenericConfig + { + void LoadData(); + string GetAttribute(string attributeName); + bool SetAttribute(string attributeName, string attributeValue); + void Commit(); + void Close(); + } +} diff --git a/OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs b/OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs new file mode 100644 index 0000000..0fafe1a --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs @@ -0,0 +1,63 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.IO; +using libsecondlife; +//using OpenSim.world; + +namespace OpenSim.Framework.Interfaces +{ + /// + /// + + + public abstract class GridConfig + { + public string GridOwner; + public string DefaultStartupMsg; + public string DefaultAssetServer; + public string AssetSendKey; + public string AssetRecvKey; + public string DefaultUserServer; + public string UserSendKey; + public string UserRecvKey; + public string SimSendKey; + public string SimRecvKey; + + + public abstract void InitConfig(); + + } + + public interface IGridConfig + { + GridConfig GetConfigObject(); + } +} diff --git a/OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs b/OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs new file mode 100644 index 0000000..2f4b340 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs @@ -0,0 +1,57 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.IO; +using libsecondlife; +//using OpenSim.world; + +namespace OpenSim.Framework.Interfaces +{ + /// + /// + + + public abstract class UserConfig + { + public string DefaultStartupMsg; + public string GridServerURL; + public string GridSendKey; + public string GridRecvKey; + + + public abstract void InitConfig(); + + } + + public interface IUserConfig + { + UserConfig GetConfigObject(); + } +} diff --git a/OpenSim/Framework/General/Interfaces/IAssetServer.cs b/OpenSim/Framework/General/Interfaces/IAssetServer.cs new file mode 100644 index 0000000..826392d --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/IAssetServer.cs @@ -0,0 +1,69 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + /// + /// Description of IAssetServer. + /// + + public interface IAssetServer + { + void SetReceiver(IAssetReceiver receiver); + void RequestAsset(LLUUID assetID, bool isTexture); + void UpdateAsset(AssetBase asset); + void UploadNewAsset(AssetBase asset); + void SetServerInfo(string ServerUrl, string ServerKey); + void Close(); + } + + // could change to delegate? + public interface IAssetReceiver + { + void AssetReceived(AssetBase asset, bool IsTexture); + void AssetNotFound(AssetBase asset); + } + + public interface IAssetPlugin + { + IAssetServer GetAssetServer(); + } + + public struct ARequest + { + public LLUUID AssetID; + public bool IsTexture; + } +} diff --git a/OpenSim/Framework/General/Interfaces/IClientAPI.cs b/OpenSim/Framework/General/Interfaces/IClientAPI.cs new file mode 100644 index 0000000..009648c --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/IClientAPI.cs @@ -0,0 +1,160 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Inventory; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + public delegate void ChatFromViewer(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID); + public delegate void RezObject(AssetBase primAsset, LLVector3 pos); + public delegate void ModifyTerrain(float height, float seconds, byte size, byte action, float north, float west); + public delegate void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam); + public delegate void StartAnim(LLUUID animID, int seq); + public delegate void LinkObjects(uint parent, List children); + public delegate void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY); + public delegate void TeleportLocationRequest(IClientAPI remoteClient, ulong regionHandle, LLVector3 position, LLVector3 lookAt, uint flags); + + public delegate void GenericCall(IClientAPI remoteClient); + public delegate void GenericCall2(); + public delegate void GenericCall3(Packet packet); // really don't want to be passing packets in these events, so this is very temporary. + public delegate void GenericCall4(Packet packet, IClientAPI remoteClient); + public delegate void GenericCall5(IClientAPI remoteClient, bool status); + public delegate void GenericCall6(LLUUID uid); + + public delegate void UpdateShape(uint localID, ObjectShapePacket.ObjectDataBlock shapeBlock); + public delegate void ObjectSelect(uint localID, IClientAPI remoteClient); + public delegate void UpdatePrimFlags(uint localID, Packet packet, IClientAPI remoteClient); + public delegate void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient); + public delegate void UpdateVector(uint localID, LLVector3 pos, IClientAPI remoteClient); + public delegate void UpdatePrimRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient); + public delegate void StatusChange(bool status); + public delegate void NewAvatar(IClientAPI remoteClient, LLUUID agentID, bool status); + public delegate void UpdateAgent(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation); + public delegate void MoveObject(LLUUID objectID, LLVector3 offset, LLVector3 grapPos, IClientAPI remoteClient); + + public delegate void ParcelPropertiesRequest(int start_x, int start_y, int end_x, int end_y, int sequence_id, bool snap_selection, IClientAPI remote_client); + public delegate void ParcelDivideRequest(int west, int south, int east, int north, IClientAPI remote_client); + public delegate void ParcelJoinRequest(int west, int south, int east, int north, IClientAPI remote_client); + public delegate void ParcelPropertiesUpdateRequest(ParcelPropertiesUpdatePacket packet, IClientAPI remote_client); // NOTETOSELFremove the packet part + + public delegate void EstateOwnerMessageRequest(EstateOwnerMessagePacket packet, IClientAPI remote_client); + + public interface IClientAPI + { + event ChatFromViewer OnChatFromViewer; + event RezObject OnRezObject; + event ModifyTerrain OnModifyTerrain; + event SetAppearance OnSetAppearance; + event StartAnim OnStartAnim; + event LinkObjects OnLinkObjects; + event RequestMapBlocks OnRequestMapBlocks; + event TeleportLocationRequest OnTeleportLocationRequest; + + event GenericCall4 OnDeRezObject; + event GenericCall OnRegionHandShakeReply; + event GenericCall OnRequestWearables; + event GenericCall2 OnCompleteMovementToRegion; + event UpdateAgent OnAgentUpdate; + event GenericCall OnRequestAvatarsData; + event GenericCall4 OnAddPrim; + event UpdateVector OnGrapObject; + event ObjectSelect OnDeGrapObject; + event MoveObject OnGrapUpdate; + + event UpdateShape OnUpdatePrimShape; + event ObjectSelect OnObjectSelect; + event UpdatePrimFlags OnUpdatePrimFlags; + event UpdatePrimTexture OnUpdatePrimTexture; + event UpdateVector OnUpdatePrimPosition; + event UpdatePrimRotation OnUpdatePrimRotation; + event UpdateVector OnUpdatePrimScale; + event StatusChange OnChildAgentStatus; + event GenericCall2 OnStopMovement; + event NewAvatar OnNewAvatar; + event GenericCall6 OnRemoveAvatar; + + event ParcelPropertiesRequest OnParcelPropertiesRequest; + event ParcelDivideRequest OnParcelDivideRequest; + event ParcelJoinRequest OnParcelJoinRequest; + event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + + event EstateOwnerMessageRequest OnEstateOwnerMessage; + + LLVector3 StartPos + { + get; + set; + } + + LLUUID AgentId + { + get; + } + + string FirstName + { + get; + } + + string LastName + { + get; + } + + void OutPacket(Packet newPack); + void SendWearables(AvatarWearable[] wearables); + void SendRegionHandshake(RegionInfo regionInfo); + void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID); + void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID); + void SendLayerData(float[] map); + void SendLayerData(int px, int py, float[] map); + void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look); + void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPAddress neighbourIP, ushort neighbourPort); + AgentCircuitData RequestClientInfo(); + void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, System.Net.IPAddress newRegionIP, ushort newRegionPort); + void SendMapBlock(List mapBlocks); + void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags); + void SendRegionTeleport(ulong regionHandle, byte simAccess, string ipAddress, ushort ipPort, uint locationID, uint flags); + void SendTeleportCancel(); + void SendTeleportLocationStart(); + void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance); + + void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry); + void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity); + + void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint); + void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID , uint flags); + void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID, uint flags); + void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation); + } +} diff --git a/OpenSim/Framework/General/Interfaces/ILocalStorage.cs b/OpenSim/Framework/General/Interfaces/ILocalStorage.cs new file mode 100644 index 0000000..4987d10 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/ILocalStorage.cs @@ -0,0 +1,69 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + /// + /// ILocalStorage. Really hacked together right now needs cleaning up + /// + public interface ILocalStorage + { + void Initialise(string datastore); + + void StorePrim(PrimData prim); + void RemovePrim(LLUUID primID); + void LoadPrimitives(ILocalStorageReceiver receiver); + + float[] LoadWorld(); + void SaveMap(float[] heightmap); + + void SaveParcels(ParcelData[] parcels); + void SaveParcel(ParcelData parcel); + void RemoveParcel(ParcelData parcel); + void RemoveAllParcels(); + void LoadParcels(ILocalStorageParcelReceiver recv); + + void ShutDown(); + } + + public interface ILocalStorageReceiver + { + void PrimFromStorage(PrimData prim); + } + + public interface ILocalStorageParcelReceiver + { + void ParcelFromStorage(ParcelData data); + void NoParcelDataFromStorage(); + } +} + diff --git a/OpenSim/Framework/General/Interfaces/IUserServer.cs b/OpenSim/Framework/General/Interfaces/IUserServer.cs new file mode 100644 index 0000000..c6e2223 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/IUserServer.cs @@ -0,0 +1,42 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Inventory; +using libsecondlife; + +namespace OpenSim.Framework.Interfaces +{ + public interface IUserServer + { + AgentInventory RequestAgentsInventory(LLUUID agentID); + void SetServerInfo(string ServerUrl, string SendKey, string RecvKey); + bool UpdateAgentsInventory(LLUUID agentID, AgentInventory inventory); + } +} diff --git a/OpenSim/Framework/General/Interfaces/IWorld.cs b/OpenSim/Framework/General/Interfaces/IWorld.cs new file mode 100644 index 0000000..4857417 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/IWorld.cs @@ -0,0 +1,45 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + public interface IWorld + { + void AddNewClient(IClientAPI remoteClient, LLUUID agentID, bool child); + void RemoveClient(LLUUID agentID); + + RegionInfo RegionInfo { get; } + object SyncRoot { get; } + uint NextLocalId { get; } + } +} diff --git a/OpenSim/Framework/General/Interfaces/Scripting/IScriptAPI.cs b/OpenSim/Framework/General/Interfaces/Scripting/IScriptAPI.cs new file mode 100644 index 0000000..0c1627b --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/Scripting/IScriptAPI.cs @@ -0,0 +1,42 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; + +using libsecondlife; +namespace OpenSim.Framework.Interfaces +{ + public interface IScriptAPI + { + LLVector3 GetEntityPosition(uint localID); + void SetEntityPosition(uint localID, float x, float y, float z); + uint GetRandomAvatarID(); + } +} diff --git a/OpenSim/Framework/General/Interfaces/Scripting/IScriptEngine.cs b/OpenSim/Framework/General/Interfaces/Scripting/IScriptEngine.cs new file mode 100644 index 0000000..ca50be0 --- /dev/null +++ b/OpenSim/Framework/General/Interfaces/Scripting/IScriptEngine.cs @@ -0,0 +1,41 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Interfaces +{ + public interface IScriptEngine + { + bool Init(IScriptAPI api); + string GetName(); + void LoadScript(string script, string scriptName, uint entityID); + void OnFrame(); + } +} diff --git a/OpenSim/Framework/General/LLSDHelpers.cs b/OpenSim/Framework/General/LLSDHelpers.cs new file mode 100644 index 0000000..051520c --- /dev/null +++ b/OpenSim/Framework/General/LLSDHelpers.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Xml; +using libsecondlife; + +namespace OpenSim.Framework +{ + public class LLSDHelpers + { + public static string SerialiseLLSDReply(object obj) + { + StringWriter sw = new StringWriter(); + XmlTextWriter writer = new XmlTextWriter(sw); + writer.Formatting = Formatting.None; + writer.WriteStartElement(String.Empty, "llsd", String.Empty); + LLSDHelpers.SerializeLLSDType(writer, obj); + writer.WriteEndElement(); + writer.Close(); + return sw.ToString(); + } + + public static void SerializeLLSDType(XmlTextWriter writer, object obj) + { + Type myType = obj.GetType(); + LLSDType[] llsdattributes = (LLSDType[])myType.GetCustomAttributes(typeof(LLSDType), false); + if (llsdattributes.Length > 0) + { + switch (llsdattributes[0].ObjectType) + { + case "MAP": + writer.WriteStartElement(String.Empty, "map", String.Empty); + System.Reflection.FieldInfo[] fields = myType.GetFields(); + for (int i = 0; i < fields.Length; i++) + { + object fieldValue = fields[i].GetValue(obj); + LLSDType[] fieldAttributes = (LLSDType[])fieldValue.GetType().GetCustomAttributes(typeof(LLSDType), false); + if (fieldAttributes.Length > 0) + { + writer.WriteStartElement(String.Empty, "key", String.Empty); + writer.WriteString(fields[i].Name); + writer.WriteEndElement(); + SerializeLLSDType(writer, fieldValue); + } + else + { + //Console.WriteLine("LLSD field name" + fields[i].Name + " , " + fields[i].GetValue(obj).GetType()); + writer.WriteStartElement(String.Empty, "key", String.Empty); + writer.WriteString(fields[i].Name); + writer.WriteEndElement(); + LLSD.LLSDWriteOne(writer, fieldValue); + } + } + writer.WriteEndElement(); + break; + case "ARRAY": + // LLSDArray arrayObject = obj as LLSDArray; + // ArrayList a = arrayObject.Array; + ArrayList a = (ArrayList)obj.GetType().GetField("Array").GetValue(obj); + writer.WriteStartElement(String.Empty, "array", String.Empty); + foreach (object item in a) + { + SerializeLLSDType(writer, item); + } + writer.WriteEndElement(); + break; + } + } + else + { + LLSD.LLSDWriteOne(writer, obj); + } + } + + public static object DeserialiseLLSDMap(Hashtable llsd, object obj) + { + Type myType = obj.GetType(); + LLSDType[] llsdattributes = (LLSDType[])myType.GetCustomAttributes(typeof(LLSDType), false); + if (llsdattributes.Length > 0) + { + switch (llsdattributes[0].ObjectType) + { + case "MAP": + IDictionaryEnumerator enumerator = llsd.GetEnumerator(); + while (enumerator.MoveNext()) + { + System.Reflection.FieldInfo field = myType.GetField((string)enumerator.Key); + if (field != null) + { + if (enumerator.Value is Hashtable) + { + object fieldValue = field.GetValue(obj); + DeserialiseLLSDMap((Hashtable) enumerator.Value, fieldValue); + } + else if (enumerator.Value is ArrayList) + { + object fieldValue = field.GetValue(obj); + fieldValue.GetType().GetField("Array").SetValue(fieldValue, enumerator.Value); + //TODO + // the LLSD map/array types in the array need to be deserialised + // but first we need to know the right class to deserialise them into. + } + else + { + field.SetValue(obj, enumerator.Value); + } + } + } + break; + } + } + return obj; + } + } + + [LLSDType("MAP")] + public class LLSDMapLayerResponse + { + public LLSDMapRequest AgentData = new LLSDMapRequest(); + public LLSDArray LayerData = new LLSDArray(); + + public LLSDMapLayerResponse() + { + + } + } + + [LLSDType("MAP")] + public class LLSDCapsDetails + { + public string MapLayer = ""; + public string NewFileAgentInventory = ""; + //public string EventQueueGet = ""; + + public LLSDCapsDetails() + { + + } + } + + [LLSDType("MAP")] + public class LLSDMapLayer + { + public int Left = 0; + public int Right = 0; + public int Top = 0; + public int Bottom = 0; + public LLUUID ImageID = LLUUID.Zero; + + public LLSDMapLayer() + { + + } + } + + [LLSDType("ARRAY")] + public class LLSDArray + { + public ArrayList Array = new ArrayList(); + + public LLSDArray() + { + + } + } + + [LLSDType("MAP")] + public class LLSDMapRequest + { + public int Flags = 0; + + public LLSDMapRequest() + { + + } + } + + [LLSDType("MAP")] + public class LLSDUploadReply + { + public string new_asset = ""; + public LLUUID new_inventory_item = LLUUID.Zero; + public string state = ""; + + public LLSDUploadReply() + { + + } + } + + [LLSDType("MAP")] + public class LLSDCapEvent + { + public int id = 0; + public LLSDArray events = new LLSDArray(); + + public LLSDCapEvent() + { + + } + } + + [LLSDType("MAP")] + public class LLSDEmpty + { + public LLSDEmpty() + { + + } + } + + [LLSDType("MAP")] + public class LLSDTest + { + public int Test1 = 20; + public int Test2 = 10; + + public LLSDTest() + { + + } + } + + + [AttributeUsage(AttributeTargets.Class)] + public class LLSDType : Attribute + { + private string myType; + + public LLSDType(string type) + { + myType = type; + + } + + public string ObjectType + { + get + { + return myType; + } + } + } +} diff --git a/OpenSim/Framework/General/Logger.cs b/OpenSim/Framework/General/Logger.cs new file mode 100644 index 0000000..e7eaa03 --- /dev/null +++ b/OpenSim/Framework/General/Logger.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework +{ + public class Logger + { + public static Logger Instance = new Logger( false ); + + public delegate void LoggerMethodDelegate(); + private delegate bool LoggerDelegate( LoggerMethodDelegate whatToDo ); + + + private LoggerDelegate m_delegate; + + public Logger( bool log ) + { + if( log ) + { + m_delegate = CatchAndLog; + } + else + { + m_delegate = DontCatch; + } + } + + public bool Wrap( LoggerMethodDelegate whatToDo ) + { + return m_delegate( whatToDo ); + } + + + private bool CatchAndLog(LoggerMethodDelegate whatToDo) + { + try + { + whatToDo(); + return true; + } + catch(Exception e) + { + System.Console.WriteLine( "Exception logged!!! Woah!!!!" ); + return false; + } + } + + private bool DontCatch(LoggerMethodDelegate whatToDo) + { + whatToDo(); + return true; + } + + public class LoggerExample + { + public void TryWrap() + { + // This will log and ignore + Logger log = new Logger(true); + + log.Wrap(delegate() + { + Int16.Parse("waa!"); + }); + + // This will throw; + try + { + + log = new Logger(false); + + log.Wrap(delegate() + { + Int16.Parse("waa!"); + }); + } + catch + { + System.Console.WriteLine("Example barfed!"); + } + } + } + } +} diff --git a/OpenSim/Framework/General/LoginService.cs b/OpenSim/Framework/General/LoginService.cs new file mode 100644 index 0000000..f14754f --- /dev/null +++ b/OpenSim/Framework/General/LoginService.cs @@ -0,0 +1,41 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using Nwc.XmlRpc; +using libsecondlife; + +namespace OpenSim.Framework.Grid +{ + public abstract class LoginService + { + + } +} \ No newline at end of file diff --git a/OpenSim/Framework/General/OpenSim.Framework.csproj b/OpenSim/Framework/General/OpenSim.Framework.csproj new file mode 100644 index 0000000..e164d5a --- /dev/null +++ b/OpenSim/Framework/General/OpenSim.Framework.csproj @@ -0,0 +1,213 @@ + + + Local + 8.0.50727 + 2.0 + {8ACA2445-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework + JScript + Grid + IE50 + false + Library + + OpenSim.Framework + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/General/OpenSim.Framework.csproj.user b/OpenSim/Framework/General/OpenSim.Framework.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/General/OpenSim.Framework.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/General/Properties/AssemblyInfo.cs b/OpenSim/Framework/General/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..86f5cdb --- /dev/null +++ b/OpenSim/Framework/General/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.FrameWork")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.FrameWork")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a08e20c7-f191-4137-b1f0-9291408fa521")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/General/RegionCommsListener.cs b/OpenSim/Framework/General/RegionCommsListener.cs new file mode 100644 index 0000000..bba928f --- /dev/null +++ b/OpenSim/Framework/General/RegionCommsListener.cs @@ -0,0 +1,69 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework +{ + public class RegionCommsListener :IRegionCommsListener + { + public event ExpectUserDelegate OnExpectUser; + public event GenericCall2 OnExpectChildAgent; + public event AgentCrossing OnAvatarCrossingIntoRegion; + public event UpdateNeighbours OnNeighboursUpdate; + + /// + /// + /// + /// + /// + public virtual bool TriggerExpectUser(ulong regionHandle, AgentCircuitData agent) + { + if(OnExpectUser != null) + { + OnExpectUser(regionHandle, agent); + return true; + } + + return false; + } + + public virtual bool TriggerExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (OnAvatarCrossingIntoRegion != null) + { + OnAvatarCrossingIntoRegion(regionHandle, agentID, position); + return true; + } + return false; + } + } +} diff --git a/OpenSim/Framework/General/Remoting.cs b/OpenSim/Framework/General/Remoting.cs new file mode 100644 index 0000000..e6fdf70 --- /dev/null +++ b/OpenSim/Framework/General/Remoting.cs @@ -0,0 +1,136 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Security.Cryptography; + +namespace OpenSim.Framework +{ + /// + /// NEEDS AUDIT. + /// + /// + /// Suggested implementation + /// Store two digests for each foreign host. A local copy of the local hash using the local challenge (when issued), and a local copy of the remote hash using the remote challenge. + /// When sending data to the foreign host - run 'Sign' on the data and affix the returned byte[] to the message. + /// When recieving data from the foreign host - run 'Authenticate' against the data and the attached byte[]. + /// Both hosts should be performing these operations for this to be effective. + /// + class RemoteDigest + { + private byte[] currentHash; + private byte[] secret; + + private SHA512Managed SHA512; + + /// + /// Initialises a new RemoteDigest authentication mechanism + /// + /// Needs an audit by a cryptographic professional - was not "roll your own"'d by choice but rather a serious lack of decent authentication mechanisms in .NET remoting + /// The shared secret between systems (for inter-sim, this is provided in encrypted form during connection, for grid this is input manually in setup) + /// Binary salt - some common value - to be decided what + /// The challenge key provided by the third party + public RemoteDigest(string sharedSecret, byte[] salt, string challenge) + { + SHA512 = new SHA512Managed(); + Rfc2898DeriveBytes RFC2898 = new Rfc2898DeriveBytes(sharedSecret,salt); + secret = RFC2898.GetBytes(512); + ASCIIEncoding ASCII = new ASCIIEncoding(); + + currentHash = SHA512.ComputeHash(AppendArrays(secret, ASCII.GetBytes(challenge))); + } + + /// + /// Authenticates a piece of incoming data against the local digest. Upon successful authentication, digest string is incremented. + /// + /// The incoming data + /// The remote digest + /// + public bool Authenticate(byte[] data, byte[] digest) + { + byte[] newHash = SHA512.ComputeHash(AppendArrays(AppendArrays(currentHash, secret), data)); + if (digest == newHash) + { + currentHash = newHash; + return true; + } + else + { + throw new Exception("Hash comparison failed. Key resync required."); + } + } + + /// + /// Signs a new bit of data with the current hash. Returns a byte array which should be affixed to the message. + /// Signing a piece of data will automatically increment the hash - if you sign data and do not send it, the + /// hashes will get out of sync and throw an exception when validation is attempted. + /// + /// The outgoing data + /// The local digest + public byte[] Sign(byte[] data) + { + currentHash = SHA512.ComputeHash(AppendArrays(AppendArrays(currentHash, secret), data)); + return currentHash; + } + + /// + /// Generates a new challenge string to be issued to a foreign host. Challenges are 1024-bit (effective strength of less than 512-bits) messages generated using the Crytographic Random Number Generator. + /// + /// A 128-character hexadecimal string containing the challenge. + public static string GenerateChallenge() + { + RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider(); + byte[] bytes = new byte[64]; + RNG.GetBytes(bytes); + + StringBuilder sb = new StringBuilder(bytes.Length * 2); + foreach (byte b in bytes) + { + sb.AppendFormat("{0:x2}", b); + } + return sb.ToString(); + } + + /// + /// Helper function, merges two byte arrays + /// + /// Sourced from MSDN Forum + /// A + /// B + /// C + private byte[] AppendArrays(byte[] a, byte[] b) + { + byte[] c = new byte[a.Length + b.Length]; + Buffer.BlockCopy(a, 0, c, 0, a.Length); + Buffer.BlockCopy(b, 0, c, a.Length, b.Length); + return c; + } + + } +} diff --git a/OpenSim/Framework/General/SimProfile.cs b/OpenSim/Framework/General/SimProfile.cs new file mode 100644 index 0000000..cfa5e50 --- /dev/null +++ b/OpenSim/Framework/General/SimProfile.cs @@ -0,0 +1,122 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Collections; +using System.Xml; +using System.Text; +using libsecondlife; +using Nwc.XmlRpc; + +namespace OpenSim.Framework.Sims +{ + public class SimProfile + { + public LLUUID UUID; + public ulong regionhandle; + public string regionname; + public string sim_ip; + public uint sim_port; + public string caps_url; + public uint RegionLocX; + public uint RegionLocY; + public string sendkey; + public string recvkey; + public bool online; + + public SimProfile LoadFromGrid(ulong region_handle, string GridURL, string SendKey, string RecvKey) + { + try + { + Hashtable GridReqParams = new Hashtable(); + GridReqParams["region_handle"] = region_handle.ToString(); + GridReqParams["authkey"] = SendKey; + ArrayList SendParams = new ArrayList(); + SendParams.Add(GridReqParams); + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams); + + XmlRpcResponse GridResp = GridReq.Send(GridURL, 3000); + + Hashtable RespData = (Hashtable)GridResp.Value; + this.UUID = new LLUUID((string)RespData["UUID"]); + this.regionhandle = Helpers.UIntsToLong(((uint)Convert.ToUInt32(RespData["region_locx"]) * 256), ((uint)Convert.ToUInt32(RespData["region_locy"]) * 256)); + this.regionname = (string)RespData["regionname"]; + this.sim_ip = (string)RespData["sim_ip"]; + this.sim_port = (uint)Convert.ToUInt16(RespData["sim_port"]); + this.caps_url = "http://" + ((string)RespData["sim_ip"]) + ":" + (string)RespData["sim_port"] + "/"; + this.RegionLocX = (uint)Convert.ToUInt32(RespData["region_locx"]); + this.RegionLocY = (uint)Convert.ToUInt32(RespData["region_locy"]); + this.sendkey = SendKey; + this.recvkey = RecvKey; + } + catch (Exception e) + { + System.Console.WriteLine(e.ToString()); + } + return this; + } + + public SimProfile LoadFromGrid(LLUUID UUID, string GridURL, string SendKey, string RecvKey) + { + try + { + Hashtable GridReqParams = new Hashtable(); + GridReqParams["UUID"] = UUID.ToString(); + GridReqParams["authkey"] = SendKey; + ArrayList SendParams = new ArrayList(); + SendParams.Add(GridReqParams); + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams); + + XmlRpcResponse GridResp = GridReq.Send(GridURL, 3000); + + Hashtable RespData = (Hashtable)GridResp.Value; + this.UUID = new LLUUID((string)RespData["UUID"]); + this.regionhandle = Helpers.UIntsToLong(((uint)Convert.ToUInt32(RespData["region_locx"]) * 256), ((uint)Convert.ToUInt32(RespData["region_locy"]) * 256)); + this.regionname = (string)RespData["regionname"]; + this.sim_ip = (string)RespData["sim_ip"]; + this.sim_port = (uint)Convert.ToUInt16(RespData["sim_port"]); + this.caps_url = "http://" + ((string)RespData["sim_ip"]) + ":" + (string)RespData["sim_port"] + "/"; + this.RegionLocX = (uint)Convert.ToUInt32(RespData["region_locx"]); + this.RegionLocY = (uint)Convert.ToUInt32(RespData["region_locy"]); + this.sendkey = SendKey; + this.recvkey = RecvKey; + } + catch (Exception e) + { + System.Console.WriteLine(e.ToString()); + } + return this; + } + + + public SimProfile() + { + } + } + +} diff --git a/OpenSim/Framework/General/Types/AgentCiruitData.cs b/OpenSim/Framework/General/Types/AgentCiruitData.cs new file mode 100644 index 0000000..a650343 --- /dev/null +++ b/OpenSim/Framework/General/Types/AgentCiruitData.cs @@ -0,0 +1,50 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class AgentCircuitData + { + public AgentCircuitData() { } + public LLUUID AgentID; + public LLUUID SessionID; + public LLUUID SecureSessionID; + public LLVector3 startpos; + public string firstname; + public string lastname; + public uint circuitcode; + public bool child; + public LLUUID InventoryFolder; + public LLUUID BaseFolder; + public string CapsPath = ""; + } +} diff --git a/OpenSim/Framework/General/Types/AgentWearable.cs b/OpenSim/Framework/General/Types/AgentWearable.cs new file mode 100644 index 0000000..4c93da7 --- /dev/null +++ b/OpenSim/Framework/General/Types/AgentWearable.cs @@ -0,0 +1,60 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class AvatarWearable + { + public LLUUID AssetID = new LLUUID("00000000-0000-0000-0000-000000000000"); + public LLUUID ItemID = new LLUUID("00000000-0000-0000-0000-000000000000"); + + public AvatarWearable() + { + + } + + public static AvatarWearable[] DefaultWearables + { + get + { + AvatarWearable[] defaultWearables = new AvatarWearable[13]; //should be 13 of these + for (int i = 0; i < 13; i++) + { + defaultWearables[i] = new AvatarWearable(); + } + defaultWearables[0].AssetID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73"); + defaultWearables[0].ItemID = LLUUID.Random(); + return defaultWearables; + } + } + } +} diff --git a/OpenSim/Framework/General/Types/AssetBase.cs b/OpenSim/Framework/General/Types/AssetBase.cs new file mode 100644 index 0000000..86586a6 --- /dev/null +++ b/OpenSim/Framework/General/Types/AssetBase.cs @@ -0,0 +1,49 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class AssetBase + { + public byte[] Data; + public LLUUID FullID; + public sbyte Type; + public sbyte InvType; + public string Name; + public string Description; + + public AssetBase() + { + + } + } +} diff --git a/OpenSim/Framework/General/Types/AssetLandmark.cs b/OpenSim/Framework/General/Types/AssetLandmark.cs new file mode 100644 index 0000000..8a10b70 --- /dev/null +++ b/OpenSim/Framework/General/Types/AssetLandmark.cs @@ -0,0 +1,61 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class AssetLandmark : AssetBase + { + public int Version; + public LLVector3 Position; + public LLUUID RegionID; + + public AssetLandmark(AssetBase a) + { + this.Data = a.Data; + this.FullID = a.FullID; + this.Type = a.Type; + this.InvType = a.InvType; + this.Name = a.Name; + this.Description = a.Description; + InternData(); + } + + private void InternData() + { + string temp = System.Text.Encoding.UTF8.GetString(Data).Trim(); + string[] parts = temp.Split('\n'); + int.TryParse(parts[0].Substring(17, 1), out Version); + LLUUID.TryParse(parts[1].Substring(10, 36), out RegionID); + LLVector3.TryParse(parts[2].Substring(11, parts[2].Length - 11), out Position); + } + } +} diff --git a/OpenSim/Framework/General/Types/AssetStorage.cs b/OpenSim/Framework/General/Types/AssetStorage.cs new file mode 100644 index 0000000..8cac23a --- /dev/null +++ b/OpenSim/Framework/General/Types/AssetStorage.cs @@ -0,0 +1,50 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class AssetStorage + { + + public AssetStorage() { + } + + public AssetStorage(LLUUID assetUUID) { + UUID=assetUUID; + } + + public byte[] Data; + public sbyte Type; + public string Name; + public LLUUID UUID; + } +} diff --git a/OpenSim/Framework/General/Types/EstateSettings.cs b/OpenSim/Framework/General/Types/EstateSettings.cs new file mode 100644 index 0000000..778c893 --- /dev/null +++ b/OpenSim/Framework/General/Types/EstateSettings.cs @@ -0,0 +1,97 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; + +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class EstateSettings + { + //Settings to this island + public float billableFactor = (float)0.0; + public uint estateID = 0; + public uint parentEstateID = 0; + + public byte maxAgents = 40; + public float objectBonusFactor = (float)1.0; + + public int redirectGridX = 0; //?? + public int redirectGridY = 0; //?? + public libsecondlife.Simulator.RegionFlags regionFlags = libsecondlife.Simulator.RegionFlags.None; //Booleam values of various region settings + public libsecondlife.Simulator.SimAccess simAccess = libsecondlife.Simulator.SimAccess.Mature; //Is sim PG, Mature, etc? Mature by default. + public float sunHour = 0; + + public float terrainRaiseLimit = 0; + public float terrainLowerLimit = 0; + + public bool useFixedSun = false; + public int pricePerMeter = 1; + + public ushort regionWaterHeight = 20; + public bool regionAllowTerraform = true; + + // Region Information + // Low resolution 'base' textures. No longer used. + public LLUUID terrainBase0 = new LLUUID("b8d3965a-ad78-bf43-699b-bff8eca6c975"); // Default + public LLUUID terrainBase1 = new LLUUID("abb783e6-3e93-26c0-248a-247666855da3"); // Default + public LLUUID terrainBase2 = new LLUUID("179cdabd-398a-9b6b-1391-4dc333ba321f"); // Default + public LLUUID terrainBase3 = new LLUUID("beb169c7-11ea-fff2-efe5-0f24dc881df2"); // Default + + // Higher resolution terrain textures + public LLUUID terrainDetail0 = new LLUUID("00000000-0000-0000-0000-000000000000"); + public LLUUID terrainDetail1 = new LLUUID("00000000-0000-0000-0000-000000000000"); + public LLUUID terrainDetail2 = new LLUUID("00000000-0000-0000-0000-000000000000"); + public LLUUID terrainDetail3 = new LLUUID("00000000-0000-0000-0000-000000000000"); + + // First quad - each point is bilinearly interpolated at each meter of terrain + public float terrainStartHeight0 = 10.0f; + public float terrainStartHeight1 = 10.0f; + public float terrainStartHeight2 = 10.0f; + public float terrainStartHeight3 = 10.0f; + + // Second quad - also bilinearly interpolated. + // Terrain texturing is done that: + // 0..3 (0 = base0, 3 = base3) = (terrain[x,y] - start[x,y]) / range[x,y] + public float terrainHeightRange0 = 60.0f; //00 + public float terrainHeightRange1 = 60.0f; //01 + public float terrainHeightRange2 = 60.0f; //10 + public float terrainHeightRange3 = 60.0f; //11 + + // Terrain Default (Must be in F32 Format!) + public string terrainFile = "default.r32"; + public double terrainMultiplier = 60.0; + public float waterHeight = (float)20.0; + + public LLUUID terrainImageID = LLUUID.Zero; // the assetID that is the current Map image for this region + + } +} diff --git a/OpenSim/Framework/General/Types/Login.cs b/OpenSim/Framework/General/Types/Login.cs new file mode 100644 index 0000000..3180a16 --- /dev/null +++ b/OpenSim/Framework/General/Types/Login.cs @@ -0,0 +1,52 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class Login + { + public string First = "Test"; + public string Last = "User"; + public LLUUID Agent; + public LLUUID Session; + public LLUUID SecureSession = LLUUID.Zero; + public LLUUID InventoryFolder; + public LLUUID BaseFolder; + public uint CircuitCode; + public string CapsPath =""; + + public Login() + { + + } + } +} diff --git a/OpenSim/Framework/General/Types/MapBlockData.cs b/OpenSim/Framework/General/Types/MapBlockData.cs new file mode 100644 index 0000000..2e6f56e --- /dev/null +++ b/OpenSim/Framework/General/Types/MapBlockData.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class MapBlockData + { + public uint Flags; + public ushort X; + public ushort Y; + public byte Agents; + public byte Access; + public byte WaterHeight; + public LLUUID MapImageId; + public String Name; + public uint RegionFlags; + + public MapBlockData() + { + + } + } +} diff --git a/OpenSim/Framework/General/Types/NeighbourInfo.cs b/OpenSim/Framework/General/Types/NeighbourInfo.cs new file mode 100644 index 0000000..310fd1c --- /dev/null +++ b/OpenSim/Framework/General/Types/NeighbourInfo.cs @@ -0,0 +1,50 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Console; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class NeighbourInfo + { + public NeighbourInfo() + { + } + + public ulong regionhandle; + public uint RegionLocX; + public uint RegionLocY; + public string sim_ip; + public uint sim_port; + } +} diff --git a/OpenSim/Framework/General/Types/NetworkServersInfo.cs b/OpenSim/Framework/General/Types/NetworkServersInfo.cs new file mode 100644 index 0000000..73d7811 --- /dev/null +++ b/OpenSim/Framework/General/Types/NetworkServersInfo.cs @@ -0,0 +1,181 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Framework.Types +{ + public class NetworkServersInfo + { + public string AssetURL = "http://127.0.0.1:8003/"; + public string AssetSendKey = ""; + + public string GridURL = ""; + public string GridSendKey = ""; + public string GridRecvKey = ""; + public string UserURL = ""; + public string UserSendKey = ""; + public string UserRecvKey = ""; + public bool isSandbox; + + public uint DefaultHomeLocX = 0; + public uint DefaultHomeLocY = 0; + + public int HttpListenerPort = 9000; + public int RemotingListenerPort = 8895; + + public void InitConfig(bool sandboxMode, IGenericConfig configData) + { + this.isSandbox = sandboxMode; + + try + { + string attri = ""; + + attri = ""; + attri = configData.GetAttribute("HttpListenerPort"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Http Listener Port", "9000"); + configData.SetAttribute("HttpListenerPort", location); + this.HttpListenerPort = Convert.ToInt32(location); + } + else + { + this.HttpListenerPort = Convert.ToInt32(attri); + } + + attri = ""; + attri = configData.GetAttribute("RemotingListenerPort"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Remoting Listener Port", "8895"); + configData.SetAttribute("RemotingListenerPort", location); + this.RemotingListenerPort = Convert.ToInt32(location); + } + else + { + this.RemotingListenerPort = Convert.ToInt32(attri); + } + + if (sandboxMode) + { + // default home location X + attri = ""; + attri = configData.GetAttribute("DefaultLocationX"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Default Home Location X", "1000"); + configData.SetAttribute("DefaultLocationX", location); + this.DefaultHomeLocX = (uint)Convert.ToUInt32(location); + } + else + { + this.DefaultHomeLocX = (uint)Convert.ToUInt32(attri); + } + + // default home location Y + attri = ""; + attri = configData.GetAttribute("DefaultLocationY"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Default Home Location Y", "1000"); + configData.SetAttribute("DefaultLocationY", location); + this.DefaultHomeLocY = (uint)Convert.ToUInt32(location); + } + else + { + this.DefaultHomeLocY = (uint)Convert.ToUInt32(attri); + } + } + if (!isSandbox) + { + //Grid Server + attri = ""; + attri = configData.GetAttribute("GridServerURL"); + if (attri == "") + { + this.GridURL = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Grid server URL", "http://127.0.0.1:8001/"); + configData.SetAttribute("GridServerURL", this.GridURL); + } + else + { + this.GridURL = attri; + } + + //Grid Send Key + attri = ""; + attri = configData.GetAttribute("GridSendKey"); + if (attri == "") + { + this.GridSendKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to send to grid server", "null"); + configData.SetAttribute("GridSendKey", this.GridSendKey); + } + else + { + this.GridSendKey = attri; + } + + //Grid Receive Key + attri = ""; + attri = configData.GetAttribute("GridRecvKey"); + if (attri == "") + { + this.GridRecvKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to expect from grid server", "null"); + configData.SetAttribute("GridRecvKey", this.GridRecvKey); + } + else + { + this.GridRecvKey = attri; + } + + attri = ""; + attri = configData.GetAttribute("AssetServerURL"); + if (attri == "") + { + this.AssetURL = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Asset server URL", "http://127.0.0.1:8003/"); + configData.SetAttribute("AssetServerURL", this.GridURL); + } + else + { + this.AssetURL = attri; + } + + } + configData.Commit(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + } + } +} diff --git a/OpenSim/Framework/General/Types/ParcelData.cs b/OpenSim/Framework/General/Types/ParcelData.cs new file mode 100644 index 0000000..40f128a --- /dev/null +++ b/OpenSim/Framework/General/Types/ParcelData.cs @@ -0,0 +1,115 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + + public class ParcelData + { + public byte[] parcelBitmapByteArray = new byte[512]; + public string parcelName = ""; + public string parcelDesc = ""; + public LLUUID ownerID = new LLUUID(); + public bool isGroupOwned = false; + public LLVector3 AABBMin = new LLVector3(); + public LLVector3 AABBMax = new LLVector3(); + public int area = 0; + public uint auctionID = 0; //Unemplemented. If set to 0, not being auctioned + public LLUUID authBuyerID = new LLUUID(); //Unemplemented. Authorized Buyer's UUID + public libsecondlife.Parcel.ParcelCategory category = new libsecondlife.Parcel.ParcelCategory(); //Unemplemented. Parcel's chosen category + public int claimDate = 0; //Unemplemented + public int claimPrice = 0; //Unemplemented + public LLUUID groupID = new LLUUID(); //Unemplemented + public int groupPrims = 0; //Unemplemented + public int salePrice = 0; //Unemeplemented. Parcels price. + public libsecondlife.Parcel.ParcelStatus parcelStatus = libsecondlife.Parcel.ParcelStatus.None; + public libsecondlife.Parcel.ParcelFlags parcelFlags = libsecondlife.Parcel.ParcelFlags.None; + public byte landingType = 0; + public byte mediaAutoScale = 0; + public LLUUID mediaID = LLUUID.Zero; + public int localID = 0; + public LLUUID globalID = new LLUUID(); + + public string mediaURL = ""; + public string musicURL = ""; + public float passHours = 0; + public int passPrice = 0; + public LLUUID snapshotID = LLUUID.Zero; + public LLVector3 userLocation = new LLVector3(); + public LLVector3 userLookAt = new LLVector3(); + + public ParcelData() + { + globalID = LLUUID.Random(); + } + + public ParcelData Copy() + { + ParcelData parcelData = new ParcelData(); + + parcelData.AABBMax = this.AABBMax; + parcelData.AABBMin = this.AABBMin; + parcelData.area = this.area; + parcelData.auctionID = this.auctionID; + parcelData.authBuyerID = this.authBuyerID; + parcelData.category = this.category; + parcelData.claimDate = this.claimDate; + parcelData.claimPrice = this.claimPrice; + parcelData.globalID = this.globalID; + parcelData.groupID = this.groupID; + parcelData.groupPrims = this.groupPrims; + parcelData.isGroupOwned = this.isGroupOwned; + parcelData.localID = this.localID; + parcelData.landingType = this.landingType; + parcelData.mediaAutoScale = this.mediaAutoScale; + parcelData.mediaID = this.mediaID; + parcelData.mediaURL = this.mediaURL; + parcelData.musicURL = this.musicURL; + parcelData.ownerID = this.ownerID; + parcelData.parcelBitmapByteArray = (byte[])this.parcelBitmapByteArray.Clone(); + parcelData.parcelDesc = this.parcelDesc; + parcelData.parcelFlags = this.parcelFlags; + parcelData.parcelName = this.parcelName; + parcelData.parcelStatus = this.parcelStatus; + parcelData.passHours = this.passHours; + parcelData.passPrice = this.passPrice; + parcelData.salePrice = this.salePrice; + parcelData.snapshotID = this.snapshotID; + parcelData.userLocation = this.userLocation; + parcelData.userLookAt = this.userLookAt; + + return parcelData; + + } + } + +} diff --git a/OpenSim/Framework/General/Types/PrimData.cs b/OpenSim/Framework/General/Types/PrimData.cs new file mode 100644 index 0000000..f84ae3e --- /dev/null +++ b/OpenSim/Framework/General/Types/PrimData.cs @@ -0,0 +1,230 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class PrimData + { + private const uint FULL_MASK_PERMISSIONS = 2147483647; + + public LLUUID OwnerID; + public byte PCode; + public ushort PathBegin; + public ushort PathEnd; + public byte PathScaleX; + public byte PathScaleY; + public byte PathShearX; + public byte PathShearY; + public sbyte PathSkew; + public ushort ProfileBegin; + public ushort ProfileEnd; + public LLVector3 Scale; + public byte PathCurve; + public byte ProfileCurve; + public uint ParentID = 0; + public ushort ProfileHollow; + public sbyte PathRadiusOffset; + public byte PathRevolutions; + public sbyte PathTaperX; + public sbyte PathTaperY; + public sbyte PathTwist; + public sbyte PathTwistBegin; + public byte[] TextureEntry; // a LL textureEntry in byte[] format + + public Int32 CreationDate; + public uint OwnerMask = FULL_MASK_PERMISSIONS; + public uint NextOwnerMask = FULL_MASK_PERMISSIONS; + public uint GroupMask = FULL_MASK_PERMISSIONS; + public uint EveryoneMask = FULL_MASK_PERMISSIONS; + public uint BaseMask = FULL_MASK_PERMISSIONS; + + //following only used during prim storage + public LLVector3 Position; + public LLQuaternion Rotation = new LLQuaternion(0, 1, 0, 0); + public uint LocalID; + public LLUUID FullID; + + public PrimData() + { + + } + + public PrimData(byte[] data) + { + int i = 0; + + this.OwnerID = new LLUUID(data, i); i += 16; + this.PCode = data[i++]; + this.PathBegin = (ushort)(data[i++] + (data[i++] << 8)); + this.PathEnd = (ushort)(data[i++] + (data[i++] << 8)); + this.PathScaleX = data[i++]; + this.PathScaleY = data[i++]; + this.PathShearX = data[i++]; + this.PathShearY = data[i++]; + this.PathSkew = (sbyte)data[i++]; + this.ProfileBegin = (ushort)(data[i++] + (data[i++] << 8)); + this.ProfileEnd = (ushort)(data[i++] + (data[i++] << 8)); + this.Scale = new LLVector3(data, i); i += 12; + this.PathCurve = data[i++]; + this.ProfileCurve = data[i++]; + this.ParentID = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.ProfileHollow = (ushort)(data[i++] + (data[i++] << 8)); + this.PathRadiusOffset = (sbyte)data[i++]; + this.PathRevolutions = data[i++]; + this.PathTaperX = (sbyte)data[i++]; + this.PathTaperY = (sbyte)data[i++]; + this.PathTwist = (sbyte)data[i++]; + this.PathTwistBegin = (sbyte)data[i++]; + ushort length = (ushort)(data[i++] + (data[i++] << 8)); + this.TextureEntry = new byte[length]; + Array.Copy(data, i, TextureEntry, 0, length); i += length; + this.CreationDate = (Int32)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.OwnerMask = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.NextOwnerMask = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.GroupMask = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.EveryoneMask = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.BaseMask = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.Position = new LLVector3(data, i); i += 12; + this.Rotation = new LLQuaternion(data, i, true); i += 12; + this.LocalID = (uint)(data[i++] + (data[i++] << 8) + (data[i++] << 16) + (data[i++] << 24)); + this.FullID = new LLUUID(data, i); i += 16; + + } + + public byte[] ToBytes() + { + int i = 0; + byte[] bytes = new byte[126 + TextureEntry.Length]; + Array.Copy(OwnerID.GetBytes(), 0, bytes, i, 16); i += 16; + bytes[i++] = this.PCode; + bytes[i++] = (byte)(this.PathBegin % 256); + bytes[i++] = (byte)((this.PathBegin >> 8) % 256); + bytes[i++] = (byte)(this.PathEnd % 256); + bytes[i++] = (byte)((this.PathEnd >> 8) % 256); + bytes[i++] = this.PathScaleX; + bytes[i++] = this.PathScaleY; + bytes[i++] = this.PathShearX; + bytes[i++] = this.PathShearY; + bytes[i++] = (byte)this.PathSkew; + bytes[i++] = (byte)(this.ProfileBegin % 256); + bytes[i++] = (byte)((this.ProfileBegin >> 8) % 256); + bytes[i++] = (byte)(this.ProfileEnd % 256); + bytes[i++] = (byte)((this.ProfileEnd >> 8) % 256); + Array.Copy(Scale.GetBytes(), 0, bytes, i, 12); i += 12; + bytes[i++] = this.PathCurve; + bytes[i++] = this.ProfileCurve; + bytes[i++] = (byte)(ParentID % 256); + bytes[i++] = (byte)((ParentID >> 8) % 256); + bytes[i++] = (byte)((ParentID >> 16) % 256); + bytes[i++] = (byte)((ParentID >> 24) % 256); + bytes[i++] = (byte)(this.ProfileHollow % 256); + bytes[i++] = (byte)((this.ProfileHollow >> 8) % 256); + bytes[i++] = ((byte)this.PathRadiusOffset); + bytes[i++] = this.PathRevolutions; + bytes[i++] = ((byte)this.PathTaperX); + bytes[i++] = ((byte)this.PathTaperY); + bytes[i++] = ((byte)this.PathTwist); + bytes[i++] = ((byte)this.PathTwistBegin); + bytes[i++] = (byte)(TextureEntry.Length % 256); + bytes[i++] = (byte)((TextureEntry.Length >> 8) % 256); + Array.Copy(TextureEntry, 0, bytes, i, TextureEntry.Length); i += TextureEntry.Length; + bytes[i++] = (byte)(this.CreationDate % 256); + bytes[i++] = (byte)((this.CreationDate >> 8) % 256); + bytes[i++] = (byte)((this.CreationDate >> 16) % 256); + bytes[i++] = (byte)((this.CreationDate >> 24) % 256); + bytes[i++] = (byte)(this.OwnerMask % 256); + bytes[i++] = (byte)((this.OwnerMask >> 8) % 256); + bytes[i++] = (byte)((this.OwnerMask >> 16) % 256); + bytes[i++] = (byte)((this.OwnerMask >> 24) % 256); + bytes[i++] = (byte)(this.NextOwnerMask % 256); + bytes[i++] = (byte)((this.NextOwnerMask >> 8) % 256); + bytes[i++] = (byte)((this.NextOwnerMask >> 16) % 256); + bytes[i++] = (byte)((this.NextOwnerMask >> 24) % 256); + bytes[i++] = (byte)(this.GroupMask % 256); + bytes[i++] = (byte)((this.GroupMask >> 8) % 256); + bytes[i++] = (byte)((this.GroupMask >> 16) % 256); + bytes[i++] = (byte)((this.GroupMask >> 24) % 256); + bytes[i++] = (byte)(this.EveryoneMask % 256); + bytes[i++] = (byte)((this.EveryoneMask >> 8) % 256); + bytes[i++] = (byte)((this.EveryoneMask >> 16) % 256); + bytes[i++] = (byte)((this.EveryoneMask >> 24) % 256); + bytes[i++] = (byte)(this.BaseMask % 256); + bytes[i++] = (byte)((this.BaseMask >> 8) % 256); + bytes[i++] = (byte)((this.BaseMask >> 16) % 256); + bytes[i++] = (byte)((this.BaseMask >> 24) % 256); + Array.Copy(this.Position.GetBytes(), 0, bytes, i, 12); i += 12; + if (this.Rotation == new LLQuaternion(0, 0, 0, 0)) + { + this.Rotation = new LLQuaternion(0, 1, 0, 0); + } + Array.Copy(this.Rotation.GetBytes(), 0, bytes, i, 12); i += 12; + bytes[i++] = (byte)(this.LocalID % 256); + bytes[i++] = (byte)((this.LocalID >> 8) % 256); + bytes[i++] = (byte)((this.LocalID >> 16) % 256); + bytes[i++] = (byte)((this.LocalID >> 24) % 256); + Array.Copy(FullID.GetBytes(), 0, bytes, i, 16); i += 16; + + return bytes; + } + + public static PrimData DefaultCube() + { + PrimData primData = new PrimData(); + primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + primData.FullID = LLUUID.Random(); + primData.Scale = new LLVector3(0.5f, 0.5f, 0.5f); + primData.Rotation = new LLQuaternion(0, 0, 0, 1); + primData.PCode = 9; + primData.ParentID = 0; + primData.PathBegin = 0; + primData.PathEnd = 0; + primData.PathScaleX = 0; + primData.PathScaleY = 0; + primData.PathShearX = 0; + primData.PathShearY = 0; + primData.PathSkew = 0; + primData.ProfileBegin = 0; + primData.ProfileEnd = 0; + primData.PathCurve = 16; + primData.ProfileCurve = 1; + primData.ProfileHollow = 0; + primData.PathRadiusOffset = 0; + primData.PathRevolutions = 0; + primData.PathTaperX = 0; + primData.PathTaperY = 0; + primData.PathTwist = 0; + primData.PathTwistBegin = 0; + + return primData; + } + } +} diff --git a/OpenSim/Framework/General/Types/RegionHandle.cs b/OpenSim/Framework/General/Types/RegionHandle.cs new file mode 100644 index 0000000..1271d04 --- /dev/null +++ b/OpenSim/Framework/General/Types/RegionHandle.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; + +namespace OpenSim.Framework.Types +{ + /// + /// A class for manipulating RegionHandle coordinates + /// + class RegionHandle + { + private UInt64 handle; + + /// + /// Initialises a new grid-aware RegionHandle + /// + /// IP Address of the Grid Server for this region + /// Grid X Coordinate + /// Grid Y Coordinate + public RegionHandle(string ip, short x, short y) + { + IPAddress addr = IPAddress.Parse(ip); + + long baseHandle = addr.Address; + + // Split the IP address in half + short a = (short)((baseHandle << 16) & 0xFFFF); + short b = (short)((baseHandle << 0) & 0xFFFF); + + // Raise the bounds a little + uint nx = (uint)x; + uint ny = (uint)y; + + // Multiply grid coords to get region coords + nx *= 256; + ny *= 256; + + // Stuff the IP address in too + nx = (uint)a << 16; + ny = (uint)b << 16; + + handle = ((UInt64)nx << 32) | (uint)ny; + } + + /// + /// Initialises a new RegionHandle that is not inter-grid aware + /// + /// Grid X Coordinate + /// Grid Y Coordinate + public RegionHandle(uint x, uint y) + { + handle = ((x * 256) << 32) | (y * 256); + } + + /// + /// Initialises a new RegionHandle from an existing value + /// + /// A U64 RegionHandle + public RegionHandle(UInt64 Region) + { + handle = Region; + } + + /// + /// Returns the Grid Masked RegionHandle - For use in Teleport packets and other packets where sending the grid IP address may be handy. + /// + /// Do not use for SimulatorEnable packets. The client will choke. + /// Region Handle including IP Address encoding + public UInt64 getTeleportHandle() + { + return handle; + } + + /// + /// Returns a RegionHandle which may be used for SimulatorEnable packets. Removes the IP address encoding and returns the lower bounds. + /// + /// A U64 RegionHandle for use in SimulatorEnable packets. + public UInt64 getNeighbourHandle() + { + UInt64 mask = 0x0000FFFF0000FFFF; + + return handle | mask; + } + + /// + /// Returns the IP Address of the GridServer from a Grid-Encoded RegionHandle + /// + /// Grid Server IP Address + public IPAddress getGridIP() + { + uint a = (uint)((handle >> 16) & 0xFFFF); + uint b = (uint)((handle >> 48) & 0xFFFF); + + return new IPAddress((long)(a << 16) | (long)b); + } + + /// + /// Returns the X Coordinate from a Grid-Encoded RegionHandle + /// + /// X Coordinate + public uint getGridX() + { + uint x = (uint)((handle >> 32) & 0xFFFF); + + return x; + } + + /// + /// Returns the Y Coordinate from a Grid-Encoded RegionHandle + /// + /// Y Coordinate + public uint getGridY() + { + uint y = (uint)((handle >> 0) & 0xFFFF); + + return y; + } + } +} diff --git a/OpenSim/Framework/General/Types/RegionInfo.cs b/OpenSim/Framework/General/Types/RegionInfo.cs new file mode 100644 index 0000000..48e6922 --- /dev/null +++ b/OpenSim/Framework/General/Types/RegionInfo.cs @@ -0,0 +1,304 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Globalization; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Console; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + public class RegionInfo + { + public LLUUID SimUUID = new LLUUID(); + public string RegionName = ""; + public uint RegionLocX = 0; + public uint RegionLocY = 0; + public ulong RegionHandle = 0; + + public string DataStore = ""; + public bool isSandbox = false; + + public LLUUID MasterAvatarAssignedUUID = new LLUUID(); + public string MasterAvatarFirstName = ""; + public string MasterAvatarLastName = ""; + public string MasterAvatarSandboxPassword = ""; + + /// + /// Port used for listening (TCP and UDP) + /// + /// Seperate TCP and UDP + public int CommsIPListenPort = 0; + /// + /// Address used for internal listening (default: 0.0.0.0?) + /// + public string CommsIPListenAddr = ""; + /// + /// Address used for external addressing (DNS or IP) + /// + public string CommsExternalAddress = ""; + + + public EstateSettings estateSettings; + + public RegionInfo() + { + estateSettings = new EstateSettings(); + } + + + public void InitConfig(bool sandboxMode, IGenericConfig configData) + { + this.isSandbox = sandboxMode; + try + { + // Sim UUID + string attri = ""; + attri = configData.GetAttribute("SimUUID"); + if (attri == "") + { + this.SimUUID = LLUUID.Random(); + configData.SetAttribute("SimUUID", this.SimUUID.ToString()); + } + else + { + this.SimUUID = new LLUUID(attri); + } + + // Sim name + attri = ""; + attri = configData.GetAttribute("SimName"); + if (attri == "") + { + this.RegionName = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Name", "OpenSim test"); + configData.SetAttribute("SimName", this.RegionName); + } + else + { + this.RegionName = attri; + } + // Sim/Grid location X + attri = ""; + attri = configData.GetAttribute("SimLocationX"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Grid Location X", "997"); + configData.SetAttribute("SimLocationX", location); + this.RegionLocX = (uint)Convert.ToUInt32(location); + } + else + { + this.RegionLocX = (uint)Convert.ToUInt32(attri); + } + // Sim/Grid location Y + attri = ""; + attri = configData.GetAttribute("SimLocationY"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Grid Location Y", "996"); + configData.SetAttribute("SimLocationY", location); + this.RegionLocY = (uint)Convert.ToUInt32(location); + } + else + { + this.RegionLocY = (uint)Convert.ToUInt32(attri); + } + + // Local storage datastore + attri = ""; + attri = configData.GetAttribute("Datastore"); + if (attri == "") + { + string datastore = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Filename for local storage", "localworld.yap"); + configData.SetAttribute("Datastore", datastore); + this.DataStore = datastore; + } + else + { + this.DataStore = attri; + } + + //Sim Listen Port + attri = ""; + attri = configData.GetAttribute("SimListenPort"); + if (attri == "") + { + string port = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("UDP port for client connections", "9000"); + configData.SetAttribute("SimListenPort", port); + this.CommsIPListenPort = Convert.ToInt32(port); + } + else + { + this.CommsIPListenPort = Convert.ToInt32(attri); + } + + //Sim Listen Address + attri = ""; + attri = configData.GetAttribute("SimListenAddress"); + if (attri == "") + { + this.CommsIPListenAddr = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("IP Address to listen on for client connections", "0.0.0.0"); + configData.SetAttribute("SimListenAddress", this.CommsIPListenAddr); + } + else + { + // Probably belongs elsewhere, but oh well. + if (attri.Trim().StartsWith("SYSTEMIP")) + { + string localhostname = System.Net.Dns.GetHostName(); + System.Net.IPAddress[] ips = System.Net.Dns.GetHostAddresses(localhostname); + try + { + this.CommsIPListenAddr = "0.0.0.0"; // Incase a IPv4 address isnt found + + foreach (System.Net.IPAddress ip in ips) + { + if (ip.AddressFamily.ToString() == System.Net.Sockets.ProtocolFamily.InterNetwork.ToString()) + { + this.CommsIPListenAddr = ip.ToString(); + break; + } + } + } + catch (Exception e) + { + e.ToString(); + this.CommsIPListenAddr = "0.0.0.0"; // Use the default if we fail + } + } + else + { + this.CommsIPListenAddr = attri; + } + } + + // Sim External Address + attri = ""; + attri = configData.GetAttribute("SimExternalAddress"); + if (attri == "") + { + this.CommsExternalAddress = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("IP or DNS address to send external clients to", "localhost"); + configData.SetAttribute("SimExternalAddress", this.CommsExternalAddress); + } + else + { + this.CommsExternalAddress = attri; + } + + attri = ""; + attri = configData.GetAttribute("TerrainFile"); + if (attri == "") + { + this.estateSettings.terrainFile = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("GENERAL SETTING: Default Terrain File", "default.r32"); + configData.SetAttribute("TerrainFile", this.estateSettings.terrainFile); + } + else + { + this.estateSettings.terrainFile = attri; + } + + attri = ""; + attri = configData.GetAttribute("TerrainMultiplier"); + if (attri == "") + { + string re = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("GENERAL SETTING: Terrain Height Multiplier", "60.0"); + this.estateSettings.terrainMultiplier = Convert.ToDouble(re, CultureInfo.InvariantCulture); + configData.SetAttribute("TerrainMultiplier", this.estateSettings.terrainMultiplier.ToString()); + } + else + { + this.estateSettings.terrainMultiplier = Convert.ToDouble(attri); + } + + attri = ""; + attri = configData.GetAttribute("MasterAvatarFirstName"); + if (attri == "") + { + this.MasterAvatarFirstName = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("First name of Master Avatar (Land and Region Owner)", "Test"); + + configData.SetAttribute("MasterAvatarFirstName", this.MasterAvatarFirstName); + } + else + { + this.MasterAvatarFirstName = attri; + } + + attri = ""; + attri = configData.GetAttribute("MasterAvatarLastName"); + if (attri == "") + { + this.MasterAvatarLastName = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Last name of Master Avatar (Land and Region Owner)", "User"); + + configData.SetAttribute("MasterAvatarLastName", this.MasterAvatarLastName); + } + else + { + this.MasterAvatarLastName = attri; + } + + if (isSandbox) //Sandbox Mode Specific Settings + { + attri = ""; + attri = configData.GetAttribute("MasterAvatarSandboxPassword"); + if (attri == "") + { + this.MasterAvatarSandboxPassword = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Password of Master Avatar (Needed for sandbox mode account creation only)", "test"); + + //Should I store this? + configData.SetAttribute("MasterAvatarSandboxPassword", this.MasterAvatarSandboxPassword); + } + else + { + this.MasterAvatarSandboxPassword = attri; + } + } + + this.RegionHandle = Util.UIntsToLong((RegionLocX * 256), (RegionLocY * 256)); + + configData.Commit(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + + OpenSim.Framework.Console.MainLog.Instance.Verbose("Sim settings loaded:"); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "UUID: " + this.SimUUID.ToStringHyphenated()); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Name: " + this.RegionName); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Region Location: [" + this.RegionLocX.ToString() + "," + this.RegionLocY + "]"); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Region Handle: " + this.RegionHandle.ToString()); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Listening on IP: " + this.CommsIPListenAddr + ":" + this.CommsIPListenPort); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Sandbox Mode? " + isSandbox.ToString()); + + } + } +} diff --git a/OpenSim/Framework/General/UserProfile.cs b/OpenSim/Framework/General/UserProfile.cs new file mode 100644 index 0000000..04ff20b --- /dev/null +++ b/OpenSim/Framework/General/UserProfile.cs @@ -0,0 +1,89 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Inventory; +using System.Security.Cryptography; + +namespace OpenSim.Framework.User +{ + public class UserProfile + { + + public string firstname; + public string lastname; + public ulong homeregionhandle; + public LLVector3 homepos; + public LLVector3 homelookat; + + public bool IsGridGod = false; + public bool IsLocal = true; // will be used in future for visitors from foreign grids + public string AssetURL; + public string MD5passwd; + + public LLUUID CurrentSessionID; + public LLUUID CurrentSecureSessionID; + public LLUUID UUID; + public Dictionary Circuits = new Dictionary(); // tracks circuit codes + + public AgentInventory Inventory; + + public UserProfile() + { + Circuits = new Dictionary(); + Inventory = new AgentInventory(); + homeregionhandle = Helpers.UIntsToLong((997 * 256), (996 * 256)); + homepos = new LLVector3(); + homelookat = new LLVector3(); + } + + public void InitSessionData() + { + RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); + + byte[] randDataS = new byte[16]; + byte[] randDataSS = new byte[16]; + + rand.GetBytes(randDataS); + rand.GetBytes(randDataSS); + + CurrentSecureSessionID = new LLUUID(randDataSS,0); + CurrentSessionID = new LLUUID(randDataS,0); + + } + + public void AddSimCircuit(uint circuitCode, LLUUID regionUUID) + { + if (this.Circuits.ContainsKey(regionUUID) == false) + this.Circuits.Add(regionUUID, circuitCode); + } + + } +} diff --git a/OpenSim/Framework/General/Util.cs b/OpenSim/Framework/General/Util.cs new file mode 100644 index 0000000..8c34c9b --- /dev/null +++ b/OpenSim/Framework/General/Util.cs @@ -0,0 +1,186 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Security.Cryptography; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim.Framework.Utilities +{ + public class Util + { + private static Random randomClass = new Random(); + private static uint nextXferID = 5000; + private static object XferLock = new object(); + + public static ulong UIntsToLong(uint X, uint Y) + { + return Helpers.UIntsToLong(X, Y); + } + + public static Random RandomClass + { + get + { + return randomClass; + } + } + + public static uint GetNextXferID() + { + uint id = 0; + lock(XferLock) + { + id = nextXferID; + nextXferID++; + } + return id; + } + + public static int UnixTimeSinceEpoch() + { + TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); + int timestamp = (int)t.TotalSeconds; + return timestamp; + } + + public static string Md5Hash(string pass) + { + MD5 md5 = MD5CryptoServiceProvider.Create(); + byte[] dataMd5 = md5.ComputeHash(Encoding.Default.GetBytes(pass)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < dataMd5.Length; i++) + sb.AppendFormat("{0:x2}", dataMd5[i]); + return sb.ToString(); + } + + public static string GetRandomCapsPath() + { + LLUUID caps = LLUUID.Random(); + string capsPath = caps.ToStringHyphenated(); + capsPath = capsPath.Remove(capsPath.Length - 4, 4); + return capsPath; + } + + //public static int fast_distance2d(int x, int y) + //{ + // x = System.Math.Abs(x); + // y = System.Math.Abs(y); + + // int min = System.Math.Min(x, y); + + // return (x + y - (min >> 1) - (min >> 2) + (min >> 4)); + //} + + public static string FieldToString(byte[] bytes) + { + return FieldToString(bytes, String.Empty); + } + + /// + /// Convert a variable length field (byte array) to a string, with a + /// field name prepended to each line of the output + /// + /// If the byte array has unprintable characters in it, a + /// hex dump will be put in the string instead + /// The byte array to convert to a string + /// A field name to prepend to each line of output + /// An ASCII string or a string containing a hex dump, minus + /// the null terminator + public static string FieldToString(byte[] bytes, string fieldName) + { + // Check for a common case + if (bytes.Length == 0) return String.Empty; + + StringBuilder output = new StringBuilder(); + bool printable = true; + + for (int i = 0; i < bytes.Length; ++i) + { + // Check if there are any unprintable characters in the array + if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 + && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) + { + printable = false; + break; + } + } + + if (printable) + { + if (fieldName.Length > 0) + { + output.Append(fieldName); + output.Append(": "); + } + + if (bytes[bytes.Length - 1] == 0x00) + output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)); + else + output.Append(UTF8Encoding.UTF8.GetString(bytes)); + } + else + { + for (int i = 0; i < bytes.Length; i += 16) + { + if (i != 0) + output.Append(Environment.NewLine); + if (fieldName.Length > 0) + { + output.Append(fieldName); + output.Append(": "); + } + + for (int j = 0; j < 16; j++) + { + if ((i + j) < bytes.Length) + output.Append(String.Format("{0:X2} ", bytes[i + j])); + else + output.Append(" "); + } + + for (int j = 0; j < 16 && (i + j) < bytes.Length; j++) + { + if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E) + output.Append((char)bytes[i + j]); + else + output.Append("."); + } + } + } + + return output.ToString(); + } + public Util() + { + + } + } +} diff --git a/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj b/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj new file mode 100644 index 0000000..aae8cd2 --- /dev/null +++ b/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj @@ -0,0 +1,93 @@ + + + Local + 8.0.50727 + 2.0 + {C74E4A30-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.GenericConfig.Xml + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.GenericConfig.Xml + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj.user b/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/GenericConfig/Xml/OpenSim.Framework.GenericConfig.Xml.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs b/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..de5f48d --- /dev/null +++ b/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.GenericConfig")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.GenericConfig")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("285a3047-f165-46c8-8767-b51428738a09")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs b/OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs new file mode 100644 index 0000000..c526aec --- /dev/null +++ b/OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs @@ -0,0 +1,123 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Xml; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.GenericConfig +{ + public class XmlConfig : IGenericConfig + { + private XmlDocument doc; + private XmlNode rootNode; + private XmlNode configNode; + private string fileName; + private bool createdFile = false; + + public XmlConfig(string filename) + { + fileName = filename; + } + + public void LoadData() + { + doc = new XmlDocument(); + + if (System.IO.File.Exists(fileName)) + { + XmlTextReader reader = new XmlTextReader(fileName); + reader.WhitespaceHandling = WhitespaceHandling.None; + doc.Load(reader); + reader.Close(); + } + else + { + createdFile = true; + rootNode = doc.CreateNode(XmlNodeType.Element, "Root", ""); + doc.AppendChild(rootNode); + configNode = doc.CreateNode(XmlNodeType.Element, "Config", ""); + rootNode.AppendChild(configNode); + } + + + rootNode = doc.FirstChild; + if (rootNode.Name != "Root") + throw new Exception("Error: Invalid .xml File. Missing "); + + configNode = rootNode.FirstChild; + if (configNode.Name != "Config") + throw new Exception("Error: Invalid .xml File. first child should be "); + + if (createdFile) + { + this.Commit(); + } + } + + public string GetAttribute(string attributeName) + { + string result = ""; + if (configNode.Attributes[attributeName] != null) + { + result = ((XmlAttribute)configNode.Attributes.GetNamedItem(attributeName)).Value; + } + return result; + } + + public bool SetAttribute(string attributeName, string attributeValue) + { + if (configNode.Attributes[attributeName] != null) + { + ((XmlAttribute)configNode.Attributes.GetNamedItem(attributeName)).Value = attributeValue; + } + else + { + XmlAttribute attri; + attri = doc.CreateAttribute(attributeName); + attri.Value = attributeValue; + configNode.Attributes.Append(attri); + } + return true; + } + + public void Commit() + { + doc.Save(fileName); + } + + public void Close() + { + configNode = null; + rootNode = null; + doc = null; + } + + } +} diff --git a/OpenSim/Framework/Servers/BaseHttpServer.cs b/OpenSim/Framework/Servers/BaseHttpServer.cs new file mode 100644 index 0000000..e55e33c --- /dev/null +++ b/OpenSim/Framework/Servers/BaseHttpServer.cs @@ -0,0 +1,312 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +//using OpenSim.CAPS; +using Nwc.XmlRpc; +using System.Collections; +using OpenSim.Framework.Console; + +namespace OpenSim.Servers +{ + public class BaseHttpServer + { + protected class RestMethodEntry + { + private string m_path; + public string Path + { + get { return m_path; } + } + + private RestMethod m_restMethod; + public RestMethod RestMethod + { + get { return m_restMethod; } + } + + public RestMethodEntry(string path, RestMethod restMethod) + { + m_path = path; + m_restMethod = restMethod; + } + } + + protected Thread m_workerThread; + protected HttpListener m_httpListener; + protected Dictionary m_restHandlers = new Dictionary(); + protected Dictionary m_rpcHandlers = new Dictionary(); + protected int m_port; + protected bool firstcaps = true; + + public BaseHttpServer(int port) + { + m_port = port; + } + + public bool AddRestHandler(string method, string path, RestMethod handler) + { + //Console.WriteLine("adding new REST handler for path " + path); + string methodKey = String.Format("{0}: {1}", method, path); + + if (!this.m_restHandlers.ContainsKey(methodKey)) + { + this.m_restHandlers.Add(methodKey, new RestMethodEntry(path, handler)); + return true; + } + + //must already have a handler for that path so return false + return false; + } + + public bool RemoveRestHandler(string method, string path) + { + string methodKey = String.Format("{0}: {1}", method, path); + if (this.m_restHandlers.ContainsKey(methodKey)) + { + this.m_restHandlers.Remove(methodKey); + return true; + } + return false; + } + + public bool AddXmlRPCHandler(string method, XmlRpcMethod handler) + { + if (!this.m_rpcHandlers.ContainsKey(method)) + { + this.m_rpcHandlers.Add(method, handler); + return true; + } + + //must already have a handler for that path so return false + return false; + } + + protected virtual string ProcessXMLRPCMethod(string methodName, XmlRpcRequest request) + { + XmlRpcResponse response; + + XmlRpcMethod method; + if (this.m_rpcHandlers.TryGetValue(methodName, out method)) + { + response = method(request); + } + else + { + response = new XmlRpcResponse(); + Hashtable unknownMethodError = new Hashtable(); + unknownMethodError["reason"] = "XmlRequest"; ; + unknownMethodError["message"] = "Unknown Rpc request"; + unknownMethodError["login"] = "false"; + response.Value = unknownMethodError; + } + + return XmlRpcResponseSerializer.Singleton.Serialize(response); + } + + protected virtual string ParseREST(string request, string path, string method) + { + string response; + + string requestKey = String.Format("{0}: {1}", method, path); + + string bestMatch = String.Empty; + foreach (string currentKey in m_restHandlers.Keys) + { + if (requestKey.StartsWith(currentKey)) + { + if (currentKey.Length > bestMatch.Length) + { + bestMatch = currentKey; + } + } + } + + RestMethodEntry restMethodEntry; + if (m_restHandlers.TryGetValue(bestMatch, out restMethodEntry)) + { + RestMethod restMethod = restMethodEntry.RestMethod; + + string param = path.Substring(restMethodEntry.Path.Length); + response = restMethod(request, path, param); + + } + else + { + response = String.Empty; + } + + return response; + } + + protected virtual string ParseLLSDXML(string requestBody) + { + // dummy function for now - IMPLEMENT ME! + Console.WriteLine("LLSD request "+requestBody); + string resp = ""; + if (firstcaps) + { + resp = "MapLayerhttp://127.0.0.1:9000/CAPS/"; + firstcaps = false; + } + return resp; + } + + protected virtual string ParseXMLRPC(string requestBody) + { + string responseString = String.Empty; + + try + { + XmlRpcRequest request = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(requestBody); + + string methodName = request.MethodName; + + responseString = ProcessXMLRPCMethod(methodName, request); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + return responseString; + } + + public virtual void HandleRequest(Object stateinfo) + { + try + { + HttpListenerContext context = (HttpListenerContext)stateinfo; + + HttpListenerRequest request = context.Request; + HttpListenerResponse response = context.Response; + + response.KeepAlive = false; + response.SendChunked = false; + + System.IO.Stream body = request.InputStream; + System.Text.Encoding encoding = System.Text.Encoding.UTF8; + System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding); + + string requestBody = reader.ReadToEnd(); + body.Close(); + reader.Close(); + + //Console.WriteLine(request.HttpMethod + " " + request.RawUrl + " Http/" + request.ProtocolVersion.ToString() + " content type: " + request.ContentType); + //Console.WriteLine(requestBody); + + string responseString = ""; + // Console.WriteLine("new request " + request.ContentType +" at "+ request.RawUrl); + switch (request.ContentType) + { + case "text/xml": + // must be XML-RPC, so pass to the XML-RPC parser + + responseString = ParseXMLRPC(requestBody); + responseString = Regex.Replace(responseString, "utf-16", "utf-8"); + + response.AddHeader("Content-type", "text/xml"); + break; + + case "application/xml": + // probably LLSD we hope, otherwise it should be ignored by the parser + // responseString = ParseLLSDXML(requestBody); + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "application/xml"); + break; + + case "application/octet-stream": + // probably LLSD we hope, otherwise it should be ignored by the parser + // responseString = ParseLLSDXML(requestBody); + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "application/xml"); + break; + + case "application/x-www-form-urlencoded": + // a form data POST so send to the REST parser + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "text/html"); + break; + + case null: + // must be REST or invalid crap, so pass to the REST parser + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "text/html"); + break; + + } + + byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); + System.IO.Stream output = response.OutputStream; + response.SendChunked = false; + response.ContentLength64 = buffer.Length; + output.Write(buffer, 0, buffer.Length); + output.Close(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } + + public void Start() + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.LOW, "BaseHttpServer.cs: Starting up HTTP Server"); + + m_workerThread = new Thread(new ThreadStart(StartHTTP)); + m_workerThread.IsBackground = true; + m_workerThread.Start(); + } + + private void StartHTTP() + { + try + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.LOW, "BaseHttpServer.cs: StartHTTP() - Spawned main thread OK"); + m_httpListener = new HttpListener(); + + m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); + m_httpListener.Start(); + + HttpListenerContext context; + while (true) + { + context = m_httpListener.GetContext(); + ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.MEDIUM, e.Message); + } + } + } +} diff --git a/OpenSim/Framework/Servers/CheckSumServer.cs b/OpenSim/Framework/Servers/CheckSumServer.cs new file mode 100644 index 0000000..a359205 --- /dev/null +++ b/OpenSim/Framework/Servers/CheckSumServer.cs @@ -0,0 +1,141 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Console; + + +namespace OpenSim.Servers +{ +/* public class CheckSumServer : UDPServerBase + { + //protected ConsoleBase m_log; + + public CheckSumServer(int port) + : base(port) + { + } + + protected override void OnReceivedData(IAsyncResult result) + { + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + Packet packet = null; + int numBytes = Server.EndReceiveFrom(result, ref epSender); + int packetEnd = numBytes - 1; + + packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer); + + if (packet.Type == PacketType.SecuredTemplateChecksumRequest) + { + SecuredTemplateChecksumRequestPacket checksum = (SecuredTemplateChecksumRequestPacket)packet; + TemplateChecksumReplyPacket checkreply = new TemplateChecksumReplyPacket(); + checkreply.DataBlock.Checksum = 3220703154;//180572585; + checkreply.DataBlock.Flags = 0; + checkreply.DataBlock.MajorVersion = 1; + checkreply.DataBlock.MinorVersion = 15; + checkreply.DataBlock.PatchVersion = 0; + checkreply.DataBlock.ServerVersion = 0; + checkreply.TokenBlock.Token = checksum.TokenBlock.Token; + this.SendPacket(checkreply, epSender); + + /* + //if we wanted to echo the the checksum/ version from the client (so that any client worked) + SecuredTemplateChecksumRequestPacket checkrequest = new SecuredTemplateChecksumRequestPacket(); + checkrequest.TokenBlock.Token = checksum.TokenBlock.Token; + this.SendPacket(checkrequest, epSender); + + } + else if (packet.Type == PacketType.TemplateChecksumReply) + { + //echo back the client checksum reply (Hegemon's method) + TemplateChecksumReplyPacket checksum2 = (TemplateChecksumReplyPacket)packet; + TemplateChecksumReplyPacket checkreply2 = new TemplateChecksumReplyPacket(); + checkreply2.DataBlock.Checksum = checksum2.DataBlock.Checksum; + checkreply2.DataBlock.Flags = checksum2.DataBlock.Flags; + checkreply2.DataBlock.MajorVersion = checksum2.DataBlock.MajorVersion; + checkreply2.DataBlock.MinorVersion = checksum2.DataBlock.MinorVersion; + checkreply2.DataBlock.PatchVersion = checksum2.DataBlock.PatchVersion; + checkreply2.DataBlock.ServerVersion = checksum2.DataBlock.ServerVersion; + checkreply2.TokenBlock.Token = checksum2.TokenBlock.Token; + this.SendPacket(checkreply2, epSender); + } + else + { + } + + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + } + + private void SendPacket(Packet Pack, EndPoint endp) + { + if (!Pack.Header.Resent) + { + Pack.Header.Sequence = 1; + } + + byte[] ZeroOutBuffer = new byte[4096]; + byte[] sendbuffer; + sendbuffer = Pack.ToBytes(); + + try + { + if (Pack.Header.Zerocoded) + { + int packetsize = Helpers.ZeroEncode(sendbuffer, sendbuffer.Length, ZeroOutBuffer); + this.SendPackTo(ZeroOutBuffer, packetsize, SocketFlags.None, endp); + } + else + { + this.SendPackTo(sendbuffer, sendbuffer.Length, SocketFlags.None, endp); + } + } + catch (Exception) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("OpenSimClient.cs:ProcessOutPacket() - WARNING: Socket exception occurred on connection "); + + } + } + + private void SendPackTo(byte[] buffer, int size, SocketFlags flags, EndPoint endp) + { + this.Server.SendTo(buffer, size, flags, endp); + } + * + }*/ +} \ No newline at end of file diff --git a/OpenSim/Framework/Servers/IRestHandler.cs b/OpenSim/Framework/Servers/IRestHandler.cs new file mode 100644 index 0000000..3aa508c --- /dev/null +++ b/OpenSim/Framework/Servers/IRestHandler.cs @@ -0,0 +1,35 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Servers +{ + public delegate string RestMethod( string request, string path, string param ); +} diff --git a/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj new file mode 100644 index 0000000..399f456 --- /dev/null +++ b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj @@ -0,0 +1,116 @@ + + + Local + 8.0.50727 + 2.0 + {2CC71860-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.Servers + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.Servers + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj.user b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/Servers/UDPServerBase.cs b/OpenSim/Framework/Servers/UDPServerBase.cs new file mode 100644 index 0000000..b472c97 --- /dev/null +++ b/OpenSim/Framework/Servers/UDPServerBase.cs @@ -0,0 +1,95 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim.Servers +{ + public class UDPServerBase + { + public Socket Server; + protected IPEndPoint ServerIncoming; + protected byte[] RecvBuffer = new byte[4096]; + protected byte[] ZeroBuffer = new byte[8192]; + protected IPEndPoint ipeSender; + protected EndPoint epSender; + protected AsyncCallback ReceivedData; + protected int listenPort; + + public UDPServerBase(int port) + { + listenPort = port; + } + + protected virtual void OnReceivedData(IAsyncResult result) + { + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + Packet packet = null; + int numBytes = Server.EndReceiveFrom(result, ref epSender); + int packetEnd = numBytes - 1; + + packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer); + + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + } + + protected virtual void AddNewClient(Packet packet) + { + } + + public virtual void ServerListener() + { + + ServerIncoming = new IPEndPoint(IPAddress.Any, listenPort); + Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + Server.Bind(ServerIncoming); + + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + ReceivedData = new AsyncCallback(this.OnReceivedData); + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + } + + public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode) + { + + } + } +} + diff --git a/OpenSim/Framework/Servers/XmlRpcMethod.cs b/OpenSim/Framework/Servers/XmlRpcMethod.cs new file mode 100644 index 0000000..05cbf2e --- /dev/null +++ b/OpenSim/Framework/Servers/XmlRpcMethod.cs @@ -0,0 +1,34 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using Nwc.XmlRpc; + +namespace OpenSim.Servers +{ + public delegate XmlRpcResponse XmlRpcMethod( XmlRpcRequest request ); +} diff --git a/OpenSim/Framework/UserManager/LoginResponse.cs b/OpenSim/Framework/UserManager/LoginResponse.cs new file mode 100644 index 0000000..5ca223f --- /dev/null +++ b/OpenSim/Framework/UserManager/LoginResponse.cs @@ -0,0 +1,645 @@ +using System; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Collections; +using System.Xml; +using libsecondlife; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Interfaces; +using Nwc.XmlRpc; + +namespace OpenSim.Framework.UserManagement +{ + + /// + /// A temp class to handle login response. + /// Should make use of UserProfileManager where possible. + /// + + public class LoginResponse + { + private Hashtable loginFlagsHash; + private Hashtable globalTexturesHash; + private Hashtable loginError; + private Hashtable eventCategoriesHash; + private Hashtable uiConfigHash; + private Hashtable classifiedCategoriesHash; + + private ArrayList loginFlags; + private ArrayList globalTextures; + private ArrayList eventCategories; + private ArrayList uiConfig; + private ArrayList classifiedCategories; + private ArrayList inventoryRoot; + private ArrayList initialOutfit; + private ArrayList agentInventory; + + private UserInfo userProfile; + + private LLUUID agentID; + private LLUUID sessionID; + private LLUUID secureSessionID; + + // Login Flags + private string dst; + private string stipendSinceLogin; + private string gendered; + private string everLoggedIn; + private string login; + private int simPort; + private string simAddress; + private string agentAccess; + private Int32 circuitCode; + private uint regionX; + private uint regionY; + + // Login + private string firstname; + private string lastname; + + // Global Textures + private string sunTexture; + private string cloudTexture; + private string moonTexture; + + // Error Flags + private string errorReason; + private string errorMessage; + + // Response + private XmlRpcResponse xmlRpcResponse; + private XmlRpcResponse defaultXmlRpcResponse; + + private string welcomeMessage; + private string startLocation; + private string allowFirstLife; + private string home; + private string seedCapability; + private string lookAt; + + public LoginResponse() + { + this.loginFlags = new ArrayList(); + this.globalTextures = new ArrayList(); + this.eventCategories = new ArrayList(); + this.uiConfig = new ArrayList(); + this.classifiedCategories = new ArrayList(); + + this.loginError = new Hashtable(); + this.eventCategoriesHash = new Hashtable(); + this.classifiedCategoriesHash = new Hashtable(); + this.uiConfigHash = new Hashtable(); + + this.defaultXmlRpcResponse = new XmlRpcResponse(); + this.userProfile = new UserInfo(); + this.inventoryRoot = new ArrayList(); + this.initialOutfit = new ArrayList(); + this.agentInventory = new ArrayList(); + + this.xmlRpcResponse = new XmlRpcResponse(); + this.defaultXmlRpcResponse = new XmlRpcResponse(); + + this.SetDefaultValues(); + } // LoginServer + + public void SetDefaultValues() + { + this.DST = "N"; + this.StipendSinceLogin = "N"; + this.Gendered = "Y"; + this.EverLoggedIn = "Y"; + this.login = "false"; + this.firstname = "Test"; + this.lastname = "User"; + this.agentAccess = "M"; + this.startLocation = "last"; + this.allowFirstLife = "Y"; + + this.SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271"; + this.CloudTexture = "fc4b9f0b-d008-45c6-96a4-01dd947ac621"; + this.MoonTexture = "fc4b9f0b-d008-45c6-96a4-01dd947ac621"; + + this.ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock."; + this.ErrorReason = "key"; + this.welcomeMessage = "Welcome to OpenSim!"; + this.seedCapability = ""; + this.home = "{'region_handle':[r" + (997 * 256).ToString() + ",r" + (996 * 256).ToString() + "], 'position':[r" + this.userProfile.homepos.X.ToString() + ",r" + this.userProfile.homepos.Y.ToString() + ",r" + this.userProfile.homepos.Z.ToString() + "], 'look_at':[r" + this.userProfile.homelookat.X.ToString() + ",r" + this.userProfile.homelookat.Y.ToString() + ",r" + this.userProfile.homelookat.Z.ToString() + "]}"; + this.lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]"; + this.RegionX = (uint)255232; + this.RegionY = (uint)254976; + + // Classifieds; + this.AddClassifiedCategory((Int32)1, "Shopping"); + this.AddClassifiedCategory((Int32)2, "Land Rental"); + this.AddClassifiedCategory((Int32)3, "Property Rental"); + this.AddClassifiedCategory((Int32)4, "Special Attraction"); + this.AddClassifiedCategory((Int32)5, "New Products"); + this.AddClassifiedCategory((Int32)6, "Employment"); + this.AddClassifiedCategory((Int32)7, "Wanted"); + this.AddClassifiedCategory((Int32)8, "Service"); + this.AddClassifiedCategory((Int32)9, "Personal"); + + + this.SessionID = LLUUID.Random(); + this.SecureSessionID = LLUUID.Random(); + this.AgentID = LLUUID.Random(); + + Hashtable InitialOutfitHash = new Hashtable(); + InitialOutfitHash["folder_name"] = "Nightclub Female"; + InitialOutfitHash["gender"] = "female"; + this.initialOutfit.Add(InitialOutfitHash); + + + } // SetDefaultValues + + #region Login Failure Methods + public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login) + { + // Overwrite any default values; + this.xmlRpcResponse = new XmlRpcResponse(); + + // Ensure Login Failed message/reason; + this.ErrorMessage = message; + this.ErrorReason = reason; + + this.loginError["reason"] = this.ErrorReason; + this.loginError["message"] = this.ErrorMessage; + this.loginError["login"] = login; + this.xmlRpcResponse.Value = this.loginError; + return (this.xmlRpcResponse); + } // GenerateResponse + + public XmlRpcResponse CreateFailedResponse() + { + return (this.CreateLoginFailedResponse()); + } // CreateErrorConnectingToGridResponse() + + public XmlRpcResponse CreateLoginFailedResponse() + { + return (this.GenerateFailureResponse("key", "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", "false")); + } // LoginFailedResponse + + public XmlRpcResponse CreateAlreadyLoggedInResponse() + { + return (this.GenerateFailureResponse("presence", "You appear to be already logged in, if this is not the case please wait for your session to timeout, if this takes longer than a few minutes please contact the grid owner", "false")); + } // CreateAlreadyLoggedInResponse() + + public XmlRpcResponse CreateDeadRegionResponse() + { + return (this.GenerateFailureResponse("key", "The region you are attempting to log into is not responding. Please select another region and try again.", "false")); + } + + public XmlRpcResponse CreateGridErrorResponse() + { + return (this.GenerateFailureResponse("key", "Error connecting to grid. Could not percieve credentials from login XML.", "false")); + } + + #endregion + + public XmlRpcResponse ToXmlRpcResponse() + { + try + { + + Hashtable responseData = new Hashtable(); + + this.loginFlagsHash = new Hashtable(); + this.loginFlagsHash["daylight_savings"] = this.DST; + this.loginFlagsHash["stipend_since_login"] = this.StipendSinceLogin; + this.loginFlagsHash["gendered"] = this.Gendered; + this.loginFlagsHash["ever_logged_in"] = this.EverLoggedIn; + this.loginFlags.Add(this.loginFlagsHash); + + responseData["first_name"] = this.Firstname; + responseData["last_name"] = this.Lastname; + responseData["agent_access"] = this.agentAccess; + + this.globalTexturesHash = new Hashtable(); + this.globalTexturesHash["sun_texture_id"] = this.SunTexture; + this.globalTexturesHash["cloud_texture_id"] = this.CloudTexture; + this.globalTexturesHash["moon_texture_id"] = this.MoonTexture; + this.globalTextures.Add(this.globalTexturesHash); + this.eventCategories.Add(this.eventCategoriesHash); + + this.AddToUIConfig("allow_first_life", this.allowFirstLife); + this.uiConfig.Add(this.uiConfigHash); + + responseData["sim_port"] =(Int32) this.SimPort; + responseData["sim_ip"] = this.SimAddress; + responseData["agent_id"] = this.AgentID.ToStringHyphenated(); + responseData["session_id"] = this.SessionID.ToStringHyphenated(); + responseData["secure_session_id"] = this.SecureSessionID.ToStringHyphenated(); + responseData["circuit_code"] = this.CircuitCode; + responseData["seconds_since_epoch"] = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + responseData["login-flags"] = this.loginFlags; + responseData["global-textures"] = this.globalTextures; + responseData["seed_capability"] = this.seedCapability; + + responseData["event_categories"] = this.eventCategories; + responseData["event_notifications"] = new ArrayList(); // todo + responseData["classified_categories"] = this.classifiedCategories; + responseData["ui-config"] = this.uiConfig; + + responseData["inventory-skeleton"] = this.agentInventory; + responseData["inventory-skel-lib"] = new ArrayList(); // todo + responseData["inventory-root"] = this.inventoryRoot; + responseData["gestures"] = new ArrayList(); // todo + responseData["inventory-lib-owner"] = new ArrayList(); // todo + responseData["initial-outfit"] = this.initialOutfit; + responseData["start_location"] = this.startLocation; + responseData["seed_capability"] = this.seedCapability; + responseData["home"] = this.home; + responseData["look_at"] = this.lookAt; + responseData["message"] = this.welcomeMessage; + responseData["region_x"] = (Int32)this.RegionX * 256; + responseData["region_y"] = (Int32)this.RegionY * 256; + + //responseData["inventory-lib-root"] = new ArrayList(); // todo + //responseData["buddy-list"] = new ArrayList(); // todo + + responseData["login"] = "true"; + this.xmlRpcResponse.Value = responseData; + + return (this.xmlRpcResponse); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine( + OpenSim.Framework.Console.LogPriority.LOW, + "LoginResponse: Error creating XML-RPC Response: " + e.Message + ); + return (this.GenerateFailureResponse("Internal Error", "Error generating Login Response", "false")); + + } + + } // ToXmlRpcResponse + + public void SetEventCategories(string category, string value) + { + this.eventCategoriesHash[category] = value; + } // SetEventCategories + + public void AddToUIConfig(string itemName, string item) + { + this.uiConfigHash[itemName] = item; + } // SetUIConfig + + public void AddClassifiedCategory(Int32 ID, string categoryName) + { + this.classifiedCategoriesHash["category_name"] = categoryName; + this.classifiedCategoriesHash["category_id"] = ID; + this.classifiedCategories.Add(this.classifiedCategoriesHash); + // this.classifiedCategoriesHash.Clear(); + } // SetClassifiedCategory + + #region Properties + public string Login + { + get + { + return this.login; + } + set + { + this.login = value; + } + } // Login + + public string DST + { + get + { + return this.dst; + } + set + { + this.dst = value; + } + } // DST + + public string StipendSinceLogin + { + get + { + return this.stipendSinceLogin; + } + set + { + this.stipendSinceLogin = value; + } + } // StipendSinceLogin + + public string Gendered + { + get + { + return this.gendered; + } + set + { + this.gendered = value; + } + } // Gendered + + public string EverLoggedIn + { + get + { + return this.everLoggedIn; + } + set + { + this.everLoggedIn = value; + } + } // EverLoggedIn + + public int SimPort + { + get + { + return this.simPort; + } + set + { + this.simPort = value; + } + } // SimPort + + public string SimAddress + { + get + { + return this.simAddress; + } + set + { + this.simAddress = value; + } + } // SimAddress + + public LLUUID AgentID + { + get + { + return this.agentID; + } + set + { + this.agentID = value; + } + } // AgentID + + public LLUUID SessionID + { + get + { + return this.sessionID; + } + set + { + this.sessionID = value; + } + } // SessionID + + public LLUUID SecureSessionID + { + get + { + return this.secureSessionID; + } + set + { + this.secureSessionID = value; + } + } // SecureSessionID + + public Int32 CircuitCode + { + get + { + return this.circuitCode; + } + set + { + this.circuitCode = value; + } + } // CircuitCode + + public uint RegionX + { + get + { + return this.regionX; + } + set + { + this.regionX = value; + } + } // RegionX + + public uint RegionY + { + get + { + return this.regionY; + } + set + { + this.regionY = value; + } + } // RegionY + + public string SunTexture + { + get + { + return this.sunTexture; + } + set + { + this.sunTexture = value; + } + } // SunTexture + + public string CloudTexture + { + get + { + return this.cloudTexture; + } + set + { + this.cloudTexture = value; + } + } // CloudTexture + + public string MoonTexture + { + get + { + return this.moonTexture; + } + set + { + this.moonTexture = value; + } + } // MoonTexture + + public string Firstname + { + get + { + return this.firstname; + } + set + { + this.firstname = value; + } + } // Firstname + + public string Lastname + { + get + { + return this.lastname; + } + set + { + this.lastname = value; + } + } // Lastname + + public string AgentAccess + { + get + { + return this.agentAccess; + } + set + { + this.agentAccess = value; + } + } + + public string StartLocation + { + get + { + return this.startLocation; + } + set + { + this.startLocation = value; + } + } // StartLocation + + public string LookAt + { + get + { + return this.lookAt; + } + set + { + this.lookAt = value; + } + } + + public string SeedCapability + { + get + { + return this.seedCapability; + } + set + { + this.seedCapability = value; + } + } // SeedCapability + + public string ErrorReason + { + get + { + return this.errorReason; + } + set + { + this.errorReason = value; + } + } // ErrorReason + + public string ErrorMessage + { + get + { + return this.errorMessage; + } + set + { + this.errorMessage = value; + } + } // ErrorMessage + + public ArrayList InventoryRoot + { + get + { + return this.inventoryRoot; + } + set + { + this.inventoryRoot = value; + } + } + + public ArrayList InventorySkeleton + { + get + { + return this.agentInventory; + } + set + { + this.agentInventory = value; + } + } + + public string Home + { + get + { + return this.home; + } + set + { + this.home = value; + } + } + + public string Message + { + get + { + return this.welcomeMessage; + } + set + { + this.welcomeMessage = value; + } + } + #endregion + + + public class UserInfo + { + public string firstname; + public string lastname; + public ulong homeregionhandle; + public LLVector3 homepos; + public LLVector3 homelookat; + } + } +} + diff --git a/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj b/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj new file mode 100644 index 0000000..02aa3f3 --- /dev/null +++ b/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj @@ -0,0 +1,125 @@ + + + Local + 8.0.50727 + 2.0 + {586E2916-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Framework.UserManagement + JScript + Grid + IE50 + false + Library + + OpenSim.Framework.UserManagement + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + OpenSim.Framework.GenericConfig.Xml.dll + False + + + OpenSim.Framework.Servers.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj.user b/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Framework/UserManager/OpenSim.Framework.UserManagement.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Framework/UserManager/UserManagerBase.cs b/OpenSim/Framework/UserManager/UserManagerBase.cs new file mode 100644 index 0000000..eb46c14 --- /dev/null +++ b/OpenSim/Framework/UserManager/UserManagerBase.cs @@ -0,0 +1,641 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Data; +using libsecondlife; +using System.Reflection; + +using System.Xml; +using Nwc.XmlRpc; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; + +using System.Security.Cryptography; + +namespace OpenSim.Framework.UserManagement +{ + public class UserManagerBase + { + public OpenSim.Framework.Interfaces.UserConfig _config; + Dictionary _plugins = new Dictionary(); + + /// + /// Adds a new user server plugin - user servers will be requested in the order they were loaded. + /// + /// The filename to the user server plugin DLL + public void AddPlugin(string FileName) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Userstorage: Attempting to load " + FileName); + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Userstorage: Found " + pluginAssembly.GetTypes().Length + " interfaces."); + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IUserData", true); + + if (typeInterface != null) + { + IUserData plug = (IUserData)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Initialise(); + this._plugins.Add(plug.getName(), plug); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Userstorage: Added IUserData Interface"); + } + + typeInterface = null; + } + } + + pluginAssembly = null; + } + + #region Get UserProfile + /// + /// Loads a user profile from a database by UUID + /// + /// The target UUID + /// A user profile + public UserProfileData getUserProfile(LLUUID uuid) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + UserProfileData profile = plugin.Value.getUserByUUID(uuid); + profile.currentAgent = getUserAgent(profile.UUID); + return profile; + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + + + /// + /// Loads a user profile by name + /// + /// The target name + /// A user profile + public UserProfileData getUserProfile(string name) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + UserProfileData profile = plugin.Value.getUserByName(name); + profile.currentAgent = getUserAgent(profile.UUID); + return profile; + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + + /// + /// Loads a user profile by name + /// + /// First name + /// Last name + /// A user profile + public UserProfileData getUserProfile(string fname, string lname) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + UserProfileData profile = plugin.Value.getUserByName(fname,lname); + try + { + profile.currentAgent = getUserAgent(profile.UUID); + } + catch (Exception e) + { + // Ignore + } + return profile; + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + #endregion + + #region Get UserAgent + /// + /// Loads a user agent by uuid (not called directly) + /// + /// The agents UUID + /// Agent profiles + public UserAgentData getUserAgent(LLUUID uuid) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + return plugin.Value.getAgentByUUID(uuid); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + + /// + /// Loads a user agent by name (not called directly) + /// + /// The agents name + /// A user agent + public UserAgentData getUserAgent(string name) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + return plugin.Value.getAgentByName(name); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + + /// + /// Loads a user agent by name (not called directly) + /// + /// The agents firstname + /// The agents lastname + /// A user agent + public UserAgentData getUserAgent(string fname, string lname) + { + foreach (KeyValuePair plugin in _plugins) + { + try + { + return plugin.Value.getAgentByName(fname,lname); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Unable to find user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + + return null; + } + + #endregion + + #region CreateAgent + /// + /// Creates and initialises a new user agent - make sure to use CommitAgent when done to submit to the DB + /// + /// The users profile + /// The users loginrequest + public void CreateAgent(ref UserProfileData profile, XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + UserAgentData agent = new UserAgentData(); + + // User connection + agent.agentIP = ""; + agent.agentOnline = true; + agent.agentPort = 0; + + // Generate sessions + RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); + byte[] randDataS = new byte[16]; + byte[] randDataSS = new byte[16]; + rand.GetBytes(randDataS); + rand.GetBytes(randDataSS); + + agent.secureSessionID = new LLUUID(randDataSS, 0); + agent.sessionID = new LLUUID(randDataS, 0); + + // Profile UUID + agent.UUID = profile.UUID; + + // Current position (from Home) + agent.currentHandle = profile.homeRegion; + agent.currentPos = profile.homeLocation; + + // If user specified additional start, use that + if (requestData.ContainsKey("start")) + { + string startLoc = ((string)requestData["start"]).Trim(); + if (!(startLoc == "last" || startLoc == "home")) + { + // Format: uri:Ahern&162&213&34 + try + { + string[] parts = startLoc.Remove(0, 4).Split('&'); + string region = parts[0]; + + //////////////////////////////////////////////////// + //SimProfile SimInfo = new SimProfile(); + //SimInfo = SimInfo.LoadFromGrid(theUser.currentAgent.currentHandle, _config.GridServerURL, _config.GridSendKey, _config.GridRecvKey); + } + catch (Exception e) + { + + } + } + } + + // What time did the user login? + agent.loginTime = Util.UnixTimeSinceEpoch(); + agent.logoutTime = 0; + + // Current location + agent.regionID = new LLUUID(); // Fill in later + agent.currentRegion = new LLUUID(); // Fill in later + + profile.currentAgent = agent; + } + + /// + /// Saves a target agent to the database + /// + /// The users profile + /// Successful? + public bool CommitAgent(ref UserProfileData profile) + { + // Saves the agent to database + return true; + } + + #endregion + + /// + /// Checks a user against it's password hash + /// + /// The users profile + /// The supplied password + /// Authenticated? + public virtual bool AuthenticateUser(ref UserProfileData profile, string password) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( + "Authenticating " + profile.username + " " + profile.surname); + + password = password.Remove(0, 3); //remove $1$ + + string s = Util.Md5Hash(password + ":" + profile.passwordSalt); + + return profile.passwordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase); + } + + #region Xml Response + + /// + /// + /// + /// + /// + /// + public virtual UserProfileData GetTheUser(string firstname, string lastname) + { + return getUserProfile(firstname, lastname); + } + + /// + /// + /// + /// + public virtual string GetMessage() + { + return _config.DefaultStartupMsg; + } + + /// + /// Customises the login response and fills in missing values. + /// + /// The existing response + /// The user profile + public virtual void CustomiseResponse(ref LoginResponse response, ref UserProfileData theUser) + { + + } + + /// + /// Main user login function + /// + /// The XMLRPC request + /// The response to send + public XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + + bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && requestData.Contains("passwd")); + bool GoodLogin = false; + string firstname = ""; + string lastname = ""; + string passwd = ""; + + UserProfileData TheUser; + LoginResponse logResponse = new LoginResponse(); + + if (GoodXML) + { + firstname = (string)requestData["first"]; + lastname = (string)requestData["last"]; + passwd = (string)requestData["passwd"]; + + TheUser = GetTheUser(firstname, lastname); + if (TheUser == null) + return logResponse.CreateLoginFailedResponse(); + + GoodLogin = AuthenticateUser(ref TheUser, passwd); + } + else + { + return logResponse.CreateGridErrorResponse(); + } + + if (!GoodLogin) + { + return logResponse.CreateLoginFailedResponse(); + } + else + { + // If we already have a session... + if (TheUser.currentAgent != null && TheUser.currentAgent.agentOnline) + { + // Reject the login + return logResponse.CreateAlreadyLoggedInResponse(); + } + // Otherwise... + // Create a new agent session + CreateAgent(ref TheUser, request); + + try + { + + LLUUID AgentID = TheUser.UUID; + + // Inventory Library Section + ArrayList AgentInventoryArray = new ArrayList(); + Hashtable TempHash; + + AgentInventory Library = new AgentInventory(); + Library.CreateRootFolder(AgentID, true); + + foreach (InventoryFolder InvFolder in Library.InventoryFolders.Values) + { + TempHash = new Hashtable(); + TempHash["name"] = InvFolder.FolderName; + TempHash["parent_id"] = InvFolder.ParentID.ToStringHyphenated(); + TempHash["version"] = (Int32)InvFolder.Version; + TempHash["type_default"] = (Int32)InvFolder.DefaultType; + TempHash["folder_id"] = InvFolder.FolderID.ToStringHyphenated(); + AgentInventoryArray.Add(TempHash); + } + + Hashtable InventoryRootHash = new Hashtable(); + InventoryRootHash["folder_id"] = Library.InventoryRoot.FolderID.ToStringHyphenated(); + ArrayList InventoryRoot = new ArrayList(); + InventoryRoot.Add(InventoryRootHash); + + // Circuit Code + uint circode = (uint)(Util.RandomClass.Next()); + + logResponse.Lastname = TheUser.surname; + logResponse.Firstname = TheUser.username; + logResponse.AgentID = AgentID.ToStringHyphenated(); + logResponse.SessionID = TheUser.currentAgent.sessionID.ToStringHyphenated(); + logResponse.SecureSessionID = TheUser.currentAgent.secureSessionID.ToStringHyphenated(); + logResponse.InventoryRoot = InventoryRoot; + logResponse.InventorySkeleton = AgentInventoryArray; + logResponse.CircuitCode = (Int32)circode; + logResponse.RegionX = 0; //overwritten + logResponse.RegionY = 0; //overwritten + logResponse.Home = "!!null temporary value {home}!!"; // Overwritten + //logResponse.LookAt = "\n[r" + TheUser.homeLookAt.X.ToString() + ",r" + TheUser.homeLookAt.Y.ToString() + ",r" + TheUser.homeLookAt.Z.ToString() + "]\n"; + logResponse.SimAddress = "127.0.0.1"; //overwritten + logResponse.SimPort = 0; //overwritten + logResponse.Message = this.GetMessage(); + + try + { + this.CustomiseResponse(ref logResponse, ref TheUser); + } + catch (Exception e) + { + System.Console.WriteLine(e.ToString()); + return logResponse.CreateDeadRegionResponse(); + } + CommitAgent(ref TheUser); + + return logResponse.ToXmlRpcResponse(); + + } + catch (Exception E) + { + System.Console.WriteLine(E.ToString()); + } + //} + } + return response; + + } + + #endregion + + /// + /// Deletes an active agent session + /// + /// The request + /// The path (eg /bork/narf/test) + /// Parameters sent + /// Success "OK" else error + public string RestDeleteUserSessionMethod(string request, string path, string param) + { + // TODO! Important! + + return "OK"; + } + + /// + /// + /// + /// + public void AddUserProfile(string firstName, string lastName, string pass, uint regX, uint regY) + { + UserProfileData user = new UserProfileData(); + user.homeLocation = new LLVector3(128, 128, 100); + user.UUID = LLUUID.Random(); + user.username = firstName; + user.surname = lastName; + user.passwordHash = pass; + user.passwordSalt = ""; + user.created = Util.UnixTimeSinceEpoch(); + user.homeLookAt = new LLVector3(100, 100, 100); + user.homeRegion = Util.UIntsToLong((regX * 256), (regY * 256)); + + foreach (KeyValuePair plugin in _plugins) + { + try + { + plugin.Value.addNewUserProfile(user); + + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Unable to add user via " + plugin.Key + "(" + e.ToString() + ")"); + } + } + } + + /// + /// Returns an error message that the user could not be found in the database + /// + /// XML string consisting of a error element containing individual error(s) + public string CreateUnknownUserErrorResponse() + { + System.IO.StringWriter sw = new System.IO.StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + // Header + xw.Formatting = Formatting.Indented; + xw.WriteStartDocument(); + xw.WriteDocType("error", null, null, null); + xw.WriteComment("An error occured"); + xw.WriteStartElement("error"); + + // User + xw.WriteElementString("unknownuser", "Unable to find a user with that name"); + + // Footer + xw.WriteEndElement(); + xw.Flush(); + xw.Close(); + + return sw.ToString(); + } + + /// + /// Converts a user profile to an XML element which can be returned + /// + /// The user profile + /// A string containing an XML Document of the user profile + public string ProfileToXml(UserProfileData profile) + { + System.IO.StringWriter sw = new System.IO.StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + // Header + xw.Formatting = Formatting.Indented; + xw.WriteStartDocument(); + xw.WriteDocType("userprofile", null, null, null); + xw.WriteComment("Found user profiles matching the request"); + xw.WriteStartElement("users"); + + // User + xw.WriteStartElement("user"); + // Account information + xw.WriteAttributeString("firstname", profile.username); + xw.WriteAttributeString("lastname", profile.surname); + xw.WriteAttributeString("uuid", profile.UUID.ToStringHyphenated()); + // Server Information + xw.WriteAttributeString("server_inventory", profile.userInventoryURI); + xw.WriteAttributeString("server_asset", profile.userAssetURI); + // Profile Information + xw.WriteAttributeString("profile_about", profile.profileAboutText); + xw.WriteAttributeString("profile_firstlife_about", profile.profileFirstText); + xw.WriteAttributeString("profile_firstlife_image", profile.profileFirstImage.ToStringHyphenated()); + xw.WriteAttributeString("profile_can_do", profile.profileCanDoMask.ToString()); + xw.WriteAttributeString("profile_want_do", profile.profileWantDoMask.ToString()); + xw.WriteAttributeString("profile_image", profile.profileImage.ToStringHyphenated()); + xw.WriteAttributeString("profile_created",profile.created.ToString()); + xw.WriteAttributeString("profile_lastlogin",profile.lastLogin.ToString()); + // Home region information + xw.WriteAttributeString("home_coordinates", profile.homeLocation.ToString()); + xw.WriteAttributeString("home_region", profile.homeRegion.ToString()); + xw.WriteAttributeString("home_look", profile.homeLookAt.ToString()); + + xw.WriteEndElement(); + + // Footer + xw.WriteEndElement(); + xw.Flush(); + xw.Close(); + + return sw.ToString(); + } + + #region REST Methods + //should most likely move out of here and into the grid's userserver sub class + public string RestGetUserMethodName(string request, string path, string param) + { + UserProfileData userProfile = getUserProfile(param.Trim()); + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXml(userProfile); + } + + public string RestGetUserMethodUUID(string request, string path, string param) + { + UserProfileData userProfile = getUserProfile(new LLUUID(param)); + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXml(userProfile); + } + #endregion + + } +} diff --git a/OpenSim/Grid/AssetServer/AssetHttpServer.cs b/OpenSim/Grid/AssetServer/AssetHttpServer.cs new file mode 100644 index 0000000..6fc6bf8 --- /dev/null +++ b/OpenSim/Grid/AssetServer/AssetHttpServer.cs @@ -0,0 +1,130 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +//using OpenSim.CAPS; +using Nwc.XmlRpc; +using System.Collections; +using OpenSim.Framework.Console; +using OpenSim.Servers; + +namespace OpenGridServices.AssetServer +{ + /// + /// An HTTP server for sending assets + /// + public class AssetHttpServer :BaseHttpServer + { + /// + /// Creates the new asset server + /// + /// Port to initalise on + public AssetHttpServer(int port) + : base(port) + { + } + + /// + /// Handles an HTTP request + /// + /// HTTP State Info + public override void HandleRequest(Object stateinfo) + { + try + { + HttpListenerContext context = (HttpListenerContext)stateinfo; + + HttpListenerRequest request = context.Request; + HttpListenerResponse response = context.Response; + + response.KeepAlive = false; + response.SendChunked = false; + + System.IO.Stream body = request.InputStream; + System.Text.Encoding encoding = System.Text.Encoding.UTF8; + System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding); + + string requestBody = reader.ReadToEnd(); + body.Close(); + reader.Close(); + + //Console.WriteLine(request.HttpMethod + " " + request.RawUrl + " Http/" + request.ProtocolVersion.ToString() + " content type: " + request.ContentType); + //Console.WriteLine(requestBody); + + string responseString = ""; + switch (request.ContentType) + { + case "text/xml": + // must be XML-RPC, so pass to the XML-RPC parser + + responseString = ParseXMLRPC(requestBody); + responseString = Regex.Replace(responseString, "utf-16", "utf-8"); + + response.AddHeader("Content-type", "text/xml"); + break; + + case "application/xml": + // probably LLSD we hope, otherwise it should be ignored by the parser + responseString = ParseLLSDXML(requestBody); + response.AddHeader("Content-type", "application/xml"); + break; + + case "application/x-www-form-urlencoded": + // a form data POST so send to the REST parser + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "text/plain"); + break; + + case null: + // must be REST or invalid crap, so pass to the REST parser + responseString = ParseREST(requestBody, request.RawUrl, request.HttpMethod); + response.AddHeader("Content-type", "text/plain"); + break; + + } + + Encoding Windows1252Encoding = Encoding.GetEncoding(1252); + byte[] buffer = Windows1252Encoding.GetBytes(responseString); + System.IO.Stream output = response.OutputStream; + response.SendChunked = false; + response.ContentLength64 = buffer.Length; + output.Write(buffer, 0, buffer.Length); + output.Close(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } + + } +} diff --git a/OpenSim/Grid/AssetServer/Main.cs b/OpenSim/Grid/AssetServer/Main.cs new file mode 100644 index 0000000..96c9dba --- /dev/null +++ b/OpenSim/Grid/AssetServer/Main.cs @@ -0,0 +1,337 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.IO; +using System.Text; +using System.Timers; +using System.Net; +using System.Reflection; +using System.Threading; +using libsecondlife; +using OpenSim.Framework; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Console; +using OpenSim.Framework.Types; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using OpenSim.Servers; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; + +namespace OpenGridServices.AssetServer +{ + /// + /// An asset server + /// + public class OpenAsset_Main : conscmd_callback + { + private IObjectContainer db; + + public static OpenAsset_Main assetserver; + + private LogBase m_console; + + [STAThread] + public static void Main(string[] args) + { + Console.WriteLine("Starting...\n"); + + assetserver = new OpenAsset_Main(); + assetserver.Startup(); + + assetserver.Work(); + } + + private void Work() + { + m_console.Notice("Enter help for a list of commands"); + + while (true) + { + m_console.MainLogPrompt(); + } + } + + private OpenAsset_Main() + { + m_console = new LogBase("opengrid-AssetServer-console.log", "OpenAsset", this, false); + OpenSim.Framework.Console.MainLog.Instance = m_console; + } + + public void Startup() + { + m_console.Verbose( "Main.cs:Startup() - Setting up asset DB"); + setupDB(); + + m_console.Verbose( "Main.cs:Startup() - Starting HTTP process"); + AssetHttpServer httpServer = new AssetHttpServer(8003); + + + httpServer.AddRestHandler("GET", "/assets/", this.assetGetMethod); + httpServer.AddRestHandler("POST", "/assets/", this.assetPostMethod); + + httpServer.Start(); + + } + + public string assetPostMethod(string requestBody, string path, string param) + { + AssetBase asset = new AssetBase(); + asset.Name = ""; + asset.FullID = new LLUUID(param); + Encoding Windows1252Encoding = Encoding.GetEncoding(1252); + byte[] buffer = Windows1252Encoding.GetBytes(requestBody); + asset.Data = buffer; + AssetStorage store = new AssetStorage(); + store.Data = asset.Data; + store.Name = asset.Name; + store.UUID = asset.FullID; + db.Set(store); + db.Commit(); + return ""; + } + + public string assetGetMethod(string request, string path, string param) + { + Console.WriteLine("got a request " + param); + byte[] assetdata = getAssetData(new LLUUID(param), false); + if (assetdata != null) + { + Encoding Windows1252Encoding = Encoding.GetEncoding(1252); + string ret = Windows1252Encoding.GetString(assetdata); + //string ret = System.Text.Encoding.Unicode.GetString(assetdata); + + return ret; + + } + else + { + return ""; + } + + } + + public byte[] getAssetData(LLUUID assetID, bool isTexture) + { + bool found = false; + AssetStorage foundAsset = null; + + IObjectSet result = db.Get(new AssetStorage(assetID)); + if (result.Count > 0) + { + foundAsset = (AssetStorage)result.Next(); + found = true; + } + + if (found) + { + return foundAsset.Data; + } + else + { + return null; + } + } + + public void setupDB() + { + bool yapfile = System.IO.File.Exists("assets.yap"); + try + { + db = Db4oFactory.OpenFile("assets.yap"); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Main.cs:setupDB() - creation"); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainLog.Instance.Warn("Main.cs:setupDB() - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + if (!yapfile) + { + this.LoadDB(); + } + } + + public void LoadDB() + { + try + { + + Console.WriteLine("setting up Asset database"); + + AssetBase Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000001"); + Image.Name = "Bricks"; + this.LoadAsset(Image, true, "bricks.jp2"); + AssetStorage store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000002"); + Image.Name = "Plywood"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000003"); + Image.Name = "Rocks"; + this.LoadAsset(Image, true, "rocks.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000004"); + Image.Name = "Granite"; + this.LoadAsset(Image, true, "granite.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000005"); + Image.Name = "Hardwood"; + this.LoadAsset(Image, true, "hardwood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-5005-000000000005"); + Image.Name = "Prim Base Texture"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73"); + Image.Name = "Shape"; + this.LoadAsset(Image, false, "base_shape.dat"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + + private void LoadAsset(AssetBase info, bool image, string filename) + { + + + string dataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "assets"); //+ folder; + string fileName = Path.Combine(dataPath, filename); + FileInfo fInfo = new FileInfo(fileName); + long numBytes = fInfo.Length; + FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + byte[] idata = new byte[numBytes]; + BinaryReader br = new BinaryReader(fStream); + idata = br.ReadBytes((int)numBytes); + br.Close(); + fStream.Close(); + info.Data = idata; + //info.loaded=true; + } + + /*private GridConfig LoadConfigDll(string dllName) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + GridConfig config = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IGridConfig", true); + + if (typeInterface != null) + { + IGridConfig plug = (IGridConfig)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + config = plug.GetConfigObject(); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + return config; + }*/ + + public void RunCmd(string cmd, string[] cmdparams) + { + switch (cmd) + { + case "help": + m_console.Notice("shutdown - shutdown this asset server (USE CAUTION!)"); + break; + + case "shutdown": + m_console.Close(); + Environment.Exit(0); + break; + } + } + + public void Show(string ShowWhat) + { + } + } +} diff --git a/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj b/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj new file mode 100644 index 0000000..caebca3 --- /dev/null +++ b/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj @@ -0,0 +1,118 @@ + + + Local + 8.0.50727 + 2.0 + {E5F1A03B-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.AssetServer + JScript + Grid + IE50 + false + Exe + + OpenSim.Grid.AssetServer + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + OpenSim.Framework.Servers.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj.user b/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/AssetServer/OpenSim.Grid.AssetServer.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs b/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f9a18a8 --- /dev/null +++ b/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs @@ -0,0 +1,60 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OGS-AssetServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OGS-AssetServer")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b541b244-3d1d-4625-9003-bc2a3a6a39a4")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Grid/Framework.Manager/GridManagementAgent.cs b/OpenSim/Grid/Framework.Manager/GridManagementAgent.cs new file mode 100644 index 0000000..dfc572a --- /dev/null +++ b/OpenSim/Grid/Framework.Manager/GridManagementAgent.cs @@ -0,0 +1,140 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using Nwc.XmlRpc; +using OpenSim.Framework; +using OpenSim.Servers; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; + +namespace OpenGrid.Framework.Manager +{ + /// + /// Used to pass messages to the gridserver + /// + /// Pass this argument + public delegate void GridManagerCallback(string param); + + /// + /// Serverside listener for grid commands + /// + public class GridManagementAgent + { + /// + /// Passes grid server messages + /// + private GridManagerCallback thecallback; + + /// + /// Security keys + /// + private string sendkey; + private string recvkey; + + /// + /// Our component type + /// + private string component_type; + + /// + /// List of active sessions + /// + private static ArrayList Sessions; + + /// + /// Initialises a new GridManagementAgent + /// + /// HTTP Daemon for this server + /// What component type are we? + /// Security send key + /// Security recieve key + /// Message callback + public GridManagementAgent(BaseHttpServer app_httpd, string component_type, string sendkey, string recvkey, GridManagerCallback thecallback) + { + this.sendkey = sendkey; + this.recvkey = recvkey; + this.component_type = component_type; + this.thecallback = thecallback; + Sessions = new ArrayList(); + + app_httpd.AddXmlRPCHandler("manager_login", XmlRpcLoginMethod); + + switch (component_type) + { + case "gridserver": + GridServerManager.sendkey = this.sendkey; + GridServerManager.recvkey = this.recvkey; + GridServerManager.thecallback = thecallback; + app_httpd.AddXmlRPCHandler("shutdown", GridServerManager.XmlRpcShutdownMethod); + break; + } + } + + /// + /// Checks if a session exists + /// + /// The session ID + /// Exists? + public static bool SessionExists(LLUUID sessionID) + { + return Sessions.Contains(sessionID); + } + + /// + /// Logs a new session to the grid manager + /// + /// the XMLRPC request + /// An XMLRPC reply + public static XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + // TODO: Switch this over to using OpenGrid.Framework.Data + if (requestData["username"].Equals("admin") && requestData["password"].Equals("supersecret")) + { + response.IsFault = false; + LLUUID new_session = LLUUID.Random(); + Sessions.Add(new_session); + responseData["session_id"] = new_session.ToString(); + responseData["msg"] = "Login OK"; + } + else + { + response.IsFault = true; + responseData["error"] = "Invalid username or password"; + } + + response.Value = responseData; + return response; + + } + + } +} diff --git a/OpenSim/Grid/Framework.Manager/GridServerManager.cs b/OpenSim/Grid/Framework.Manager/GridServerManager.cs new file mode 100644 index 0000000..e276556 --- /dev/null +++ b/OpenSim/Grid/Framework.Manager/GridServerManager.cs @@ -0,0 +1,94 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using Nwc.XmlRpc; +using System.Threading; +using libsecondlife; + +namespace OpenGrid.Framework.Manager { + + /// + /// A remote management system for the grid server + /// + public class GridServerManager + { + /// + /// Triggers events from the grid manager + /// + public static GridManagerCallback thecallback; + + /// + /// Security keys + /// + public static string sendkey; + public static string recvkey; + + /// + /// Disconnects the grid server and shuts it down + /// + /// XmlRpc Request + /// An XmlRpc response containing either a "msg" or an "error" + public static XmlRpcResponse XmlRpcShutdownMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if(requestData.ContainsKey("session_id")) { + if(GridManagementAgent.SessionExists(new LLUUID((string)requestData["session_id"]))) { + responseData["msg"]="Shutdown command accepted"; + (new Thread(new ThreadStart(ShutdownServer))).Start(); + } else { + response.IsFault=true; + responseData["error"]="bad session ID"; + } + } else { + response.IsFault=true; + responseData["error"]="no session ID"; + } + + response.Value = responseData; + return response; + } + + /// + /// Shuts down the grid server + /// + public static void ShutdownServer() + { + Console.WriteLine("Shutting down the grid server - recieved a grid manager request"); + Console.WriteLine("Terminating in three seconds..."); + Thread.Sleep(3000); + thecallback("shutdown"); + } + } +} + diff --git a/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj b/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj new file mode 100644 index 0000000..9a98ff4 --- /dev/null +++ b/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj @@ -0,0 +1,99 @@ + + + Local + 8.0.50727 + 2.0 + {4B7BFD1C-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.Framework.Manager + JScript + Grid + IE50 + false + Library + + OpenSim.Grid.Framework.Manager + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Servers.dll + False + + + System.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj.user b/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/Framework.Manager/OpenSim.Grid.Framework.Manager.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs b/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs new file mode 100644 index 0000000..c9701d6 --- /dev/null +++ b/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("GridConfig")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GridConfig")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Grid/GridServer.Config/DbGridConfig.cs b/OpenSim/Grid/GridServer.Config/DbGridConfig.cs new file mode 100644 index 0000000..2218004 --- /dev/null +++ b/OpenSim/Grid/GridServer.Config/DbGridConfig.cs @@ -0,0 +1,161 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using Db4objects.Db4o; + +namespace OpenGrid.Config.GridConfigDb4o +{ + /// + /// A grid configuration interface for returning the DB4o Config Provider + /// + public class Db40ConfigPlugin: IGridConfig + { + /// + /// Loads and returns a configuration objeect + /// + /// A grid configuration object + public GridConfig GetConfigObject() + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Loading Db40Config dll"); + return ( new DbGridConfig()); + } + } + + /// + /// A DB4o based Gridserver configuration object + /// + public class DbGridConfig : GridConfig + { + /// + /// The DB4o Database + /// + private IObjectContainer db; + + /// + /// User configuration for the Grid Config interfaces + /// + public void LoadDefaults() { + OpenSim.Framework.Console.MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); + + // About the grid options + this.GridOwner = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Grid owner", "OGS development team"); + + // Asset Options + this.DefaultAssetServer = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Default asset server","http://127.0.0.1:8003/"); + this.AssetSendKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to send to asset server","null"); + this.AssetRecvKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to expect from asset server","null"); + + // User Server Options + this.DefaultUserServer = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Default user server","http://127.0.0.1:8002/"); + this.UserSendKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to send to user server","null"); + this.UserRecvKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to expect from user server","null"); + + // Region Server Options + this.SimSendKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to send to sims","null"); + this.SimRecvKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to expect from sims","null"); + } + + /// + /// Initialises a new configuration object + /// + public override void InitConfig() { + try { + // Perform Db4o initialisation + db = Db4oFactory.OpenFile("opengrid.yap"); + + // Locate the grid configuration object + IObjectSet result = db.Get(typeof(DbGridConfig)); + // Found? + if(result.Count==1) { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Config.cs:InitConfig() - Found a GridConfig object in the local database, loading"); + foreach (DbGridConfig cfg in result) { + // Import each setting into this class + // Grid Settings + this.GridOwner=cfg.GridOwner; + // Asset Settings + this.DefaultAssetServer=cfg.DefaultAssetServer; + this.AssetSendKey=cfg.AssetSendKey; + this.AssetRecvKey=cfg.AssetRecvKey; + // User Settings + this.DefaultUserServer=cfg.DefaultUserServer; + this.UserSendKey=cfg.UserSendKey; + this.UserRecvKey=cfg.UserRecvKey; + // Region Settings + this.SimSendKey=cfg.SimSendKey; + this.SimRecvKey=cfg.SimRecvKey; + } + // Create a new configuration object from this class + } else { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Config.cs:InitConfig() - Could not find object in database, loading precompiled defaults"); + + // Load default settings into this class + LoadDefaults(); + + // Saves to the database file... + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Writing out default settings to local database"); + db.Set(this); + + // Closes file locks + db.Close(); + } + } catch(Exception e) { + OpenSim.Framework.Console.MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + + // Grid Settings + OpenSim.Framework.Console.MainLog.Instance.Verbose("Grid settings loaded:"); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Grid owner: " + this.GridOwner); + + // Asset Settings + OpenSim.Framework.Console.MainLog.Instance.Verbose("Default asset server: " + this.DefaultAssetServer); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to send to asset server: " + this.AssetSendKey); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to expect from asset server: " + this.AssetRecvKey); + + // User Settings + OpenSim.Framework.Console.MainLog.Instance.Verbose("Default user server: " + this.DefaultUserServer); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to send to user server: " + this.UserSendKey); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to expect from user server: " + this.UserRecvKey); + + // Region Settings + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to send to sims: " + this.SimSendKey); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to expect from sims: " + this.SimRecvKey); + } + + /// + /// Closes down the database and releases filesystem locks + /// + public void Shutdown() { + db.Close(); + } + } + +} diff --git a/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj b/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj new file mode 100644 index 0000000..24e845c --- /dev/null +++ b/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj @@ -0,0 +1,107 @@ + + + Local + 8.0.50727 + 2.0 + {1442B635-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.GridServer.Config + JScript + Grid + IE50 + false + Library + + OpenSim.Grid.GridServer.Config + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + System.dll + False + + + ..\..\..\bin\System.Data.dll + False + + + System.Xml.dll + False + + + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj.user b/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/GridServer.Config/OpenSim.Grid.GridServer.Config.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/GridServer/GridManager.cs b/OpenSim/Grid/GridServer/GridManager.cs new file mode 100644 index 0000000..bf80652 --- /dev/null +++ b/OpenSim/Grid/GridServer/GridManager.cs @@ -0,0 +1,599 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using OpenGrid.Framework.Data; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Console; +using OpenSim.Framework.Sims; +using libsecondlife; +using Nwc.XmlRpc; +using System.Xml; + +namespace OpenGridServices.GridServer +{ + class GridManager + { + Dictionary _plugins = new Dictionary(); + Dictionary _logplugins = new Dictionary(); + + public OpenSim.Framework.Interfaces.GridConfig config; + + /// + /// Adds a new grid server plugin - grid servers will be requested in the order they were loaded. + /// + /// The filename to the grid server plugin DLL + public void AddPlugin(string FileName) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Storage: Attempting to load " + FileName); + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + OpenSim.Framework.Console.MainLog.Instance.Verbose("Storage: Found " + pluginAssembly.GetTypes().Length + " interfaces."); + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (!pluginType.IsAbstract) + { + // Regions go here + Type typeInterface = pluginType.GetInterface("IGridData", true); + + if (typeInterface != null) + { + IGridData plug = (IGridData)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Initialise(); + this._plugins.Add(plug.getName(), plug); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Storage: Added IGridData Interface"); + } + + typeInterface = null; + + // Logs go here + typeInterface = pluginType.GetInterface("ILogData", true); + + if (typeInterface != null) + { + ILogData plug = (ILogData)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Initialise(); + this._logplugins.Add(plug.getName(), plug); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Storage: Added ILogData Interface"); + } + + typeInterface = null; + } + } + + pluginAssembly = null; + } + + /// + /// Logs a piece of information to the database + /// + /// What you were operating on (in grid server, this will likely be the region UUIDs) + /// Which method is being called? + /// What arguments are being passed? + /// How high priority is this? 1 = Max, 6 = Verbose + /// The message to log + private void logToDB(string target, string method, string args, int priority, string message) + { + foreach (KeyValuePair kvp in _logplugins) + { + try + { + kvp.Value.saveLog("Gridserver", target, method, args, priority, message); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: unable to write log via " + kvp.Key); + } + } + } + + /// + /// Returns a region by argument + /// + /// A UUID key of the region to return + /// A SimProfileData for the region + public SimProfileData getRegion(libsecondlife.LLUUID uuid) + { + foreach(KeyValuePair kvp in _plugins) { + try + { + return kvp.Value.GetProfileByLLUUID(uuid); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: Unable to find region " + uuid.ToStringHyphenated() + " via " + kvp.Key); + } + } + return null; + } + + /// + /// Returns a region by argument + /// + /// A regionHandle of the region to return + /// A SimProfileData for the region + public SimProfileData getRegion(ulong handle) + { + foreach (KeyValuePair kvp in _plugins) + { + try + { + return kvp.Value.GetProfileByHandle(handle); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: Unable to find region " + handle.ToString() + " via " + kvp.Key); + } + } + return null; + } + + public Dictionary getRegions(uint xmin, uint ymin, uint xmax, uint ymax) + { + Dictionary regions = new Dictionary(); + + SimProfileData[] neighbours; + + foreach (KeyValuePair kvp in _plugins) + { + try + { + neighbours = kvp.Value.GetProfilesInRange(xmin, ymin, xmax, ymax); + foreach (SimProfileData neighbour in neighbours) + { + regions[neighbour.regionHandle] = neighbour; + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: Unable to query regionblock via " + kvp.Key); + } + } + + return regions; + } + + /// + /// Returns a XML String containing a list of the neighbouring regions + /// + /// The regionhandle for the center sim + /// An XML string containing neighbour entities + public string GetXMLNeighbours(ulong reqhandle) + { + string response = ""; + SimProfileData central_region = getRegion(reqhandle); + SimProfileData neighbour; + for (int x = -1; x < 2; x++) for (int y = -1; y < 2; y++) + { + if (getRegion(Util.UIntsToLong((uint)((central_region.regionLocX + x) * 256), (uint)(central_region.regionLocY + y) * 256)) != null) + { + neighbour = getRegion(Util.UIntsToLong((uint)((central_region.regionLocX + x) * 256), (uint)(central_region.regionLocY + y) * 256)); + response += ""; + response += "" + neighbour.serverIP + ""; + response += "" + neighbour.serverPort.ToString() + ""; + response += "" + neighbour.regionLocX.ToString() + ""; + response += "" + neighbour.regionLocY.ToString() + ""; + response += "" + neighbour.regionHandle.ToString() + ""; + response += ""; + + } + } + return response; + } + + /// + /// Performed when a region connects to the grid server initially. + /// + /// The XMLRPC Request + /// Startup parameters + public XmlRpcResponse XmlRpcLoginToSimulatorMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + response.Value = responseData; + + SimProfileData TheSim = null; + Hashtable requestData = (Hashtable)request.Params[0]; + + if (requestData.ContainsKey("UUID")) + { + TheSim = getRegion(new LLUUID((string)requestData["UUID"])); + logToDB((new LLUUID((string)requestData["UUID"])).ToStringHyphenated(),"XmlRpcLoginToSimulatorMethod","", 5,"Region attempting login with UUID."); + } + else if (requestData.ContainsKey("region_handle")) + { + TheSim = getRegion((ulong)Convert.ToUInt64(requestData["region_handle"])); + logToDB((string)requestData["region_handle"], "XmlRpcLoginToSimulatorMethod", "", 5, "Region attempting login with regionHandle."); + } + else + { + responseData["error"] = "No UUID or region_handle passed to grid server - unable to connect you"; + return response; + } + + if (TheSim == null) + { + responseData["error"] = "sim not found"; + return response; + } + else + { + + ArrayList SimNeighboursData = new ArrayList(); + + SimProfileData neighbour; + Hashtable NeighbourBlock; + + bool fastMode = false; // Only compatible with MySQL right now + + if (fastMode) + { + Dictionary neighbours = getRegions(TheSim.regionLocX - 1, TheSim.regionLocY - 1, TheSim.regionLocX + 1, TheSim.regionLocY + 1); + + foreach (KeyValuePair aSim in neighbours) + { + NeighbourBlock = new Hashtable(); + NeighbourBlock["sim_ip"] = aSim.Value.serverIP.ToString(); + NeighbourBlock["sim_port"] = aSim.Value.serverPort.ToString(); + NeighbourBlock["region_locx"] = aSim.Value.regionLocX.ToString(); + NeighbourBlock["region_locy"] = aSim.Value.regionLocY.ToString(); + NeighbourBlock["UUID"] = aSim.Value.UUID.ToString(); + + if (aSim.Value.UUID != TheSim.UUID) + SimNeighboursData.Add(NeighbourBlock); + } + } + else + { + for (int x = -1; x < 2; x++) for (int y = -1; y < 2; y++) + { + if (getRegion(Helpers.UIntsToLong((uint)((TheSim.regionLocX + x) * 256), (uint)(TheSim.regionLocY + y) * 256)) != null) + { + neighbour = getRegion(Helpers.UIntsToLong((uint)((TheSim.regionLocX + x) * 256), (uint)(TheSim.regionLocY + y) * 256)); + + NeighbourBlock = new Hashtable(); + NeighbourBlock["sim_ip"] = neighbour.serverIP; + NeighbourBlock["sim_port"] = neighbour.serverPort.ToString(); + NeighbourBlock["region_locx"] = neighbour.regionLocX.ToString(); + NeighbourBlock["region_locy"] = neighbour.regionLocY.ToString(); + NeighbourBlock["UUID"] = neighbour.UUID.ToString(); + + if (neighbour.UUID != TheSim.UUID) SimNeighboursData.Add(NeighbourBlock); + } + } + } + + responseData["UUID"] = TheSim.UUID.ToString(); + responseData["region_locx"] = TheSim.regionLocX.ToString(); + responseData["region_locy"] = TheSim.regionLocY.ToString(); + responseData["regionname"] = TheSim.regionName; + responseData["estate_id"] = "1"; + responseData["neighbours"] = SimNeighboursData; + + responseData["sim_ip"] = TheSim.serverIP; + responseData["sim_port"] = TheSim.serverPort.ToString(); + responseData["asset_url"] = TheSim.regionAssetURI; + responseData["asset_sendkey"] = TheSim.regionAssetSendKey; + responseData["asset_recvkey"] = TheSim.regionAssetRecvKey; + responseData["user_url"] = TheSim.regionUserURI; + responseData["user_sendkey"] = TheSim.regionUserSendKey; + responseData["user_recvkey"] = TheSim.regionUserRecvKey; + responseData["authkey"] = TheSim.regionSecret; + + // New! If set, use as URL to local sim storage (ie http://remotehost/region.yap) + responseData["data_uri"] = TheSim.regionDataURI; + } + + return response; + } + + public XmlRpcResponse XmlRpcMapBlockMethod(XmlRpcRequest request) + { + int xmin=980, ymin=980, xmax=1020, ymax=1020; + + Hashtable requestData = (Hashtable)request.Params[0]; + if (requestData.ContainsKey("xmin")) + { + xmin = (Int32)requestData["xmin"]; + } + if (requestData.ContainsKey("ymin")) + { + ymin = (Int32)requestData["ymin"]; + } + if (requestData.ContainsKey("xmax")) + { + xmax = (Int32)requestData["xmax"]; + } + if (requestData.ContainsKey("ymax")) + { + ymax = (Int32)requestData["ymax"]; + } + + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + response.Value = responseData; + IList simProfileList = new ArrayList(); + + bool fastMode = true; // MySQL Only + + if (fastMode) + { + Dictionary neighbours = getRegions((uint)xmin, (uint)ymin, (uint)xmax, (uint)ymax); + + foreach (KeyValuePair aSim in neighbours) + { + Hashtable simProfileBlock = new Hashtable(); + simProfileBlock["x"] = aSim.Value.regionLocX.ToString(); + simProfileBlock["y"] = aSim.Value.regionLocY.ToString(); + simProfileBlock["name"] = aSim.Value.regionName; + simProfileBlock["access"] = 21; + simProfileBlock["region-flags"] = 512; + simProfileBlock["water-height"] = 0; + simProfileBlock["agents"] = 1; + simProfileBlock["map-image-id"] = aSim.Value.regionMapTextureID.ToString(); + + // For Sugilite compatibility + simProfileBlock["regionhandle"] = aSim.Value.regionHandle.ToString(); + simProfileBlock["sim_ip"] = aSim.Value.serverIP.ToString(); + simProfileBlock["sim_port"] = aSim.Value.serverPort.ToString(); + simProfileBlock["sim_uri"] = aSim.Value.serverURI.ToString(); + simProfileBlock["uuid"] = aSim.Value.UUID.ToStringHyphenated(); + + simProfileList.Add(simProfileBlock); + } + OpenSim.Framework.Console.MainLog.Instance.Verbose("World map request processed, returned " + simProfileList.Count.ToString() + " region(s) in range via FastMode"); + } + else + { + SimProfileData simProfile; + for (int x = xmin; x < xmax; x++) + { + for (int y = ymin; y < ymax; y++) + { + simProfile = getRegion(Helpers.UIntsToLong((uint)(x * 256), (uint)(y * 256))); + if (simProfile != null) + { + Hashtable simProfileBlock = new Hashtable(); + simProfileBlock["x"] = x; + simProfileBlock["y"] = y; + simProfileBlock["name"] = simProfile.regionName; + simProfileBlock["access"] = 0; + simProfileBlock["region-flags"] = 0; + simProfileBlock["water-height"] = 20; + simProfileBlock["agents"] = 1; + simProfileBlock["map-image-id"] = simProfile.regionMapTextureID.ToString(); + + // For Sugilite compatibility + simProfileBlock["regionhandle"] = simProfile.regionHandle.ToString(); + simProfileBlock["sim_ip"] = simProfile.serverIP.ToString(); + simProfileBlock["sim_port"] = simProfile.serverPort.ToString(); + simProfileBlock["sim_uri"] = simProfile.serverURI.ToString(); + simProfileBlock["uuid"] = simProfile.UUID.ToStringHyphenated(); + + simProfileList.Add(simProfileBlock); + } + } + } + OpenSim.Framework.Console.MainLog.Instance.Verbose("World map request processed, returned " + simProfileList.Count.ToString() + " region(s) in range via Standard Mode"); + } + + responseData["sim-profiles"] = simProfileList; + + return response; + } + + + + /// + /// Performs a REST Get Operation + /// + /// + /// + /// + /// + public string RestGetRegionMethod(string request, string path, string param) + { + return RestGetSimMethod("", "/sims/", param); + } + + /// + /// Performs a REST Set Operation + /// + /// + /// + /// + /// + public string RestSetRegionMethod(string request, string path, string param) + { + return RestSetSimMethod("", "/sims/", param); + } + + /// + /// Returns information about a sim via a REST Request + /// + /// + /// + /// + /// Information about the sim in XML + public string RestGetSimMethod(string request, string path, string param) + { + string respstring = String.Empty; + + SimProfileData TheSim; + LLUUID UUID = new LLUUID(param); + TheSim = getRegion(UUID); + + if (!(TheSim == null)) + { + respstring = ""; + respstring += "" + TheSim.regionSendKey + ""; + respstring += ""; + respstring += "" + TheSim.UUID.ToString() + ""; + respstring += "" + TheSim.regionName + ""; + respstring += "" + TheSim.serverIP + ""; + respstring += "" + TheSim.serverPort.ToString() + ""; + respstring += "" + TheSim.regionLocX.ToString() + ""; + respstring += "" + TheSim.regionLocY.ToString() + ""; + respstring += "1"; + respstring += ""; + respstring += ""; + } + + return respstring; + } + + /// + /// Creates or updates a sim via a REST Method Request + /// BROKEN with SQL Update + /// + /// + /// + /// + /// "OK" or an error + public string RestSetSimMethod(string request, string path, string param) + { + Console.WriteLine("Processing region update"); + SimProfileData TheSim; + TheSim = getRegion(new LLUUID(param)); + if ((TheSim) == null) + { + TheSim = new SimProfileData(); + LLUUID UUID = new LLUUID(param); + TheSim.UUID = UUID; + TheSim.regionRecvKey = config.SimRecvKey; + } + + XmlDocument doc = new XmlDocument(); + doc.LoadXml(request); + XmlNode rootnode = doc.FirstChild; + XmlNode authkeynode = rootnode.ChildNodes[0]; + if (authkeynode.Name != "authkey") + { + return "ERROR! bad XML - expected authkey tag"; + } + + XmlNode simnode = rootnode.ChildNodes[1]; + if (simnode.Name != "sim") + { + return "ERROR! bad XML - expected sim tag"; + } + + if (authkeynode.InnerText != TheSim.regionRecvKey) + { + return "ERROR! invalid key"; + } + + //TheSim.regionSendKey = Cfg; + TheSim.regionRecvKey = config.SimRecvKey; + TheSim.regionSendKey = config.SimSendKey; + TheSim.regionSecret = config.SimRecvKey; + TheSim.regionDataURI = ""; + TheSim.regionAssetURI = config.DefaultAssetServer; + TheSim.regionAssetRecvKey = config.AssetRecvKey; + TheSim.regionAssetSendKey = config.AssetSendKey; + TheSim.regionUserURI = config.DefaultUserServer; + TheSim.regionUserSendKey = config.UserSendKey; + TheSim.regionUserRecvKey = config.UserRecvKey; + + + for (int i = 0; i < simnode.ChildNodes.Count; i++) + { + switch (simnode.ChildNodes[i].Name) + { + case "regionname": + TheSim.regionName = simnode.ChildNodes[i].InnerText; + break; + + case "sim_ip": + TheSim.serverIP = simnode.ChildNodes[i].InnerText; + break; + + case "sim_port": + TheSim.serverPort = Convert.ToUInt32(simnode.ChildNodes[i].InnerText); + break; + + case "region_locx": + TheSim.regionLocX = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); + TheSim.regionHandle = Helpers.UIntsToLong((TheSim.regionLocX * 256), (TheSim.regionLocY * 256)); + break; + + case "region_locy": + TheSim.regionLocY = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); + TheSim.regionHandle = Helpers.UIntsToLong((TheSim.regionLocX * 256), (TheSim.regionLocY * 256)); + break; + } + } + + TheSim.serverURI = "http://" + TheSim.serverIP + ":" + TheSim.serverPort + "/"; + + bool requirePublic = false; + + if (requirePublic && (TheSim.serverIP.StartsWith("172.16") || TheSim.serverIP.StartsWith("192.168") || TheSim.serverIP.StartsWith("10.") || TheSim.serverIP.StartsWith("0.") || TheSim.serverIP.StartsWith("255."))) + { + return "ERROR! Servers must register with public addresses."; + } + + + try + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Updating / adding via " + _plugins.Count + " storage provider(s) registered."); + foreach (KeyValuePair kvp in _plugins) + { + try + { + //Check reservations + ReservationData reserveData = kvp.Value.GetReservationAtPoint(TheSim.regionLocX, TheSim.regionLocY); + if ((reserveData != null && reserveData.gridRecvKey == TheSim.regionRecvKey) || (reserveData == null)) + { + kvp.Value.AddProfile(TheSim); + OpenSim.Framework.Console.MainLog.Instance.Verbose("New sim added to grid (" + TheSim.regionName + ")"); + logToDB(TheSim.UUID.ToStringHyphenated(), "RestSetSimMethod", "", 5, "Region successfully updated and connected to grid."); + } + else + { + return "Unable to update region (RestSetSimMethod): Incorrect auth key."; + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("getRegionPlugin Handle " + kvp.Key + " unable to add new sim: " + e.ToString()); + } + } + return "OK"; + } + catch (Exception e) + { + return "ERROR! Could not save to database! (" + e.ToString() + ")"; + } + } + + } +} diff --git a/OpenSim/Grid/GridServer/Main.cs b/OpenSim/Grid/GridServer/Main.cs new file mode 100644 index 0000000..b948fd6 --- /dev/null +++ b/OpenSim/Grid/GridServer/Main.cs @@ -0,0 +1,271 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.IO; +using System.Text; +using System.Timers; +using System.Net; +using System.Threading; +using System.Reflection; +using libsecondlife; +using OpenGrid.Framework.Manager; +using OpenSim.Framework; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenGridServices.GridServer +{ + /// + /// + public class OpenGrid_Main : conscmd_callback + { + private string ConfigDll = "OpenGrid.Config.GridConfigDb4o.dll"; + private string GridDll = "OpenGrid.Framework.Data.MySQL.dll"; + public GridConfig Cfg; + + public static OpenGrid_Main thegrid; + protected IGenericConfig localXMLConfig; + + public static bool setuponly; + + //public LLUUID highestUUID; + + // private SimProfileManager m_simProfileManager; + + private GridManager m_gridManager; + + private LogBase m_console; + + [STAThread] + public static void Main(string[] args) + { + if (args.Length > 0) + { + if (args[0] == "-setuponly") setuponly = true; + } + Console.WriteLine("Starting...\n"); + + thegrid = new OpenGrid_Main(); + thegrid.Startup(); + + thegrid.Work(); + } + + private void Work() + { + while (true) + { + Thread.Sleep(5000); + // should flush the DB etc here + } + } + + private OpenGrid_Main() + { + m_console = new LogBase("opengrid-gridserver-console.log", "OpenGrid", this, false); + MainLog.Instance = m_console; + + + } + + public void managercallback(string cmd) + { + switch (cmd) + { + case "shutdown": + RunCmd("shutdown", new string[0]); + break; + } + } + + + public void Startup() + { + this.localXMLConfig = new XmlConfig("GridServerConfig.xml"); + this.localXMLConfig.LoadData(); + this.ConfigDB(this.localXMLConfig); + this.localXMLConfig.Close(); + + m_console.Verbose( "Main.cs:Startup() - Loading configuration"); + Cfg = this.LoadConfigDll(this.ConfigDll); + Cfg.InitConfig(); + if (setuponly) Environment.Exit(0); + + m_console.Verbose( "Main.cs:Startup() - Connecting to Storage Server"); + m_gridManager = new GridManager(); + m_gridManager.AddPlugin(GridDll); // Made of win + m_gridManager.config = Cfg; + + m_console.Verbose( "Main.cs:Startup() - Starting HTTP process"); + BaseHttpServer httpServer = new BaseHttpServer(8001); + //GridManagementAgent GridManagerAgent = new GridManagementAgent(httpServer, "gridserver", Cfg.SimSendKey, Cfg.SimRecvKey, managercallback); + + httpServer.AddXmlRPCHandler("simulator_login", m_gridManager.XmlRpcLoginToSimulatorMethod); + httpServer.AddXmlRPCHandler("map_block", m_gridManager.XmlRpcMapBlockMethod); + + httpServer.AddRestHandler("GET", "/sims/", m_gridManager.RestGetSimMethod); + httpServer.AddRestHandler("POST", "/sims/", m_gridManager.RestSetSimMethod); + httpServer.AddRestHandler("GET", "/regions/", m_gridManager.RestGetRegionMethod); + httpServer.AddRestHandler("POST", "/regions/", m_gridManager.RestSetRegionMethod); + + + // lbsa71 : This code snippet taken from old http server. + // I have no idea what this was supposed to do - looks like an infinite recursion to me. + // case "regions": + //// DIRTY HACK ALERT + //Console.Notice("/regions/ accessed"); + //TheSim = OpenGrid_Main.thegrid._regionmanager.GetProfileByHandle((ulong)Convert.ToUInt64(rest_params[1])); + //respstring = ParseREST("/regions/" + rest_params[1], requestBody, HTTPmethod); + //break; + + // lbsa71 : I guess these were never used? + //Listener.Prefixes.Add("http://+:8001/gods/"); + //Listener.Prefixes.Add("http://+:8001/highestuuid/"); + //Listener.Prefixes.Add("http://+:8001/uuidblocks/"); + + httpServer.Start(); + + m_console.Verbose( "Main.cs:Startup() - Starting sim status checker"); + + System.Timers.Timer simCheckTimer = new System.Timers.Timer(3600000 * 3); // 3 Hours between updates. + simCheckTimer.Elapsed += new ElapsedEventHandler(CheckSims); + simCheckTimer.Enabled = true; + } + + private GridConfig LoadConfigDll(string dllName) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + GridConfig config = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IGridConfig", true); + + if (typeInterface != null) + { + IGridConfig plug = (IGridConfig)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + config = plug.GetConfigObject(); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + return config; + } + + public void CheckSims(object sender, ElapsedEventArgs e) + { + /* + foreach (SimProfileBase sim in m_simProfileManager.SimProfiles.Values) + { + string SimResponse = ""; + try + { + WebRequest CheckSim = WebRequest.Create("http://" + sim.sim_ip + ":" + sim.sim_port.ToString() + "/checkstatus/"); + CheckSim.Method = "GET"; + CheckSim.ContentType = "text/plaintext"; + CheckSim.ContentLength = 0; + + StreamWriter stOut = new StreamWriter(CheckSim.GetRequestStream(), System.Text.Encoding.ASCII); + stOut.Write(""); + stOut.Close(); + + StreamReader stIn = new StreamReader(CheckSim.GetResponse().GetResponseStream()); + SimResponse = stIn.ReadToEnd(); + stIn.Close(); + } + catch + { + } + + if (SimResponse == "OK") + { + m_simProfileManager.SimProfiles[sim.UUID].online = true; + } + else + { + m_simProfileManager.SimProfiles[sim.UUID].online = false; + } + } + */ + } + + public void RunCmd(string cmd, string[] cmdparams) + { + switch (cmd) + { + case "help": + m_console.Notice("shutdown - shutdown the grid (USE CAUTION!)"); + break; + + case "shutdown": + m_console.Close(); + Environment.Exit(0); + break; + } + } + + public void Show(string ShowWhat) + { + } + + private void ConfigDB(IGenericConfig configData) + { + try + { + string attri = ""; + attri = configData.GetAttribute("DataBaseProvider"); + if (attri == "") + { + GridDll = "OpenGrid.Framework.Data.DB4o.dll"; + configData.SetAttribute("DataBaseProvider", "OpenGrid.Framework.Data.DB4o.dll"); + } + else + { + GridDll = attri; + } + configData.Commit(); + } + catch (Exception e) + { + + } + } + } +} diff --git a/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj b/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj new file mode 100644 index 0000000..424072e --- /dev/null +++ b/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj @@ -0,0 +1,134 @@ + + + Local + 8.0.50727 + 2.0 + {60FCC3A6-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.GridServer + JScript + Grid + IE50 + false + Exe + + OpenSim.Grid.GridServer + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + OpenSim.Framework.GenericConfig.Xml.dll + False + + + OpenSim.Framework.Servers.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Grid.Framework.Manager + {4B7BFD1C-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj.user b/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/GridServer/OpenSim.Grid.GridServer.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs b/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..303dddf --- /dev/null +++ b/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs @@ -0,0 +1,60 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OGS-GridServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OGS-GridServer")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b541b244-3d1d-4625-9003-bc2a3a6a39a4")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Grid/InventoryServer/InventoryManager.cs b/OpenSim/Grid/InventoryServer/InventoryManager.cs new file mode 100644 index 0000000..9ca9b5e --- /dev/null +++ b/OpenSim/Grid/InventoryServer/InventoryManager.cs @@ -0,0 +1,125 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; +using libsecondlife; +using System.Reflection; + +using System.Xml; +using Nwc.XmlRpc; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; + +using System.Security.Cryptography; + +namespace OpenGridServices.InventoryServer +{ + class InventoryManager + { + Dictionary _plugins = new Dictionary(); + + /// + /// Adds a new inventory server plugin - user servers will be requested in the order they were loaded. + /// + /// The filename to the inventory server plugin DLL + public void AddPlugin(string FileName) + { + OpenSim.Framework.Console.MainConsole.Instance.Verbose( "Invenstorage: Attempting to load " + FileName); + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + OpenSim.Framework.Console.MainConsole.Instance.Verbose( "Invenstorage: Found " + pluginAssembly.GetTypes().Length + " interfaces."); + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IInventoryData", true); + + if (typeInterface != null) + { + IInventoryData plug = (IInventoryData)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Initialise(); + this._plugins.Add(plug.getName(), plug); + OpenSim.Framework.Console.MainConsole.Instance.Verbose( "Invenstorage: Added IUserData Interface"); + } + + typeInterface = null; + } + } + + pluginAssembly = null; + } + + public List getRootFolders(LLUUID user) + { + foreach (KeyValuePair kvp in _plugins) + { + try + { + return kvp.Value.getUserRootFolders(user); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.Notice("Unable to get root folders via " + kvp.Key + " (" + e.ToString() + ")"); + } + } + return null; + } + + public XmlRpcResponse XmlRpcInventoryRequest(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + + Hashtable responseData = new Hashtable(); + + // Stuff happens here + + if (requestData.ContainsKey("Access-type")) + { + if (requestData["access-type"] == "rootfolders") + { +// responseData["rootfolders"] = + } + } + else + { + responseData["error"] = "No access-type specified."; + } + + + // Stuff stops happening here + + response.Value = responseData; + return response; + } + } +} diff --git a/OpenSim/Grid/InventoryServer/Main.cs b/OpenSim/Grid/InventoryServer/Main.cs new file mode 100644 index 0000000..f479a79 --- /dev/null +++ b/OpenSim/Grid/InventoryServer/Main.cs @@ -0,0 +1,87 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.IO; +using System.Text; +using libsecondlife; +using OpenSim.Framework.User; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Console; +using OpenSim.Servers; +using OpenSim.Framework.Utilities; + +namespace OpenGridServices.InventoryServer +{ + public class OpenInventory_Main : BaseServer, conscmd_callback + { + ConsoleBase m_console; + InventoryManager m_inventoryManager; + + public static void Main(string[] args) + { + } + + public OpenInventory_Main() + { + m_console = new ConsoleBase("opengrid-inventory-console.log", "OpenInventory", this, false); + MainConsole.Instance = m_console; + } + + public void Startup() + { + MainConsole.Instance.Notice("Initialising inventory manager..."); + m_inventoryManager = new InventoryManager(); + + MainConsole.Instance.Notice("Starting HTTP server"); + BaseHttpServer httpServer = new BaseHttpServer(8004); + + httpServer.AddXmlRPCHandler("rootfolders", m_inventoryManager.XmlRpcInventoryRequest); + //httpServer.AddRestHandler("GET","/rootfolders/",Rest + } + + public void RunCmd(string cmd, string[] cmdparams) + { + switch (cmd) + { + case "shutdown": + m_console.Close(); + Environment.Exit(0); + break; + } + } + + public void Show(string ShowWhat) + { + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager.mds b/OpenSim/Grid/Manager/OpenGridServices.Manager.mds new file mode 100644 index 0000000..ed7bc24 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager.mds @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager.userprefs b/OpenSim/Grid/Manager/OpenGridServices.Manager.userprefs new file mode 100644 index 0000000..f221509 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager.userprefs @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager.usertasks b/OpenSim/Grid/Manager/OpenGridServices.Manager.usertasks new file mode 100644 index 0000000..d887d0e --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager.usertasks @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/AssemblyInfo.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/AssemblyInfo.cs new file mode 100644 index 0000000..af4e275 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/AssemblyInfo.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] + +// The following attributes specify the key for the sign of your assembly. See the +// .NET Framework documentation for more information about signing. +// This is not required, if you don't want signing let these attributes like they're. +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile("")] diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs new file mode 100644 index 0000000..83685fc --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading; +using System.Collections.Generic; +using System.Text; + +namespace OpenGridServices.Manager +{ + public class BlockingQueue + { + private Queue _queue = new Queue(); + private object _queueSync = new object(); + + public void Enqueue(T value) + { + lock (_queueSync) + { + _queue.Enqueue(value); + Monitor.Pulse(_queueSync); + } + } + + public T Dequeue() + { + lock (_queueSync) + { + if (_queue.Count < 1) + Monitor.Wait(_queueSync); + + return _queue.Dequeue(); + } + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/Connect to grid server.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/Connect to grid server.cs new file mode 100644 index 0000000..0d509ef --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/Connect to grid server.cs @@ -0,0 +1,16 @@ + +using System; + +namespace OpenGridServices.Manager +{ + + + public partial class Connect to grid server : Gtk.Dialog + { + + public Connect to grid server() + { + this.Build(); + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/ConnectToGridServerDialog.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/ConnectToGridServerDialog.cs new file mode 100644 index 0000000..8a80b1d --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/ConnectToGridServerDialog.cs @@ -0,0 +1,29 @@ +using Gtk; +using System; + +namespace OpenGridServices.Manager { + public partial class ConnectToGridServerDialog : Gtk.Dialog + { + + public ConnectToGridServerDialog() + { + this.Build(); + } + + protected virtual void OnResponse(object o, Gtk.ResponseArgs args) + { + switch(args.ResponseId) { + case Gtk.ResponseType.Ok: + MainClass.PendingOperations.Enqueue("connect_to_gridserver " + this.entry1.Text + " " + this.entry2.Text + " " + this.entry3.Text); + break; + + case Gtk.ResponseType.Cancel: + break; + } + this.Hide(); + + } + + } + +} \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/GridServerConnectionManager.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/GridServerConnectionManager.cs new file mode 100644 index 0000000..6b632d6 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/GridServerConnectionManager.cs @@ -0,0 +1,106 @@ +using Nwc.XmlRpc; +using System; +using System.Net; +using System.IO; +using System.Xml; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; + +namespace OpenGridServices.Manager +{ + public class GridServerConnectionManager + { + private string ServerURL; + public LLUUID SessionID; + public bool connected=false; + + public RegionBlock[][] WorldMap; + + public bool Connect(string GridServerURL, string username, string password) + { + try { + this.ServerURL=GridServerURL; + Hashtable LoginParamsHT = new Hashtable(); + LoginParamsHT["username"]=username; + LoginParamsHT["password"]=password; + ArrayList LoginParams = new ArrayList(); + LoginParams.Add(LoginParamsHT); + XmlRpcRequest GridLoginReq = new XmlRpcRequest("manager_login",LoginParams); + XmlRpcResponse GridResp = GridLoginReq.Send(ServerURL,3000); + if(GridResp.IsFault) { + connected=false; + return false; + } else { + Hashtable gridrespData = (Hashtable)GridResp.Value; + this.SessionID = new LLUUID((string)gridrespData["session_id"]); + connected=true; + return true; + } + } catch(Exception e) { + Console.WriteLine(e.ToString()); + connected=false; + return false; + } + } + + public void DownloadMap() + { + System.Net.WebClient mapdownloader = new WebClient(); + Stream regionliststream = mapdownloader.OpenRead(ServerURL + "/regionlist"); + + RegionBlock TempRegionData; + + XmlDocument doc = new XmlDocument(); + doc.Load(regionliststream); + regionliststream.Close(); + XmlNode rootnode = doc.FirstChild; + if (rootnode.Name != "regions") + { + // TODO - ERROR! + } + + for(int i=0; i<=rootnode.ChildNodes.Count; i++) + { + if(rootnode.ChildNodes.Item(i).Name != "region") { + // TODO - ERROR! + } else { + TempRegionData = new RegionBlock(); + + + } + } + } + + public bool RestartServer() + { + return true; + } + + public bool ShutdownServer() + { + try { + Hashtable ShutdownParamsHT = new Hashtable(); + ArrayList ShutdownParams = new ArrayList(); + ShutdownParamsHT["session_id"]=this.SessionID.ToString(); + ShutdownParams.Add(ShutdownParamsHT); + XmlRpcRequest GridShutdownReq = new XmlRpcRequest("shutdown",ShutdownParams); + XmlRpcResponse GridResp = GridShutdownReq.Send(this.ServerURL,3000); + if(GridResp.IsFault) { + return false; + } else { + connected=false; + return true; + } + } catch(Exception e) { + Console.WriteLine(e.ToString()); + return false; + } + } + + public void DisconnectServer() + { + this.connected=false; + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/Main.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/Main.cs new file mode 100644 index 0000000..42e09e0 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/Main.cs @@ -0,0 +1,96 @@ +// project created on 5/14/2007 at 2:04 PM +using System; +using System.Threading; +using Gtk; + +namespace OpenGridServices.Manager +{ + class MainClass + { + + public static bool QuitReq=false; + public static BlockingQueue PendingOperations = new BlockingQueue(); + + private static Thread OperationsRunner; + + private static GridServerConnectionManager gridserverConn; + + private static MainWindow win; + + public static void DoMainLoop() + { + while(!QuitReq) + { + Application.RunIteration(); + } + } + + public static void RunOperations() + { + string operation; + string cmd; + char[] sep = new char[1]; + sep[0]=' '; + while(!QuitReq) + { + operation=PendingOperations.Dequeue(); + Console.WriteLine(operation); + cmd = operation.Split(sep)[0]; + switch(cmd) { + case "connect_to_gridserver": + win.SetStatus("Connecting to grid server..."); + if(gridserverConn.Connect(operation.Split(sep)[1],operation.Split(sep)[2],operation.Split(sep)[3])) { + win.SetStatus("Connected OK with session ID:" + gridserverConn.SessionID); + win.SetGridServerConnected(true); + Thread.Sleep(3000); + win.SetStatus("Downloading region maps..."); + gridserverConn.DownloadMap(); + } else { + win.SetStatus("Could not connect"); + } + break; + + case "restart_gridserver": + win.SetStatus("Restarting grid server..."); + if(gridserverConn.RestartServer()) { + win.SetStatus("Restarted server OK"); + Thread.Sleep(3000); + win.SetStatus(""); + } else { + win.SetStatus("Error restarting grid server!!!"); + } + break; + + case "shutdown_gridserver": + win.SetStatus("Shutting down grid server..."); + if(gridserverConn.ShutdownServer()) { + win.SetStatus("Grid server shutdown"); + win.SetGridServerConnected(false); + Thread.Sleep(3000); + win.SetStatus(""); + } else { + win.SetStatus("Could not shutdown grid server!!!"); + } + break; + + case "disconnect_gridserver": + gridserverConn.DisconnectServer(); + win.SetGridServerConnected(false); + break; + } + } + } + + public static void Main (string[] args) + { + gridserverConn = new GridServerConnectionManager(); + Application.Init (); + win = new MainWindow (); + win.Show (); + OperationsRunner = new Thread(new ThreadStart(RunOperations)); + OperationsRunner.IsBackground=true; + OperationsRunner.Start(); + DoMainLoop(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/MainWindow.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/MainWindow.cs new file mode 100644 index 0000000..1db38f0 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/MainWindow.cs @@ -0,0 +1,76 @@ +using System; +using Gtk; + +namespace OpenGridServices.Manager { + public partial class MainWindow: Gtk.Window + { + public MainWindow (): base (Gtk.WindowType.Toplevel) + { + Build (); + } + + public void SetStatus(string statustext) + { + this.statusbar1.Pop(0); + this.statusbar1.Push(0,statustext); + } + + public void DrawGrid(RegionBlock[][] regions) + { + for(int x=0; x<=regions.GetUpperBound(0); x++) { + for(int y=0; y<=regions.GetUpperBound(1); y++) { + Gdk.Image themap = new Gdk.Image(Gdk.ImageType.Fastest,Gdk.Visual.System,256,256); + this.drawingarea1.GdkWindow.DrawImage(new Gdk.GC(this.drawingarea1.GdkWindow),themap,0,0,x*256,y*256,256,256); + } + } + } + + public void SetGridServerConnected(bool connected) + { + if(connected) { + this.ConnectToGridserver.Visible=false; + this.DisconnectFromGridServer.Visible=true; + } else { + this.ConnectToGridserver.Visible=true; + this.DisconnectFromGridServer.Visible=false; + } + } + + protected void OnDeleteEvent (object sender, DeleteEventArgs a) + { + Application.Quit (); + MainClass.QuitReq=true; + a.RetVal = true; + } + + protected virtual void QuitMenu(object sender, System.EventArgs e) + { + MainClass.QuitReq=true; + Application.Quit(); + } + + protected virtual void ConnectToGridServerMenu(object sender, System.EventArgs e) + { + ConnectToGridServerDialog griddialog = new ConnectToGridServerDialog (); + griddialog.Show(); + } + + protected virtual void RestartGridserverMenu(object sender, System.EventArgs e) + { + MainClass.PendingOperations.Enqueue("restart_gridserver"); + } + + protected virtual void ShutdownGridserverMenu(object sender, System.EventArgs e) + { + MainClass.PendingOperations.Enqueue("shutdown_gridserver"); + } + + protected virtual void DisconnectGridServerMenu(object sender, System.EventArgs e) + { + MainClass.PendingOperations.Enqueue("disconnect_gridserver"); + } + + } +} + + \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.mdp b/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.mdp new file mode 100644 index 0000000..cfdc085 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.mdp @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.pidb b/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.pidb new file mode 100644 index 0000000..44e7a61 Binary files /dev/null and b/OpenSim/Grid/Manager/OpenGridServices.Manager/OpenGridServices.Manager.pidb differ diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/RegionBlock.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/RegionBlock.cs new file mode 100644 index 0000000..00f7c65 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/RegionBlock.cs @@ -0,0 +1,37 @@ +using System; +using System.Xml; +using libsecondlife; +using OpenSim.Framework.Utilities; + +namespace OpenGridServices.Manager +{ + + + public class RegionBlock + { + public uint regloc_x; + public uint regloc_y; + + public string httpd_url; + + public string region_name; + + public ulong regionhandle { + get { return Util.UIntsToLong(regloc_x*256,regloc_y*256); } + } + + public Gdk.Pixbuf MiniMap; + + public RegionBlock() + { + } + + public void LoadFromXmlNode(XmlNode sourcenode) + { + this.regloc_x=Convert.ToUInt32(sourcenode.Attributes.GetNamedItem("loc_x").Value); + this.regloc_y=Convert.ToUInt32(sourcenode.Attributes.GetNamedItem("loc_y").Value); + this.region_name=sourcenode.Attributes.GetNamedItem("region_name").Value; + this.httpd_url=sourcenode.Attributes.GetNamedItem("httpd_url").Value; + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs new file mode 100644 index 0000000..5bf7ff9 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim.Framework.Utilities +{ + public class Util + { + private static Random randomClass = new Random(); + private static uint nextXferID = 5000; + private static object XferLock = new object(); + + public static ulong UIntsToLong(uint X, uint Y) + { + return Helpers.UIntsToLong(X, Y); + } + + public static Random RandomClass + { + get + { + return randomClass; + } + } + + public static uint GetNextXferID() + { + uint id = 0; + lock(XferLock) + { + id = nextXferID; + nextXferID++; + } + return id; + } + + //public static int fast_distance2d(int x, int y) + //{ + // x = System.Math.Abs(x); + // y = System.Math.Abs(y); + + // int min = System.Math.Min(x, y); + + // return (x + y - (min >> 1) - (min >> 2) + (min >> 4)); + //} + + public static string FieldToString(byte[] bytes) + { + return FieldToString(bytes, String.Empty); + } + + /// + /// Convert a variable length field (byte array) to a string, with a + /// field name prepended to each line of the output + /// + /// If the byte array has unprintable characters in it, a + /// hex dump will be put in the string instead + /// The byte array to convert to a string + /// A field name to prepend to each line of output + /// An ASCII string or a string containing a hex dump, minus + /// the null terminator + public static string FieldToString(byte[] bytes, string fieldName) + { + // Check for a common case + if (bytes.Length == 0) return String.Empty; + + StringBuilder output = new StringBuilder(); + bool printable = true; + + for (int i = 0; i < bytes.Length; ++i) + { + // Check if there are any unprintable characters in the array + if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 + && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) + { + printable = false; + break; + } + } + + if (printable) + { + if (fieldName.Length > 0) + { + output.Append(fieldName); + output.Append(": "); + } + + if (bytes[bytes.Length - 1] == 0x00) + output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)); + else + output.Append(UTF8Encoding.UTF8.GetString(bytes)); + } + else + { + for (int i = 0; i < bytes.Length; i += 16) + { + if (i != 0) + output.Append(Environment.NewLine); + if (fieldName.Length > 0) + { + output.Append(fieldName); + output.Append(": "); + } + + for (int j = 0; j < 16; j++) + { + if ((i + j) < bytes.Length) + output.Append(String.Format("{0:X2} ", bytes[i + j])); + else + output.Append(" "); + } + + for (int j = 0; j < 16 && (i + j) < bytes.Length; j++) + { + if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E) + output.Append((char)bytes[i + j]); + else + output.Append("."); + } + } + } + + return output.ToString(); + } + public Util() + { + + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.ConnectToGridServerDialog.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.ConnectToGridServerDialog.cs new file mode 100644 index 0000000..da6739e --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.ConnectToGridServerDialog.cs @@ -0,0 +1,226 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Mono Runtime Version: 2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +namespace OpenGridServices.Manager { + + + public partial class ConnectToGridServerDialog { + + private Gtk.VBox vbox2; + + private Gtk.VBox vbox3; + + private Gtk.HBox hbox1; + + private Gtk.Label label1; + + private Gtk.Entry entry1; + + private Gtk.HBox hbox2; + + private Gtk.Label label2; + + private Gtk.Entry entry2; + + private Gtk.HBox hbox3; + + private Gtk.Label label3; + + private Gtk.Entry entry3; + + private Gtk.Button button2; + + private Gtk.Button button8; + + protected virtual void Build() { + Stetic.Gui.Initialize(); + // Widget OpenGridServices.Manager.ConnectToGridServerDialog + this.Events = ((Gdk.EventMask)(256)); + this.Name = "OpenGridServices.Manager.ConnectToGridServerDialog"; + this.Title = Mono.Unix.Catalog.GetString("Connect to Grid server"); + this.WindowPosition = ((Gtk.WindowPosition)(4)); + this.HasSeparator = false; + // Internal child OpenGridServices.Manager.ConnectToGridServerDialog.VBox + Gtk.VBox w1 = this.VBox; + w1.Events = ((Gdk.EventMask)(256)); + w1.Name = "dialog_VBox"; + w1.BorderWidth = ((uint)(2)); + // Container child dialog_VBox.Gtk.Box+BoxChild + this.vbox2 = new Gtk.VBox(); + this.vbox2.Name = "vbox2"; + // Container child vbox2.Gtk.Box+BoxChild + this.vbox3 = new Gtk.VBox(); + this.vbox3.Name = "vbox3"; + // Container child vbox3.Gtk.Box+BoxChild + this.hbox1 = new Gtk.HBox(); + this.hbox1.Name = "hbox1"; + // Container child hbox1.Gtk.Box+BoxChild + this.label1 = new Gtk.Label(); + this.label1.Name = "label1"; + this.label1.Xalign = 1F; + this.label1.LabelProp = Mono.Unix.Catalog.GetString("Grid server URL: "); + this.label1.Justify = ((Gtk.Justification)(1)); + this.hbox1.Add(this.label1); + Gtk.Box.BoxChild w2 = ((Gtk.Box.BoxChild)(this.hbox1[this.label1])); + w2.Position = 0; + // Container child hbox1.Gtk.Box+BoxChild + this.entry1 = new Gtk.Entry(); + this.entry1.CanFocus = true; + this.entry1.Name = "entry1"; + this.entry1.Text = Mono.Unix.Catalog.GetString("http://gridserver:8001"); + this.entry1.IsEditable = true; + this.entry1.MaxLength = 255; + this.entry1.InvisibleChar = '•'; + this.hbox1.Add(this.entry1); + Gtk.Box.BoxChild w3 = ((Gtk.Box.BoxChild)(this.hbox1[this.entry1])); + w3.Position = 1; + this.vbox3.Add(this.hbox1); + Gtk.Box.BoxChild w4 = ((Gtk.Box.BoxChild)(this.vbox3[this.hbox1])); + w4.Position = 0; + w4.Expand = false; + w4.Fill = false; + // Container child vbox3.Gtk.Box+BoxChild + this.hbox2 = new Gtk.HBox(); + this.hbox2.Name = "hbox2"; + // Container child hbox2.Gtk.Box+BoxChild + this.label2 = new Gtk.Label(); + this.label2.Name = "label2"; + this.label2.Xalign = 1F; + this.label2.LabelProp = Mono.Unix.Catalog.GetString("Username:"); + this.label2.Justify = ((Gtk.Justification)(1)); + this.hbox2.Add(this.label2); + Gtk.Box.BoxChild w5 = ((Gtk.Box.BoxChild)(this.hbox2[this.label2])); + w5.Position = 0; + // Container child hbox2.Gtk.Box+BoxChild + this.entry2 = new Gtk.Entry(); + this.entry2.CanFocus = true; + this.entry2.Name = "entry2"; + this.entry2.IsEditable = true; + this.entry2.InvisibleChar = '•'; + this.hbox2.Add(this.entry2); + Gtk.Box.BoxChild w6 = ((Gtk.Box.BoxChild)(this.hbox2[this.entry2])); + w6.Position = 1; + this.vbox3.Add(this.hbox2); + Gtk.Box.BoxChild w7 = ((Gtk.Box.BoxChild)(this.vbox3[this.hbox2])); + w7.Position = 1; + w7.Expand = false; + w7.Fill = false; + // Container child vbox3.Gtk.Box+BoxChild + this.hbox3 = new Gtk.HBox(); + this.hbox3.Name = "hbox3"; + // Container child hbox3.Gtk.Box+BoxChild + this.label3 = new Gtk.Label(); + this.label3.Name = "label3"; + this.label3.Xalign = 1F; + this.label3.LabelProp = Mono.Unix.Catalog.GetString("Password:"); + this.label3.Justify = ((Gtk.Justification)(1)); + this.hbox3.Add(this.label3); + Gtk.Box.BoxChild w8 = ((Gtk.Box.BoxChild)(this.hbox3[this.label3])); + w8.Position = 0; + // Container child hbox3.Gtk.Box+BoxChild + this.entry3 = new Gtk.Entry(); + this.entry3.CanFocus = true; + this.entry3.Name = "entry3"; + this.entry3.IsEditable = true; + this.entry3.InvisibleChar = '•'; + this.hbox3.Add(this.entry3); + Gtk.Box.BoxChild w9 = ((Gtk.Box.BoxChild)(this.hbox3[this.entry3])); + w9.Position = 1; + this.vbox3.Add(this.hbox3); + Gtk.Box.BoxChild w10 = ((Gtk.Box.BoxChild)(this.vbox3[this.hbox3])); + w10.Position = 2; + w10.Expand = false; + w10.Fill = false; + this.vbox2.Add(this.vbox3); + Gtk.Box.BoxChild w11 = ((Gtk.Box.BoxChild)(this.vbox2[this.vbox3])); + w11.Position = 2; + w11.Expand = false; + w11.Fill = false; + w1.Add(this.vbox2); + Gtk.Box.BoxChild w12 = ((Gtk.Box.BoxChild)(w1[this.vbox2])); + w12.Position = 0; + // Internal child OpenGridServices.Manager.ConnectToGridServerDialog.ActionArea + Gtk.HButtonBox w13 = this.ActionArea; + w13.Events = ((Gdk.EventMask)(256)); + w13.Name = "OpenGridServices.Manager.ConnectToGridServerDialog_ActionArea"; + w13.Spacing = 6; + w13.BorderWidth = ((uint)(5)); + w13.LayoutStyle = ((Gtk.ButtonBoxStyle)(4)); + // Container child OpenGridServices.Manager.ConnectToGridServerDialog_ActionArea.Gtk.ButtonBox+ButtonBoxChild + this.button2 = new Gtk.Button(); + this.button2.CanDefault = true; + this.button2.CanFocus = true; + this.button2.Name = "button2"; + this.button2.UseUnderline = true; + // Container child button2.Gtk.Container+ContainerChild + Gtk.Alignment w14 = new Gtk.Alignment(0.5F, 0.5F, 0F, 0F); + w14.Name = "GtkAlignment"; + // Container child GtkAlignment.Gtk.Container+ContainerChild + Gtk.HBox w15 = new Gtk.HBox(); + w15.Name = "GtkHBox"; + w15.Spacing = 2; + // Container child GtkHBox.Gtk.Container+ContainerChild + Gtk.Image w16 = new Gtk.Image(); + w16.Name = "image1"; + w16.Pixbuf = Gtk.IconTheme.Default.LoadIcon("gtk-apply", 16, 0); + w15.Add(w16); + // Container child GtkHBox.Gtk.Container+ContainerChild + Gtk.Label w18 = new Gtk.Label(); + w18.Name = "GtkLabel"; + w18.LabelProp = Mono.Unix.Catalog.GetString("Connect"); + w18.UseUnderline = true; + w15.Add(w18); + w14.Add(w15); + this.button2.Add(w14); + this.AddActionWidget(this.button2, -5); + Gtk.ButtonBox.ButtonBoxChild w22 = ((Gtk.ButtonBox.ButtonBoxChild)(w13[this.button2])); + w22.Expand = false; + w22.Fill = false; + // Container child OpenGridServices.Manager.ConnectToGridServerDialog_ActionArea.Gtk.ButtonBox+ButtonBoxChild + this.button8 = new Gtk.Button(); + this.button8.CanDefault = true; + this.button8.CanFocus = true; + this.button8.Name = "button8"; + this.button8.UseUnderline = true; + // Container child button8.Gtk.Container+ContainerChild + Gtk.Alignment w23 = new Gtk.Alignment(0.5F, 0.5F, 0F, 0F); + w23.Name = "GtkAlignment1"; + // Container child GtkAlignment1.Gtk.Container+ContainerChild + Gtk.HBox w24 = new Gtk.HBox(); + w24.Name = "GtkHBox1"; + w24.Spacing = 2; + // Container child GtkHBox1.Gtk.Container+ContainerChild + Gtk.Image w25 = new Gtk.Image(); + w25.Name = "image2"; + w25.Pixbuf = Gtk.IconTheme.Default.LoadIcon("gtk-cancel", 16, 0); + w24.Add(w25); + // Container child GtkHBox1.Gtk.Container+ContainerChild + Gtk.Label w27 = new Gtk.Label(); + w27.Name = "GtkLabel1"; + w27.LabelProp = Mono.Unix.Catalog.GetString("Cancel"); + w27.UseUnderline = true; + w24.Add(w27); + w23.Add(w24); + this.button8.Add(w23); + this.AddActionWidget(this.button8, -6); + Gtk.ButtonBox.ButtonBoxChild w31 = ((Gtk.ButtonBox.ButtonBoxChild)(w13[this.button8])); + w31.Position = 1; + w31.Expand = false; + w31.Fill = false; + if ((this.Child != null)) { + this.Child.ShowAll(); + } + this.DefaultWidth = 476; + this.DefaultHeight = 137; + this.Show(); + this.Response += new Gtk.ResponseHandler(this.OnResponse); + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.MainWindow.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.MainWindow.cs new file mode 100644 index 0000000..8798dac --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/OpenGridServices.Manager.MainWindow.cs @@ -0,0 +1,256 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Mono Runtime Version: 2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +namespace OpenGridServices.Manager { + + + public partial class MainWindow { + + private Gtk.Action Grid; + + private Gtk.Action User; + + private Gtk.Action Asset; + + private Gtk.Action Region; + + private Gtk.Action Services; + + private Gtk.Action ConnectToGridserver; + + private Gtk.Action RestartWholeGrid; + + private Gtk.Action ShutdownWholeGrid; + + private Gtk.Action ExitGridManager; + + private Gtk.Action ConnectToUserserver; + + private Gtk.Action AccountManagment; + + private Gtk.Action GlobalNotice; + + private Gtk.Action DisableAllLogins; + + private Gtk.Action DisableNonGodUsersOnly; + + private Gtk.Action ShutdownUserServer; + + private Gtk.Action ShutdownGridserverOnly; + + private Gtk.Action RestartGridserverOnly; + + private Gtk.Action DefaultLocalGridUserserver; + + private Gtk.Action CustomUserserver; + + private Gtk.Action RemoteGridDefaultUserserver; + + private Gtk.Action DisconnectFromGridServer; + + private Gtk.Action UploadAsset; + + private Gtk.Action AssetManagement; + + private Gtk.Action ConnectToAssetServer; + + private Gtk.Action ConnectToDefaultAssetServerForGrid; + + private Gtk.Action DefaultForLocalGrid; + + private Gtk.Action DefaultForRemoteGrid; + + private Gtk.Action CustomAssetServer; + + private Gtk.VBox vbox1; + + private Gtk.MenuBar menubar2; + + private Gtk.HBox hbox1; + + private Gtk.ScrolledWindow scrolledwindow1; + + private Gtk.DrawingArea drawingarea1; + + private Gtk.TreeView treeview1; + + private Gtk.Statusbar statusbar1; + + protected virtual void Build() { + Stetic.Gui.Initialize(); + // Widget OpenGridServices.Manager.MainWindow + Gtk.UIManager w1 = new Gtk.UIManager(); + Gtk.ActionGroup w2 = new Gtk.ActionGroup("Default"); + this.Grid = new Gtk.Action("Grid", Mono.Unix.Catalog.GetString("Grid"), null, null); + this.Grid.HideIfEmpty = false; + this.Grid.ShortLabel = Mono.Unix.Catalog.GetString("Grid"); + w2.Add(this.Grid, "g"); + this.User = new Gtk.Action("User", Mono.Unix.Catalog.GetString("User"), null, null); + this.User.HideIfEmpty = false; + this.User.ShortLabel = Mono.Unix.Catalog.GetString("User"); + w2.Add(this.User, null); + this.Asset = new Gtk.Action("Asset", Mono.Unix.Catalog.GetString("Asset"), null, null); + this.Asset.HideIfEmpty = false; + this.Asset.ShortLabel = Mono.Unix.Catalog.GetString("Asset"); + w2.Add(this.Asset, null); + this.Region = new Gtk.Action("Region", Mono.Unix.Catalog.GetString("Region"), null, null); + this.Region.ShortLabel = Mono.Unix.Catalog.GetString("Region"); + w2.Add(this.Region, null); + this.Services = new Gtk.Action("Services", Mono.Unix.Catalog.GetString("Services"), null, null); + this.Services.ShortLabel = Mono.Unix.Catalog.GetString("Services"); + w2.Add(this.Services, null); + this.ConnectToGridserver = new Gtk.Action("ConnectToGridserver", Mono.Unix.Catalog.GetString("Connect to gridserver..."), null, "gtk-connect"); + this.ConnectToGridserver.HideIfEmpty = false; + this.ConnectToGridserver.ShortLabel = Mono.Unix.Catalog.GetString("Connect to gridserver"); + w2.Add(this.ConnectToGridserver, null); + this.RestartWholeGrid = new Gtk.Action("RestartWholeGrid", Mono.Unix.Catalog.GetString("Restart whole grid"), null, "gtk-refresh"); + this.RestartWholeGrid.ShortLabel = Mono.Unix.Catalog.GetString("Restart whole grid"); + w2.Add(this.RestartWholeGrid, null); + this.ShutdownWholeGrid = new Gtk.Action("ShutdownWholeGrid", Mono.Unix.Catalog.GetString("Shutdown whole grid"), null, "gtk-stop"); + this.ShutdownWholeGrid.ShortLabel = Mono.Unix.Catalog.GetString("Shutdown whole grid"); + w2.Add(this.ShutdownWholeGrid, null); + this.ExitGridManager = new Gtk.Action("ExitGridManager", Mono.Unix.Catalog.GetString("Exit grid manager"), null, "gtk-close"); + this.ExitGridManager.ShortLabel = Mono.Unix.Catalog.GetString("Exit grid manager"); + w2.Add(this.ExitGridManager, null); + this.ConnectToUserserver = new Gtk.Action("ConnectToUserserver", Mono.Unix.Catalog.GetString("Connect to userserver"), null, "gtk-connect"); + this.ConnectToUserserver.ShortLabel = Mono.Unix.Catalog.GetString("Connect to userserver"); + w2.Add(this.ConnectToUserserver, null); + this.AccountManagment = new Gtk.Action("AccountManagment", Mono.Unix.Catalog.GetString("Account managment"), null, "gtk-properties"); + this.AccountManagment.ShortLabel = Mono.Unix.Catalog.GetString("Account managment"); + w2.Add(this.AccountManagment, null); + this.GlobalNotice = new Gtk.Action("GlobalNotice", Mono.Unix.Catalog.GetString("Global notice"), null, "gtk-network"); + this.GlobalNotice.ShortLabel = Mono.Unix.Catalog.GetString("Global notice"); + w2.Add(this.GlobalNotice, null); + this.DisableAllLogins = new Gtk.Action("DisableAllLogins", Mono.Unix.Catalog.GetString("Disable all logins"), null, "gtk-no"); + this.DisableAllLogins.ShortLabel = Mono.Unix.Catalog.GetString("Disable all logins"); + w2.Add(this.DisableAllLogins, null); + this.DisableNonGodUsersOnly = new Gtk.Action("DisableNonGodUsersOnly", Mono.Unix.Catalog.GetString("Disable non-god users only"), null, "gtk-no"); + this.DisableNonGodUsersOnly.ShortLabel = Mono.Unix.Catalog.GetString("Disable non-god users only"); + w2.Add(this.DisableNonGodUsersOnly, null); + this.ShutdownUserServer = new Gtk.Action("ShutdownUserServer", Mono.Unix.Catalog.GetString("Shutdown user server"), null, "gtk-stop"); + this.ShutdownUserServer.ShortLabel = Mono.Unix.Catalog.GetString("Shutdown user server"); + w2.Add(this.ShutdownUserServer, null); + this.ShutdownGridserverOnly = new Gtk.Action("ShutdownGridserverOnly", Mono.Unix.Catalog.GetString("Shutdown gridserver only"), null, "gtk-stop"); + this.ShutdownGridserverOnly.ShortLabel = Mono.Unix.Catalog.GetString("Shutdown gridserver only"); + w2.Add(this.ShutdownGridserverOnly, null); + this.RestartGridserverOnly = new Gtk.Action("RestartGridserverOnly", Mono.Unix.Catalog.GetString("Restart gridserver only"), null, "gtk-refresh"); + this.RestartGridserverOnly.ShortLabel = Mono.Unix.Catalog.GetString("Restart gridserver only"); + w2.Add(this.RestartGridserverOnly, null); + this.DefaultLocalGridUserserver = new Gtk.Action("DefaultLocalGridUserserver", Mono.Unix.Catalog.GetString("Default local grid userserver"), null, null); + this.DefaultLocalGridUserserver.ShortLabel = Mono.Unix.Catalog.GetString("Default local grid userserver"); + w2.Add(this.DefaultLocalGridUserserver, null); + this.CustomUserserver = new Gtk.Action("CustomUserserver", Mono.Unix.Catalog.GetString("Custom userserver..."), null, null); + this.CustomUserserver.ShortLabel = Mono.Unix.Catalog.GetString("Custom userserver"); + w2.Add(this.CustomUserserver, null); + this.RemoteGridDefaultUserserver = new Gtk.Action("RemoteGridDefaultUserserver", Mono.Unix.Catalog.GetString("Remote grid default userserver..."), null, null); + this.RemoteGridDefaultUserserver.ShortLabel = Mono.Unix.Catalog.GetString("Remote grid default userserver"); + w2.Add(this.RemoteGridDefaultUserserver, null); + this.DisconnectFromGridServer = new Gtk.Action("DisconnectFromGridServer", Mono.Unix.Catalog.GetString("Disconnect from grid server"), null, "gtk-disconnect"); + this.DisconnectFromGridServer.ShortLabel = Mono.Unix.Catalog.GetString("Disconnect from grid server"); + this.DisconnectFromGridServer.Visible = false; + w2.Add(this.DisconnectFromGridServer, null); + this.UploadAsset = new Gtk.Action("UploadAsset", Mono.Unix.Catalog.GetString("Upload asset"), null, null); + this.UploadAsset.ShortLabel = Mono.Unix.Catalog.GetString("Upload asset"); + w2.Add(this.UploadAsset, null); + this.AssetManagement = new Gtk.Action("AssetManagement", Mono.Unix.Catalog.GetString("Asset management"), null, null); + this.AssetManagement.ShortLabel = Mono.Unix.Catalog.GetString("Asset management"); + w2.Add(this.AssetManagement, null); + this.ConnectToAssetServer = new Gtk.Action("ConnectToAssetServer", Mono.Unix.Catalog.GetString("Connect to asset server"), null, null); + this.ConnectToAssetServer.ShortLabel = Mono.Unix.Catalog.GetString("Connect to asset server"); + w2.Add(this.ConnectToAssetServer, null); + this.ConnectToDefaultAssetServerForGrid = new Gtk.Action("ConnectToDefaultAssetServerForGrid", Mono.Unix.Catalog.GetString("Connect to default asset server for grid"), null, null); + this.ConnectToDefaultAssetServerForGrid.ShortLabel = Mono.Unix.Catalog.GetString("Connect to default asset server for grid"); + w2.Add(this.ConnectToDefaultAssetServerForGrid, null); + this.DefaultForLocalGrid = new Gtk.Action("DefaultForLocalGrid", Mono.Unix.Catalog.GetString("Default for local grid"), null, null); + this.DefaultForLocalGrid.ShortLabel = Mono.Unix.Catalog.GetString("Default for local grid"); + w2.Add(this.DefaultForLocalGrid, null); + this.DefaultForRemoteGrid = new Gtk.Action("DefaultForRemoteGrid", Mono.Unix.Catalog.GetString("Default for remote grid..."), null, null); + this.DefaultForRemoteGrid.ShortLabel = Mono.Unix.Catalog.GetString("Default for remote grid..."); + w2.Add(this.DefaultForRemoteGrid, null); + this.CustomAssetServer = new Gtk.Action("CustomAssetServer", Mono.Unix.Catalog.GetString("Custom asset server..."), null, null); + this.CustomAssetServer.ShortLabel = Mono.Unix.Catalog.GetString("Custom asset server..."); + w2.Add(this.CustomAssetServer, null); + w1.InsertActionGroup(w2, 0); + this.AddAccelGroup(w1.AccelGroup); + this.WidthRequest = 800; + this.HeightRequest = 600; + this.Name = "OpenGridServices.Manager.MainWindow"; + this.Title = Mono.Unix.Catalog.GetString("Open Grid Services Manager"); + this.Icon = Gtk.IconTheme.Default.LoadIcon("gtk-network", 48, 0); + // Container child OpenGridServices.Manager.MainWindow.Gtk.Container+ContainerChild + this.vbox1 = new Gtk.VBox(); + this.vbox1.Name = "vbox1"; + // Container child vbox1.Gtk.Box+BoxChild + w1.AddUiFromString(""); + this.menubar2 = ((Gtk.MenuBar)(w1.GetWidget("/menubar2"))); + this.menubar2.HeightRequest = 25; + this.menubar2.Name = "menubar2"; + this.vbox1.Add(this.menubar2); + Gtk.Box.BoxChild w3 = ((Gtk.Box.BoxChild)(this.vbox1[this.menubar2])); + w3.Position = 0; + w3.Expand = false; + w3.Fill = false; + // Container child vbox1.Gtk.Box+BoxChild + this.hbox1 = new Gtk.HBox(); + this.hbox1.Name = "hbox1"; + // Container child hbox1.Gtk.Box+BoxChild + this.scrolledwindow1 = new Gtk.ScrolledWindow(); + this.scrolledwindow1.CanFocus = true; + this.scrolledwindow1.Name = "scrolledwindow1"; + this.scrolledwindow1.VscrollbarPolicy = ((Gtk.PolicyType)(1)); + this.scrolledwindow1.HscrollbarPolicy = ((Gtk.PolicyType)(1)); + // Container child scrolledwindow1.Gtk.Container+ContainerChild + Gtk.Viewport w4 = new Gtk.Viewport(); + w4.Name = "GtkViewport"; + w4.ShadowType = ((Gtk.ShadowType)(0)); + // Container child GtkViewport.Gtk.Container+ContainerChild + this.drawingarea1 = new Gtk.DrawingArea(); + this.drawingarea1.Name = "drawingarea1"; + w4.Add(this.drawingarea1); + this.scrolledwindow1.Add(w4); + this.hbox1.Add(this.scrolledwindow1); + Gtk.Box.BoxChild w7 = ((Gtk.Box.BoxChild)(this.hbox1[this.scrolledwindow1])); + w7.Position = 1; + // Container child hbox1.Gtk.Box+BoxChild + this.treeview1 = new Gtk.TreeView(); + this.treeview1.CanFocus = true; + this.treeview1.Name = "treeview1"; + this.hbox1.Add(this.treeview1); + Gtk.Box.BoxChild w8 = ((Gtk.Box.BoxChild)(this.hbox1[this.treeview1])); + w8.Position = 2; + this.vbox1.Add(this.hbox1); + Gtk.Box.BoxChild w9 = ((Gtk.Box.BoxChild)(this.vbox1[this.hbox1])); + w9.Position = 1; + // Container child vbox1.Gtk.Box+BoxChild + this.statusbar1 = new Gtk.Statusbar(); + this.statusbar1.Name = "statusbar1"; + this.statusbar1.Spacing = 5; + this.vbox1.Add(this.statusbar1); + Gtk.Box.BoxChild w10 = ((Gtk.Box.BoxChild)(this.vbox1[this.statusbar1])); + w10.PackType = ((Gtk.PackType)(1)); + w10.Position = 2; + w10.Expand = false; + w10.Fill = false; + this.Add(this.vbox1); + if ((this.Child != null)) { + this.Child.ShowAll(); + } + this.DefaultWidth = 800; + this.DefaultHeight = 800; + this.Show(); + this.DeleteEvent += new Gtk.DeleteEventHandler(this.OnDeleteEvent); + this.ConnectToGridserver.Activated += new System.EventHandler(this.ConnectToGridServerMenu); + this.ExitGridManager.Activated += new System.EventHandler(this.QuitMenu); + this.ShutdownGridserverOnly.Activated += new System.EventHandler(this.ShutdownGridserverMenu); + this.RestartGridserverOnly.Activated += new System.EventHandler(this.RestartGridserverMenu); + this.DisconnectFromGridServer.Activated += new System.EventHandler(this.DisconnectGridServerMenu); + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/generated.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/generated.cs new file mode 100644 index 0000000..dd4abdd --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/generated.cs @@ -0,0 +1,35 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Mono Runtime Version: 2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +namespace Stetic { + + + internal class Gui { + + private static bool initialized; + + internal static void Initialize() { + if ((Stetic.Gui.initialized == false)) { + Stetic.Gui.initialized = true; + } + } + } + + internal class ActionGroups { + + public static Gtk.ActionGroup GetActionGroup(System.Type type) { + return Stetic.ActionGroups.GetActionGroup(type.FullName); + } + + public static Gtk.ActionGroup GetActionGroup(string name) { + return null; + } + } +} diff --git a/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/gui.stetic b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/gui.stetic new file mode 100644 index 0000000..c883f08 --- /dev/null +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/gtk-gui/gui.stetic @@ -0,0 +1,502 @@ + + + + + + Action + <Alt><Mod2>g + False + Grid + Grid + + + Action + False + User + User + + + Action + False + Asset + Asset + + + Action + Region + Region + + + Action + Services + Services + + + Action + False + Connect to gridserver... + Connect to gridserver + gtk-connect + + + + Action + Restart whole grid + Restart whole grid + gtk-refresh + + + Action + Shutdown whole grid + Shutdown whole grid + gtk-stop + + + Action + Exit grid manager + Exit grid manager + gtk-close + + + + Action + Connect to userserver + Connect to userserver + gtk-connect + + + Action + Account managment + Account managment + gtk-properties + + + Action + Global notice + Global notice + gtk-network + + + Action + Disable all logins + Disable all logins + gtk-no + + + Action + Disable non-god users only + Disable non-god users only + gtk-no + + + Action + Shutdown user server + Shutdown user server + gtk-stop + + + Action + Shutdown gridserver only + Shutdown gridserver only + gtk-stop + + + + Action + Restart gridserver only + Restart gridserver only + gtk-refresh + + + + Action + Default local grid userserver + Default local grid userserver + + + Action + Custom userserver... + Custom userserver + + + Action + Remote grid default userserver... + Remote grid default userserver + + + Action + Disconnect from grid server + Disconnect from grid server + gtk-disconnect + False + + + + Action + Upload asset + Upload asset + + + Action + Asset management + Asset management + + + Action + Connect to asset server + Connect to asset server + + + Action + Connect to default asset server for grid + Connect to default asset server for grid + + + Action + Default for local grid + Default for local grid + + + Action + Default for remote grid... + Default for remote grid... + + + Action + Custom asset server... + Custom asset server... + + + + 800 + 600 + Open Grid Services Manager + stock:gtk-network Dialog + + + + + + + + 25 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + False + False + False + + + + + + + + + + + + True + Automatic + Automatic + + + + None + + + + + + + + + + 1 + True + + + + + + True + + + 2 + True + + + + + 1 + True + + + + + statusBar1 + 5 + + + + + + + + + End + 2 + False + False + False + + + + + + + + ButtonPressMask + Connect to Grid server + CenterOnParent + 2 + False + False + + + + + ButtonPressMask + 2 + + + + + + + + + + + + + + + + + + + 1 + Grid server URL: + Right + + + 0 + False + + + + + + True + http://gridserver:8001 + True + 255 + + + + 1 + False + + + + + + + + 0 + True + False + False + + + + + + + + + 1 + Username: + Right + + + 0 + False + + + + + + True + True + + + + 1 + True + + + + + + + + 1 + False + False + False + + + + + + + + + 1 + Password: + Right + + + 0 + False + + + + + + True + True + + + + 1 + True + + + + + + + + 2 + True + False + False + + + + + 2 + True + False + False + + + + + 0 + True + + + + + + + + ButtonPressMask + 6 + 5 + 2 + End + + + + True + True + TextAndIcon + stock:gtk-apply Menu + Connect + True + True + -5 + + + False + False + + + + + + True + True + TextAndIcon + stock:gtk-cancel Menu + Cancel + True + True + -6 + + + 1 + False + False + + + + + + \ No newline at end of file diff --git a/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs b/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs new file mode 100644 index 0000000..25e0211 --- /dev/null +++ b/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("UserConfig")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UserConfig")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Grid/UserServer.Config/DbUserConfig.cs b/OpenSim/Grid/UserServer.Config/DbUserConfig.cs new file mode 100644 index 0000000..770a6b9 --- /dev/null +++ b/OpenSim/Grid/UserServer.Config/DbUserConfig.cs @@ -0,0 +1,96 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using Db4objects.Db4o; + +namespace OpenUser.Config.UserConfigDb4o +{ + public class Db4oConfigPlugin: IUserConfig + { + public UserConfig GetConfigObject() + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Loading Db40Config dll"); + return ( new DbUserConfig()); + } + } + + public class DbUserConfig : UserConfig + { + private IObjectContainer db; + + public void LoadDefaults() { + OpenSim.Framework.Console.MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); + + this.DefaultStartupMsg = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Default startup message", "Welcome to OGS"); + + this.GridServerURL = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Grid server URL","http://127.0.0.1:8001/"); + this.GridSendKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to send to grid server","null"); + this.GridRecvKey = OpenSim.Framework.Console.MainLog.Instance.CmdPrompt("Key to expect from grid server","null"); + } + + public override void InitConfig() { + try { + db = Db4oFactory.OpenFile("openuser.yap"); + IObjectSet result = db.Get(typeof(DbUserConfig)); + if(result.Count==1) { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Config.cs:InitConfig() - Found a UserConfig object in the local database, loading"); + foreach (DbUserConfig cfg in result) { + this.GridServerURL=cfg.GridServerURL; + this.GridSendKey=cfg.GridSendKey; + this.GridRecvKey=cfg.GridRecvKey; + this.DefaultStartupMsg=cfg.DefaultStartupMsg; + } + } else { + OpenSim.Framework.Console.MainLog.Instance.Verbose("Config.cs:InitConfig() - Could not find object in database, loading precompiled defaults"); + LoadDefaults(); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Writing out default settings to local database"); + db.Set(this); + db.Close(); + } + } catch(Exception e) { + OpenSim.Framework.Console.MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + + OpenSim.Framework.Console.MainLog.Instance.Verbose("User settings loaded:"); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Default startup message: " + this.DefaultStartupMsg); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Grid server URL: " + this.GridServerURL); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to send to grid: " + this.GridSendKey); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Key to expect from grid: " + this.GridRecvKey); + } + + + public void Shutdown() { + db.Close(); + } + } + +} diff --git a/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj b/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj new file mode 100644 index 0000000..1ae9589 --- /dev/null +++ b/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj @@ -0,0 +1,107 @@ + + + Local + 8.0.50727 + 2.0 + {08F87229-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.UserServer.Config + JScript + Grid + IE50 + false + Library + + OpenSim.Grid.UserServer.Config + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + System.dll + False + + + ..\..\..\bin\System.Data.dll + False + + + System.Xml.dll + False + + + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj.user b/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/UserServer.Config/OpenSim.Grid.UserServer.Config.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/UserServer/Main.cs b/OpenSim/Grid/UserServer/Main.cs new file mode 100644 index 0000000..5c27d57 --- /dev/null +++ b/OpenSim/Grid/UserServer/Main.cs @@ -0,0 +1,219 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.IO; +using System.Text; +using libsecondlife; +using OpenSim.Framework.User; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Console; +using OpenSim.Servers; +using OpenSim.Framework.Utilities; +using OpenSim.GenericConfig; + +namespace OpenGridServices.UserServer +{ + /// + /// + public class OpenUser_Main : conscmd_callback + { + private string ConfigDll = "OpenUser.Config.UserConfigDb4o.dll"; + private string StorageDll = "OpenGrid.Framework.Data.MySQL.dll"; + private UserConfig Cfg; + protected IGenericConfig localXMLConfig; + + public UserManager m_userManager; + + public Dictionary UserSessions = new Dictionary(); + + LogBase m_console; + + [STAThread] + public static void Main(string[] args) + { + Console.WriteLine("Launching UserServer..."); + + OpenUser_Main userserver = new OpenUser_Main(); + + userserver.Startup(); + userserver.Work(); + } + + private OpenUser_Main() + { + m_console = new LogBase("opengrid-userserver-console.log", "OpenUser", this , false); + OpenSim.Framework.Console.MainLog.Instance = m_console; + } + + private void Work() + { + m_console.Notice("Enter help for a list of commands\n"); + + while (true) + { + m_console.MainLogPrompt(); + } + } + + public void Startup() + { + this.localXMLConfig = new XmlConfig("UserServerConfig.xml"); + this.localXMLConfig.LoadData(); + this.ConfigDB(this.localXMLConfig); + this.localXMLConfig.Close(); + + OpenSim.Framework.Console.MainLog.Instance.Verbose("Main.cs:Startup() - Loading configuration"); + Cfg = this.LoadConfigDll(this.ConfigDll); + Cfg.InitConfig(); + + OpenSim.Framework.Console.MainLog.Instance.Verbose("Main.cs:Startup() - Establishing data connection"); + m_userManager = new UserManager(); + m_userManager._config = Cfg; + m_userManager.AddPlugin(StorageDll); + + OpenSim.Framework.Console.MainLog.Instance.Verbose("Main.cs:Startup() - Starting HTTP process"); + BaseHttpServer httpServer = new BaseHttpServer(8002); + + httpServer.AddXmlRPCHandler("login_to_simulator", m_userManager.XmlRpcLoginMethod); + + httpServer.AddRestHandler("GET", "/user/name/", m_userManager.RestGetUserMethodName); + httpServer.AddRestHandler("GET", "/user/uuid/", m_userManager.RestGetUserMethodUUID); + + httpServer.AddRestHandler("DELETE", "/usersessions/", m_userManager.RestDeleteUserSessionMethod); + + httpServer.Start(); + m_console.Status("Userserver 0.3 - Startup complete"); + } + + + public void do_create(string what) + { + switch (what) + { + case "user": + string tempfirstname; + string templastname; + string tempMD5Passwd; + uint regX = 997; + uint regY = 996; + + tempfirstname = m_console.CmdPrompt("First name"); + templastname = m_console.CmdPrompt("Last name"); + tempMD5Passwd = m_console.PasswdPrompt("Password"); + regX = Convert.ToUInt32(m_console.CmdPrompt("Start Region X")); + regY = Convert.ToUInt32(m_console.CmdPrompt("Start Region Y")); + + tempMD5Passwd = Util.Md5Hash(Util.Md5Hash(tempMD5Passwd) + ":" + ""); + + m_userManager.AddUserProfile(tempfirstname, templastname, tempMD5Passwd, regX, regY); + break; + } + } + + public void RunCmd(string cmd, string[] cmdparams) + { + switch (cmd) + { + case "help": + m_console.Notice("create user - create a new user"); + m_console.Notice("shutdown - shutdown the grid (USE CAUTION!)"); + break; + + case "create": + do_create(cmdparams[0]); + break; + + case "shutdown": + m_console.Close(); + Environment.Exit(0); + break; + } + } + + private void ConfigDB(IGenericConfig configData) + { + try + { + string attri = ""; + attri = configData.GetAttribute("DataBaseProvider"); + if (attri == "") + { + StorageDll = "OpenGrid.Framework.Data.DB4o.dll"; + configData.SetAttribute("DataBaseProvider", "OpenGrid.Framework.Data.DB4o.dll"); + } + else + { + StorageDll = attri; + } + configData.Commit(); + } + catch (Exception e) + { + + } + } + + private UserConfig LoadConfigDll(string dllName) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + UserConfig config = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IUserConfig", true); + + if (typeInterface != null) + { + IUserConfig plug = (IUserConfig)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + config = plug.GetConfigObject(); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + return config; + } + + public void Show(string ShowWhat) + { + } + } +} diff --git a/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj b/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj new file mode 100644 index 0000000..3c93b78 --- /dev/null +++ b/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj @@ -0,0 +1,132 @@ + + + Local + 8.0.50727 + 2.0 + {2FC96F92-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Grid.UserServer + JScript + Grid + IE50 + false + Exe + + OpenSim.Grid.UserServer + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Framework.dll + False + + + OpenSim.Framework.Console.dll + False + + + OpenSim.Framework.GenericConfig.Xml.dll + False + + + OpenSim.Framework.Servers.dll + False + + + OpenSim.Framework.UserManager.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj.user b/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Grid/UserServer/OpenSim.Grid.UserServer.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs b/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..5d5ce8d --- /dev/null +++ b/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OGS-UserServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OGS-UserServer")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e266513a-090b-4d38-80f6-8599eef68c8c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Grid/UserServer/UserManager.cs b/OpenSim/Grid/UserServer/UserManager.cs new file mode 100644 index 0000000..0704de1 --- /dev/null +++ b/OpenSim/Grid/UserServer/UserManager.cs @@ -0,0 +1,103 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Data; +using libsecondlife; +using System.Reflection; + +using System.Xml; +using Nwc.XmlRpc; +using OpenSim.Framework.Sims; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenGrid.Framework.UserManagement; + +using System.Security.Cryptography; + +namespace OpenGridServices.UserServer +{ + public class UserManager : UserManagerBase + { + public UserManager() + { + } + + /// + /// Customises the login response and fills in missing values. + /// + /// The existing response + /// The user profile + public override void CustomiseResponse(ref LoginResponse response, ref UserProfileData theUser) + { + // Load information from the gridserver + SimProfile SimInfo = new SimProfile(); + SimInfo = SimInfo.LoadFromGrid(theUser.currentAgent.currentHandle, _config.GridServerURL, _config.GridSendKey, _config.GridRecvKey); + + // Customise the response + // Home Location + response.Home = "{'region_handle':[r" + (SimInfo.RegionLocX * 256).ToString() + ",r" + (SimInfo.RegionLocY * 256).ToString() + "], " + + "'position':[r" + theUser.homeLocation.X.ToString() + ",r" + theUser.homeLocation.Y.ToString() + ",r" + theUser.homeLocation.Z.ToString() + "], " + + "'look_at':[r" + theUser.homeLocation.X.ToString() + ",r" + theUser.homeLocation.Y.ToString() + ",r" + theUser.homeLocation.Z.ToString() + "]}"; + + // Destination + response.SimAddress = SimInfo.sim_ip; + response.SimPort = (Int32)SimInfo.sim_port; + response.RegionX = SimInfo.RegionLocY ; + response.RegionY = SimInfo.RegionLocX ; + + // Notify the target of an incoming user + Console.WriteLine("Notifying " + SimInfo.regionname + " (" + SimInfo.caps_url + ")"); + + // Prepare notification + Hashtable SimParams = new Hashtable(); + SimParams["session_id"] = theUser.currentAgent.sessionID.ToString(); + SimParams["secure_session_id"] = theUser.currentAgent.secureSessionID.ToString(); + SimParams["firstname"] = theUser.username; + SimParams["lastname"] = theUser.surname; + SimParams["agent_id"] = theUser.UUID.ToString(); + SimParams["circuit_code"] = (Int32)Convert.ToUInt32(response.CircuitCode); + SimParams["startpos_x"] = theUser.currentAgent.currentPos.X.ToString(); + SimParams["startpos_y"] = theUser.currentAgent.currentPos.Y.ToString(); + SimParams["startpos_z"] = theUser.currentAgent.currentPos.Z.ToString(); + SimParams["regionhandle"] = theUser.currentAgent.currentHandle.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(SimParams); + + // Update agent with target sim + theUser.currentAgent.currentRegion = SimInfo.UUID; + theUser.currentAgent.currentHandle = SimInfo.regionhandle; + + // Send + XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.caps_url, 3000); + } + } +} diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs new file mode 100644 index 0000000..40701b0 --- /dev/null +++ b/OpenSim/Region/Application/Application.cs @@ -0,0 +1,121 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Console; + +namespace OpenSim +{ + public class Application + { + //could move our main function into OpenSimMain and kill this class + [STAThread] + public static void Main(string[] args) + { + Console.WriteLine("OpenSim " + VersionInfo.Version + "\n"); + Console.WriteLine("Starting...\n"); + + bool sandBoxMode = false; + bool startLoginServer = false; + string physicsEngine = "basicphysics"; + bool allowFlying = false; + bool userAccounts = false; + bool gridLocalAsset = false; + bool useConfigFile = false; + bool silent = false; + string configFile = "simconfig.xml"; + + for (int i = 0; i < args.Length; i++) + { + if (args[i] == "-sandbox") + { + sandBoxMode = true; + startLoginServer = true; + } + /* + if (args[i] == "-loginserver") + { + startLoginServer = true; + }*/ + if (args[i] == "-accounts") + { + userAccounts = true; + } + if (args[i] == "-realphysx") + { + physicsEngine = "RealPhysX"; + allowFlying = true; + } + if (args[i] == "-ode") + { + physicsEngine = "OpenDynamicsEngine"; + allowFlying = true; + } + if (args[i] == "-localasset") + { + gridLocalAsset = true; + } + if (args[i] == "-configfile") + { + useConfigFile = true; + } + if (args[i] == "-noverbose") + { + silent = true; + } + if (args[i] == "-config") + { + try + { + i++; + configFile = args[i]; + } + catch (Exception e) + { + Console.WriteLine("-config: Please specify a config file. (" + e.ToString() + ")"); + } + } + } + + OpenSimMain sim = new OpenSimMain(sandBoxMode, startLoginServer, physicsEngine, useConfigFile, silent, configFile); + // OpenSimRoot.Instance.Application = sim; + sim.m_sandbox = sandBoxMode; + sim.user_accounts = userAccounts; + sim.gridLocalAsset = gridLocalAsset; + OpenSim.Region.Scenes.ScenePresence.PhysicsEngineFlying = allowFlying; + + sim.StartUp(); + + while (true) + { + OpenSim.Framework.Console.MainLog.Instance.MainLogPrompt(); + } + } + } +} diff --git a/OpenSim/Region/Application/OpenSim.csproj b/OpenSim/Region/Application/OpenSim.csproj new file mode 100644 index 0000000..214f2cf --- /dev/null +++ b/OpenSim/Region/Application/OpenSim.csproj @@ -0,0 +1,181 @@ + + + Local + 8.0.50727 + 2.0 + {438A9556-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim + JScript + Grid + IE50 + false + Exe + + OpenSim + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Axiom.MathLib.dll + False + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications + {CB52B7E7-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications.OGS1 + {6109024D-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.GenericConfig.Xml + {C74E4A30-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Servers + {2CC71860-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.UserManagement + {586E2916-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Caches + {61FCCDB3-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.ClientStack + {DC3698B2-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.LocalCommunications + {EB3A1BA8-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Simulation + {C0DAB338-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Terrain.BasicTerrain + {C9E0F891-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Application/OpenSim.csproj.user b/OpenSim/Region/Application/OpenSim.csproj.user new file mode 100644 index 0000000..2ff1c4c --- /dev/null +++ b/OpenSim/Region/Application/OpenSim.csproj.user @@ -0,0 +1,13 @@ + + + Debug + AnyCPU + -loginserver -sandbox -accounts + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Application/OpenSimMain.cs b/OpenSim/Region/Application/OpenSimMain.cs new file mode 100644 index 0000000..7da2263 --- /dev/null +++ b/OpenSim/Region/Application/OpenSimMain.cs @@ -0,0 +1,476 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Region; +using OpenSim.Region.Scenes; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework; +using OpenSim.Assets; +using OpenSim.Caches; +using OpenSim.Framework.Console; +using OpenSim.Physics.Manager; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; +using OpenGrid.Framework.Communications; +using OpenSim.LocalCommunications; +using OpenGrid.Framework.Communications.OGS1; + +namespace OpenSim +{ + + public class OpenSimMain : RegionApplicationBase, conscmd_callback + { + // private CheckSumServer checkServer; + protected CommunicationsManager commsManager; + + private bool m_silent; + private string m_logFilename = "region-console-" + Guid.NewGuid().ToString() + ".log"; + + public OpenSimMain(bool sandBoxMode, bool startLoginServer, string physicsEngine, bool useConfigFile, bool silent, string configFile) + { + this.configFileSetup = useConfigFile; + m_sandbox = sandBoxMode; + m_loginserver = startLoginServer; + m_physicsEngine = physicsEngine; + m_config = configFile; + m_silent = silent; + } + + /// + /// Performs initialisation of the world, such as loading configuration from disk. + /// + public override void StartUp() + { + this.serversData = new NetworkServersInfo(); + + this.localConfig = new XmlConfig(m_config); + this.localConfig.LoadData(); + + if (this.configFileSetup) + { + this.SetupFromConfigFile(this.localConfig); + } + + m_log = new LogBase(m_logFilename, "Region", this, m_silent); + OpenSim.Framework.Console.MainLog.Instance = m_log; + + m_log.Verbose( "Main.cs:Startup() - Loading configuration"); + this.serversData.InitConfig(this.m_sandbox, this.localConfig); + this.localConfig.Close();//for now we can close it as no other classes read from it , but this should change + + ScenePresence.LoadTextureFile("avatar-texture.dat"); + + ClientView.TerrainManager = new TerrainManager(new SecondLife()); + + CommunicationsLocal sandboxCommunications = null; + if (m_sandbox) + { + this.SetupLocalGridServers(); + // this.checkServer = new CheckSumServer(12036); + // this.checkServer.ServerListener(); + sandboxCommunications = new CommunicationsLocal(this.serversData); + this.commsManager = sandboxCommunications; + } + else + { + this.SetupRemoteGridServers(); + this.commsManager = new GridCommsManager(this.serversData); + } + + startuptime = DateTime.Now; + + this.physManager = new OpenSim.Physics.Manager.PhysicsManager(); + this.physManager.LoadPlugins(); + + this.SetupHttpListener(); + + this.SetupWorld(); + + m_log.Verbose( "Main.cs:Startup() - Initialising HTTP server"); + + + + if (m_sandbox) + { + httpServer.AddXmlRPCHandler("login_to_simulator", sandboxCommunications.UserServices.XmlRpcLoginMethod); + } + + //Start http server + m_log.Verbose( "Main.cs:Startup() - Starting HTTP server"); + httpServer.Start(); + + // Start UDP servers + for (int i = 0; i < m_udpServer.Count; i++) + { + this.m_udpServer[i].ServerListener(); + } + + } + + # region Setup methods + protected override void SetupLocalGridServers() + { + try + { + AssetCache = new AssetCache("OpenSim.GridInterfaces.Local.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); + InventoryCache = new InventoryCache(); + } + catch (Exception e) + { + m_log.Error( e.Message + "\nSorry, could not setup local cache"); + Environment.Exit(1); + } + + } + + protected override void SetupRemoteGridServers() + { + try + { + AssetCache = new AssetCache("OpenSim.GridInterfaces.Remote.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); + InventoryCache = new InventoryCache(); + } + catch (Exception e) + { + m_log.Error( e.Message + "\nSorry, could not setup remote cache"); + Environment.Exit(1); + } + } + + protected override void SetupWorld() + { + IGenericConfig regionConfig; + Scene LocalWorld; + UDPServer udpServer; + RegionInfo regionDat = new RegionInfo(); + AuthenticateSessionsBase authenBase; + + string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Regions"); + string[] configFiles = Directory.GetFiles(path, "*.xml"); + + if (configFiles.Length == 0) + { + string path2 = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Regions"); + string path3 = Path.Combine(path2, "default.xml"); + Console.WriteLine("Creating default region config file"); + //TODO create default region + IGenericConfig defaultConfig = new XmlConfig(path3); + defaultConfig.LoadData(); + defaultConfig.Commit(); + defaultConfig.Close(); + defaultConfig = null; + configFiles = Directory.GetFiles(path, "*.xml"); + } + + for (int i = 0; i < configFiles.Length; i++) + { + regionDat = new RegionInfo(); + if (m_sandbox) + { + AuthenticateSessionsBase authen = new AuthenticateSessionsBase(); // new AuthenticateSessionsLocal(); + this.AuthenticateSessionsHandler.Add(authen); + authenBase = authen; + } + else + { + AuthenticateSessionsBase authen = new AuthenticateSessionsBase(); //new AuthenticateSessionsRemote(); + this.AuthenticateSessionsHandler.Add(authen); + authenBase = authen; + } + Console.WriteLine("Loading region config file"); + regionConfig = new XmlConfig(configFiles[i]); + regionConfig.LoadData(); + regionDat.InitConfig(this.m_sandbox, regionConfig); + regionConfig.Close(); + + udpServer = new UDPServer(regionDat.CommsIPListenPort, this.AssetCache, this.InventoryCache, this.m_log, authenBase); + + m_udpServer.Add(udpServer); + this.regionData.Add(regionDat); + + /* + m_log.WriteLine(OpenSim.Framework.Console.LogPriority.NORMAL, "Main.cs:Startup() - We are " + regionData.RegionName + " at " + regionData.RegionLocX.ToString() + "," + regionData.RegionLocY.ToString()); + m_log.Verbose( "Initialising world"); + m_log.componentname = "Region " + regionData.RegionName; + */ + + LocalWorld = new Scene(udpServer.PacketServer.ClientAPIs, regionDat, authenBase, commsManager, this.AssetCache, httpServer); + this.m_localWorld.Add(LocalWorld); + //LocalWorld.InventoryCache = InventoryCache; + //LocalWorld.AssetCache = AssetCache; + + udpServer.LocalWorld = LocalWorld; + + LocalWorld.LoadStorageDLL("OpenSim.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded. + LocalWorld.LoadWorldMap(); + + m_log.Verbose( "Main.cs:Startup() - Starting up messaging system"); + LocalWorld.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); + LocalWorld.PhysScene.SetTerrain(LocalWorld.Terrain.getHeights1D()); + LocalWorld.LoadPrimsFromStorage(); + LocalWorld.localStorage.LoadParcels((ILocalStorageParcelReceiver)LocalWorld.parcelManager); + + + LocalWorld.StartTimer(); + } + } + + protected override void SetupHttpListener() + { + httpServer = new BaseHttpServer(this.serversData.HttpListenerPort); //regionData[0].IPListenPort); + + if (!this.m_sandbox) + { + + // we are in Grid mode so set a XmlRpc handler to handle "expect_user" calls from the user server + + + httpServer.AddRestHandler("GET", "/simstatus/", + delegate(string request, string path, string param) + { + return "OK"; + }); + } + } + + protected override void ConnectToRemoteGridServer() + { + + } + + #endregion + + private void SetupFromConfigFile(IGenericConfig configData) + { + // Log filename + string attri = ""; + attri = configData.GetAttribute("LogFilename"); + if (String.IsNullOrEmpty(attri)) + { + } + else + { + m_logFilename = attri; + } + + // SandBoxMode + attri = ""; + attri = configData.GetAttribute("SandBox"); + if ((attri == "") || ((attri != "false") && (attri != "true"))) + { + this.m_sandbox = false; + configData.SetAttribute("SandBox", "false"); + } + else + { + this.m_sandbox = Convert.ToBoolean(attri); + } + + // LoginServer + attri = ""; + attri = configData.GetAttribute("LoginServer"); + if ((attri == "") || ((attri != "false") && (attri != "true"))) + { + this.m_loginserver = false; + configData.SetAttribute("LoginServer", "false"); + } + else + { + this.m_loginserver = Convert.ToBoolean(attri); + } + + // Sandbox User accounts + attri = ""; + attri = configData.GetAttribute("UserAccount"); + if ((attri == "") || ((attri != "false") && (attri != "true"))) + { + this.user_accounts = false; + configData.SetAttribute("UserAccounts", "false"); + } + else if (attri == "true") + { + this.user_accounts = Convert.ToBoolean(attri); + } + + // Grid mode hack to use local asset server + attri = ""; + attri = configData.GetAttribute("LocalAssets"); + if ((attri == "") || ((attri != "false") && (attri != "true"))) + { + this.gridLocalAsset = false; + configData.SetAttribute("LocalAssets", "false"); + } + else if (attri == "true") + { + this.gridLocalAsset = Convert.ToBoolean(attri); + } + + + attri = ""; + attri = configData.GetAttribute("PhysicsEngine"); + switch (attri) + { + default: + m_log.Warn( "Main.cs: SetupFromConfig() - Invalid value for PhysicsEngine attribute, terminating"); + Environment.Exit(1); + break; + + case "": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.Region.Scenes.ScenePresence.PhysicsEngineFlying = false; + break; + + case "basicphysics": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.Region.Scenes.ScenePresence.PhysicsEngineFlying = false; + break; + + case "RealPhysX": + this.m_physicsEngine = "RealPhysX"; + OpenSim.Region.Scenes.ScenePresence.PhysicsEngineFlying = true; + break; + + case "OpenDynamicsEngine": + this.m_physicsEngine = "OpenDynamicsEngine"; + OpenSim.Region.Scenes.ScenePresence.PhysicsEngineFlying = true; + break; + } + + configData.Commit(); + + } + + /// + /// Performs any last-minute sanity checking and shuts down the region server + /// + public virtual void Shutdown() + { + m_log.Verbose( "Main.cs:Shutdown() - Closing all threads"); + m_log.Verbose( "Main.cs:Shutdown() - Killing listener thread"); + m_log.Verbose( "Main.cs:Shutdown() - Killing clients"); + // IMPLEMENT THIS + m_log.Verbose( "Main.cs:Shutdown() - Closing console and terminating"); + for (int i = 0; i < m_localWorld.Count; i++) + { + ((Scene)m_localWorld[i]).Close(); + } + m_log.Close(); + Environment.Exit(0); + } + + #region Console Commands + /// + /// Runs commands issued by the server console from the operator + /// + /// The first argument of the parameter (the command) + /// Additional arguments passed to the command + public void RunCmd(string command, string[] cmdparams) + { + switch (command) + { + case "help": + m_log.Error( "show users - show info about connected users"); + m_log.Error( "shutdown - disconnect all clients and shutdown"); + break; + + case "show": + if (cmdparams.Length > 0) + { + Show(cmdparams[0]); + } + break; + + case "terrain": + string result = ""; + for (int i = 0; i < m_localWorld.Count; i++) + { + if (!((Scene)m_localWorld[i]).Terrain.RunTerrainCmd(cmdparams, ref result)) + { + m_log.Error(result); + } + } + break; + + case "shutdown": + Shutdown(); + break; + + default: + m_log.Error( "Unknown command"); + break; + } + } + + /// + /// Outputs to the console information about the region + /// + /// What information to display (valid arguments are "uptime", "users") + public void Show(string ShowWhat) + { + switch (ShowWhat) + { + case "uptime": + m_log.Error( "OpenSim has been running since " + startuptime.ToString()); + m_log.Error( "That is " + (DateTime.Now - startuptime).ToString()); + break; + case "users": + OpenSim.Region.Scenes.ScenePresence TempAv; + m_log.Error( String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP")); + /* foreach (libsecondlife.LLUUID UUID in LocalWorld.Entities.Keys) + { + if (LocalWorld.Entities[UUID].ToString() == "OpenSim.world.Avatar") + { + TempAv = (OpenSim.world.Avatar)LocalWorld.Entities[UUID]; + m_log.Error( String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.SessionID, TempAv.ControllingClient.CircuitCode, TempAv.ControllingClient.userEP.ToString())); + } + }*/ + break; + } + } + #endregion + } + + +} \ No newline at end of file diff --git a/OpenSim/Region/Caches/AssetCache.cs b/OpenSim/Region/Caches/AssetCache.cs new file mode 100644 index 0000000..d0cc370 --- /dev/null +++ b/OpenSim/Region/Caches/AssetCache.cs @@ -0,0 +1,670 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Reflection; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Caches +{ + public delegate void DownloadComplete(AssetCache.TextureSender sender); + + /// + /// Manages local cache of assets and their sending to viewers. + /// + public class AssetCache : IAssetReceiver + { + public Dictionary Assets; + public Dictionary Textures; + + public List AssetRequests = new List(); //assets ready to be sent to viewers + public List TextureRequests = new List(); //textures ready to be sent + + public Dictionary RequestedAssets = new Dictionary(); //Assets requested from the asset server + public Dictionary RequestedTextures = new Dictionary(); //Textures requested from the asset server + + public Dictionary SendingTextures = new Dictionary(); + private IAssetServer _assetServer; + private Thread _assetCacheThread; + private LLUUID[] textureList = new LLUUID[5]; + + /// + /// + /// + public AssetCache(IAssetServer assetServer) + { + Console.WriteLine("Creating Asset cache"); + _assetServer = assetServer; + _assetServer.SetReceiver(this); + Assets = new Dictionary(); + Textures = new Dictionary(); + this._assetCacheThread = new Thread(new ThreadStart(RunAssetManager)); + this._assetCacheThread.IsBackground = true; + this._assetCacheThread.Start(); + + } + + public AssetCache(string assetServerDLLName, string assetServerURL, string assetServerKey) + { + Console.WriteLine("Creating Asset cache"); + _assetServer = this.LoadAssetDll(assetServerDLLName); + _assetServer.SetServerInfo(assetServerURL, assetServerKey); + _assetServer.SetReceiver(this); + Assets = new Dictionary(); + Textures = new Dictionary(); + this._assetCacheThread = new Thread(new ThreadStart(RunAssetManager)); + this._assetCacheThread.IsBackground = true; + this._assetCacheThread.Start(); + + } + + /// + /// + /// + public void RunAssetManager() + { + while (true) + { + try + { + //Console.WriteLine("Asset cache loop"); + this.ProcessAssetQueue(); + this.ProcessTextureQueue(); + Thread.Sleep(500); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + } + + public void LoadDefaultTextureSet() + { + //hack: so we can give each user a set of textures + textureList[0] = new LLUUID("00000000-0000-0000-9999-000000000001"); + textureList[1] = new LLUUID("00000000-0000-0000-9999-000000000002"); + textureList[2] = new LLUUID("00000000-0000-0000-9999-000000000003"); + textureList[3] = new LLUUID("00000000-0000-0000-9999-000000000004"); + textureList[4] = new LLUUID("00000000-0000-0000-9999-000000000005"); + + for (int i = 0; i < textureList.Length; i++) + { + this._assetServer.RequestAsset(textureList[i], true); + } + + } + + public AssetBase[] CreateNewInventorySet(LLUUID agentID) + { + AssetBase[] inventorySet = new AssetBase[this.textureList.Length]; + for (int i = 0; i < textureList.Length; i++) + { + if (this.Textures.ContainsKey(textureList[i])) + { + inventorySet[i] = this.CloneImage(agentID, this.Textures[textureList[i]]); + TextureImage image = new TextureImage(inventorySet[i]); + this.Textures.Add(image.FullID, image); + this._assetServer.UploadNewAsset(image); //save the asset to the asset server + } + } + return inventorySet; + } + + public AssetBase GetAsset(LLUUID assetID) + { + AssetBase asset = null; + if (this.Textures.ContainsKey(assetID)) + { + asset = this.Textures[assetID]; + } + else if (this.Assets.ContainsKey(assetID)) + { + asset = this.Assets[assetID]; + } + return asset; + } + + public void AddAsset(AssetBase asset) + { + // Console.WriteLine("adding asset " + asset.FullID.ToStringHyphenated()); + if (asset.Type == 0) + { + //Console.WriteLine("which is a texture"); + if (!this.Textures.ContainsKey(asset.FullID)) + { //texture + TextureImage textur = new TextureImage(asset); + this.Textures.Add(textur.FullID, textur); + this._assetServer.UploadNewAsset(asset); + } + } + else + { + if (!this.Assets.ContainsKey(asset.FullID)) + { + AssetInfo assetInf = new AssetInfo(asset); + this.Assets.Add(assetInf.FullID, assetInf); + this._assetServer.UploadNewAsset(asset); + } + } + } + + /// + /// + /// + private void ProcessTextureQueue() + { + if (this.TextureRequests.Count == 0) + { + //no requests waiting + return; + } + int num; + num = this.TextureRequests.Count; + + AssetRequest req; + for (int i = 0; i < num; i++) + { + req = (AssetRequest)this.TextureRequests[i]; + if (!this.SendingTextures.ContainsKey(req.ImageInfo.FullID)) + { + TextureSender sender = new TextureSender(req); + sender.OnComplete += this.TextureSent; + lock (this.SendingTextures) + { + this.SendingTextures.Add(req.ImageInfo.FullID, sender); + } + } + + } + + this.TextureRequests.Clear(); + } + + /// + /// Event handler, called by a TextureSender object to say that texture has been sent + /// + /// + public void TextureSent(AssetCache.TextureSender sender) + { + if (this.SendingTextures.ContainsKey(sender.request.ImageInfo.FullID)) + { + lock (this.SendingTextures) + { + this.SendingTextures.Remove(sender.request.ImageInfo.FullID); + } + } + } + + public void AssetReceived(AssetBase asset, bool IsTexture) + { + if (asset.FullID != LLUUID.Zero) // if it is set to zero then the asset wasn't found by the server + { + //check if it is a texture or not + //then add to the correct cache list + //then check for waiting requests for this asset/texture (in the Requested lists) + //and move those requests into the Requests list. + if (IsTexture) + { + TextureImage image = new TextureImage(asset); + this.Textures.Add(image.FullID, image); + if (this.RequestedTextures.ContainsKey(image.FullID)) + { + AssetRequest req = this.RequestedTextures[image.FullID]; + req.ImageInfo = image; + if (image.Data.LongLength > 600) + { + //over 600 bytes so split up file + req.NumPackets = 1 + (int)(image.Data.Length - 600 + 999) / 1000; + } + else + { + req.NumPackets = 1; + } + this.RequestedTextures.Remove(image.FullID); + this.TextureRequests.Add(req); + } + } + else + { + AssetInfo assetInf = new AssetInfo(asset); + this.Assets.Add(assetInf.FullID, assetInf); + if (this.RequestedAssets.ContainsKey(assetInf.FullID)) + { + AssetRequest req = this.RequestedAssets[assetInf.FullID]; + req.AssetInf = assetInf; + if (assetInf.Data.LongLength > 600) + { + //over 600 bytes so split up file + req.NumPackets = 1 + (int)(assetInf.Data.Length - 600 + 999) / 1000; + } + else + { + req.NumPackets = 1; + } + this.RequestedAssets.Remove(assetInf.FullID); + this.AssetRequests.Add(req); + } + } + } + } + + public void AssetNotFound(AssetBase asset) + { + //the asset server had no knowledge of requested asset + + } + + #region Assets + /// + /// + /// + /// + /// + public void AddAssetRequest(IClientAPI userInfo, TransferRequestPacket transferRequest) + { + LLUUID requestID = new LLUUID(transferRequest.TransferInfo.Params, 0); + //check to see if asset is in local cache, if not we need to request it from asset server. + + if (!this.Assets.ContainsKey(requestID)) + { + //not found asset + // so request from asset server + if (!this.RequestedAssets.ContainsKey(requestID)) + { + AssetRequest request = new AssetRequest(); + request.RequestUser = userInfo; + request.RequestAssetID = requestID; + request.TransferRequestID = transferRequest.TransferInfo.TransferID; + this.RequestedAssets.Add(requestID, request); + this._assetServer.RequestAsset(requestID, false); + } + return; + } + //it is in our cache + AssetInfo asset = this.Assets[requestID]; + + //work out how many packets it should be sent in + // and add to the AssetRequests list + AssetRequest req = new AssetRequest(); + req.RequestUser = userInfo; + req.RequestAssetID = requestID; + req.TransferRequestID = transferRequest.TransferInfo.TransferID; + req.AssetInf = asset; + + if (asset.Data.LongLength > 600) + { + //over 600 bytes so split up file + req.NumPackets = 1 + (int)(asset.Data.Length - 600 + 999) / 1000; + } + else + { + req.NumPackets = 1; + } + + this.AssetRequests.Add(req); + } + + /// + /// + /// + private void ProcessAssetQueue() + { + if (this.AssetRequests.Count == 0) + { + //no requests waiting + return; + } + int num; + + if (this.AssetRequests.Count < 5) + { + //lower than 5 so do all of them + num = this.AssetRequests.Count; + } + else + { + num = 5; + } + AssetRequest req; + for (int i = 0; i < num; i++) + { + req = (AssetRequest)this.AssetRequests[i]; + + TransferInfoPacket Transfer = new TransferInfoPacket(); + Transfer.TransferInfo.ChannelType = 2; + Transfer.TransferInfo.Status = 0; + Transfer.TransferInfo.TargetType = 0; + Transfer.TransferInfo.Params = req.RequestAssetID.GetBytes(); + Transfer.TransferInfo.Size = (int)req.AssetInf.Data.Length; + Transfer.TransferInfo.TransferID = req.TransferRequestID; + req.RequestUser.OutPacket(Transfer); + + if (req.NumPackets == 1) + { + TransferPacketPacket TransferPacket = new TransferPacketPacket(); + TransferPacket.TransferData.Packet = 0; + TransferPacket.TransferData.ChannelType = 2; + TransferPacket.TransferData.TransferID = req.TransferRequestID; + TransferPacket.TransferData.Data = req.AssetInf.Data; + TransferPacket.TransferData.Status = 1; + req.RequestUser.OutPacket(TransferPacket); + } + else + { + //more than one packet so split file up , for now it can't be bigger than 2000 bytes + TransferPacketPacket TransferPacket = new TransferPacketPacket(); + TransferPacket.TransferData.Packet = 0; + TransferPacket.TransferData.ChannelType = 2; + TransferPacket.TransferData.TransferID = req.TransferRequestID; + byte[] chunk = new byte[1000]; + Array.Copy(req.AssetInf.Data, chunk, 1000); + TransferPacket.TransferData.Data = chunk; + TransferPacket.TransferData.Status = 0; + req.RequestUser.OutPacket(TransferPacket); + + TransferPacket = new TransferPacketPacket(); + TransferPacket.TransferData.Packet = 1; + TransferPacket.TransferData.ChannelType = 2; + TransferPacket.TransferData.TransferID = req.TransferRequestID; + byte[] chunk1 = new byte[(req.AssetInf.Data.Length - 1000)]; + Array.Copy(req.AssetInf.Data, 1000, chunk1, 0, chunk1.Length); + TransferPacket.TransferData.Data = chunk1; + TransferPacket.TransferData.Status = 1; + req.RequestUser.OutPacket(TransferPacket); + } + + } + + //remove requests that have been completed + for (int i = 0; i < num; i++) + { + this.AssetRequests.RemoveAt(0); + } + + } + + public AssetInfo CloneAsset(LLUUID newOwner, AssetInfo sourceAsset) + { + AssetInfo newAsset = new AssetInfo(); + newAsset.Data = new byte[sourceAsset.Data.Length]; + Array.Copy(sourceAsset.Data, newAsset.Data, sourceAsset.Data.Length); + newAsset.FullID = LLUUID.Random(); + newAsset.Type = sourceAsset.Type; + newAsset.InvType = sourceAsset.InvType; + return (newAsset); + } + #endregion + + #region Textures + /// + /// + /// + /// + /// + public void AddTextureRequest(IClientAPI userInfo, LLUUID imageID) + { + //Console.WriteLine("texture request for " + imageID.ToStringHyphenated()); + //check to see if texture is in local cache, if not request from asset server + if (!this.Textures.ContainsKey(imageID)) + { + if (!this.RequestedTextures.ContainsKey(imageID)) + { + //not is cache so request from asset server + AssetRequest request = new AssetRequest(); + request.RequestUser = userInfo; + request.RequestAssetID = imageID; + request.IsTextureRequest = true; + this.RequestedTextures.Add(imageID, request); + this._assetServer.RequestAsset(imageID, true); + } + return; + } + + //Console.WriteLine("texture already in cache"); + TextureImage imag = this.Textures[imageID]; + AssetRequest req = new AssetRequest(); + req.RequestUser = userInfo; + req.RequestAssetID = imageID; + req.IsTextureRequest = true; + req.ImageInfo = imag; + + if (imag.Data.LongLength > 600) + { + //over 600 bytes so split up file + req.NumPackets = 1 + (int)(imag.Data.Length - 600 + 999) / 1000; + } + else + { + req.NumPackets = 1; + } + this.TextureRequests.Add(req); + } + + public TextureImage CloneImage(LLUUID newOwner, TextureImage source) + { + TextureImage newImage = new TextureImage(); + newImage.Data = new byte[source.Data.Length]; + Array.Copy(source.Data, newImage.Data, source.Data.Length); + //newImage.filename = source.filename; + newImage.FullID = LLUUID.Random(); + newImage.Name = source.Name; + return (newImage); + } + #endregion + + private IAssetServer LoadAssetDll(string dllName) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + IAssetServer server = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IAssetPlugin", true); + + if (typeInterface != null) + { + IAssetPlugin plug = (IAssetPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + server = plug.GetAssetServer(); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + return server; + } + + public class AssetRequest + { + public IClientAPI RequestUser; + public LLUUID RequestAssetID; + public AssetInfo AssetInf; + public TextureImage ImageInfo; + public LLUUID TransferRequestID; + public long DataPointer = 0; + public int NumPackets = 0; + public int PacketCounter = 0; + public bool IsTextureRequest; + //public bool AssetInCache; + //public int TimeRequested; + + public AssetRequest() + { + + } + } + + public class AssetInfo : AssetBase + { + public AssetInfo() + { + + } + + public AssetInfo(AssetBase aBase) + { + Data = aBase.Data; + FullID = aBase.FullID; + Type = aBase.Type; + InvType = aBase.InvType; + Name = aBase.Name; + Description = aBase.Description; + } + } + + public class TextureImage : AssetBase + { + public TextureImage() + { + + } + + public TextureImage(AssetBase aBase) + { + Data = aBase.Data; + FullID = aBase.FullID; + Type = aBase.Type; + InvType = aBase.InvType; + Name = aBase.Name; + Description = aBase.Description; + } + } + + public class TextureSender + { + public AssetRequest request; + public event DownloadComplete OnComplete; + Thread m_thread; + public TextureSender(AssetRequest req) + { + request = req; + //Console.WriteLine("creating worker thread for texture " + req.ImageInfo.FullID.ToStringHyphenated()); + //Console.WriteLine("texture data length is " + req.ImageInfo.Data.Length); + // Console.WriteLine("in " + req.NumPackets + " packets"); + //ThreadPool.QueueUserWorkItem(new WaitCallback(SendTexture), new object()); + + //need some sort of custom threadpool here, as using the .net one, overloads it and stops the handling of incoming packets etc + //but don't really want to create a thread for every texture download + m_thread = new Thread(new ThreadStart(SendTexture)); + m_thread.IsBackground = true; + m_thread.Start(); + } + + public void SendTexture() + { + //Console.WriteLine("starting to send sending texture " + request.ImageInfo.FullID.ToStringHyphenated()); + while (request.PacketCounter != request.NumPackets) + { + SendPacket(); + Thread.Sleep(500); + } + + //Console.WriteLine("finished sending texture " + request.ImageInfo.FullID.ToStringHyphenated()); + if (OnComplete != null) + { + OnComplete(this); + } + } + + public void SendPacket() + { + AssetRequest req = request; + // Console.WriteLine("sending " + req.ImageInfo.FullID); + + // if (req.ImageInfo.FullID == new LLUUID("00000000-0000-0000-5005-000000000005")) + if (req.PacketCounter == 0) + { + //first time for this request so send imagedata packet + if (req.NumPackets == 1) + { + //only one packet so send whole file + ImageDataPacket im = new ImageDataPacket(); + im.ImageID.Packets = 1; + im.ImageID.ID = req.ImageInfo.FullID; + im.ImageID.Size = (uint)req.ImageInfo.Data.Length; + im.ImageData.Data = req.ImageInfo.Data; + im.ImageID.Codec = 2; + req.RequestUser.OutPacket(im); + req.PacketCounter++; + //req.ImageInfo.l= time; + //System.Console.WriteLine("sent texture: " + req.ImageInfo.FullID); + // Console.WriteLine("sending packet 1 for " + req.ImageInfo.FullID.ToStringHyphenated()); + } + else + { + //more than one packet so split file up + ImageDataPacket im = new ImageDataPacket(); + im.ImageID.Packets = (ushort)req.NumPackets; + im.ImageID.ID = req.ImageInfo.FullID; + im.ImageID.Size = (uint)req.ImageInfo.Data.Length; + im.ImageData.Data = new byte[600]; + Array.Copy(req.ImageInfo.Data, 0, im.ImageData.Data, 0, 600); + im.ImageID.Codec = 2; + req.RequestUser.OutPacket(im); + req.PacketCounter++; + //req.ImageInfo.last_used = time; + //System.Console.WriteLine("sent first packet of texture: + // Console.WriteLine("sending packet 1 for " + req.ImageInfo.FullID.ToStringHyphenated()); + } + } + else + { + //Console.WriteLine("sending packet" + req.PacketCounter + "for " + req.ImageInfo.FullID.ToStringHyphenated()); + //send imagepacket + //more than one packet so split file up + ImagePacketPacket im = new ImagePacketPacket(); + im.ImageID.Packet = (ushort)req.PacketCounter; + im.ImageID.ID = req.ImageInfo.FullID; + int size = req.ImageInfo.Data.Length - 600 - 1000 * (req.PacketCounter - 1); + if (size > 1000) size = 1000; + im.ImageData.Data = new byte[size]; + Array.Copy(req.ImageInfo.Data, 600 + 1000 * (req.PacketCounter - 1), im.ImageData.Data, 0, size); + req.RequestUser.OutPacket(im); + req.PacketCounter++; + //req.ImageInfo.last_used = time; + //System.Console.WriteLine("sent a packet of texture: "+req.image_info.FullID); + } + + } + } + } +} + diff --git a/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj b/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj new file mode 100644 index 0000000..4a73d08 --- /dev/null +++ b/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj @@ -0,0 +1,97 @@ + + + Local + 8.0.50727 + 2.0 + {61FCCDB3-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Caches + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Caches + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj.user b/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Caches/OpenSim.Region.Caches.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Caches/Properties/AssemblyInfo.cs b/OpenSim/Region/Caches/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..00f5dfe --- /dev/null +++ b/OpenSim/Region/Caches/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Caches")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Caches")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2b15ddbf-0341-49a6-85c0-cece268a4518")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Caps/Caps.cs b/OpenSim/Region/Caps/Caps.cs new file mode 100644 index 0000000..13a351d --- /dev/null +++ b/OpenSim/Region/Caps/Caps.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Xml; +using OpenSim.Servers; +using OpenSim.Framework; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Types; +using OpenSim.Caches; +using libsecondlife; + +namespace OpenSim.Region +{ + public delegate void UpLoadedTexture(LLUUID assetID, LLUUID inventoryItem, byte[] data); + + public class Caps + { + private string httpListenerAddress; + private uint httpListenPort; + private string capsObjectPath = "00001-"; + private string requestPath = "0000/"; + private string mapLayerPath = "0001/"; + private string newInventory = "0002/"; + private string requestTexture = "0003/"; + private string eventQueue = "0100/"; + private BaseHttpServer httpListener; + private LLUUID agentID; + private AssetCache assetCache; + private int eventQueueCount = 1; + private Queue CapsEventQueue = new Queue(); + + public Caps(AssetCache assetCach, BaseHttpServer httpServer, string httpListen, uint httpPort, string capsPath, LLUUID agent) + { + assetCache = assetCach; + capsObjectPath = capsPath; + httpListener = httpServer; + httpListenerAddress = httpListen; + httpListenPort = httpPort; + agentID = agent; + } + + /// + /// + /// + public void RegisterHandlers() + { + Console.WriteLine("registering CAPS handlers"); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + requestPath, CapsRequest); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + mapLayerPath, MapLayer); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + newInventory, NewAgentInventory); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + eventQueue, ProcessEventQueue); + } + + /// + /// + /// + /// + /// + /// + /// + public string CapsRequest(string request, string path, string param) + { + // Console.WriteLine("Caps Request " + request); + string result = ""; + result = LLSDHelpers.SerialiseLLSDReply(this.GetCapabilities()); + return result; + } + + /// + /// + /// + /// + protected LLSDCapsDetails GetCapabilities() + { + /* string capURLS = ""; + capURLS += "MapLayerhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + mapLayerPath + ""; + capURLS += "NewFileAgentInventoryhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + newInventory + ""; + //capURLS += "RequestTextureDownloadhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + requestTexture + ""; + //capURLS += "EventQueueGethttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + eventQueue + ""; + return capURLS;*/ + + LLSDCapsDetails caps = new LLSDCapsDetails(); + caps.MapLayer = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + mapLayerPath; + caps.NewFileAgentInventory = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + newInventory; + return caps; + } + + /// + /// + /// + /// + /// + /// + /// + public string MapLayer(string request, string path, string param) + { + Encoding _enc = System.Text.Encoding.UTF8; + Hashtable hash =(Hashtable) LLSD.LLSDDeserialize(_enc.GetBytes(request)); + LLSDMapRequest mapReq = new LLSDMapRequest(); + LLSDHelpers.DeserialiseLLSDMap(hash, mapReq ); + + LLSDMapLayerResponse mapResponse= new LLSDMapLayerResponse(); + mapResponse.LayerData.Array.Add(this.BuildLLSDMapLayerResponse()); + string res = LLSDHelpers.SerialiseLLSDReply(mapResponse); + + //Console.WriteLine(" Maplayer response is " + res); + + return res; + } + + /// + /// + /// + /// + protected LLSDMapLayer BuildLLSDMapLayerResponse() + { + LLSDMapLayer mapLayer = new LLSDMapLayer(); + mapLayer.Right = 5000; + mapLayer.Top = 5000; + mapLayer.ImageID = new LLUUID("00000000-0000-0000-9999-000000000006"); + + return mapLayer; + } + + public string ProcessEventQueue(string request, string path, string param) + { + // Console.WriteLine("event queue request " + request); + string res = ""; + int timer = 0; + + /*while ((timer < 200) || (this.CapsEventQueue.Count < 1)) + { + timer++; + }*/ + if (this.CapsEventQueue.Count > 0) + { + lock (this.CapsEventQueue) + { + string item = CapsEventQueue.Dequeue(); + res = item; + } + } + else + { + res = this.CreateEmptyEventResponse(); + } + return res; + } + + public string CreateEstablishAgentComms(string caps, string ipAddressPort) + { + string res = "id" + eventQueueCount + ""; + res += "events"; + res += "messageEstablishAgentCommunication"; + res += "body"; + res += "sim-ip-and-port" + ipAddressPort + ""; + res += "seed-capability" + caps + ""; + res += "agent-id" + this.agentID.ToStringHyphenated() + ""; + res += ""; + res += ""; + res += ""; + eventQueueCount++; + this.CapsEventQueue.Enqueue(res); + return res; + } + + public string CreateEmptyEventResponse() + { + string res = "id" + eventQueueCount + ""; + res += "events"; + res += ""; + res += ""; + eventQueueCount++; + return res; + } + + public string NewAgentInventory(string request, string path, string param) + { + //Console.WriteLine("received upload request:"+ request); + string res = ""; + LLUUID newAsset = LLUUID.Random(); + LLUUID newInvItem = LLUUID.Random(); + string uploaderPath = capsObjectPath + Util.RandomClass.Next(5000, 8000).ToString("0000"); + AssetUploader uploader = new AssetUploader(newAsset, newInvItem, uploaderPath, this.httpListener); + httpListener.AddRestHandler("POST", "/CAPS/" + uploaderPath, uploader.uploaderCaps); + string uploaderURL = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + uploaderPath; + //Console.WriteLine("uploader url is " + uploaderURL); + res += ""; + res += "uploader" + uploaderURL + ""; + //res += "successtrue"; + res += "stateupload"; + res += ""; + uploader.OnUpLoad += this.UploadHandler; + return res; + } + + public void UploadHandler(LLUUID assetID, LLUUID inventoryItem, byte[] data) + { + // Console.WriteLine("upload handler called"); + AssetBase asset; + asset = new AssetBase(); + asset.FullID = assetID; + asset.Type = 0; + asset.InvType = 0; + asset.Name = "UploadedTexture" + Util.RandomClass.Next(1, 1000).ToString("000"); + asset.Data = data; + this.assetCache.AddAsset(asset); + } + + public class AssetUploader + { + public event UpLoadedTexture OnUpLoad; + + private string uploaderPath = ""; + private LLUUID newAssetID; + private LLUUID inventoryItemID; + private BaseHttpServer httpListener; + public AssetUploader(LLUUID assetID, LLUUID inventoryItem, string path, BaseHttpServer httpServer) + { + newAssetID = assetID; + inventoryItemID = inventoryItem; + uploaderPath = path; + httpListener = httpServer; + + } + + public string uploaderCaps(string request, string path, string param) + { + Encoding _enc = System.Text.Encoding.UTF8; + byte[] data = _enc.GetBytes(request); + //Console.WriteLine("recieved upload " + Util.FieldToString(data)); + LLUUID inv = this.inventoryItemID; + string res = ""; + res += ""; + res += "new_asset" + newAssetID.ToStringHyphenated() + ""; + res += "new_inventory_item" + inv.ToStringHyphenated() + ""; + res += "statecomplete"; + res += ""; + + // Console.WriteLine("asset " + newAssetID.ToStringHyphenated() + " , inventory item " + inv.ToStringHyphenated()); + httpListener.RemoveRestHandler("POST", "/CAPS/" + uploaderPath); + if (OnUpLoad != null) + { + OnUpLoad(newAssetID, inv, data); + } + + /*FileStream fs = File.Create("upload.jp2"); + BinaryWriter bw = new BinaryWriter(fs); + bw.Write(data); + bw.Close(); + fs.Close();*/ + return res; + } + } + } +} diff --git a/OpenSim/Region/Caps/LLSDHelpers.cs b/OpenSim/Region/Caps/LLSDHelpers.cs new file mode 100644 index 0000000..051520c --- /dev/null +++ b/OpenSim/Region/Caps/LLSDHelpers.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Xml; +using libsecondlife; + +namespace OpenSim.Framework +{ + public class LLSDHelpers + { + public static string SerialiseLLSDReply(object obj) + { + StringWriter sw = new StringWriter(); + XmlTextWriter writer = new XmlTextWriter(sw); + writer.Formatting = Formatting.None; + writer.WriteStartElement(String.Empty, "llsd", String.Empty); + LLSDHelpers.SerializeLLSDType(writer, obj); + writer.WriteEndElement(); + writer.Close(); + return sw.ToString(); + } + + public static void SerializeLLSDType(XmlTextWriter writer, object obj) + { + Type myType = obj.GetType(); + LLSDType[] llsdattributes = (LLSDType[])myType.GetCustomAttributes(typeof(LLSDType), false); + if (llsdattributes.Length > 0) + { + switch (llsdattributes[0].ObjectType) + { + case "MAP": + writer.WriteStartElement(String.Empty, "map", String.Empty); + System.Reflection.FieldInfo[] fields = myType.GetFields(); + for (int i = 0; i < fields.Length; i++) + { + object fieldValue = fields[i].GetValue(obj); + LLSDType[] fieldAttributes = (LLSDType[])fieldValue.GetType().GetCustomAttributes(typeof(LLSDType), false); + if (fieldAttributes.Length > 0) + { + writer.WriteStartElement(String.Empty, "key", String.Empty); + writer.WriteString(fields[i].Name); + writer.WriteEndElement(); + SerializeLLSDType(writer, fieldValue); + } + else + { + //Console.WriteLine("LLSD field name" + fields[i].Name + " , " + fields[i].GetValue(obj).GetType()); + writer.WriteStartElement(String.Empty, "key", String.Empty); + writer.WriteString(fields[i].Name); + writer.WriteEndElement(); + LLSD.LLSDWriteOne(writer, fieldValue); + } + } + writer.WriteEndElement(); + break; + case "ARRAY": + // LLSDArray arrayObject = obj as LLSDArray; + // ArrayList a = arrayObject.Array; + ArrayList a = (ArrayList)obj.GetType().GetField("Array").GetValue(obj); + writer.WriteStartElement(String.Empty, "array", String.Empty); + foreach (object item in a) + { + SerializeLLSDType(writer, item); + } + writer.WriteEndElement(); + break; + } + } + else + { + LLSD.LLSDWriteOne(writer, obj); + } + } + + public static object DeserialiseLLSDMap(Hashtable llsd, object obj) + { + Type myType = obj.GetType(); + LLSDType[] llsdattributes = (LLSDType[])myType.GetCustomAttributes(typeof(LLSDType), false); + if (llsdattributes.Length > 0) + { + switch (llsdattributes[0].ObjectType) + { + case "MAP": + IDictionaryEnumerator enumerator = llsd.GetEnumerator(); + while (enumerator.MoveNext()) + { + System.Reflection.FieldInfo field = myType.GetField((string)enumerator.Key); + if (field != null) + { + if (enumerator.Value is Hashtable) + { + object fieldValue = field.GetValue(obj); + DeserialiseLLSDMap((Hashtable) enumerator.Value, fieldValue); + } + else if (enumerator.Value is ArrayList) + { + object fieldValue = field.GetValue(obj); + fieldValue.GetType().GetField("Array").SetValue(fieldValue, enumerator.Value); + //TODO + // the LLSD map/array types in the array need to be deserialised + // but first we need to know the right class to deserialise them into. + } + else + { + field.SetValue(obj, enumerator.Value); + } + } + } + break; + } + } + return obj; + } + } + + [LLSDType("MAP")] + public class LLSDMapLayerResponse + { + public LLSDMapRequest AgentData = new LLSDMapRequest(); + public LLSDArray LayerData = new LLSDArray(); + + public LLSDMapLayerResponse() + { + + } + } + + [LLSDType("MAP")] + public class LLSDCapsDetails + { + public string MapLayer = ""; + public string NewFileAgentInventory = ""; + //public string EventQueueGet = ""; + + public LLSDCapsDetails() + { + + } + } + + [LLSDType("MAP")] + public class LLSDMapLayer + { + public int Left = 0; + public int Right = 0; + public int Top = 0; + public int Bottom = 0; + public LLUUID ImageID = LLUUID.Zero; + + public LLSDMapLayer() + { + + } + } + + [LLSDType("ARRAY")] + public class LLSDArray + { + public ArrayList Array = new ArrayList(); + + public LLSDArray() + { + + } + } + + [LLSDType("MAP")] + public class LLSDMapRequest + { + public int Flags = 0; + + public LLSDMapRequest() + { + + } + } + + [LLSDType("MAP")] + public class LLSDUploadReply + { + public string new_asset = ""; + public LLUUID new_inventory_item = LLUUID.Zero; + public string state = ""; + + public LLSDUploadReply() + { + + } + } + + [LLSDType("MAP")] + public class LLSDCapEvent + { + public int id = 0; + public LLSDArray events = new LLSDArray(); + + public LLSDCapEvent() + { + + } + } + + [LLSDType("MAP")] + public class LLSDEmpty + { + public LLSDEmpty() + { + + } + } + + [LLSDType("MAP")] + public class LLSDTest + { + public int Test1 = 20; + public int Test2 = 10; + + public LLSDTest() + { + + } + } + + + [AttributeUsage(AttributeTargets.Class)] + public class LLSDType : Attribute + { + private string myType; + + public LLSDType(string type) + { + myType = type; + + } + + public string ObjectType + { + get + { + return myType; + } + } + } +} diff --git a/OpenSim/Region/ClientStack/Assets/InventoryCache.cs b/OpenSim/Region/ClientStack/Assets/InventoryCache.cs new file mode 100644 index 0000000..5d5021c --- /dev/null +++ b/OpenSim/Region/ClientStack/Assets/InventoryCache.cs @@ -0,0 +1,337 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using libsecondlife; +using OpenSim; +using libsecondlife.Packets; +//using OpenSim.GridServers; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Types; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Assets +{ + /// + /// Description of InventoryManager. + /// + public class InventoryCache + { + private Dictionary _agentsInventory; + private List _serverRequests; //list of requests made to user server. + private System.Text.Encoding _enc = System.Text.Encoding.ASCII; + private const uint FULL_MASK_PERMISSIONS = 2147483647; + + public InventoryCache() + { + _agentsInventory = new Dictionary(); + _serverRequests = new List(); + } + + public void AddNewAgentsInventory(AgentInventory agentInventory) + { + if (!this._agentsInventory.ContainsKey(agentInventory.AgentID)) + { + this._agentsInventory.Add(agentInventory.AgentID, agentInventory); + } + } + + public AgentInventory FetchAgentsInventory(LLUUID agentID, IUserServer userserver) + { + AgentInventory res = null; + if (!this._agentsInventory.ContainsKey(agentID)) + { + res = userserver.RequestAgentsInventory(agentID); + this._agentsInventory.Add(agentID,res); + } + return res; + } + + public AgentInventory GetAgentsInventory(LLUUID agentID) + { + if (this._agentsInventory.ContainsKey(agentID)) + { + return this._agentsInventory[agentID]; + } + + return null; + } + + public void ClientLeaving(LLUUID clientID, IUserServer userserver) + { + if (this._agentsInventory.ContainsKey(clientID)) + { + if (userserver != null) + { + userserver.UpdateAgentsInventory(clientID, this._agentsInventory[clientID]); + } + this._agentsInventory.Remove(clientID); + } + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID) + { + return this.CreateNewInventoryFolder(remoteClient, folderID, 0); + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID, ushort type) + { + bool res = false; + if (folderID != LLUUID.Zero) //don't create a folder with a zero id + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].CreateNewFolder(folderID, type); + } + } + return res; + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID, ushort type, string folderName, LLUUID parent) + { + bool res = false; + if (folderID != LLUUID.Zero) //don't create a folder with a zero id + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].CreateNewFolder(folderID, type, folderName, parent); + } + } + return res; + } + + public LLUUID AddNewInventoryItem(ClientView remoteClient, LLUUID folderID, OpenSim.Framework.Types.AssetBase asset) + { + LLUUID newItem = null; + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + newItem = this._agentsInventory[remoteClient.AgentID].AddToInventory(folderID, asset); + if (newItem != null) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[newItem]; + this.SendItemUpdateCreate(remoteClient, Item); + } + } + + return newItem; + } + public bool DeleteInventoryItem(ClientView remoteClient, LLUUID itemID) + { + bool res = false; + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].DeleteFromInventory(itemID); + if (res) + { + RemoveInventoryItemPacket remove = new RemoveInventoryItemPacket(); + remove.AgentData.AgentID = remoteClient.AgentID; + remove.AgentData.SessionID = remoteClient.SessionID; + remove.InventoryData = new RemoveInventoryItemPacket.InventoryDataBlock[1]; + remove.InventoryData[0] = new RemoveInventoryItemPacket.InventoryDataBlock(); + remove.InventoryData[0].ItemID = itemID; + remoteClient.OutPacket(remove); + } + } + + return res; + } + + public bool UpdateInventoryItemAsset(ClientView remoteClient, LLUUID itemID, OpenSim.Framework.Types.AssetBase asset) + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + bool res = _agentsInventory[remoteClient.AgentID].UpdateItemAsset(itemID, asset); + if (res) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[itemID]; + this.SendItemUpdateCreate(remoteClient, Item); + } + return res; + } + + return false; + } + + public bool UpdateInventoryItemDetails(ClientView remoteClient, LLUUID itemID, UpdateInventoryItemPacket.InventoryDataBlock packet) + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + bool res = _agentsInventory[remoteClient.AgentID].UpdateItemDetails(itemID, packet); + if (res) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[itemID]; + this.SendItemUpdateCreate(remoteClient, Item); + } + return res; + } + + return false; + } + + public void FetchInventoryDescendents(ClientView userInfo, FetchInventoryDescendentsPacket FetchDescend) + { + if (this._agentsInventory.ContainsKey(userInfo.AgentID)) + { + AgentInventory agentInventory = this._agentsInventory[userInfo.AgentID]; + if (FetchDescend.InventoryData.FetchItems) + { + if (agentInventory.InventoryFolders.ContainsKey(FetchDescend.InventoryData.FolderID)) + { + InventoryFolder Folder = agentInventory.InventoryFolders[FetchDescend.InventoryData.FolderID]; + InventoryDescendentsPacket Descend = new InventoryDescendentsPacket(); + Descend.AgentData.AgentID = userInfo.AgentID; + Descend.AgentData.OwnerID = Folder.OwnerID; + Descend.AgentData.FolderID = FetchDescend.InventoryData.FolderID; + Descend.AgentData.Descendents = Folder.Items.Count; + Descend.AgentData.Version = Folder.Items.Count; + + + Descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[Folder.Items.Count]; + for (int i = 0; i < Folder.Items.Count; i++) + { + + InventoryItem Item = Folder.Items[i]; + Descend.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock(); + Descend.ItemData[i].ItemID = Item.ItemID; + Descend.ItemData[i].AssetID = Item.AssetID; + Descend.ItemData[i].CreatorID = Item.CreatorID; + Descend.ItemData[i].BaseMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].CreationDate = 1000; + Descend.ItemData[i].Description = _enc.GetBytes(Item.Description + "\0"); + Descend.ItemData[i].EveryoneMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].Flags = 1; + Descend.ItemData[i].FolderID = Item.FolderID; + Descend.ItemData[i].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + Descend.ItemData[i].GroupMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].InvType = Item.InvType; + Descend.ItemData[i].Name = _enc.GetBytes(Item.Name + "\0"); + Descend.ItemData[i].NextOwnerMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].OwnerID = Item.OwnerID; + Descend.ItemData[i].OwnerMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].SalePrice = 100; + Descend.ItemData[i].SaleType = 0; + Descend.ItemData[i].Type = Item.Type; + Descend.ItemData[i].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, Descend.ItemData[i].InvType, Descend.ItemData[i].Type, Descend.ItemData[i].AssetID, Descend.ItemData[i].GroupID, 100, Descend.ItemData[i].OwnerID, Descend.ItemData[i].CreatorID, Descend.ItemData[i].ItemID, Descend.ItemData[i].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + } + + userInfo.OutPacket(Descend); + + } + } + else + { + Console.WriteLine("fetch subfolders"); + } + } + } + + public void FetchInventory(ClientView userInfo, FetchInventoryPacket FetchItems) + { + if (this._agentsInventory.ContainsKey(userInfo.AgentID)) + { + AgentInventory agentInventory = this._agentsInventory[userInfo.AgentID]; + + for (int i = 0; i < FetchItems.InventoryData.Length; i++) + { + if (agentInventory.InventoryItems.ContainsKey(FetchItems.InventoryData[i].ItemID)) + { + InventoryItem Item = agentInventory.InventoryItems[FetchItems.InventoryData[i].ItemID]; + FetchInventoryReplyPacket InventoryReply = new FetchInventoryReplyPacket(); + InventoryReply.AgentData.AgentID = userInfo.AgentID; + InventoryReply.InventoryData = new FetchInventoryReplyPacket.InventoryDataBlock[1]; + InventoryReply.InventoryData[0] = new FetchInventoryReplyPacket.InventoryDataBlock(); + InventoryReply.InventoryData[0].ItemID = Item.ItemID; + InventoryReply.InventoryData[0].AssetID = Item.AssetID; + InventoryReply.InventoryData[0].CreatorID = Item.CreatorID; + InventoryReply.InventoryData[0].BaseMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].CreationDate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + InventoryReply.InventoryData[0].Description = _enc.GetBytes(Item.Description + "\0"); + InventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].Flags = 0; + InventoryReply.InventoryData[0].FolderID = Item.FolderID; + InventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + InventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].InvType = Item.InvType; + InventoryReply.InventoryData[0].Name = _enc.GetBytes(Item.Name + "\0"); + InventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].OwnerID = Item.OwnerID; + InventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].SalePrice = 100; + InventoryReply.InventoryData[0].SaleType = 0; + InventoryReply.InventoryData[0].Type = Item.Type; + InventoryReply.InventoryData[0].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, InventoryReply.InventoryData[0].InvType, InventoryReply.InventoryData[0].Type, InventoryReply.InventoryData[0].AssetID, InventoryReply.InventoryData[0].GroupID, 100, InventoryReply.InventoryData[0].OwnerID, InventoryReply.InventoryData[0].CreatorID, InventoryReply.InventoryData[0].ItemID, InventoryReply.InventoryData[0].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + userInfo.OutPacket(InventoryReply); + } + } + } + } + + private void SendItemUpdateCreate(ClientView remoteClient, InventoryItem Item) + { + + UpdateCreateInventoryItemPacket InventoryReply = new UpdateCreateInventoryItemPacket(); + InventoryReply.AgentData.AgentID = remoteClient.AgentID; + InventoryReply.AgentData.SimApproved = true; + InventoryReply.InventoryData = new UpdateCreateInventoryItemPacket.InventoryDataBlock[1]; + InventoryReply.InventoryData[0] = new UpdateCreateInventoryItemPacket.InventoryDataBlock(); + InventoryReply.InventoryData[0].ItemID = Item.ItemID; + InventoryReply.InventoryData[0].AssetID = Item.AssetID; + InventoryReply.InventoryData[0].CreatorID = Item.CreatorID; + InventoryReply.InventoryData[0].BaseMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].CreationDate = 1000; + InventoryReply.InventoryData[0].Description = _enc.GetBytes(Item.Description + "\0"); + InventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].Flags = 0; + InventoryReply.InventoryData[0].FolderID = Item.FolderID; + InventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + InventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].InvType = Item.InvType; + InventoryReply.InventoryData[0].Name = _enc.GetBytes(Item.Name + "\0"); + InventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].OwnerID = Item.OwnerID; + InventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].SalePrice = 100; + InventoryReply.InventoryData[0].SaleType = 0; + InventoryReply.InventoryData[0].Type = Item.Type; + InventoryReply.InventoryData[0].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, InventoryReply.InventoryData[0].InvType, InventoryReply.InventoryData[0].Type, InventoryReply.InventoryData[0].AssetID, InventoryReply.InventoryData[0].GroupID, 100, InventoryReply.InventoryData[0].OwnerID, InventoryReply.InventoryData[0].CreatorID, InventoryReply.InventoryData[0].ItemID, InventoryReply.InventoryData[0].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + + remoteClient.OutPacket(InventoryReply); + } + } + + + + public class UserServerRequest + { + public UserServerRequest() + { + + } + } +} diff --git a/OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs b/OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs new file mode 100644 index 0000000..7552195 --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs @@ -0,0 +1,46 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Net.Sockets; +using libsecondlife; + + +namespace OpenSim +{ + + public interface ClientStackNetworkHandler + { + void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode);// EndPoint packetSender); + void RemoveClientCircuit(uint circuitcode); + void RegisterPacketServer(PacketServer server); + } + +} diff --git a/OpenSim/Region/ClientStack/ClientView.API.cs b/OpenSim/Region/ClientStack/ClientView.API.cs new file mode 100644 index 0000000..902f3c7 --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientView.API.cs @@ -0,0 +1,975 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Types; + +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim +{ + partial class ClientView + { + public event ChatFromViewer OnChatFromViewer; + public event RezObject OnRezObject; + public event GenericCall4 OnDeRezObject; + public event ModifyTerrain OnModifyTerrain; + public event GenericCall OnRegionHandShakeReply; + public event GenericCall OnRequestWearables; + public event SetAppearance OnSetAppearance; + public event GenericCall2 OnCompleteMovementToRegion; + public event UpdateAgent OnAgentUpdate; + public event StartAnim OnStartAnim; + public event GenericCall OnRequestAvatarsData; + public event LinkObjects OnLinkObjects; + public event UpdateVector OnGrapObject; + public event ObjectSelect OnDeGrapObject; + public event MoveObject OnGrapUpdate; + public event GenericCall4 OnAddPrim; + public event UpdateShape OnUpdatePrimShape; + public event ObjectSelect OnObjectSelect; + public event UpdatePrimFlags OnUpdatePrimFlags; + public event UpdatePrimTexture OnUpdatePrimTexture; + public event UpdateVector OnUpdatePrimPosition; + public event UpdatePrimRotation OnUpdatePrimRotation; + public event UpdateVector OnUpdatePrimScale; + public event StatusChange OnChildAgentStatus; + public event GenericCall2 OnStopMovement; + public event NewAvatar OnNewAvatar; + public event GenericCall6 OnRemoveAvatar; + public event RequestMapBlocks OnRequestMapBlocks; + public event TeleportLocationRequest OnTeleportLocationRequest; + + public event ParcelPropertiesRequest OnParcelPropertiesRequest; + public event ParcelDivideRequest OnParcelDivideRequest; + public event ParcelJoinRequest OnParcelJoinRequest; + public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + + public event EstateOwnerMessageRequest OnEstateOwnerMessage; + + /// + /// + /// + public LLVector3 StartPos + { + get + { + return startpos; + } + set + { + startpos = value; + } + } + + /// + /// + /// + public LLUUID AgentId + { + get + { + return this.AgentID; + } + } + + /// + /// + /// + public string FirstName + { + get + { + return this.firstName; + } + + } + + /// + /// + /// + public string LastName + { + get + { + return this.lastName; + } + } + + #region World/Avatar to Client + + /// + /// + /// + /// + public void SendRegionHandshake(RegionInfo regionInfo) + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + RegionHandshakePacket handshake = new RegionHandshakePacket(); + + handshake.RegionInfo.BillableFactor = regionInfo.estateSettings.billableFactor; + handshake.RegionInfo.IsEstateManager = false; + handshake.RegionInfo.TerrainHeightRange00 = regionInfo.estateSettings.terrainHeightRange0; + handshake.RegionInfo.TerrainHeightRange01 = regionInfo.estateSettings.terrainHeightRange1; + handshake.RegionInfo.TerrainHeightRange10 = regionInfo.estateSettings.terrainHeightRange2; + handshake.RegionInfo.TerrainHeightRange11 = regionInfo.estateSettings.terrainHeightRange3; + handshake.RegionInfo.TerrainStartHeight00 = regionInfo.estateSettings.terrainStartHeight0; + handshake.RegionInfo.TerrainStartHeight01 = regionInfo.estateSettings.terrainStartHeight1; + handshake.RegionInfo.TerrainStartHeight10 = regionInfo.estateSettings.terrainStartHeight2; + handshake.RegionInfo.TerrainStartHeight11 = regionInfo.estateSettings.terrainStartHeight3; + handshake.RegionInfo.SimAccess = (byte)regionInfo.estateSettings.simAccess; + handshake.RegionInfo.WaterHeight = regionInfo.estateSettings.waterHeight; + + + handshake.RegionInfo.RegionFlags = (uint)regionInfo.estateSettings.regionFlags; + + handshake.RegionInfo.SimName = _enc.GetBytes(regionInfo.RegionName + "\0"); + handshake.RegionInfo.SimOwner = regionInfo.MasterAvatarAssignedUUID; + handshake.RegionInfo.TerrainBase0 = regionInfo.estateSettings.terrainBase0; + handshake.RegionInfo.TerrainBase1 = regionInfo.estateSettings.terrainBase1; + handshake.RegionInfo.TerrainBase2 = regionInfo.estateSettings.terrainBase2; + handshake.RegionInfo.TerrainBase3 = regionInfo.estateSettings.terrainBase3; + handshake.RegionInfo.TerrainDetail0 = regionInfo.estateSettings.terrainDetail0; + handshake.RegionInfo.TerrainDetail1 = regionInfo.estateSettings.terrainDetail1; + handshake.RegionInfo.TerrainDetail2 = regionInfo.estateSettings.terrainDetail2; + handshake.RegionInfo.TerrainDetail3 = regionInfo.estateSettings.terrainDetail3; + handshake.RegionInfo.CacheID = LLUUID.Random(); //I guess this is for the client to remember an old setting? + + this.OutPacket(handshake); + } + + /// + /// + /// + /// + public void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look) + { + AgentMovementCompletePacket mov = new AgentMovementCompletePacket(); + mov.AgentData.SessionID = this.SessionID; + mov.AgentData.AgentID = this.AgentID; + mov.Data.RegionHandle = regInfo.RegionHandle; + mov.Data.Timestamp = 1172750370; // TODO - dynamicalise this + + if ((pos.X == 0) && (pos.Y == 0) && (pos.Z == 0)) + { + mov.Data.Position = this.startpos; + } + else + { + mov.Data.Position = pos; + } + mov.Data.LookAt = look; + + OutPacket(mov); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + SendChatMessage(Helpers.StringToField(message), type, fromPos, fromName, fromAgentID); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + System.Text.Encoding enc = System.Text.Encoding.ASCII; + libsecondlife.Packets.ChatFromSimulatorPacket reply = new ChatFromSimulatorPacket(); + reply.ChatData.Audible = 1; + reply.ChatData.Message = message; + reply.ChatData.ChatType = type; + reply.ChatData.SourceType = 1; + reply.ChatData.Position = fromPos; + reply.ChatData.FromName = enc.GetBytes(fromName + "\0"); + reply.ChatData.OwnerID = fromAgentID; + reply.ChatData.SourceID = fromAgentID; + + this.OutPacket(reply); + } + + + /// + /// Send the region heightmap to the client + /// + /// heightmap + public virtual void SendLayerData(float[] map) + { + try + { + int[] patches = new int[4]; + + for (int y = 0; y < 16; y++) + { + for (int x = 0; x < 16; x = x + 4) + { + patches[0] = x + 0 + y * 16; + patches[1] = x + 1 + y * 16; + patches[2] = x + 2 + y * 16; + patches[3] = x + 3 + y * 16; + + Packet layerpack = TerrainManager.CreateLandPacket(map, patches); + OutPacket(layerpack); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("ClientView API.cs: SendLayerData() - Failed with exception " + e.ToString()); + } + } + + /// + /// Sends a specified patch to a client + /// + /// Patch coordinate (x) 0..16 + /// Patch coordinate (y) 0..16 + /// heightmap + public void SendLayerData(int px, int py, float[] map) + { + try + { + int[] patches = new int[1]; + int patchx, patchy; + patchx = px / 16; + patchy = py / 16; + + patches[0] = patchx + 0 + patchy * 16; + + Packet layerpack = TerrainManager.CreateLandPacket(map, patches); + OutPacket(layerpack); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("ClientView API .cs: SendLayerData() - Failed with exception " + e.ToString()); + } + } + + /// + /// + /// + /// + /// + /// + public void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPAddress neighbourIP, ushort neighbourPort) + { + EnableSimulatorPacket enablesimpacket = new EnableSimulatorPacket(); + enablesimpacket.SimulatorInfo = new EnableSimulatorPacket.SimulatorInfoBlock(); + enablesimpacket.SimulatorInfo.Handle = neighbourHandle; + + byte[] byteIP = neighbourIP.GetAddressBytes(); + enablesimpacket.SimulatorInfo.IP = (uint)byteIP[3] << 24; + enablesimpacket.SimulatorInfo.IP += (uint)byteIP[2] << 16; + enablesimpacket.SimulatorInfo.IP += (uint)byteIP[1] << 8; + enablesimpacket.SimulatorInfo.IP += (uint)byteIP[0]; + enablesimpacket.SimulatorInfo.Port = neighbourPort; + OutPacket(enablesimpacket); + } + + /// + /// + /// + /// + public AgentCircuitData RequestClientInfo() + { + AgentCircuitData agentData = new AgentCircuitData(); + agentData.AgentID = this.AgentId; + agentData.SessionID = this.SessionID; + agentData.SecureSessionID = this.SecureSessionID; + agentData.circuitcode = this.CircuitCode; + agentData.child = false; + agentData.firstname = this.firstName; + agentData.lastname = this.lastName; + + return agentData; + } + + public void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, System.Net.IPAddress newRegionIP, ushort newRegionPort) + { + LLVector3 look = new LLVector3(lookAt.X * 10, lookAt.Y * 10, lookAt.Z * 10); + + CrossedRegionPacket newSimPack = new CrossedRegionPacket(); + newSimPack.AgentData = new CrossedRegionPacket.AgentDataBlock(); + newSimPack.AgentData.AgentID = this.AgentID; + newSimPack.AgentData.SessionID = this.SessionID; + newSimPack.Info = new CrossedRegionPacket.InfoBlock(); + newSimPack.Info.Position = pos; + newSimPack.Info.LookAt = look; // new LLVector3(0.0f, 0.0f, 0.0f); // copied from Avatar.cs - SHOULD BE DYNAMIC!!!!!!!!!! + newSimPack.RegionData = new libsecondlife.Packets.CrossedRegionPacket.RegionDataBlock(); + newSimPack.RegionData.RegionHandle = newRegionHandle; + byte[] byteIP = newRegionIP.GetAddressBytes(); + newSimPack.RegionData.SimIP = (uint)byteIP[3] << 24; + newSimPack.RegionData.SimIP += (uint)byteIP[2] << 16; + newSimPack.RegionData.SimIP += (uint)byteIP[1] << 8; + newSimPack.RegionData.SimIP += (uint)byteIP[0]; + newSimPack.RegionData.SimPort = newRegionPort; + newSimPack.RegionData.SeedCapability = new byte[0]; + + this.OutPacket(newSimPack); + //this.DowngradeClient(); + } + + public void SendMapBlock(List mapBlocks) + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + + MapBlockReplyPacket mapReply = new MapBlockReplyPacket(); + mapReply.AgentData.AgentID = this.AgentID; + mapReply.Data = new MapBlockReplyPacket.DataBlock[mapBlocks.Count]; + mapReply.AgentData.Flags = 0; + + for (int i = 0; i < mapBlocks.Count; i++) + { + mapReply.Data[i] = new MapBlockReplyPacket.DataBlock(); + mapReply.Data[i].MapImageID = mapBlocks[i].MapImageId; + mapReply.Data[i].X = mapBlocks[i].X; + mapReply.Data[i].Y = mapBlocks[i].Y; + mapReply.Data[i].WaterHeight = mapBlocks[i].WaterHeight; + mapReply.Data[i].Name = _enc.GetBytes(mapBlocks[i].Name); + mapReply.Data[i].RegionFlags = mapBlocks[i].RegionFlags; + mapReply.Data[i].Access = mapBlocks[i].Access; + mapReply.Data[i].Agents = mapBlocks[i].Agents; + } + this.OutPacket(mapReply); + } + + public void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags) + { + TeleportLocalPacket tpLocal = new TeleportLocalPacket(); + tpLocal.Info.AgentID = this.AgentID; + tpLocal.Info.TeleportFlags = flags; + tpLocal.Info.LocationID = 2; + tpLocal.Info.LookAt = lookAt; + tpLocal.Info.Position = position; + OutPacket(tpLocal); + } + + public void SendRegionTeleport(ulong regionHandle, byte simAccess, string ipAddress, ushort ipPort, uint locationID, uint flags) + { + TeleportFinishPacket teleport = new TeleportFinishPacket(); + teleport.Info.AgentID = this.AgentID; + teleport.Info.RegionHandle = regionHandle; + teleport.Info.SimAccess = simAccess; + teleport.Info.SeedCapability = new byte[0]; + + System.Net.IPAddress oIP = System.Net.IPAddress.Parse(ipAddress); + byte[] byteIP = oIP.GetAddressBytes(); + uint ip = (uint)byteIP[3] << 24; + ip += (uint)byteIP[2] << 16; + ip += (uint)byteIP[1] << 8; + ip += (uint)byteIP[0]; + + teleport.Info.SimIP = ip; + teleport.Info.SimPort = ipPort; + teleport.Info.LocationID = 4; + teleport.Info.TeleportFlags = 1 << 4; + OutPacket(teleport); + } + + /// + /// + /// + public void SendTeleportCancel() + { + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.SessionID = this.SessionID; + tpCancel.Info.AgentID = this.AgentID; + + OutPacket(tpCancel); + } + + /// + /// + /// + public void SendTeleportLocationStart() + { + TeleportStartPacket tpStart = new TeleportStartPacket(); + tpStart.Info.TeleportFlags = 16; // Teleport via location + OutPacket(tpStart); + } + + public void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance) + { + MoneyBalanceReplyPacket money = new MoneyBalanceReplyPacket(); + money.MoneyData.AgentID = this.AgentID; + money.MoneyData.TransactionID = transaction; + money.MoneyData.TransactionSuccess = success; + money.MoneyData.Description = description; + money.MoneyData.MoneyBalance = balance; + OutPacket(money); + } + + #region Appearance/ Wearables Methods + + /// + /// + /// + /// + public void SendWearables(AvatarWearable[] wearables) + { + AgentWearablesUpdatePacket aw = new AgentWearablesUpdatePacket(); + aw.AgentData.AgentID = this.AgentID; + aw.AgentData.SerialNum = 0; + aw.AgentData.SessionID = this.SessionID; + + aw.WearableData = new AgentWearablesUpdatePacket.WearableDataBlock[13]; + AgentWearablesUpdatePacket.WearableDataBlock awb; + for (int i = 0; i < wearables.Length; i++) + { + awb = new AgentWearablesUpdatePacket.WearableDataBlock(); + awb.WearableType = (byte)i; + awb.AssetID = wearables[i].AssetID; + awb.ItemID = wearables[i].ItemID; + aw.WearableData[i] = awb; + } + + this.OutPacket(aw); + } + + /// + /// + /// + /// + /// + /// + public void SendAppearance(LLUUID agentID, byte[] visualParams, byte[] textureEntry) + { + AvatarAppearancePacket avp = new AvatarAppearancePacket(); + avp.VisualParam = new AvatarAppearancePacket.VisualParamBlock[218]; + avp.ObjectData.TextureEntry = textureEntry; + + AvatarAppearancePacket.VisualParamBlock avblock = null; + for (int i = 0; i < visualParams.Length; i++) + { + avblock = new AvatarAppearancePacket.VisualParamBlock(); + avblock.ParamValue = visualParams[i]; + avp.VisualParam[i] = avblock; + } + + avp.Sender.IsTrial = false; + avp.Sender.ID = agentID; + OutPacket(avp); + } + + #endregion + + #region Avatar Packet/data sending Methods + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry) + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + //send a objectupdate packet with information about the clients avatar + + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = regionHandle; + objupdate.RegionData.TimeDilation = 64096; + objupdate.ObjectData = new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock[1]; + objupdate.ObjectData[0] = this.CreateDefaultAvatarPacket(textureEntry); + //give this avatar object a local id and assign the user a name + + objupdate.ObjectData[0].ID = avatarLocalID; + objupdate.ObjectData[0].FullID = avatarID; + objupdate.ObjectData[0].NameValue = _enc.GetBytes("FirstName STRING RW SV " + firstName + "\nLastName STRING RW SV " + lastName + " \0"); + libsecondlife.LLVector3 pos2 = new LLVector3((float)Pos.X, (float)Pos.Y, (float)Pos.Z); + byte[] pb = pos2.GetBytes(); + Array.Copy(pb, 0, objupdate.ObjectData[0].ObjectData, 16, pb.Length); + + OutPacket(objupdate); + + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity) + { + ImprovedTerseObjectUpdatePacket.ObjectDataBlock terseBlock = this.CreateAvatarImprovedBlock(localID, position, velocity); + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = regionHandle; + terse.RegionData.TimeDilation = timeDilation; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = terseBlock; + + this.OutPacket(terse); + } + + #endregion + + #region Primitive Packet/data Sending Methods + + /// + /// + /// + /// + /// + /// + public void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint) + { + ObjectAttachPacket attach = new ObjectAttachPacket(); + attach.AgentData.AgentID = this.AgentID; + attach.AgentData.SessionID = this.SessionID; + attach.AgentData.AttachmentPoint = attachPoint; + attach.ObjectData = new ObjectAttachPacket.ObjectDataBlock[1]; + attach.ObjectData[0] = new ObjectAttachPacket.ObjectDataBlock(); + attach.ObjectData[0].ObjectLocalID = localID; + attach.ObjectData[0].Rotation = rotation; + + this.OutPacket(attach); + } + + /// + /// Sends a full ObjectUpdatePacket to a client to inform it of a new primitive + /// or big changes to a existing primitive. + /// + /// + /// + /// + /// + /// + /// + /// + public void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID, uint flags) + { + ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); + outPacket.RegionData.RegionHandle = regionHandle; + outPacket.RegionData.TimeDilation = timeDilation; + outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; + outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primData, textureID, flags); + outPacket.ObjectData[0].ID = localID; + outPacket.ObjectData[0].FullID = primData.FullID; + byte[] pb = pos.GetBytes(); + Array.Copy(pb, 0, outPacket.ObjectData[0].ObjectData, 0, pb.Length); + byte[] rot = rotation.GetBytes(); + Array.Copy(rot, 0, outPacket.ObjectData[0].ObjectData, 48, rot.Length); + OutPacket(outPacket); + } + + /// + /// Sends a full ObjectUpdatePacket to a client to inform it of a new primitive + /// or big changes to a existing primitive. + /// Uses default rotation + /// + /// + /// + public void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID , uint flags) + { + ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); + outPacket.RegionData.RegionHandle = regionHandle; + outPacket.RegionData.TimeDilation = timeDilation; + outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; + outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primData, textureID, flags); + outPacket.ObjectData[0].ID = localID; + outPacket.ObjectData[0].FullID = primData.FullID; + byte[] pb = pos.GetBytes(); + Array.Copy(pb, 0, outPacket.ObjectData[0].ObjectData, 0, pb.Length); + + OutPacket(outPacket); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation) + { + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = regionHandle; + terse.RegionData.TimeDilation = timeDilation; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = this.CreatePrimImprovedBlock(localID, position, rotation); + + this.OutPacket(terse); + } + + #endregion + + #endregion + + #region Helper Methods + + protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateAvatarImprovedBlock(uint localID, LLVector3 pos, LLVector3 velocity) + { + byte[] bytes = new byte[60]; + int i = 0; + ImprovedTerseObjectUpdatePacket.ObjectDataBlock dat = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock(); + + dat.TextureEntry = new byte[0];// AvatarTemplate.TextureEntry; + + uint ID = localID; + + bytes[i++] = (byte)(ID % 256); + bytes[i++] = (byte)((ID >> 8) % 256); + bytes[i++] = (byte)((ID >> 16) % 256); + bytes[i++] = (byte)((ID >> 24) % 256); + bytes[i++] = 0; + bytes[i++] = 1; + i += 14; + bytes[i++] = 128; + bytes[i++] = 63; + + byte[] pb = pos.GetBytes(); + Array.Copy(pb, 0, bytes, i, pb.Length); + i += 12; + ushort InternVelocityX; + ushort InternVelocityY; + ushort InternVelocityZ; + Axiom.MathLib.Vector3 internDirec = new Axiom.MathLib.Vector3(0, 0, 0); + + internDirec = new Axiom.MathLib.Vector3(velocity.X, velocity.Y, velocity.Z); + + internDirec = internDirec / 128.0f; + internDirec.x += 1; + internDirec.y += 1; + internDirec.z += 1; + + InternVelocityX = (ushort)(32768 * internDirec.x); + InternVelocityY = (ushort)(32768 * internDirec.y); + InternVelocityZ = (ushort)(32768 * internDirec.z); + + ushort ac = 32767; + bytes[i++] = (byte)(InternVelocityX % 256); + bytes[i++] = (byte)((InternVelocityX >> 8) % 256); + bytes[i++] = (byte)(InternVelocityY % 256); + bytes[i++] = (byte)((InternVelocityY >> 8) % 256); + bytes[i++] = (byte)(InternVelocityZ % 256); + bytes[i++] = (byte)((InternVelocityZ >> 8) % 256); + + //accel + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + //rot + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + //rotation vel + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + dat.Data = bytes; + return (dat); + } + + /// + /// + /// + /// + /// + /// + /// + protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreatePrimImprovedBlock(uint localID, LLVector3 position, LLQuaternion rotation) + { + uint ID = localID; + byte[] bytes = new byte[60]; + + int i = 0; + ImprovedTerseObjectUpdatePacket.ObjectDataBlock dat = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock(); + dat.TextureEntry = new byte[0]; + bytes[i++] = (byte)(ID % 256); + bytes[i++] = (byte)((ID >> 8) % 256); + bytes[i++] = (byte)((ID >> 16) % 256); + bytes[i++] = (byte)((ID >> 24) % 256); + bytes[i++] = 0; + bytes[i++] = 0; + + byte[] pb = position.GetBytes(); + Array.Copy(pb, 0, bytes, i, pb.Length); + i += 12; + ushort ac = 32767; + + //vel + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + //accel + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + ushort rw, rx, ry, rz; + rw = (ushort)(32768 * (rotation.W + 1)); + rx = (ushort)(32768 * (rotation.X + 1)); + ry = (ushort)(32768 * (rotation.Y + 1)); + rz = (ushort)(32768 * (rotation.Z + 1)); + + //rot + bytes[i++] = (byte)(rx % 256); + bytes[i++] = (byte)((rx >> 8) % 256); + bytes[i++] = (byte)(ry % 256); + bytes[i++] = (byte)((ry >> 8) % 256); + bytes[i++] = (byte)(rz % 256); + bytes[i++] = (byte)((rz >> 8) % 256); + bytes[i++] = (byte)(rw % 256); + bytes[i++] = (byte)((rw >> 8) % 256); + + //rotation vel + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + bytes[i++] = (byte)(ac % 256); + bytes[i++] = (byte)((ac >> 8) % 256); + + dat.Data = bytes; + return dat; + } + + + /// + /// Create the ObjectDataBlock for a ObjectUpdatePacket (for a Primitive) + /// + /// + /// + protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(PrimData primData, LLUUID textureID, uint flags) + { + ObjectUpdatePacket.ObjectDataBlock objupdate = new ObjectUpdatePacket.ObjectDataBlock(); + this.SetDefaultPrimPacketValues(objupdate); + objupdate.UpdateFlags = flags; + this.SetPrimPacketShapeData(objupdate, primData, textureID); + + return objupdate; + } + + /// + /// Copy the data from a PrimData object to a ObjectUpdatePacket + /// + /// + /// + protected void SetPrimPacketShapeData(ObjectUpdatePacket.ObjectDataBlock objectData, PrimData primData, LLUUID textureID) + { + LLObject.TextureEntry ntex = new LLObject.TextureEntry(textureID); + objectData.TextureEntry = ntex.ToBytes(); + objectData.OwnerID = primData.OwnerID; + objectData.PCode = primData.PCode; + objectData.PathBegin = primData.PathBegin; + objectData.PathEnd = primData.PathEnd; + objectData.PathScaleX = primData.PathScaleX; + objectData.PathScaleY = primData.PathScaleY; + objectData.PathShearX = primData.PathShearX; + objectData.PathShearY = primData.PathShearY; + objectData.PathSkew = primData.PathSkew; + objectData.ProfileBegin = primData.ProfileBegin; + objectData.ProfileEnd = primData.ProfileEnd; + objectData.Scale = primData.Scale; + objectData.PathCurve = primData.PathCurve; + objectData.ProfileCurve = primData.ProfileCurve; + objectData.ParentID = primData.ParentID; + objectData.ProfileHollow = primData.ProfileHollow; + objectData.PathRadiusOffset = primData.PathRadiusOffset; + objectData.PathRevolutions = primData.PathRevolutions; + objectData.PathTaperX = primData.PathTaperX; + objectData.PathTaperY = primData.PathTaperY; + objectData.PathTwist = primData.PathTwist; + objectData.PathTwistBegin = primData.PathTwistBegin; + } + + /// + /// Set some default values in a ObjectUpdatePacket + /// + /// + protected void SetDefaultPrimPacketValues(ObjectUpdatePacket.ObjectDataBlock objdata) + { + objdata.PSBlock = new byte[0]; + objdata.ExtraParams = new byte[1]; + objdata.MediaURL = new byte[0]; + objdata.NameValue = new byte[0]; + objdata.Text = new byte[0]; + objdata.TextColor = new byte[4]; + objdata.JointAxisOrAnchor = new LLVector3(0, 0, 0); + objdata.JointPivot = new LLVector3(0, 0, 0); + objdata.Material = 3; + objdata.TextureAnim = new byte[0]; + objdata.Sound = LLUUID.Zero; + objdata.State = 0; + objdata.Data = new byte[0]; + + objdata.ObjectData = new byte[60]; + objdata.ObjectData[46] = 128; + objdata.ObjectData[47] = 63; + } + + + /// + /// + /// + /// + protected ObjectUpdatePacket.ObjectDataBlock CreateDefaultAvatarPacket(byte[] textureEntry) + { + libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock objdata = new ObjectUpdatePacket.ObjectDataBlock(); // new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock(data1, ref i); + + SetDefaultAvatarPacketValues(ref objdata); + objdata.UpdateFlags = 61 + (9 << 8) + (130 << 16) + (16 << 24); + objdata.PathCurve = 16; + objdata.ProfileCurve = 1; + objdata.PathScaleX = 100; + objdata.PathScaleY = 100; + objdata.ParentID = 0; + objdata.OwnerID = LLUUID.Zero; + objdata.Scale = new LLVector3(1, 1, 1); + objdata.PCode = 47; + if (textureEntry != null) + { + objdata.TextureEntry = textureEntry; + } + System.Text.Encoding enc = System.Text.Encoding.ASCII; + libsecondlife.LLVector3 pos = new LLVector3(objdata.ObjectData, 16); + pos.X = 100f; + objdata.ID = 8880000; + objdata.NameValue = enc.GetBytes("FirstName STRING RW SV Test \nLastName STRING RW SV User \0"); + libsecondlife.LLVector3 pos2 = new LLVector3(100f, 100f, 23f); + //objdata.FullID=user.AgentID; + byte[] pb = pos.GetBytes(); + Array.Copy(pb, 0, objdata.ObjectData, 16, pb.Length); + + return objdata; + } + + /// + /// + /// + /// + protected void SetDefaultAvatarPacketValues(ref ObjectUpdatePacket.ObjectDataBlock objdata) + { + objdata.PSBlock = new byte[0]; + objdata.ExtraParams = new byte[1]; + objdata.MediaURL = new byte[0]; + objdata.NameValue = new byte[0]; + objdata.Text = new byte[0]; + objdata.TextColor = new byte[4]; + objdata.JointAxisOrAnchor = new LLVector3(0, 0, 0); + objdata.JointPivot = new LLVector3(0, 0, 0); + objdata.Material = 4; + objdata.TextureAnim = new byte[0]; + objdata.Sound = LLUUID.Zero; + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + objdata.TextureEntry = ntex.ToBytes(); + objdata.State = 0; + objdata.Data = new byte[0]; + + objdata.ObjectData = new byte[76]; + objdata.ObjectData[15] = 128; + objdata.ObjectData[16] = 63; + objdata.ObjectData[56] = 128; + objdata.ObjectData[61] = 102; + objdata.ObjectData[62] = 40; + objdata.ObjectData[63] = 61; + objdata.ObjectData[64] = 189; + } + + /// + /// + /// + /// + /// + protected PrimData CreatePrimFromObjectAdd(ObjectAddPacket addPacket) + { + PrimData PData = new PrimData(); + PData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + PData.PCode = addPacket.ObjectData.PCode; + PData.PathBegin = addPacket.ObjectData.PathBegin; + PData.PathEnd = addPacket.ObjectData.PathEnd; + PData.PathScaleX = addPacket.ObjectData.PathScaleX; + PData.PathScaleY = addPacket.ObjectData.PathScaleY; + PData.PathShearX = addPacket.ObjectData.PathShearX; + PData.PathShearY = addPacket.ObjectData.PathShearY; + PData.PathSkew = addPacket.ObjectData.PathSkew; + PData.ProfileBegin = addPacket.ObjectData.ProfileBegin; + PData.ProfileEnd = addPacket.ObjectData.ProfileEnd; + PData.Scale = addPacket.ObjectData.Scale; + PData.PathCurve = addPacket.ObjectData.PathCurve; + PData.ProfileCurve = addPacket.ObjectData.ProfileCurve; + PData.ParentID = 0; + PData.ProfileHollow = addPacket.ObjectData.ProfileHollow; + PData.PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; + PData.PathRevolutions = addPacket.ObjectData.PathRevolutions; + PData.PathTaperX = addPacket.ObjectData.PathTaperX; + PData.PathTaperY = addPacket.ObjectData.PathTaperY; + PData.PathTwist = addPacket.ObjectData.PathTwist; + PData.PathTwistBegin = addPacket.ObjectData.PathTwistBegin; + + return PData; + } + #endregion + + } +} diff --git a/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs b/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs new file mode 100644 index 0000000..914c38a --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs @@ -0,0 +1,358 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Assets; +using OpenSim.Framework.Types; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using OpenSim.Caches; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim +{ + partial class ClientView + { + public class AgentAssetUpload + { + private Dictionary transactions = new Dictionary(); + private ClientView ourClient; + private AssetCache m_assetCache; + private InventoryCache m_inventoryCache; + + public AgentAssetUpload(ClientView client, AssetCache assetCache, InventoryCache inventoryCache) + { + this.ourClient = client; + m_assetCache = assetCache; + m_inventoryCache = inventoryCache; + } + + public void AddUpload(LLUUID transactionID, AssetBase asset) + { + AssetTransaction upload = new AssetTransaction(); + lock (this.transactions) + { + upload.Asset = asset; + upload.TransactionID = transactionID; + this.transactions.Add(transactionID, upload); + } + if (upload.Asset.Data.Length > 2) + { + //is complete + upload.UploadComplete = true; + AssetUploadCompletePacket response = new AssetUploadCompletePacket(); + response.AssetBlock.Type = asset.Type; + response.AssetBlock.Success = true; + response.AssetBlock.UUID = transactionID.Combine(this.ourClient.SecureSessionID); + this.ourClient.OutPacket(response); + m_assetCache.AddAsset(asset); + } + else + { + upload.UploadComplete = false; + upload.XferID = Util.GetNextXferID(); + RequestXferPacket xfer = new RequestXferPacket(); + xfer.XferID.ID = upload.XferID; + xfer.XferID.VFileType = upload.Asset.Type; + xfer.XferID.VFileID = transactionID.Combine(this.ourClient.SecureSessionID); + xfer.XferID.FilePath = 0; + xfer.XferID.Filename = new byte[0]; + this.ourClient.OutPacket(xfer); + } + + } + + public AssetBase GetUpload(LLUUID transactionID) + { + if (this.transactions.ContainsKey(transactionID)) + { + return this.transactions[transactionID].Asset; + } + + return null; + } + + public void HandleUploadPacket(AssetUploadRequestPacket pack, LLUUID assetID) + { + // Console.Write("asset upload request , type = " + pack.AssetBlock.Type.ToString()); + AssetBase asset = null; + if (pack.AssetBlock.Type == 0) + { + + //first packet for transaction + asset = new AssetBase(); + asset.FullID = assetID; + asset.Type = pack.AssetBlock.Type; + asset.InvType = asset.Type; + asset.Name = "UploadedTexture" + Util.RandomClass.Next(1, 1000).ToString("000"); + asset.Data = pack.AssetBlock.AssetData; + + + } + else if (pack.AssetBlock.Type == 13 | pack.AssetBlock.Type == 5 | pack.AssetBlock.Type == 7) + { + + asset = new AssetBase(); + asset.FullID = assetID; + // Console.WriteLine("skin asset id is " + assetID.ToStringHyphenated()); + asset.Type = pack.AssetBlock.Type; + asset.InvType = asset.Type; + asset.Name = "NewClothing" + Util.RandomClass.Next(1, 1000).ToString("000"); + asset.Data = pack.AssetBlock.AssetData; + + + } + + if (asset != null) + { + this.AddUpload(pack.AssetBlock.TransactionID, asset); + } + else + { + + //currently we don't support this asset type + //so lets just tell the client that the upload is complete + AssetUploadCompletePacket response = new AssetUploadCompletePacket(); + response.AssetBlock.Type = pack.AssetBlock.Type; + response.AssetBlock.Success = true; + response.AssetBlock.UUID = pack.AssetBlock.TransactionID.Combine(this.ourClient.SecureSessionID); + this.ourClient.OutPacket(response); + } + + } + + #region Xfer packet system for larger uploads + + public void HandleXferPacket(SendXferPacketPacket xferPacket) + { + lock (this.transactions) + { + foreach (AssetTransaction trans in this.transactions.Values) + { + if (trans.XferID == xferPacket.XferID.ID) + { + if (trans.Asset.Data.Length > 1) + { + byte[] newArray = new byte[trans.Asset.Data.Length + xferPacket.DataPacket.Data.Length]; + Array.Copy(trans.Asset.Data, 0, newArray, 0, trans.Asset.Data.Length); + Array.Copy(xferPacket.DataPacket.Data, 0, newArray, trans.Asset.Data.Length, xferPacket.DataPacket.Data.Length); + trans.Asset.Data = newArray; + } + else + { + byte[] newArray = new byte[xferPacket.DataPacket.Data.Length - 4]; + Array.Copy(xferPacket.DataPacket.Data, 4, newArray, 0, xferPacket.DataPacket.Data.Length - 4); + trans.Asset.Data = newArray; + } + + if ((xferPacket.XferID.Packet & 2147483648) != 0) + { + //end of transfer + trans.UploadComplete = true; + AssetUploadCompletePacket response = new AssetUploadCompletePacket(); + response.AssetBlock.Type = trans.Asset.Type; + response.AssetBlock.Success = true; + response.AssetBlock.UUID = trans.TransactionID.Combine(this.ourClient.SecureSessionID); + this.ourClient.OutPacket(response); + + m_assetCache.AddAsset(trans.Asset); + //check if we should add it to inventory + if (trans.AddToInventory) + { + // m_assetCache.AddAsset(trans.Asset); + m_inventoryCache.AddNewInventoryItem(this.ourClient, trans.InventFolder, trans.Asset); + } + + + } + break; + } + + } + } + + ConfirmXferPacketPacket confirmXfer = new ConfirmXferPacketPacket(); + confirmXfer.XferID.ID = xferPacket.XferID.ID; + confirmXfer.XferID.Packet = xferPacket.XferID.Packet; + this.ourClient.OutPacket(confirmXfer); + } + + #endregion + + public AssetBase AddUploadToAssetCache(LLUUID transactionID) + { + AssetBase asset = null; + if (this.transactions.ContainsKey(transactionID)) + { + AssetTransaction trans = this.transactions[transactionID]; + if (trans.UploadComplete) + { + m_assetCache.AddAsset(trans.Asset); + asset = trans.Asset; + } + } + + return asset; + } + + public void CreateInventoryItem(CreateInventoryItemPacket packet) + { + if (this.transactions.ContainsKey(packet.InventoryBlock.TransactionID)) + { + AssetTransaction trans = this.transactions[packet.InventoryBlock.TransactionID]; + trans.Asset.Description = Util.FieldToString(packet.InventoryBlock.Description); + trans.Asset.Name = Util.FieldToString(packet.InventoryBlock.Name); + trans.Asset.Type = packet.InventoryBlock.Type; + trans.Asset.InvType = packet.InventoryBlock.InvType; + if (trans.UploadComplete) + { + //already complete so we can add it to the inventory + //m_assetCache.AddAsset(trans.Asset); + m_inventoryCache.AddNewInventoryItem(this.ourClient, packet.InventoryBlock.FolderID, trans.Asset); + } + else + { + trans.AddToInventory = true; + trans.InventFolder = packet.InventoryBlock.FolderID; + } + } + } + + private class AssetTransaction + { + public uint XferID; + public AssetBase Asset; + public bool AddToInventory; + public LLUUID InventFolder = LLUUID.Zero; + public bool UploadComplete = false; + public LLUUID TransactionID = LLUUID.Zero; + + public AssetTransaction() + { + + } + } + + //new class , not currently used. + public class AssetXferUploader + { + private IClientAPI ourClient; + + public bool UploadComplete = false; + + public bool AddToInventory; + public LLUUID InventFolder = LLUUID.Zero; + + public uint XferID; + public AssetBase Asset; + public LLUUID TransactionID = LLUUID.Zero; + + + public AssetXferUploader(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data) + { + ourClient = remoteClient; + Asset = new AssetBase(); + Asset.FullID = assetID; + Asset.InvType = type; + Asset.Type = type; + Asset.Data = data; + Asset.Name = "blank"; + Asset.Description = "empty"; + TransactionID = transaction; + + if (Asset.Data.Length > 2) + { + //data block should only have data in it, if there is no more data to be uploaded + this.SendCompleteMessage(); + } + else + { + this.ReqestStartXfer(); + } + } + + protected void SendCompleteMessage() + { + UploadComplete = true; + AssetUploadCompletePacket response = new AssetUploadCompletePacket(); + response.AssetBlock.Type = Asset.Type; + response.AssetBlock.Success = true; + response.AssetBlock.UUID = Asset.FullID; + this.ourClient.OutPacket(response); + + //TODO trigger event + } + + protected void ReqestStartXfer() + { + UploadComplete = false; + XferID = Util.GetNextXferID(); + RequestXferPacket xfer = new RequestXferPacket(); + xfer.XferID.ID = XferID; + xfer.XferID.VFileType = Asset.Type; + xfer.XferID.VFileID = Asset.FullID; + xfer.XferID.FilePath = 0; + xfer.XferID.Filename = new byte[0]; + this.ourClient.OutPacket(xfer); + } + + public void HandleXferPacket(uint xferID, uint packetID, byte[] data) + { + if (XferID == xferID) + { + if (Asset.Data.Length > 1) + { + byte[] newArray = new byte[Asset.Data.Length + data.Length]; + Array.Copy(Asset.Data, 0, newArray, 0, Asset.Data.Length); + Array.Copy(data, 0, newArray, Asset.Data.Length, data.Length); + Asset.Data = newArray; + } + else + { + byte[] newArray = new byte[data.Length - 4]; + Array.Copy(data, 4, newArray, 0, data.Length - 4); + Asset.Data = newArray; + } + + ConfirmXferPacketPacket confirmXfer = new ConfirmXferPacketPacket(); + confirmXfer.XferID.ID = xferID; + confirmXfer.XferID.Packet = packetID; + this.ourClient.OutPacket(confirmXfer); + + if ((packetID & 2147483648) != 0) + { + this.SendCompleteMessage(); + } + } + } + } + } + } +} diff --git a/OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs b/OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs new file mode 100644 index 0000000..32aed02 --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs @@ -0,0 +1,198 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.Assets; + +namespace OpenSim +{ + public partial class ClientView + { + protected virtual void RegisterLocalPacketHandlers() + { + this.AddLocalPacketHandler(PacketType.LogoutRequest, this.Logout); + this.AddLocalPacketHandler(PacketType.AgentCachedTexture, this.AgentTextureCached); + this.AddLocalPacketHandler(PacketType.MultipleObjectUpdate, this.MultipleObjUpdate); + } + + protected virtual bool Logout(ClientView simClient, Packet packet) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "OpenSimClient.cs:ProcessInPacket() - Got a logout request"); + //send reply to let the client logout + LogoutReplyPacket logReply = new LogoutReplyPacket(); + logReply.AgentData.AgentID = this.AgentID; + logReply.AgentData.SessionID = this.SessionID; + logReply.InventoryData = new LogoutReplyPacket.InventoryDataBlock[1]; + logReply.InventoryData[0] = new LogoutReplyPacket.InventoryDataBlock(); + logReply.InventoryData[0].ItemID = LLUUID.Zero; + OutPacket(logReply); + //tell all clients to kill our object + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + // kill.ObjectData[0].ID = this.ClientAvatar.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + + this.m_inventoryCache.ClientLeaving(this.AgentID, null); + + + // m_gridServer.LogoutSession(this.SessionID, this.AgentID, this.CircuitCode); + /*lock (m_world.Entities) + { + m_world.Entities.Remove(this.AgentID); + }*/ + // m_world.RemoveViewerAgent(this); + //need to do other cleaning up here too + m_clientThreads.Remove(this.CircuitCode); + m_networkServer.RemoveClientCircuit(this.CircuitCode); + this.ClientThread.Abort(); + return true; + } + + protected bool AgentTextureCached(ClientView simclient, Packet packet) + { + // Console.WriteLine(packet.ToString()); + AgentCachedTexturePacket chechedtex = (AgentCachedTexturePacket)packet; + AgentCachedTextureResponsePacket cachedresp = new AgentCachedTextureResponsePacket(); + cachedresp.AgentData.AgentID = this.AgentID; + cachedresp.AgentData.SessionID = this.SessionID; + cachedresp.AgentData.SerialNum = this.cachedtextureserial; + this.cachedtextureserial++; + cachedresp.WearableData = new AgentCachedTextureResponsePacket.WearableDataBlock[chechedtex.WearableData.Length]; + for (int i = 0; i < chechedtex.WearableData.Length; i++) + { + cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock(); + cachedresp.WearableData[i].TextureIndex = chechedtex.WearableData[i].TextureIndex; + cachedresp.WearableData[i].TextureID = LLUUID.Zero; + cachedresp.WearableData[i].HostName = new byte[0]; + } + this.OutPacket(cachedresp); + return true; + } + + protected bool MultipleObjUpdate(ClientView simClient, Packet packet) + { + MultipleObjectUpdatePacket multipleupdate = (MultipleObjectUpdatePacket)packet; + for (int i = 0; i < multipleupdate.ObjectData.Length; i++) + { + if (multipleupdate.ObjectData[i].Type == 9) //change position + { + if (OnUpdatePrimPosition != null) + { + libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + OnUpdatePrimPosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); + } + //should update stored position of the prim + } + else if (multipleupdate.ObjectData[i].Type == 10)//rotation + { + if (OnUpdatePrimRotation != null) + { + libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); + OnUpdatePrimRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 13)//scale + { + if (OnUpdatePrimScale != null) + { + libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); + OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + } + return true; + } + + public void RequestMapLayer() + { + //should be getting the map layer from the grid server + //send a layer covering the 800,800 - 1200,1200 area (should be covering the requested area) + MapLayerReplyPacket mapReply = new MapLayerReplyPacket(); + mapReply.AgentData.AgentID = this.AgentID; + mapReply.AgentData.Flags = 0; + mapReply.LayerData = new MapLayerReplyPacket.LayerDataBlock[1]; + mapReply.LayerData[0] = new MapLayerReplyPacket.LayerDataBlock(); + mapReply.LayerData[0].Bottom = 0; + mapReply.LayerData[0].Left = 0; + mapReply.LayerData[0].Top = 30000; + mapReply.LayerData[0].Right = 30000; + mapReply.LayerData[0].ImageID = new LLUUID("00000000-0000-0000-9999-000000000006"); + this.OutPacket(mapReply); + } + + public void RequestMapBlocks(int minX, int minY, int maxX, int maxY) + { + /* + IList simMapProfiles = m_gridServer.RequestMapBlocks(minX, minY, maxX, maxY); + MapBlockReplyPacket mbReply = new MapBlockReplyPacket(); + mbReply.AgentData.AgentID = this.AgentID; + int len; + if (simMapProfiles == null) + len = 0; + else + len = simMapProfiles.Count; + + mbReply.Data = new MapBlockReplyPacket.DataBlock[len]; + int iii; + for (iii = 0; iii < len; iii++) + { + Hashtable mp = (Hashtable)simMapProfiles[iii]; + mbReply.Data[iii] = new MapBlockReplyPacket.DataBlock(); + mbReply.Data[iii].Name = System.Text.Encoding.UTF8.GetBytes((string)mp["name"]); + mbReply.Data[iii].Access = System.Convert.ToByte(mp["access"]); + mbReply.Data[iii].Agents = System.Convert.ToByte(mp["agents"]); + mbReply.Data[iii].MapImageID = new LLUUID((string)mp["map-image-id"]); + mbReply.Data[iii].RegionFlags = System.Convert.ToUInt32(mp["region-flags"]); + mbReply.Data[iii].WaterHeight = System.Convert.ToByte(mp["water-height"]); + mbReply.Data[iii].X = System.Convert.ToUInt16(mp["x"]); + mbReply.Data[iii].Y = System.Convert.ToUInt16(mp["y"]); + } + this.OutPacket(mbReply); + */ + } + + + } +} diff --git a/OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs b/OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs new file mode 100644 index 0000000..191ef21 --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs @@ -0,0 +1,550 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.Assets; + +namespace OpenSim +{ + public partial class ClientView + { + protected override void ProcessInPacket(Packet Pack) + { + ack_pack(Pack); + if (debug) + { + if (Pack.Type != PacketType.AgentUpdate) + { + Console.WriteLine(Pack.Type.ToString()); + } + } + + if (this.ProcessPacketMethod(Pack)) + { + //there is a handler registered that handled this packet type + return; + } + else + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + + switch (Pack.Type) + { + case PacketType.ViewerEffect: + ViewerEffectPacket viewer = (ViewerEffectPacket)Pack; + foreach (ClientView client in m_clientThreads.Values) + { + if (client.AgentID != this.AgentID) + { + viewer.AgentData.AgentID = client.AgentID; + viewer.AgentData.SessionID = client.SessionID; + client.OutPacket(viewer); + } + } + break; + + #region World/Avatar + case PacketType.ChatFromViewer: + ChatFromViewerPacket inchatpack = (ChatFromViewerPacket)Pack; + if (Util.FieldToString(inchatpack.ChatData.Message) == "") + { + //empty message so don't bother with it + break; + } + string fromName = ""; //ClientAvatar.firstname + " " + ClientAvatar.lastname; + byte[] message = inchatpack.ChatData.Message; + byte type = inchatpack.ChatData.Type; + LLVector3 fromPos = new LLVector3(); // ClientAvatar.Pos; + LLUUID fromAgentID = AgentID; + if (OnChatFromViewer != null) + { + this.OnChatFromViewer(message, type, fromPos, fromName, fromAgentID); + } + break; + case PacketType.RezObject: + RezObjectPacket rezPacket = (RezObjectPacket)Pack; + AgentInventory inven = this.m_inventoryCache.GetAgentsInventory(this.AgentID); + if (inven != null) + { + if (inven.InventoryItems.ContainsKey(rezPacket.InventoryData.ItemID)) + { + AssetBase asset = this.m_assetCache.GetAsset(inven.InventoryItems[rezPacket.InventoryData.ItemID].AssetID); + if (asset != null) + { + if (OnRezObject != null) + { + this.OnRezObject(asset, rezPacket.RezData.RayEnd); + this.m_inventoryCache.DeleteInventoryItem(this, rezPacket.InventoryData.ItemID); + } + } + } + } + break; + case PacketType.DeRezObject: + if (OnDeRezObject != null) + { + OnDeRezObject(Pack, this); + } + break; + case PacketType.ModifyLand: + ModifyLandPacket modify = (ModifyLandPacket)Pack; + if (modify.ParcelData.Length > 0) + { + if (OnModifyTerrain != null) + { + OnModifyTerrain(modify.ModifyBlock.Height, modify.ModifyBlock.Seconds, modify.ModifyBlock.BrushSize, + modify.ModifyBlock.Action, modify.ParcelData[0].North, modify.ParcelData[0].West); + } + } + break; + case PacketType.RegionHandshakeReply: + if (OnRegionHandShakeReply != null) + { + OnRegionHandShakeReply(this); + } + break; + case PacketType.AgentWearablesRequest: + if (OnRequestWearables != null) + { + OnRequestWearables(this); + } + if (OnRequestAvatarsData != null) + { + OnRequestAvatarsData(this); + } + break; + case PacketType.AgentSetAppearance: + AgentSetAppearancePacket appear = (AgentSetAppearancePacket)Pack; + if (OnSetAppearance != null) + { + OnSetAppearance(appear.ObjectData.TextureEntry, appear.VisualParam); + } + break; + case PacketType.CompleteAgentMovement: + if (OnCompleteMovementToRegion != null) + { + OnCompleteMovementToRegion(); + } + break; + case PacketType.AgentUpdate: + if (OnAgentUpdate != null) + { + AgentUpdatePacket agenUpdate = (AgentUpdatePacket) Pack; + OnAgentUpdate(this, agenUpdate.AgentData.ControlFlags, agenUpdate.AgentData.BodyRotation ); + } + break; + case PacketType.AgentAnimation: + if (!m_child) + { + AgentAnimationPacket AgentAni = (AgentAnimationPacket)Pack; + for (int i = 0; i < AgentAni.AnimationList.Length; i++) + { + if (AgentAni.AnimationList[i].StartAnim) + { + if (OnStartAnim != null) + { + OnStartAnim(AgentAni.AnimationList[i].AnimID, 1); + } + } + } + } + break; + + #endregion + + #region Objects/Prims + case PacketType.ObjectLink: + // OpenSim.Framework.Console.MainLog.Instance.Verbose( Pack.ToString()); + ObjectLinkPacket link = (ObjectLinkPacket)Pack; + uint parentprimid = 0; + List childrenprims = new List(); + if (link.ObjectData.Length > 1) + { + parentprimid = link.ObjectData[0].ObjectLocalID; + + for (int i = 1; i < link.ObjectData.Length; i++) + { + childrenprims.Add(link.ObjectData[i].ObjectLocalID); + } + } + if (OnLinkObjects != null) + { + OnLinkObjects(parentprimid, childrenprims); + } + break; + case PacketType.ObjectAdd: + // m_world.AddNewPrim((ObjectAddPacket)Pack, this); + if (OnAddPrim != null) + { + OnAddPrim(Pack, this); + } + break; + case PacketType.ObjectShape: + ObjectShapePacket shape = (ObjectShapePacket)Pack; + for (int i = 0; i < shape.ObjectData.Length; i++) + { + if (OnUpdatePrimShape != null) + { + OnUpdatePrimShape(shape.ObjectData[i].ObjectLocalID, shape.ObjectData[i]); + } + } + break; + case PacketType.ObjectSelect: + ObjectSelectPacket incomingselect = (ObjectSelectPacket)Pack; + for (int i = 0; i < incomingselect.ObjectData.Length; i++) + { + if (OnObjectSelect != null) + { + OnObjectSelect(incomingselect.ObjectData[i].ObjectLocalID, this); + } + } + break; + case PacketType.ObjectFlagUpdate: + ObjectFlagUpdatePacket flags = (ObjectFlagUpdatePacket)Pack; + if (OnUpdatePrimFlags != null) + { + OnUpdatePrimFlags(flags.AgentData.ObjectLocalID, Pack, this); + } + break; + case PacketType.ObjectImage: + ObjectImagePacket imagePack = (ObjectImagePacket)Pack; + for (int i = 0; i < imagePack.ObjectData.Length; i++) + { + if (OnUpdatePrimTexture != null) + { + OnUpdatePrimTexture(imagePack.ObjectData[i].ObjectLocalID, imagePack.ObjectData[i].TextureEntry, this); + } + } + break; + case PacketType.ObjectGrab: + ObjectGrabPacket grap = (ObjectGrabPacket)Pack; + if (OnGrapObject != null) + { + OnGrapObject(grap.ObjectData.LocalID, grap.ObjectData.GrabOffset, this); + } + break; + case PacketType.ObjectGrabUpdate: + ObjectGrabUpdatePacket grapUpdate = (ObjectGrabUpdatePacket)Pack; + if (OnGrapUpdate != null) + { + OnGrapUpdate(grapUpdate.ObjectData.ObjectID, grapUpdate.ObjectData.GrabOffsetInitial, grapUpdate.ObjectData.GrabPosition, this); + } + break; + case PacketType.ObjectDeGrab: + ObjectDeGrabPacket deGrap = (ObjectDeGrabPacket)Pack; + if (OnDeGrapObject != null) + { + OnDeGrapObject(deGrap.ObjectData.LocalID, this); + } + break; + #endregion + + #region Inventory/Asset/Other related packets + case PacketType.RequestImage: + RequestImagePacket imageRequest = (RequestImagePacket)Pack; + for (int i = 0; i < imageRequest.RequestImage.Length; i++) + { + m_assetCache.AddTextureRequest(this, imageRequest.RequestImage[i].Image); + } + break; + case PacketType.TransferRequest: + //Console.WriteLine("OpenSimClient.cs:ProcessInPacket() - Got transfer request"); + TransferRequestPacket transfer = (TransferRequestPacket)Pack; + m_assetCache.AddAssetRequest(this, transfer); + break; + case PacketType.AssetUploadRequest: + AssetUploadRequestPacket request = (AssetUploadRequestPacket)Pack; + this.UploadAssets.HandleUploadPacket(request, request.AssetBlock.TransactionID.Combine(this.SecureSessionID)); + break; + case PacketType.RequestXfer: + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.SendXferPacket: + this.UploadAssets.HandleXferPacket((SendXferPacketPacket)Pack); + break; + case PacketType.CreateInventoryFolder: + CreateInventoryFolderPacket invFolder = (CreateInventoryFolderPacket)Pack; + m_inventoryCache.CreateNewInventoryFolder(this, invFolder.FolderData.FolderID, (ushort)invFolder.FolderData.Type, Util.FieldToString(invFolder.FolderData.Name), invFolder.FolderData.ParentID); + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.CreateInventoryItem: + //Console.WriteLine(Pack.ToString()); + CreateInventoryItemPacket createItem = (CreateInventoryItemPacket)Pack; + if (createItem.InventoryBlock.TransactionID != LLUUID.Zero) + { + this.UploadAssets.CreateInventoryItem(createItem); + } + else + { + // Console.Write(Pack.ToString()); + this.CreateInventoryItem(createItem); + } + break; + case PacketType.FetchInventory: + //Console.WriteLine("fetch item packet"); + FetchInventoryPacket FetchInventory = (FetchInventoryPacket)Pack; + m_inventoryCache.FetchInventory(this, FetchInventory); + break; + case PacketType.FetchInventoryDescendents: + FetchInventoryDescendentsPacket Fetch = (FetchInventoryDescendentsPacket)Pack; + m_inventoryCache.FetchInventoryDescendents(this, Fetch); + break; + case PacketType.UpdateInventoryItem: + UpdateInventoryItemPacket update = (UpdateInventoryItemPacket)Pack; + //Console.WriteLine(Pack.ToString()); + for (int i = 0; i < update.InventoryData.Length; i++) + { + if (update.InventoryData[i].TransactionID != LLUUID.Zero) + { + AssetBase asset = m_assetCache.GetAsset(update.InventoryData[i].TransactionID.Combine(this.SecureSessionID)); + if (asset != null) + { + // Console.WriteLine("updating inventory item, found asset" + asset.FullID.ToStringHyphenated() + " already in cache"); + m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset); + } + else + { + asset = this.UploadAssets.AddUploadToAssetCache(update.InventoryData[i].TransactionID); + if (asset != null) + { + //Console.WriteLine("updating inventory item, adding asset" + asset.FullID.ToStringHyphenated() + " to cache"); + m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset); + } + else + { + //Console.WriteLine("trying to update inventory item, but asset is null"); + } + } + } + else + { + m_inventoryCache.UpdateInventoryItemDetails(this, update.InventoryData[i].ItemID, update.InventoryData[i]); ; + } + } + break; + case PacketType.RequestTaskInventory: + // Console.WriteLine(Pack.ToString()); + RequestTaskInventoryPacket requesttask = (RequestTaskInventoryPacket)Pack; + ReplyTaskInventoryPacket replytask = new ReplyTaskInventoryPacket(); + bool foundent = false; + /* foreach (Entity ent in m_world.Entities.Values) + { + if (ent.localid == requesttask.InventoryData.LocalID) + { + replytask.InventoryData.TaskID = ent.uuid; + replytask.InventoryData.Serial = 0; + replytask.InventoryData.Filename = new byte[0]; + foundent = true; + } + } + if (foundent) + { + this.OutPacket(replytask); + }*/ + break; + case PacketType.UpdateTaskInventory: + // Console.WriteLine(Pack.ToString()); + UpdateTaskInventoryPacket updatetask = (UpdateTaskInventoryPacket)Pack; + AgentInventory myinventory = this.m_inventoryCache.GetAgentsInventory(this.AgentID); + /*if (myinventory != null) + { + if (updatetask.UpdateData.Key == 0) + { + if (myinventory.InventoryItems[updatetask.InventoryData.ItemID] != null) + { + if (myinventory.InventoryItems[updatetask.InventoryData.ItemID].Type == 7) + { + LLUUID noteaid = myinventory.InventoryItems[updatetask.InventoryData.ItemID].AssetID; + AssetBase assBase = this.m_assetCache.GetAsset(noteaid); + if (assBase != null) + { + foreach (Entity ent in m_world.Entities.Values) + { + if (ent.localid == updatetask.UpdateData.LocalID) + { + if (ent is OpenSim.world.Primitive) + { + this.m_world.AddScript(ent, Util.FieldToString(assBase.Data)); + } + } + } + } + } + } + } + }*/ + break; + case PacketType.MapLayerRequest: + this.RequestMapLayer(); + break; + case PacketType.MapBlockRequest: + MapBlockRequestPacket MapRequest = (MapBlockRequestPacket)Pack; + if (OnRequestMapBlocks != null) + { + OnRequestMapBlocks(this, MapRequest.PositionData.MinX, MapRequest.PositionData.MinY, MapRequest.PositionData.MaxX, MapRequest.PositionData.MaxY); + } + break; + case PacketType.TeleportLandmarkRequest: + TeleportLandmarkRequestPacket tpReq = (TeleportLandmarkRequestPacket)Pack; + + TeleportStartPacket tpStart = new TeleportStartPacket(); + tpStart.Info.TeleportFlags = 8; // tp via lm + this.OutPacket(tpStart); + + TeleportProgressPacket tpProgress = new TeleportProgressPacket(); + tpProgress.Info.Message = (new System.Text.ASCIIEncoding()).GetBytes("sending_landmark"); + tpProgress.Info.TeleportFlags = 8; + tpProgress.AgentData.AgentID = tpReq.Info.AgentID; + this.OutPacket(tpProgress); + + // Fetch landmark + LLUUID lmid = tpReq.Info.LandmarkID; + AssetBase lma = this.m_assetCache.GetAsset(lmid); + if (lma != null) + { + AssetLandmark lm = new AssetLandmark(lma); + + if (lm.RegionID == m_regionData.SimUUID) + { + TeleportLocalPacket tpLocal = new TeleportLocalPacket(); + + tpLocal.Info.AgentID = tpReq.Info.AgentID; + tpLocal.Info.TeleportFlags = 8; // Teleport via landmark + tpLocal.Info.LocationID = 2; + tpLocal.Info.Position = lm.Position; + OutPacket(tpLocal); + } + else + { + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.AgentID = tpReq.Info.AgentID; + tpCancel.Info.SessionID = tpReq.Info.SessionID; + OutPacket(tpCancel); + } + } + else + { + Console.WriteLine("Cancelling Teleport - fetch asset not yet implemented"); + + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.AgentID = tpReq.Info.AgentID; + tpCancel.Info.SessionID = tpReq.Info.SessionID; + OutPacket(tpCancel); + } + break; + case PacketType.TeleportLocationRequest: + TeleportLocationRequestPacket tpLocReq = (TeleportLocationRequestPacket)Pack; + // Console.WriteLine(tpLocReq.ToString()); + + if (OnTeleportLocationRequest != null) + { + OnTeleportLocationRequest(this, tpLocReq.Info.RegionHandle, tpLocReq.Info.Position, tpLocReq.Info.LookAt, 16); + } + else + { + //no event handler so cancel request + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.SessionID = tpLocReq.AgentData.SessionID; + tpCancel.Info.AgentID = tpLocReq.AgentData.AgentID; + OutPacket(tpCancel); + } + break; + #endregion + + case PacketType.MoneyBalanceRequest: + this.SendMoneyBalance(LLUUID.Zero, true, new byte[0], 1000); + break; + + #region Parcel related packets + case PacketType.ParcelPropertiesRequest: + ParcelPropertiesRequestPacket propertiesRequest = (ParcelPropertiesRequestPacket)Pack; + if (OnParcelPropertiesRequest != null) + { + OnParcelPropertiesRequest((int)Math.Round(propertiesRequest.ParcelData.West), (int)Math.Round(propertiesRequest.ParcelData.South), (int)Math.Round(propertiesRequest.ParcelData.East), (int)Math.Round(propertiesRequest.ParcelData.North), propertiesRequest.ParcelData.SequenceID, propertiesRequest.ParcelData.SnapSelection, this); + } + break; + case PacketType.ParcelDivide: + ParcelDividePacket parcelDivide = (ParcelDividePacket)Pack; + if (OnParcelDivideRequest != null) + { + OnParcelDivideRequest((int)Math.Round(parcelDivide.ParcelData.West), (int)Math.Round(parcelDivide.ParcelData.South), (int)Math.Round(parcelDivide.ParcelData.East), (int)Math.Round(parcelDivide.ParcelData.North), this); + } + break; + case PacketType.ParcelJoin: + ParcelJoinPacket parcelJoin = (ParcelJoinPacket)Pack; + if (OnParcelJoinRequest != null) + { + OnParcelJoinRequest((int)Math.Round(parcelJoin.ParcelData.West), (int)Math.Round(parcelJoin.ParcelData.South), (int)Math.Round(parcelJoin.ParcelData.East), (int)Math.Round(parcelJoin.ParcelData.North), this); + } + break; + case PacketType.ParcelPropertiesUpdate: + ParcelPropertiesUpdatePacket updatePacket = (ParcelPropertiesUpdatePacket)Pack; + if (OnParcelPropertiesUpdateRequest != null) + { + OnParcelPropertiesUpdateRequest(updatePacket, this); + } + break; + #endregion + + #region Estate Packets + case PacketType.EstateOwnerMessage: + EstateOwnerMessagePacket messagePacket = (EstateOwnerMessagePacket)Pack; + if (OnEstateOwnerMessage != null) + { + OnEstateOwnerMessage(messagePacket, this); + } + break; + #endregion + + #region unimplemented handlers + case PacketType.AgentIsNowWearing: + // AgentIsNowWearingPacket wear = (AgentIsNowWearingPacket)Pack; + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.ObjectScale: + //OpenSim.Framework.Console.MainLog.Instance.Verbose( Pack.ToString()); + break; + #endregion + } + } + } + } +} diff --git a/OpenSim/Region/ClientStack/ClientView.cs b/OpenSim/Region/ClientStack/ClientView.cs new file mode 100644 index 0000000..312da9d --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientView.cs @@ -0,0 +1,273 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.Assets; +using OpenSim.Caches; + +namespace OpenSim +{ + public delegate bool PacketMethod(ClientView simClient, Packet packet); + + /// + /// Handles new client connections + /// Constructor takes a single Packet and authenticates everything + /// + public partial class ClientView : ClientViewBase, IClientAPI + { + public static TerrainManager TerrainManager; + + protected static Dictionary PacketHandlers = new Dictionary(); //Global/static handlers for all clients + protected Dictionary m_packetHandlers = new Dictionary(); //local handlers for this instance + + public LLUUID AgentID; + public LLUUID SessionID; + public LLUUID SecureSessionID = LLUUID.Zero; + public string firstName; + public string lastName; + public bool m_child = false; + private UseCircuitCodePacket cirpack; + public Thread ClientThread; + public LLVector3 startpos; + + private AgentAssetUpload UploadAssets; + private LLUUID newAssetFolder = LLUUID.Zero; + private bool debug = false; + protected IWorld m_world; + private Dictionary m_clientThreads; + private AssetCache m_assetCache; + private InventoryCache m_inventoryCache; + private int cachedtextureserial = 0; + private RegionInfo m_regionData; + protected AuthenticateSessionsBase m_authenticateSessionsHandler; + + public ClientView(EndPoint remoteEP, UseCircuitCodePacket initialcirpack, Dictionary clientThreads, IWorld world, AssetCache assetCache, PacketServer packServer, InventoryCache inventoryCache, AuthenticateSessionsBase authenSessions ) + { + m_world = world; + m_clientThreads = clientThreads; + m_assetCache = assetCache; + + m_networkServer = packServer; + m_inventoryCache = inventoryCache; + m_authenticateSessionsHandler = authenSessions; + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "OpenSimClient.cs - Started up new client thread to handle incoming request"); + cirpack = initialcirpack; + userEP = remoteEP; + + this.startpos = m_authenticateSessionsHandler.GetPosition(initialcirpack.CircuitCode.Code); + + PacketQueue = new BlockingQueue(); + + this.UploadAssets = new AgentAssetUpload(this, m_assetCache, m_inventoryCache); + AckTimer = new System.Timers.Timer(500); + AckTimer.Elapsed += new ElapsedEventHandler(AckTimer_Elapsed); + AckTimer.Start(); + + this.RegisterLocalPacketHandlers(); + + ClientThread = new Thread(new ThreadStart(AuthUser)); + ClientThread.IsBackground = true; + ClientThread.Start(); + } + + # region Client Methods + + public void KillClient() + { + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + //kill.ObjectData[0].ID = this.ClientAvatar.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + + this.m_inventoryCache.ClientLeaving(this.AgentID, null); + m_world.RemoveClient(this.AgentId); + + m_clientThreads.Remove(this.CircuitCode); + m_networkServer.RemoveClientCircuit(this.CircuitCode); + this.ClientThread.Abort(); + } + #endregion + + # region Packet Handling + public static bool AddPacketHandler(PacketType packetType, PacketMethod handler) + { + bool result = false; + lock (PacketHandlers) + { + if (!PacketHandlers.ContainsKey(packetType)) + { + PacketHandlers.Add(packetType, handler); + result = true; + } + } + return result; + } + + public bool AddLocalPacketHandler(PacketType packetType, PacketMethod handler) + { + bool result = false; + lock (m_packetHandlers) + { + if (!m_packetHandlers.ContainsKey(packetType)) + { + m_packetHandlers.Add(packetType, handler); + result = true; + } + } + return result; + } + + protected virtual bool ProcessPacketMethod(Packet packet) + { + bool result = false; + bool found = false; + PacketMethod method; + if (m_packetHandlers.TryGetValue(packet.Type, out method)) + { + //there is a local handler for this packet type + result = method(this, packet); + } + else + { + //there is not a local handler so see if there is a Global handler + lock (PacketHandlers) + { + found = PacketHandlers.TryGetValue(packet.Type, out method); + } + if (found) + { + result = method(this, packet); + } + } + return result; + } + + protected virtual void ClientLoop() + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "OpenSimClient.cs:ClientLoop() - Entered loop"); + while (true) + { + QueItem nextPacket = PacketQueue.Dequeue(); + if (nextPacket.Incoming) + { + //is a incoming packet + ProcessInPacket(nextPacket.Packet); + } + else + { + //is a out going packet + ProcessOutPacket(nextPacket.Packet); + } + } + } + # endregion + + # region Setup + + protected virtual void InitNewClient() + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "OpenSimClient.cs:InitNewClient() - Adding viewer agent to world"); + this.m_world.AddNewClient(this, this.AgentID, false); + } + + protected virtual void AuthUser() + { + // AuthenticateResponse sessionInfo = m_gridServer.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code); + AuthenticateResponse sessionInfo = this.m_authenticateSessionsHandler.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code); + if (!sessionInfo.Authorised) + { + //session/circuit not authorised + OpenSim.Framework.Console.MainLog.Instance.Notice("OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString()); + ClientThread.Abort(); + } + else + { + OpenSim.Framework.Console.MainLog.Instance.Notice("OpenSimClient.cs:AuthUser() - Got authenticated connection from " + userEP.ToString()); + //session is authorised + this.AgentID = cirpack.CircuitCode.ID; + this.SessionID = cirpack.CircuitCode.SessionID; + this.CircuitCode = cirpack.CircuitCode.Code; + this.firstName = sessionInfo.LoginInfo.First; + this.lastName = sessionInfo.LoginInfo.Last; + + if (sessionInfo.LoginInfo.SecureSession != LLUUID.Zero) + { + this.SecureSessionID = sessionInfo.LoginInfo.SecureSession; + } + InitNewClient(); + + ClientLoop(); + } + } + # endregion + + + protected override void KillThread() + { + this.ClientThread.Abort(); + } + + #region Inventory Creation + private void SetupInventory(AuthenticateResponse sessionInfo) + { + + } + private AgentInventory CreateInventory(LLUUID baseFolder) + { + AgentInventory inventory = null; + + return inventory; + } + + private void CreateInventoryItem(CreateInventoryItemPacket packet) + { + + } + #endregion + + } +} diff --git a/OpenSim/Region/ClientStack/ClientViewBase.cs b/OpenSim/Region/ClientStack/ClientViewBase.cs new file mode 100644 index 0000000..8b503f0 --- /dev/null +++ b/OpenSim/Region/ClientStack/ClientViewBase.cs @@ -0,0 +1,327 @@ + +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Interfaces; + +namespace OpenSim +{ + public class ClientViewBase + { + protected BlockingQueue PacketQueue; + protected Dictionary PendingAcks = new Dictionary(); + protected Dictionary NeedAck = new Dictionary(); + + protected System.Timers.Timer AckTimer; + protected uint Sequence = 0; + protected object SequenceLock = new object(); + protected const int MAX_APPENDED_ACKS = 10; + protected const int RESEND_TIMEOUT = 4000; + protected const int MAX_SEQUENCE = 0xFFFFFF; + + public uint CircuitCode; + public EndPoint userEP; + + protected PacketServer m_networkServer; + + public ClientViewBase() + { + + } + + protected virtual void ProcessInPacket(Packet Pack) + { + + } + + protected virtual void ProcessOutPacket(Packet Pack) + { + // Keep track of when this packet was sent out + Pack.TickCount = Environment.TickCount; + + if (!Pack.Header.Resent) + { + // Set the sequence number + lock (SequenceLock) + { + if (Sequence >= MAX_SEQUENCE) + Sequence = 1; + else + Sequence++; + Pack.Header.Sequence = Sequence; + } + + if (Pack.Header.Reliable) //DIRTY HACK + { + lock (NeedAck) + { + if (!NeedAck.ContainsKey(Pack.Header.Sequence)) + { + try + { + NeedAck.Add(Pack.Header.Sequence, Pack); + } + catch (Exception e) // HACKY + { + e.ToString(); + // Ignore + // Seems to throw a exception here occasionally + // of 'duplicate key' despite being locked. + // !?!?!? + } + } + else + { + // Client.Log("Attempted to add a duplicate sequence number (" + + // packet.Header.Sequence + ") to the NeedAck dictionary for packet type " + + // packet.Type.ToString(), Helpers.LogLevel.Warning); + } + } + + // Don't append ACKs to resent packets, in case that's what was causing the + // delivery to fail + if (!Pack.Header.Resent) + { + // Append any ACKs that need to be sent out to this packet + lock (PendingAcks) + { + if (PendingAcks.Count > 0 && PendingAcks.Count < MAX_APPENDED_ACKS && + Pack.Type != PacketType.PacketAck && + Pack.Type != PacketType.LogoutRequest) + { + Pack.Header.AckList = new uint[PendingAcks.Count]; + int i = 0; + + foreach (uint ack in PendingAcks.Values) + { + Pack.Header.AckList[i] = ack; + i++; + } + + PendingAcks.Clear(); + Pack.Header.AppendedAcks = true; + } + } + } + } + } + + byte[] ZeroOutBuffer = new byte[4096]; + byte[] sendbuffer; + sendbuffer = Pack.ToBytes(); + + try + { + if (Pack.Header.Zerocoded) + { + int packetsize = Helpers.ZeroEncode(sendbuffer, sendbuffer.Length, ZeroOutBuffer); + m_networkServer.SendPacketTo(ZeroOutBuffer, packetsize, SocketFlags.None, CircuitCode);//userEP); + } + else + { + m_networkServer.SendPacketTo(sendbuffer, sendbuffer.Length, SocketFlags.None, CircuitCode); //userEP); + } + } + catch (Exception) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("OpenSimClient.cs:ProcessOutPacket() - WARNING: Socket exception occurred on connection " + userEP.ToString() + " - killing thread"); + this.KillThread(); + } + + } + + public virtual void InPacket(Packet NewPack) + { + // Handle appended ACKs + if (NewPack.Header.AppendedAcks) + { + lock (NeedAck) + { + foreach (uint ack in NewPack.Header.AckList) + { + NeedAck.Remove(ack); + } + } + } + + // Handle PacketAck packets + if (NewPack.Type == PacketType.PacketAck) + { + PacketAckPacket ackPacket = (PacketAckPacket)NewPack; + + lock (NeedAck) + { + foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets) + { + NeedAck.Remove(block.ID); + } + } + } + else if ((NewPack.Type == PacketType.StartPingCheck)) + { + //reply to pingcheck + libsecondlife.Packets.StartPingCheckPacket startPing = (libsecondlife.Packets.StartPingCheckPacket)NewPack; + libsecondlife.Packets.CompletePingCheckPacket endPing = new CompletePingCheckPacket(); + endPing.PingID.PingID = startPing.PingID.PingID; + OutPacket(endPing); + } + else + { + QueItem item = new QueItem(); + item.Packet = NewPack; + item.Incoming = true; + this.PacketQueue.Enqueue(item); + } + + } + + public virtual void OutPacket(Packet NewPack) + { + QueItem item = new QueItem(); + item.Packet = NewPack; + item.Incoming = false; + this.PacketQueue.Enqueue(item); + } + + # region Low Level Packet Methods + + protected void ack_pack(Packet Pack) + { + if (Pack.Header.Reliable) + { + libsecondlife.Packets.PacketAckPacket ack_it = new PacketAckPacket(); + ack_it.Packets = new PacketAckPacket.PacketsBlock[1]; + ack_it.Packets[0] = new PacketAckPacket.PacketsBlock(); + ack_it.Packets[0].ID = Pack.Header.Sequence; + ack_it.Header.Reliable = false; + + OutPacket(ack_it); + + } + /* + if (Pack.Header.Reliable) + { + lock (PendingAcks) + { + uint sequence = (uint)Pack.Header.Sequence; + if (!PendingAcks.ContainsKey(sequence)) { PendingAcks[sequence] = sequence; } + } + }*/ + } + + protected void ResendUnacked() + { + int now = Environment.TickCount; + + lock (NeedAck) + { + foreach (Packet packet in NeedAck.Values) + { + if ((now - packet.TickCount > RESEND_TIMEOUT) && (!packet.Header.Resent)) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Resending " + packet.Type.ToString() + " packet, " + + (now - packet.TickCount) + "ms have passed"); + + packet.Header.Resent = true; + OutPacket(packet); + } + } + } + } + + protected void SendAcks() + { + lock (PendingAcks) + { + if (PendingAcks.Count > 0) + { + if (PendingAcks.Count > 250) + { + // FIXME: Handle the odd case where we have too many pending ACKs queued up + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Too many ACKs queued up!"); + return; + } + + //OpenSim.Framework.Console.MainLog.Instance.WriteLine("Sending PacketAck"); + + + int i = 0; + PacketAckPacket acks = new PacketAckPacket(); + acks.Packets = new PacketAckPacket.PacketsBlock[PendingAcks.Count]; + + foreach (uint ack in PendingAcks.Values) + { + acks.Packets[i] = new PacketAckPacket.PacketsBlock(); + acks.Packets[i].ID = ack; + i++; + } + + acks.Header.Reliable = false; + OutPacket(acks); + + PendingAcks.Clear(); + } + } + } + + protected void AckTimer_Elapsed(object sender, ElapsedEventArgs ea) + { + SendAcks(); + ResendUnacked(); + } + #endregion + + protected virtual void KillThread() + { + + } + + #region Nested Classes + + public class QueItem + { + public QueItem() + { + } + + public Packet Packet; + public bool Incoming; + } + #endregion + } +} diff --git a/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj b/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj new file mode 100644 index 0000000..0b19359 --- /dev/null +++ b/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj @@ -0,0 +1,173 @@ + + + Local + 8.0.50727 + 2.0 + {DC3698B2-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.ClientStack + JScript + Grid + IE50 + false + Library + + OpenSim.Region.ClientStack + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Axiom.MathLib.dll + False + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + OpenSim.FrameworkGenericConfig.Xml.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Servers + {2CC71860-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Caches + {61FCCDB3-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Terrain.BasicTerrain + {C9E0F891-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj.user b/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/ClientStack/OpenSim.Region.ClientStack.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/ClientStack/PacketServer.cs b/OpenSim/Region/ClientStack/PacketServer.cs new file mode 100644 index 0000000..229570c --- /dev/null +++ b/OpenSim/Region/ClientStack/PacketServer.cs @@ -0,0 +1,183 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework; +using System.Net; +using System.Net.Sockets; +using OpenSim.Assets; +using OpenSim.Caches; + +namespace OpenSim +{ + public class PacketServer + { + private ClientStackNetworkHandler _networkHandler; + private IWorld _localWorld; + public Dictionary ClientThreads = new Dictionary(); + public Dictionary ClientAPIs = new Dictionary(); + protected uint serverPort; + + public PacketServer(ClientStackNetworkHandler networkHandler, uint port) + { + _networkHandler = networkHandler; + this.serverPort = port; + _networkHandler.RegisterPacketServer(this); + } + + public IWorld LocalWorld + { + set + { + this._localWorld = value; + } + } + + /// + /// + /// + /// + /// + public virtual void ClientInPacket(uint circuitCode, Packet packet) + { + if (this.ClientThreads.ContainsKey(circuitCode)) + { + ClientThreads[circuitCode].InPacket(packet); + } + } + + /// + /// + /// + /// + /// + public virtual bool AddNewCircuitCodeClient(uint circuitCode) + { + return false; + } + + /// + /// + /// + /// + public virtual void SendPacketToAllClients(Packet packet) + { + + } + + /// + /// + /// + /// + /// + public virtual void SendPacketToAllExcept(Packet packet, ClientView simClient) + { + + } + + /// + /// + /// + /// + /// + public virtual void AddClientPacketHandler(PacketType packetType, PacketMethod handler) + { + + } + + /// + /// + /// + public virtual void RegisterClientPacketHandlers() + { + + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected virtual ClientView CreateNewClient(EndPoint remoteEP, UseCircuitCodePacket initialcirpack, Dictionary clientThreads, IWorld world, AssetCache assetCache, PacketServer packServer, InventoryCache inventoryCache, AuthenticateSessionsBase authenSessions) + { + return new ClientView(remoteEP, initialcirpack, clientThreads, world, assetCache, packServer, inventoryCache, authenSessions ); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual bool AddNewClient(EndPoint epSender, UseCircuitCodePacket useCircuit, AssetCache assetCache, InventoryCache inventoryCache, AuthenticateSessionsBase authenticateSessionsClass) + { + ClientView newuser = + CreateNewClient(epSender, useCircuit, ClientThreads, _localWorld, assetCache, this, inventoryCache, + authenticateSessionsClass); + + this.ClientThreads.Add(useCircuit.CircuitCode.Code, newuser); + this.ClientAPIs.Add(useCircuit.CircuitCode.Code, (IClientAPI)newuser); + + return true; + } + + /// + /// + /// + /// + /// + /// + /// + public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode) + { + this._networkHandler.SendPacketTo(buffer, size, flags, circuitcode); + } + + /// + /// + /// + /// + public virtual void RemoveClientCircuit(uint circuitcode) + { + this._networkHandler.RemoveClientCircuit(circuitcode); + } + } +} diff --git a/OpenSim/Region/ClientStack/RegionApplicationBase.cs b/OpenSim/Region/ClientStack/RegionApplicationBase.cs new file mode 100644 index 0000000..b421fbd --- /dev/null +++ b/OpenSim/Region/ClientStack/RegionApplicationBase.cs @@ -0,0 +1,129 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework; +using OpenSim.Assets; +using OpenSim.Caches; +using OpenSim.Framework.Console; +using OpenSim.Physics.Manager; +using Nwc.XmlRpc; +using OpenSim.Framework.Servers; +using OpenSim.Framework.GenericConfig; + +namespace OpenSim +{ + public class RegionApplicationBase + { + protected IGenericConfig localConfig; + protected PhysicsManager physManager; + protected AssetCache AssetCache; + protected InventoryCache InventoryCache; + protected Dictionary clientCircuits = new Dictionary(); + protected DateTime startuptime; + protected NetworkServersInfo serversData; + + public string m_physicsEngine; + public bool m_sandbox = false; + public bool m_loginserver; + public bool user_accounts = false; + public bool gridLocalAsset = false; + protected bool configFileSetup = false; + public string m_config; + + protected List m_udpServer = new List(); + protected List regionData = new List(); + protected List m_localWorld = new List(); + protected BaseHttpServer httpServer; + protected List AuthenticateSessionsHandler = new List(); + + protected LogBase m_log; + + public RegionApplicationBase() + { + + } + + public RegionApplicationBase(bool sandBoxMode, bool startLoginServer, string physicsEngine, bool useConfigFile, bool silent, string configFile) + { + this.configFileSetup = useConfigFile; + m_sandbox = sandBoxMode; + m_loginserver = startLoginServer; + m_physicsEngine = physicsEngine; + m_config = configFile; + } + + /*protected World m_localWorld; + public World LocalWorld + { + get { return m_localWorld; } + }*/ + + /// + /// Performs initialisation of the world, such as loading configuration from disk. + /// + public virtual void StartUp() + { + } + + protected virtual void SetupLocalGridServers() + { + } + + protected virtual void SetupRemoteGridServers() + { + + } + + protected virtual void SetupWorld() + { + } + + protected virtual void SetupHttpListener() + { + } + + protected virtual void ConnectToRemoteGridServer() + { + + } + } +} diff --git a/OpenSim/Region/ClientStack/UDPServer.cs b/OpenSim/Region/ClientStack/UDPServer.cs new file mode 100644 index 0000000..f2a02d9 --- /dev/null +++ b/OpenSim/Region/ClientStack/UDPServer.cs @@ -0,0 +1,208 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Assets; +using OpenSim.Caches; +using OpenSim.Framework.Console; +using OpenSim.Framework; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenSim +{ + + public class UDPServer : ClientStackNetworkHandler + { + protected Dictionary clientCircuits = new Dictionary(); + public Socket Server; + protected IPEndPoint ServerIncoming; + protected byte[] RecvBuffer = new byte[4096]; + protected byte[] ZeroBuffer = new byte[8192]; + protected IPEndPoint ipeSender; + protected EndPoint epSender; + protected AsyncCallback ReceivedData; + protected PacketServer _packetServer; + + protected int listenPort; + protected IWorld m_localWorld; + protected AssetCache m_assetCache; + protected InventoryCache m_inventoryCache; + protected LogBase m_log; + protected AuthenticateSessionsBase m_authenticateSessionsClass; + + public PacketServer PacketServer + { + get + { + return _packetServer; + } + set + { + _packetServer = value; + } + } + + public IWorld LocalWorld + { + set + { + this.m_localWorld = value; + this._packetServer.LocalWorld = this.m_localWorld; + } + } + + public UDPServer() + { + } + + public UDPServer(int port, AssetCache assetCache, InventoryCache inventoryCache, LogBase console, AuthenticateSessionsBase authenticateClass) + { + listenPort = port; + this.m_assetCache = assetCache; + this.m_inventoryCache = inventoryCache; + this.m_log = console; + this.m_authenticateSessionsClass = authenticateClass; + this.CreatePacketServer(); + + } + + protected virtual void CreatePacketServer() + { + PacketServer packetServer = new PacketServer(this, (uint) listenPort); + } + + protected virtual void OnReceivedData(IAsyncResult result) + { + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + Packet packet = null; + int numBytes = Server.EndReceiveFrom(result, ref epSender); + int packetEnd = numBytes - 1; + + packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer); + + // do we already have a circuit for this endpoint + if (this.clientCircuits.ContainsKey(epSender)) + { + //if so then send packet to the packetserver + this._packetServer.ClientInPacket(this.clientCircuits[epSender], packet); + } + else if (packet.Type == PacketType.UseCircuitCode) + { + // new client + this.AddNewClient(packet); + } + else + { // invalid client + m_log.Warn("UDPServer.cs:OnReceivedData() - WARNING: Got a packet from an invalid client - " + epSender.ToString()); + } + + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + } + + protected virtual void AddNewClient(Packet packet) + { + UseCircuitCodePacket useCircuit = (UseCircuitCodePacket)packet; + this.clientCircuits.Add(epSender, useCircuit.CircuitCode.Code); + + this.PacketServer.AddNewClient(epSender, useCircuit, m_assetCache, m_inventoryCache, m_authenticateSessionsClass); + } + + public void ServerListener() + { + m_log.Status("UDPServer.cs:ServerListener() - Opening UDP socket on " + listenPort); + + ServerIncoming = new IPEndPoint(IPAddress.Any, listenPort); + Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + Server.Bind(ServerIncoming); + + m_log.Verbose("UDPServer.cs:ServerListener() - UDP socket bound, getting ready to listen"); + + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + ReceivedData = new AsyncCallback(this.OnReceivedData); + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + + m_log.Verbose("UDPServer.cs:ServerListener() - Listening..."); + + } + + public virtual void RegisterPacketServer(PacketServer server) + { + this._packetServer = server; + } + + public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode)//EndPoint packetSender) + { + // find the endpoint for this circuit + EndPoint sendto = null; + foreach (KeyValuePair p in this.clientCircuits) + { + if (p.Value == circuitcode) + { + sendto = p.Key; + break; + } + } + if (sendto != null) + { + //we found the endpoint so send the packet to it + this.Server.SendTo(buffer, size, flags, sendto); + } + } + + public virtual void RemoveClientCircuit(uint circuitcode) + { + foreach (KeyValuePair p in this.clientCircuits) + { + if (p.Value == circuitcode) + { + this.clientCircuits.Remove(p.Key); + break; + } + } + } + + + } +} \ No newline at end of file diff --git a/OpenSim/Region/ClientStack/VersionInfo.cs b/OpenSim/Region/ClientStack/VersionInfo.cs new file mode 100644 index 0000000..5d1354e --- /dev/null +++ b/OpenSim/Region/ClientStack/VersionInfo.cs @@ -0,0 +1,38 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; + +namespace OpenSim +{ + /// + /// + public class VersionInfo + { + public static string Version = "0.3, SVN build "; + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/MyWorld.cs b/OpenSim/Region/Examples/SimpleApp/MyWorld.cs new file mode 100644 index 0000000..01e0c59 --- /dev/null +++ b/OpenSim/Region/Examples/SimpleApp/MyWorld.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Console; +using libsecondlife; +using OpenSim.Region; +using Avatar=OpenSim.Region.Scenes.ScenePresence; +using OpenSim.Region.Scenes; +using OpenSim.Framework; +using OpenSim.Caches; +using OpenGrid.Framework.Communications; +using OpenSim.Servers; + +namespace SimpleApp +{ + public class MyWorld : Scene + { + private RegionInfo m_regionInfo; + private List m_avatars; + + public MyWorld(Dictionary clientThreads, RegionInfo regionInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, BaseHttpServer httpServer) + : base(clientThreads, regionInfo, authen, commsMan, assetCach, httpServer) + { + m_regionInfo = regionInfo; + m_avatars = new List(); + } + + public override void SendLayerData(IClientAPI remoteClient) + { + float[] map = new float[65536]; + + for (int i = 0; i < 65536; i++) + { + int x = i % 256; + int y = i / 256; + + map[i] = (float)(x + y / 2); + } + + remoteClient.SendLayerData(map); + } + + #region IWorld Members + + override public void AddNewClient(IClientAPI client, LLUUID agentID, bool child) + + { + LLVector3 pos = new LLVector3(128, 128, 128); + + client.OnRegionHandShakeReply += SendLayerData; + client.OnChatFromViewer += + delegate(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + // Echo it (so you know what you typed) + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + client.SendChatMessage("Ready.", 1, pos, "System", LLUUID.Zero ); + }; + + client.OnRequestWearables += SendWearables; + + client.OnCompleteMovementToRegion += delegate() + { + client.MoveAgentIntoRegion(m_regionInfo, pos, LLVector3.Zero ); + }; + + client.OnCompleteMovementToRegion += delegate() + { + client.SendAvatarData(m_regionInfo.RegionHandle, client.FirstName, + client.LastName, client.AgentId, 0, + pos, null); + + client.SendChatMessage("Welcome to My World.", 1, pos, "System", LLUUID.Zero ); + }; + + client.SendRegionHandshake(m_regionInfo); + + OpenSim.Region.Scenes.ScenePresence avatar = new Avatar( client, this, m_regionInfo ); + + } + + private void SendWearables( IClientAPI client ) + { + client.SendWearables( AvatarWearable.DefaultWearables ); + } + + + override public void RemoveClient(LLUUID agentID) + { + + } + + public RegionInfo RegionInfo + { + get { return m_regionInfo; } + } + + public object SyncRoot + { + get { return this; } + } + + private uint m_nextLocalId = 1; + + public uint NextLocalId + { + get { return m_nextLocalId++; } + } + + #endregion + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/Program.cs b/OpenSim/Region/Examples/SimpleApp/Program.cs new file mode 100644 index 0000000..e1465d1 --- /dev/null +++ b/OpenSim/Region/Examples/SimpleApp/Program.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim; +using OpenSim.GridInterfaces.Local; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Console; +using OpenSim.Assets; +using libsecondlife; +using OpenSim.Servers; +using OpenSim.Framework; +using OpenSim.Caches; +using OpenGrid.Framework.Communications; +using OpenSim.LocalCommunications; + +namespace SimpleApp +{ + class Program : IAssetReceiver, conscmd_callback + { + private LogBase m_log; + AuthenticateSessionsBase m_circuitManager; + + private void Run() + { + m_log = new LogBase(null, "SimpleApp", this, false); + MainLog.Instance = m_log; + + // CheckSumServer checksumServer = new CheckSumServer(12036); + // checksumServer.ServerListener(); + + string simAddr = "127.0.0.1"; + int simPort = 9000; + /* + LoginServer loginServer = new LoginServer( simAddr, simPort, 0, 0, false ); + loginServer.Startup(); + loginServer.SetSessionHandler( AddNewSessionHandler );*/ + + m_circuitManager = new AuthenticateSessionsBase(); + + InventoryCache inventoryCache = new InventoryCache(); + + LocalAssetServer assetServer = new LocalAssetServer(); + assetServer.SetServerInfo("http://127.0.0.1:8003/", ""); + assetServer.SetReceiver(this); + + AssetCache assetCache = new AssetCache(assetServer); + + UDPServer udpServer = new UDPServer(simPort, assetCache, inventoryCache, m_log, m_circuitManager ); + PacketServer packetServer = new PacketServer( udpServer, (uint) simPort ); + udpServer.ServerListener(); + + ClientView.TerrainManager = new TerrainManager(new SecondLife()); + + CommunicationsManager communicationsManager = new CommunicationsLocal(null); + + RegionInfo regionInfo = new RegionInfo( ); + BaseHttpServer httpServer = new BaseHttpServer(simPort); + udpServer.LocalWorld = new MyWorld( packetServer.ClientAPIs, regionInfo, m_circuitManager, communicationsManager, assetCache, httpServer ); + + // World world = new World(udpServer.PacketServer.ClientAPIs, regionInfo); + // PhysicsScene physicsScene = new NullPhysicsScene(); + // world.PhysicsScene = physicsScene; + // udpServer.LocalWorld = world; + + // httpServer.AddXmlRPCHandler( "login_to_simulator", loginServer.XmlRpcLoginMethod ); + httpServer.Start(); + + m_log.WriteLine( LogPriority.NORMAL, "Press enter to quit."); + m_log.ReadLine(); + } + + private bool AddNewSessionHandler(ulong regionHandle, Login loginData) + { + m_log.WriteLine(LogPriority.NORMAL, "Region [{0}] recieved Login from [{1}] [{2}]", regionHandle, loginData.First, loginData.Last); + + AgentCircuitData agent = new AgentCircuitData(); + agent.AgentID = loginData.Agent; + agent.firstname = loginData.First; + agent.lastname = loginData.Last; + agent.SessionID = loginData.Session; + agent.SecureSessionID = loginData.SecureSession; + agent.circuitcode = loginData.CircuitCode; + agent.BaseFolder = loginData.BaseFolder; + agent.InventoryFolder = loginData.InventoryFolder; + agent.startpos = new LLVector3(128, 128, 70); + + m_circuitManager.AddNewCircuit(agent.circuitcode, agent); + + return true; + } + + #region IAssetReceiver Members + + public void AssetReceived( AssetBase asset, bool IsTexture) + { + throw new Exception("The method or operation is not implemented."); + } + + public void AssetNotFound( AssetBase asset) + { + throw new Exception("The method or operation is not implemented."); + } + + #endregion + + #region conscmd_callback Members + + public void RunCmd(string cmd, string[] cmdparams) + { + throw new Exception("The method or operation is not implemented."); + } + + public void Show(string ShowWhat) + { + throw new Exception("The method or operation is not implemented."); + } + + #endregion + + static void Main(string[] args) + { + Program app = new Program(); + + app.Run(); + } + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs b/OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0f9bf0f --- /dev/null +++ b/OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Playahead AB")] +[assembly: AssemblyProduct("SimpleApp")] +[assembly: AssemblyCopyright("Copyright © Playahead AB 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a5cfa45f-5acf-4b2e-9c50-1dd1fd7608ee")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj b/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj new file mode 100644 index 0000000..5129be2 --- /dev/null +++ b/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj @@ -0,0 +1,154 @@ + + + Local + 8.0.50727 + 2.0 + {24B12448-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + SimpleApp + JScript + Grid + IE50 + false + Exe + + SimpleApp + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\libsecondlife.dll + False + + + OpenSim.Servers.dll + False + + + System.dll + False + + + ..\..\..\..\bin\System.Data.dll + False + + + System.Xml.dll + False + + + ..\..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications + {CB52B7E7-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Caches + {61FCCDB3-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.ClientStack + {DC3698B2-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.GridInterfaces.Local + {241A8CDD-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.LocalCommunications + {EB3A1BA8-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Simulation + {C0DAB338-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj.user b/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Examples/SimpleApp/SimpleApp.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs b/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs new file mode 100644 index 0000000..52ecd6b --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("LocalGridServers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LocalGridServers")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs b/OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs new file mode 100644 index 0000000..87eff49 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs @@ -0,0 +1,312 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.IO; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Console; +using libsecondlife; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; + +namespace OpenSim.GridInterfaces.Local +{ + public class LocalAssetPlugin : IAssetPlugin + { + public LocalAssetPlugin() + { + + } + + public IAssetServer GetAssetServer() + { + return (new LocalAssetServer()); + } + } + + public class LocalAssetServer : IAssetServer + { + private IAssetReceiver _receiver; + private BlockingQueue _assetRequests; + private IObjectContainer db; + private Thread _localAssetServerThread; + + public LocalAssetServer() + { + bool yapfile; + this._assetRequests = new BlockingQueue(); + yapfile = System.IO.File.Exists("assets.yap"); + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Local Asset Server class created"); + try + { + db = Db4oFactory.OpenFile("assets.yap"); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Db4 Asset database creation"); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.MEDIUM, "Db4 Asset server :Constructor - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + if (!yapfile) + { + this.SetUpAssetDatabase(); + } + this._localAssetServerThread = new Thread(new ThreadStart(RunRequests)); + this._localAssetServerThread.IsBackground = true; + this._localAssetServerThread.Start(); + + } + + public void SetReceiver(IAssetReceiver receiver) + { + this._receiver = receiver; + } + + public void RequestAsset(LLUUID assetID, bool isTexture) + { + ARequest req = new ARequest(); + req.AssetID = assetID; + req.IsTexture = isTexture; + this._assetRequests.Enqueue(req); + } + + public void UpdateAsset(AssetBase asset) + { + + } + + public void UploadNewAsset(AssetBase asset) + { + AssetStorage store = new AssetStorage(); + store.Data = asset.Data; + store.Name = asset.Name; + store.UUID = asset.FullID; + db.Set(store); + db.Commit(); + } + + public void SetServerInfo(string ServerUrl, string ServerKey) + { + + } + public void Close() + { + if (db != null) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Closing local asset server database"); + db.Close(); + } + } + + private void RunRequests() + { + while (true) + { + byte[] idata = null; + bool found = false; + AssetStorage foundAsset = null; + ARequest req = this._assetRequests.Dequeue(); + IObjectSet result = db.Query(new AssetUUIDQuery(req.AssetID)); + if (result.Count > 0) + { + foundAsset = (AssetStorage)result.Next(); + found = true; + } + + AssetBase asset = new AssetBase(); + if (found) + { + asset.FullID = foundAsset.UUID; + asset.Type = foundAsset.Type; + asset.InvType = foundAsset.Type; + asset.Name = foundAsset.Name; + idata = foundAsset.Data; + } + else + { + asset.FullID = LLUUID.Zero; + } + asset.Data = idata; + _receiver.AssetReceived(asset, req.IsTexture); + } + + } + + private void SetUpAssetDatabase() + { + try + { + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "Setting up asset database"); + + AssetBase Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000001"); + Image.Name = "Bricks"; + this.LoadAsset(Image, true, "bricks.jp2"); + AssetStorage store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000002"); + Image.Name = "Plywood"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000003"); + Image.Name = "Rocks"; + this.LoadAsset(Image, true, "rocks.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000004"); + Image.Name = "Granite"; + this.LoadAsset(Image, true, "granite.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000005"); + Image.Name = "Hardwood"; + this.LoadAsset(Image, true, "hardwood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-5005-000000000005"); + Image.Name = "Prim Base Texture"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000006"); + Image.Name = "Map Base Texture"; + this.LoadAsset(Image, true, "map_base.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000007"); + Image.Name = "Map Texture"; + this.LoadAsset(Image, true, "map1.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73"); + Image.Name = "Shape"; + this.LoadAsset(Image, false, "base_shape.dat"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + } + + private void LoadAsset(AssetBase info, bool image, string filename) + { + //should request Asset from storage manager + //but for now read from file + + string dataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "assets"); //+ folder; + string fileName = Path.Combine(dataPath, filename); + FileInfo fInfo = new FileInfo(fileName); + long numBytes = fInfo.Length; + FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + byte[] idata = new byte[numBytes]; + BinaryReader br = new BinaryReader(fStream); + idata = br.ReadBytes((int)numBytes); + br.Close(); + fStream.Close(); + info.Data = idata; + //info.loaded=true; + } + } + public class AssetUUIDQuery : Predicate + { + private LLUUID _findID; + + public AssetUUIDQuery(LLUUID find) + { + _findID = find; + } + public bool Match(AssetStorage asset) + { + return (asset.UUID == _findID); + } + } + +} diff --git a/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj b/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj new file mode 100644 index 0000000..484a205 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj @@ -0,0 +1,107 @@ + + + Local + 8.0.50727 + 2.0 + {241A8CDD-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.GridInterfaces.Local + JScript + Grid + IE50 + false + Library + + OpenSim.Region.GridInterfaces.Local + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj.user b/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Local/OpenSim.Region.GridInterfaces.Local.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs b/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs new file mode 100644 index 0000000..51596d0 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("RemoteGridServers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RemoteGridServers")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj b/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj new file mode 100644 index 0000000..793fde2 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj @@ -0,0 +1,107 @@ + + + Local + 8.0.50727 + 2.0 + {98C7B681-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.GridInterfaces.Remote + JScript + Grid + IE50 + false + Library + + OpenSim.Region.GridInterfaces.Remote + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj.user b/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Remote/OpenSim.Region.GridInterfaces.Remote.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs b/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs new file mode 100644 index 0000000..ca01c68 --- /dev/null +++ b/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs @@ -0,0 +1,135 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.IO; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.GridInterfaces.Remote +{ + public class RemoteAssetServer : IAssetServer + { + private IAssetReceiver _receiver; + private BlockingQueue _assetRequests; + private Thread _remoteAssetServerThread; + private string AssetServerUrl; + private string AssetSendKey; + + public RemoteAssetServer() + { + this._assetRequests = new BlockingQueue(); + this._remoteAssetServerThread = new Thread(new ThreadStart(RunRequests)); + this._remoteAssetServerThread.IsBackground = true; + this._remoteAssetServerThread.Start(); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Remote Asset Server class created"); + } + + public void SetReceiver(IAssetReceiver receiver) + { + this._receiver = receiver; + } + + public void RequestAsset(LLUUID assetID, bool isTexture) + { + ARequest req = new ARequest(); + req.AssetID = assetID; + req.IsTexture = isTexture; + this._assetRequests.Enqueue(req); + } + + public void UpdateAsset(AssetBase asset) + { + + } + + public void UploadNewAsset(AssetBase asset) + { + Encoding Windows1252Encoding = Encoding.GetEncoding(1252); + string ret = Windows1252Encoding.GetString(asset.Data); + byte[] buffer = Windows1252Encoding.GetBytes(ret); + WebClient client = new WebClient(); + client.UploadData(this.AssetServerUrl + "assets/" + asset.FullID, buffer); + + } + + public void SetServerInfo(string ServerUrl, string ServerKey) + { + this.AssetServerUrl = ServerUrl; + this.AssetSendKey = ServerKey; + } + + private void RunRequests() + { + while (true) + { + //we need to add support for the asset server not knowing about a requested asset + // 404... THE MAGIC FILE NOT FOUND ERROR, very useful for telling you things such as a file (or asset ;) ) not being found!!!!!!!!!!! it's 2:22AM + ARequest req = this._assetRequests.Dequeue(); + LLUUID assetID = req.AssetID; + // OpenSim.Framework.Console.MainLog.Instance.Verbose(" RemoteAssetServer- Got a AssetServer request, processing it - " + this.AssetServerUrl + "assets/" + assetID); + WebRequest AssetLoad = WebRequest.Create(this.AssetServerUrl + "assets/" + assetID); + WebResponse AssetResponse = AssetLoad.GetResponse(); + byte[] idata = new byte[(int)AssetResponse.ContentLength]; + BinaryReader br = new BinaryReader(AssetResponse.GetResponseStream()); + idata = br.ReadBytes((int)AssetResponse.ContentLength); + br.Close(); + + AssetBase asset = new AssetBase(); + asset.FullID = assetID; + asset.Data = idata; + _receiver.AssetReceived(asset, req.IsTexture); + } + } + + public void Close() + { + + } + } + + public class RemoteAssetPlugin : IAssetPlugin + { + public RemoteAssetPlugin() + { + + } + + public IAssetServer GetAssetServer() + { + return (new RemoteAssetServer()); + } + } + +} diff --git a/OpenSim/Region/LocalCommunications/CommunicationsLocal.cs b/OpenSim/Region/LocalCommunications/CommunicationsLocal.cs new file mode 100644 index 0000000..743b9b4 --- /dev/null +++ b/OpenSim/Region/LocalCommunications/CommunicationsLocal.cs @@ -0,0 +1,61 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenGrid.Framework.Communications; + + +namespace OpenSim.LocalCommunications +{ + public class CommunicationsLocal : CommunicationsManager + { + public LocalBackEndServices SandBoxServices = new LocalBackEndServices(); + public LocalUserServices UserServices; + + public CommunicationsLocal(NetworkServersInfo serversInfo) + : base(serversInfo) + { + UserServices = new LocalUserServices(this , serversInfo.DefaultHomeLocX, serversInfo.DefaultHomeLocY); + UserServices.AddPlugin("OpenGrid.Framework.Data.DB4o.dll"); + UserServer = UserServices; + GridServer = SandBoxServices; + InterRegion = SandBoxServices; + } + + internal void InformRegionOfLogin(ulong regionHandle, Login login) + { + this.SandBoxServices.AddNewSession(regionHandle, login); + } + } +} diff --git a/OpenSim/Region/LocalCommunications/LocalBackEndServices.cs b/OpenSim/Region/LocalCommunications/LocalBackEndServices.cs new file mode 100644 index 0000000..ce48c6e --- /dev/null +++ b/OpenSim/Region/LocalCommunications/LocalBackEndServices.cs @@ -0,0 +1,209 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Communications; +using libsecondlife; +using OpenSim.Framework.Types; +using OpenSim.Framework; + +namespace OpenSim.LocalCommunications +{ + + public class LocalBackEndServices : IGridServices, IInterRegionCommunications + { + protected Dictionary regions = new Dictionary(); + protected Dictionary regionHosts = new Dictionary(); + + public LocalBackEndServices() + { + + } + + /// + /// Register a region method with the BackEnd Services. + /// + /// + /// + public RegionCommsListener RegisterRegion(RegionInfo regionInfo, GridInfo gridInfo) + { + //Console.WriteLine("CommsManager - Region " + regionInfo.RegionHandle + " , " + regionInfo.RegionLocX + " , "+ regionInfo.RegionLocY +" is registering"); + if (!this.regions.ContainsKey((uint)regionInfo.RegionHandle)) + { + //Console.WriteLine("CommsManager - Adding Region " + regionInfo.RegionHandle ); + this.regions.Add(regionInfo.RegionHandle, regionInfo); + RegionCommsListener regionHost = new RegionCommsListener(); + this.regionHosts.Add(regionInfo.RegionHandle, regionHost); + + return regionHost; + } + + //already in our list of regions so for now lets return null + return null; + } + + /// + /// + /// + /// + public List RequestNeighbours(RegionInfo regionInfo) + { + // Console.WriteLine("Finding Neighbours to " + regionInfo.RegionHandle); + List neighbours = new List(); + + foreach (RegionInfo reg in this.regions.Values) + { + // Console.WriteLine("CommsManager- RequestNeighbours() checking region " + reg.RegionLocX + " , "+ reg.RegionLocY); + if (reg.RegionHandle != regionInfo.RegionHandle) + { + //Console.WriteLine("CommsManager- RequestNeighbours() - found a different region in list, checking location"); + if ((reg.RegionLocX > (regionInfo.RegionLocX - 2)) && (reg.RegionLocX < (regionInfo.RegionLocX + 2))) + { + if ((reg.RegionLocY > (regionInfo.RegionLocY - 2)) && (reg.RegionLocY < (regionInfo.RegionLocY + 2))) + { + neighbours.Add(reg); + } + } + } + } + return neighbours; + } + + /// + /// + /// + /// + /// + public RegionInfo RequestNeighbourInfo(ulong regionHandle) + { + if (this.regions.ContainsKey(regionHandle)) + { + return this.regions[regionHandle]; + } + return null; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) + { + List mapBlocks = new List(); + foreach(RegionInfo regInfo in this.regions.Values) + { + if (((regInfo.RegionLocX >= minX) && (regInfo.RegionLocX <= maxX)) && ((regInfo.RegionLocY >= minY) && (regInfo.RegionLocY <= maxY))) + { + MapBlockData map = new MapBlockData(); + map.Name = regInfo.RegionName; + map.X = (ushort)regInfo.RegionLocX; + map.Y = (ushort)regInfo.RegionLocY; + map.WaterHeight =(byte) regInfo.estateSettings.waterHeight; + map.MapImageId = regInfo.estateSettings.terrainImageID; //new LLUUID("00000000-0000-0000-9999-000000000007"); + map.Agents = 1; + map.RegionFlags = 72458694; + map.Access = 13; + mapBlocks.Add(map); + } + } + return mapBlocks; + } + + /// + /// + /// + /// + /// + public bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData) //should change from agentCircuitData + { + //Console.WriteLine("CommsManager- Trying to Inform a region to expect child agent"); + if (this.regionHosts.ContainsKey(regionHandle)) + { + // Console.WriteLine("CommsManager- Informing a region to expect child agent"); + this.regionHosts[regionHandle].TriggerExpectUser(regionHandle, agentData); + return true; + } + return false; + } + + /// + /// + /// + /// + /// + /// + /// + public bool ExpectAvatarCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (this.regionHosts.ContainsKey(regionHandle)) + { + // Console.WriteLine("CommsManager- Informing a region to expect avatar crossing"); + this.regionHosts[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); + return true; + } + return false; + } + + /// + /// Is a Sandbox mode method, used by the local Login server to inform a region of a connection user/session + /// + /// + /// + /// + public bool AddNewSession(ulong regionHandle, Login loginData) + { + //Console.WriteLine(" comms manager been told to expect new user"); + AgentCircuitData agent = new AgentCircuitData(); + agent.AgentID = loginData.Agent; + agent.firstname = loginData.First; + agent.lastname = loginData.Last; + agent.SessionID = loginData.Session; + agent.SecureSessionID = loginData.SecureSession; + agent.circuitcode = loginData.CircuitCode; + agent.BaseFolder = loginData.BaseFolder; + agent.InventoryFolder = loginData.InventoryFolder; + agent.startpos = new LLVector3(128, 128, 70); + agent.CapsPath = loginData.CapsPath; + + if (this.regionHosts.ContainsKey(regionHandle)) + { + this.regionHosts[regionHandle].TriggerExpectUser(regionHandle, agent); + return true; + } + + // region not found + return false; + } + } +} + diff --git a/OpenSim/Region/LocalCommunications/LocalUserServices.cs b/OpenSim/Region/LocalCommunications/LocalUserServices.cs new file mode 100644 index 0000000..a7f7aa4 --- /dev/null +++ b/OpenSim/Region/LocalCommunications/LocalUserServices.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +using OpenGrid.Framework.Communications; +//using OpenSim.Framework.User; +using OpenGrid.Framework.UserManagement; +using OpenGrid.Framework.Data; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +using libsecondlife; + +namespace OpenSim.LocalCommunications +{ + public class LocalUserServices : UserManagerBase, IUserServices + { + private CommunicationsLocal m_Parent; + + private uint defaultHomeX ; + private uint defaultHomeY; + public LocalUserServices(CommunicationsLocal parent, uint defHomeX, uint defHomeY) + { + m_Parent = parent; + defaultHomeX = defHomeX; + defaultHomeY = defHomeY; + } + + public UserProfileData GetUserProfile(string firstName, string lastName) + { + return GetUserProfile(firstName + " " + lastName); + } + + public UserProfileData GetUserProfile(string name) + { + return this.getUserProfile(name); + } + public UserProfileData GetUserProfile(LLUUID avatarID) + { + return this.getUserProfile(avatarID); + } + + /// + /// + /// + /// + public override string GetMessage() + { + return "Welcome to OpenSim"; + } + + public override UserProfileData GetTheUser(string firstname, string lastname) + { + UserProfileData profile = getUserProfile(firstname, lastname); + if (profile != null) + { + + return profile; + } + + //no current user account so make one + Console.WriteLine("No User account found so creating a new one "); + this.AddUserProfile(firstname, lastname, "test", defaultHomeX, defaultHomeY); + + profile = getUserProfile(firstname, lastname); + + return profile; + } + + public override bool AuthenticateUser(ref UserProfileData profile, string password) + { + //for now we will accept any password in sandbox mode + Console.WriteLine("authorising user"); + return true; + } + + public override void CustomiseResponse(ref LoginResponse response, ref UserProfileData theUser) + { + ulong currentRegion = theUser.currentAgent.currentHandle; + RegionInfo reg = m_Parent.GridServer.RequestNeighbourInfo(currentRegion); + + + if (reg != null) + { + response.Home = "{'region_handle':[r" + (reg.RegionLocX * 256).ToString() + ",r" + (reg.RegionLocY * 256).ToString() + "], " + + "'position':[r" + theUser.homeLocation.X.ToString() + ",r" + theUser.homeLocation.Y.ToString() + ",r" + theUser.homeLocation.Z.ToString() + "], " + + "'look_at':[r" + theUser.homeLocation.X.ToString() + ",r" + theUser.homeLocation.Y.ToString() + ",r" + theUser.homeLocation.Z.ToString() + "]}"; + string capsPath = Util.GetRandomCapsPath(); + response.SimAddress = reg.CommsIPListenAddr; + response.SimPort = (Int32)reg.CommsIPListenPort; + response.RegionX = reg.RegionLocX ; + response.RegionY = reg.RegionLocY ; + response.SeedCapability = "http://" + reg.CommsIPListenAddr + ":" + "9000" + "/CAPS/" + capsPath + "0000/"; + theUser.currentAgent.currentRegion = reg.SimUUID; + theUser.currentAgent.currentHandle = reg.RegionHandle; + + Login _login = new Login(); + //copy data to login object + _login.First = response.Firstname; + _login.Last = response.Lastname; + _login.Agent = response.AgentID; + _login.Session = response.SessionID; + _login.SecureSession = response.SecureSessionID; + _login.CircuitCode = (uint)response.CircuitCode; + _login.CapsPath = capsPath; + + m_Parent.InformRegionOfLogin(currentRegion, _login); + } + else + { + Console.WriteLine("not found region " + currentRegion); + } + + } + + } +} diff --git a/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj b/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj new file mode 100644 index 0000000..6b2b78c --- /dev/null +++ b/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj @@ -0,0 +1,121 @@ + + + Local + 8.0.50727 + 2.0 + {EB3A1BA8-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.LocalCommunications + JScript + Grid + IE50 + false + Library + + OpenSim.Region.LocalCommunications + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications + {CB52B7E7-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Data + {36B72A9B-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.UserManagement + {586E2916-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj.user b/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/LocalCommunications/OpenSim.Region.LocalCommunications.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/LocalCommunications/Properties/AssemblyInfo.cs b/OpenSim/Region/LocalCommunications/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8e6e711 --- /dev/null +++ b/OpenSim/Region/LocalCommunications/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.LocalCommunications")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.LocalCommunications")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("fb173926-bd0a-4cd0-bb45-185b2f72ddfb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs new file mode 100644 index 0000000..177c49d --- /dev/null +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("PhysXplugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PhysXplugin")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs new file mode 100644 index 0000000..dcb8f3b --- /dev/null +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs @@ -0,0 +1,294 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Physics.Manager; + +namespace OpenSim.Region.Physics.BasicPhysicsPlugin +{ + /// + /// Will be the PhysX plugin but for now will be a very basic physics engine + /// + public class BasicPhysicsPlugin : IPhysicsPlugin + { + private BasicScene _mScene; + + public BasicPhysicsPlugin() + { + + } + + public bool Init() + { + return true; + } + + public PhysicsScene GetScene() + { + return new BasicScene(); + } + + public string GetName() + { + return("basicphysics"); + } + + public void Dispose() + { + + } + } + + public class BasicScene :PhysicsScene + { + private List _actors = new List(); + private float[] _heightMap; + + public BasicScene() + { + + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + BasicActor act = new BasicActor(); + act.Position = position; + _actors.Add(act); + return act; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + BasicActor act = (BasicActor)actor; + if(_actors.Contains(act)) + { + _actors.Remove(act); + } + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + return null; + } + + public override void Simulate(float timeStep) + { + foreach (BasicActor actor in _actors) + { + actor.Position.X = actor.Position.X + (actor.Velocity.X * timeStep); + actor.Position.Y = actor.Position.Y + (actor.Velocity.Y * timeStep); + actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); + /*if(actor.Flying) + { + actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); + } + else + { + actor.Position.Z = actor.Position.Z + ((-9.8f + actor.Velocity.Z) * timeStep); + } + if(actor.Position.Z < (_heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X]+1)) + {*/ + if ((actor.Position.Y > 0 && actor.Position.Y < 256) && (actor.Position.X > 0 && actor.Position.X < 256)) + { + actor.Position.Z = _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 1; + } + else + { + if (actor.Position.Y < 0) + { + actor.Position.Y = 0; + } + else if (actor.Position.Y > 256) + { + actor.Position.Y = 256; + } + + if (actor.Position.X < 0) + { + actor.Position.X = 0; + } + if (actor.Position.X > 256) + { + actor.Position.X = 256; + } + } + //} + + + + // This code needs sorting out - border crossings etc +/* if(actor.Position.X<0) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.X = 0; + actor.Velocity.X = 0; + } + if(actor.Position.Y < 0) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.Y = 0; + actor.Velocity.Y = 0; + } + if(actor.Position.X > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.X = 255; + actor.Velocity.X = 0; + } + if(actor.Position.Y > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.Y = 255; + actor.Velocity.X = 0; + }*/ + } + } + + public override void GetResults() + { + + } + + public override bool IsThreaded + { + get + { + return(false); // for now we won't be multithreaded + } + } + + public override void SetTerrain(float[] heightMap) + { + this._heightMap = heightMap; + } + + public override void DeleteTerrain() + { + + } + } + + public class BasicActor : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private bool flying; + public BasicActor() + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + } + + public override bool Flying + { + get + { + return false; + } + set + { + flying= value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + + public override bool Kinematic + { + get + { + return true; + } + set + { + + } + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + } + +} diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj b/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj new file mode 100644 index 0000000..7dad533 --- /dev/null +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj @@ -0,0 +1,93 @@ + + + Local + 8.0.50727 + 2.0 + {15B4FEF3-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Physics.BasicPhysicsPlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Physics.BasicPhysicsPlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Axiom.MathLib.dll + False + + + System.dll + False + + + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj.user b/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/OpenSim.Region.Physics.BasicPhysicsPlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs new file mode 100644 index 0000000..132f64a --- /dev/null +++ b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("PhysicsManager")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PhysicsManager")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj b/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj new file mode 100644 index 0000000..f340400 --- /dev/null +++ b/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {F4FF31EB-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Physics.Manager + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Physics.Manager + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Axiom.MathLib.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj.user b/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Physics/Manager/OpenSim.Region.Physics.Manager.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs new file mode 100644 index 0000000..6366fb8 --- /dev/null +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -0,0 +1,161 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Physics.Manager +{ + public abstract class PhysicsActor + { + public static PhysicsActor Null + { + get + { + return new NullPhysicsActor(); + } + } + + public abstract PhysicsVector Position + { + get; + set; + } + + public abstract PhysicsVector Velocity + { + get; + set; + } + + public abstract PhysicsVector Acceleration + { + get; + } + + public abstract Axiom.MathLib.Quaternion Orientation + { + get; + set; + } + + public abstract bool Flying + { + get; + set; + } + + public abstract bool Kinematic + { + get; + set; + } + + public abstract void AddForce(PhysicsVector force); + + public abstract void SetMomentum(PhysicsVector momentum); + } + + public class NullPhysicsActor : PhysicsActor + { + public override PhysicsVector Position + { + get + { + return PhysicsVector.Zero; + } + set + { + return; + } + } + + public override PhysicsVector Velocity + { + get + { + return PhysicsVector.Zero; + } + set + { + return; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get { return PhysicsVector.Zero; } + } + + public override bool Flying + { + get + { + return false; + } + set + { + return; + } + } + + public override bool Kinematic + { + get + { + return true; + } + set + { + return; + } + } + + public override void AddForce(PhysicsVector force) + { + return; + } + + public override void SetMomentum(PhysicsVector momentum) + { + return; + } + } +} diff --git a/OpenSim/Region/Physics/Manager/PhysicsManager.cs b/OpenSim/Region/Physics/Manager/PhysicsManager.cs new file mode 100644 index 0000000..efccb36 --- /dev/null +++ b/OpenSim/Region/Physics/Manager/PhysicsManager.cs @@ -0,0 +1,117 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System.Reflection; +using Axiom.MathLib; +using OpenSim.Framework.Console; + +namespace OpenSim.Physics.Manager +{ + /// + /// Description of MyClass. + /// + public class PhysicsManager + { + private Dictionary _plugins=new Dictionary(); + + public PhysicsManager() + { + + } + + public PhysicsScene GetPhysicsScene(string engineName) + { + if (String.IsNullOrEmpty(engineName)) + { + return new NullPhysicsScene(); + } + + if(_plugins.ContainsKey(engineName)) + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.LOW,"creating "+engineName); + return _plugins[engineName].GetScene(); + } + else + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(LogPriority.MEDIUM,"couldn't find physicsEngine: {0}",engineName); + throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}",engineName)); + } + } + + public void LoadPlugins() + { + string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory ,"Physics"); + string[] pluginFiles = Directory.GetFiles(path, "*.dll"); + + + for(int i= 0; i + /// ODE plugin + /// + public class OdePlugin : IPhysicsPlugin + { + private OdeScene _mScene; + + public OdePlugin() + { + + } + + public bool Init() + { + return true; + } + + public PhysicsScene GetScene() + { + if (_mScene == null) + { + _mScene = new OdeScene(); + } + return (_mScene); + } + + public string GetName() + { + return ("OpenDynamicsEngine"); + } + + public void Dispose() + { + + } + } + + public class OdeScene : PhysicsScene + { + static public IntPtr world; + static public IntPtr space; + static private IntPtr contactgroup; + static private IntPtr LandGeom; + //static private IntPtr Land; + private double[] _heightmap; + static private d.NearCallback nearCallback = near; + private List _characters = new List(); + private static d.ContactGeom[] contacts = new d.ContactGeom[30]; + private static d.Contact contact; + + public OdeScene() + { + contact.surface.mode = d.ContactFlags.Bounce | d.ContactFlags.SoftCFM; + contact.surface.mu = d.Infinity; + contact.surface.mu2 = 0.0f; + contact.surface.bounce = 0.1f; + contact.surface.bounce_vel = 0.1f; + contact.surface.soft_cfm = 0.01f; + + world = d.WorldCreate(); + space = d.HashSpaceCreate(IntPtr.Zero); + contactgroup = d.JointGroupCreate(0); + d.WorldSetGravity(world, 0.0f, 0.0f, -0.5f); + //d.WorldSetCFM(world, 1e-5f); + d.WorldSetAutoDisableFlag(world, false); + d.WorldSetContactSurfaceLayer(world, 0.001f); + // d.CreatePlane(space, 0, 0, 1, 0); + this._heightmap = new double[65536]; + } + + // This function blatantly ripped off from BoxStack.cs + static private void near(IntPtr space, IntPtr g1, IntPtr g2) + { + IntPtr b1 = d.GeomGetBody(g1); + IntPtr b2 = d.GeomGetBody(g2); + if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact)) + return; + + int count = d.Collide(g1, g2, 500, contacts, d.ContactGeom.SizeOf); + for (int i = 0; i < count; ++i) + { + contact.geom = contacts[i]; + IntPtr joint = d.JointCreateContact(world, contactgroup, ref contact); + d.JointAttach(joint, b1, b2); + } + + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + PhysicsVector pos = new PhysicsVector(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z + 20; + OdeCharacter newAv = new OdeCharacter(this, pos); + this._characters.Add(newAv); + return newAv; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + PhysicsVector pos = new PhysicsVector(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z; + PhysicsVector siz = new PhysicsVector(); + siz.X = size.X; + siz.Y = size.Y; + siz.Z = size.Z; + return new OdePrim(); + } + + public override void Simulate(float timeStep) + { + foreach (OdeCharacter actor in _characters) + { + actor.Move(timeStep * 5f); + } + d.SpaceCollide(space, IntPtr.Zero, nearCallback); + d.WorldQuickStep(world, timeStep * 5f); + d.JointGroupEmpty(contactgroup); + foreach (OdeCharacter actor in _characters) + { + actor.UpdatePosition(); + } + + } + + public override void GetResults() + { + + } + + public override bool IsThreaded + { + get + { + return (false); // for now we won't be multithreaded + } + } + + public override void SetTerrain(float[] heightMap) + { + for (int i = 0; i < 65536; i++) + { + // this._heightmap[i] = (double)heightMap[i]; + // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...) + int x = i & 0xff; + int y = i >> 8; + this._heightmap[i] = (double)heightMap[x * 256 + y]; + } + IntPtr HeightmapData = d.GeomHeightfieldDataCreate(); + d.GeomHeightfieldDataBuildDouble(HeightmapData, _heightmap, 0, 256, 256, 256, 256, 1.0f, 0.0f, 2.0f, 0); + d.GeomHeightfieldDataSetBounds(HeightmapData, 256, 256); + LandGeom = d.CreateHeightfield(space, HeightmapData, 1); + d.Matrix3 R = new d.Matrix3(); + + Axiom.MathLib.Quaternion q1 =Axiom.MathLib.Quaternion.FromAngleAxis(1.5707f, new Axiom.MathLib.Vector3(1,0,0)); + Axiom.MathLib.Quaternion q2 =Axiom.MathLib.Quaternion.FromAngleAxis(1.5707f, new Axiom.MathLib.Vector3(0,1,0)); + //Axiom.MathLib.Quaternion q3 = Axiom.MathLib.Quaternion.FromAngleAxis(3.14f, new Axiom.MathLib.Vector3(0, 0, 1)); + + q1 = q1 * q2; + //q1 = q1 * q3; + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(); + float angle = 0; + q1.ToAngleAxis(ref angle, ref v3); + + d.RFromAxisAndAngle(out R, v3.x, v3.y, v3.z, angle); + d.GeomSetRotation(LandGeom, ref R); + d.GeomSetPosition(LandGeom, 128, 128, 0); + } + + public override void DeleteTerrain() + { + + } + } + + public class OdeCharacter : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private bool flying; + //private float gravityAccel; + private IntPtr BoundingCapsule; + IntPtr capsule_geom; + d.Mass capsule_mass; + + public OdeCharacter(OdeScene parent_scene, PhysicsVector pos) + { + _velocity = new PhysicsVector(); + _position = pos; + _acceleration = new PhysicsVector(); + d.MassSetCapsule(out capsule_mass, 5.0f, 3, 0.5f, 2f); + capsule_geom = d.CreateCapsule(OdeScene.space, 0.5f, 2f); + this.BoundingCapsule = d.BodyCreate(OdeScene.world); + d.BodySetMass(BoundingCapsule, ref capsule_mass); + d.BodySetPosition(BoundingCapsule, pos.X, pos.Y, pos.Z); + d.GeomSetBody(capsule_geom, BoundingCapsule); + } + + public override bool Flying + { + get + { + return flying; + } + set + { + flying = value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + } + set + { + + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration(PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + public void Move(float timeStep) + { + PhysicsVector vec = new PhysicsVector(); + vec.X = this._velocity.X * timeStep; + vec.Y = this._velocity.Y * timeStep; + if (flying) + { + vec.Z = (this._velocity.Z + 0.5f) * timeStep; + } + d.BodySetLinearVel(this.BoundingCapsule, vec.X, vec.Y, vec.Z); + } + + public void UpdatePosition() + { + d.Vector3 vec = d.BodyGetPosition(BoundingCapsule); + this._position.X = vec.X; + this._position.Y = vec.Y; + this._position.Z = vec.Z+1.0f; + } + } + + public class OdePrim : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + + public OdePrim() + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + } + public override bool Flying + { + get + { + return false; //no flying prims for you + } + set + { + + } + } + public override PhysicsVector Position + { + get + { + PhysicsVector pos = new PhysicsVector(); + // PhysicsVector vec = this._prim.Position; + //pos.X = vec.X; + //pos.Y = vec.Y; + //pos.Z = vec.Z; + return pos; + + } + set + { + /*PhysicsVector vec = value; + PhysicsVector pos = new PhysicsVector(); + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + this._prim.Position = pos;*/ + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + //return this._prim.Kinematic; + } + set + { + //this._prim.Kinematic = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + Axiom.MathLib.Quaternion res = new Axiom.MathLib.Quaternion(); + return res; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration(PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + + } + +} diff --git a/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj b/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj new file mode 100644 index 0000000..490c681 --- /dev/null +++ b/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj @@ -0,0 +1,97 @@ + + + Local + 8.0.50727 + 2.0 + {90620634-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Physics.OdePlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Physics.OdePlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Axiom.MathLib.dll + False + + + ..\..\..\..\bin\Ode.NET.dll + False + + + System.dll + False + + + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj.user b/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Physics/OdePlugin/OpenSim.Region.Physics.OdePlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs new file mode 100644 index 0000000..b49c8da --- /dev/null +++ b/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("RealPhysXplugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RealPhysXplugin")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj b/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj new file mode 100644 index 0000000..77da908 --- /dev/null +++ b/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj @@ -0,0 +1,97 @@ + + + Local + 8.0.50727 + 2.0 + {A6D191D8-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Physics.PhysXPlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Physics.PhysXPlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\Physics\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Axiom.MathLib.dll + False + + + ..\..\..\..\bin\PhysX_Wrapper_Dotnet.dll + False + + + System.dll + False + + + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj.user b/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Physics/PhysXPlugin/OpenSim.Region.Physics.PhysXPlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs b/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs new file mode 100644 index 0000000..8bf794b --- /dev/null +++ b/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs @@ -0,0 +1,424 @@ +/*/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Physics.Manager; +using PhysXWrapper; + +namespace OpenSim.Region.Physics.PhysXPlugin +{ + /// + /// Will be the PhysX plugin but for now will be a very basic physics engine + /// + public class PhysXPlugin : IPhysicsPlugin + { + private PhysXScene _mScene; + + public PhysXPlugin() + { + + } + + public bool Init() + { + return true; + } + + public PhysicsScene GetScene() + { + if(_mScene == null) + { + _mScene = new PhysXScene(); + } + return(_mScene); + } + + public string GetName() + { + return("RealPhysX"); + } + + public void Dispose() + { + + } + } + + public class PhysXScene :PhysicsScene + { + private List _characters = new List(); + private List _prims = new List(); + private float[] _heightMap = null; + private NxPhysicsSDK mySdk; + private NxScene scene; + + public PhysXScene() + { + mySdk = NxPhysicsSDK.CreateSDK(); + Console.WriteLine("Sdk created - now creating scene"); + scene = mySdk.CreateScene(); + + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + Vec3 pos = new Vec3(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z; + PhysXCharacter act = new PhysXCharacter( scene.AddCharacter(pos)); + act.Position = position; + _characters.Add(act); + return act; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + Vec3 pos = new Vec3(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z; + Vec3 siz = new Vec3(); + siz.X = size.X; + siz.Y = size.Y; + siz.Z = size.Z; + PhysXPrim act = new PhysXPrim( scene.AddNewBox(pos, siz)); + _prims.Add(act); + return act; + } + public override void Simulate(float timeStep) + { + try + { + foreach (PhysXCharacter actor in _characters) + { + actor.Move(timeStep); + } + scene.Simulate(timeStep); + scene.FetchResults(); + scene.UpdateControllers(); + + foreach (PhysXCharacter actor in _characters) + { + actor.UpdatePosition(); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + } + + public override void GetResults() + { + + } + + public override bool IsThreaded + { + get + { + return(false); // for now we won't be multithreaded + } + } + + public override void SetTerrain(float[] heightMap) + { + if (this._heightMap != null) + { + Console.WriteLine("PhysX - deleting old terrain"); + this.scene.DeleteTerrain(); + } + this._heightMap = heightMap; + this.scene.AddTerrain(heightMap); + } + + public override void DeleteTerrain() + { + this.scene.DeleteTerrain(); + } + } + + public class PhysXCharacter : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private NxCharacter _character; + private bool flying; + private float gravityAccel; + + public PhysXCharacter(NxCharacter character) + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + _character = character; + } + + public override bool Flying + { + get + { + return flying; + } + set + { + flying = value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + Vec3 ps = new Vec3(); + ps.X = value.X; + ps.Y = value.Y; + ps.Z = value.Z; + this._character.Position = ps; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + } + set + { + + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + public void Move(float timeStep) + { + Vec3 vec = new Vec3(); + vec.X = this._velocity.X * timeStep; + vec.Y = this._velocity.Y * timeStep; + if(flying) + { + vec.Z = ( this._velocity.Z) * timeStep; + } + else + { + gravityAccel+= -9.8f; + vec.Z = (gravityAccel + this._velocity.Z) * timeStep; + } + int res = this._character.Move(vec); + if(res == 1) + { + gravityAccel = 0; + } + } + + public void UpdatePosition() + { + Vec3 vec = this._character.Position; + this._position.X = vec.X; + this._position.Y = vec.Y; + this._position.Z = vec.Z; + } + } + + public class PhysXPrim : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private NxActor _prim; + + public PhysXPrim(NxActor prim) + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + _prim = prim; + } + public override bool Flying + { + get + { + return false; //no flying prims for you + } + set + { + + } + } + public override PhysicsVector Position + { + get + { + PhysicsVector pos = new PhysicsVector(); + Vec3 vec = this._prim.Position; + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + return pos; + + } + set + { + PhysicsVector vec = value; + Vec3 pos = new Vec3(); + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + this._prim.Position = pos; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return this._prim.Kinematic; + } + set + { + this._prim.Kinematic = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + Axiom.MathLib.Quaternion res = new Axiom.MathLib.Quaternion(); + PhysXWrapper.Quaternion quat = this._prim.GetOrientation(); + res.w = quat.W; + res.x = quat.X; + res.y = quat.Y; + res.z = quat.Z; + return res; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + + } + +} diff --git a/OpenSim/Region/Scripting/Properties/AssemblyInfo.cs b/OpenSim/Region/Scripting/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f5da4c0 --- /dev/null +++ b/OpenSim/Region/Scripting/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Scripting")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Scripting")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("61eae1ad-82aa-4c77-8bc5-b5a8c9522b18")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Scripting/Script.cs b/OpenSim/Region/Scripting/Script.cs new file mode 100644 index 0000000..0f4af00 --- /dev/null +++ b/OpenSim/Region/Scripting/Script.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using OpenSim.Framework.Console; +using OpenSim.Framework; +using OpenSim.Region; +using OpenSim.Region.Scenes; + +namespace OpenSim.Scripting +{ + public interface IScript + { + void Initialise(ScriptInfo scriptInfo); + } + + public class TestScript : IScript + { + ScriptInfo script; + + public void Initialise(ScriptInfo scriptInfo) + { + script = scriptInfo; + script.events.OnFrame += new OpenSim.Region.Scenes.EventManager.OnFrameDelegate(events_OnFrame); + } + + void events_OnFrame() + { + script.logger.Verbose("Hello World!"); + } + } +} diff --git a/OpenSim/Region/Scripting/ScriptAccess.cs b/OpenSim/Region/Scripting/ScriptAccess.cs new file mode 100644 index 0000000..a9fede5 --- /dev/null +++ b/OpenSim/Region/Scripting/ScriptAccess.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using OpenSim.Region.Scenes; +using OpenSim.Framework.Console; + +namespace OpenSim.Scripting +{ + /// + /// Class which provides access to the world + /// + public class ScriptInfo + { + // Reference to world.eventsManager provided for convenience + public EventManager events; + + // The main world + public Scene world; + + // The console + public LogBase logger; + + public ScriptInfo(Scene scene) + { + world = scene; + events = world.eventManager; + logger = OpenSim.Framework.Console.MainLog.Instance; + } + } +} diff --git a/OpenSim/Region/Simulation/Caps.cs b/OpenSim/Region/Simulation/Caps.cs new file mode 100644 index 0000000..13a351d --- /dev/null +++ b/OpenSim/Region/Simulation/Caps.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Xml; +using OpenSim.Servers; +using OpenSim.Framework; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Types; +using OpenSim.Caches; +using libsecondlife; + +namespace OpenSim.Region +{ + public delegate void UpLoadedTexture(LLUUID assetID, LLUUID inventoryItem, byte[] data); + + public class Caps + { + private string httpListenerAddress; + private uint httpListenPort; + private string capsObjectPath = "00001-"; + private string requestPath = "0000/"; + private string mapLayerPath = "0001/"; + private string newInventory = "0002/"; + private string requestTexture = "0003/"; + private string eventQueue = "0100/"; + private BaseHttpServer httpListener; + private LLUUID agentID; + private AssetCache assetCache; + private int eventQueueCount = 1; + private Queue CapsEventQueue = new Queue(); + + public Caps(AssetCache assetCach, BaseHttpServer httpServer, string httpListen, uint httpPort, string capsPath, LLUUID agent) + { + assetCache = assetCach; + capsObjectPath = capsPath; + httpListener = httpServer; + httpListenerAddress = httpListen; + httpListenPort = httpPort; + agentID = agent; + } + + /// + /// + /// + public void RegisterHandlers() + { + Console.WriteLine("registering CAPS handlers"); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + requestPath, CapsRequest); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + mapLayerPath, MapLayer); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + newInventory, NewAgentInventory); + httpListener.AddRestHandler("POST", "/CAPS/" + capsObjectPath + eventQueue, ProcessEventQueue); + } + + /// + /// + /// + /// + /// + /// + /// + public string CapsRequest(string request, string path, string param) + { + // Console.WriteLine("Caps Request " + request); + string result = ""; + result = LLSDHelpers.SerialiseLLSDReply(this.GetCapabilities()); + return result; + } + + /// + /// + /// + /// + protected LLSDCapsDetails GetCapabilities() + { + /* string capURLS = ""; + capURLS += "MapLayerhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + mapLayerPath + ""; + capURLS += "NewFileAgentInventoryhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + newInventory + ""; + //capURLS += "RequestTextureDownloadhttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + requestTexture + ""; + //capURLS += "EventQueueGethttp://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + eventQueue + ""; + return capURLS;*/ + + LLSDCapsDetails caps = new LLSDCapsDetails(); + caps.MapLayer = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + mapLayerPath; + caps.NewFileAgentInventory = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + capsObjectPath + newInventory; + return caps; + } + + /// + /// + /// + /// + /// + /// + /// + public string MapLayer(string request, string path, string param) + { + Encoding _enc = System.Text.Encoding.UTF8; + Hashtable hash =(Hashtable) LLSD.LLSDDeserialize(_enc.GetBytes(request)); + LLSDMapRequest mapReq = new LLSDMapRequest(); + LLSDHelpers.DeserialiseLLSDMap(hash, mapReq ); + + LLSDMapLayerResponse mapResponse= new LLSDMapLayerResponse(); + mapResponse.LayerData.Array.Add(this.BuildLLSDMapLayerResponse()); + string res = LLSDHelpers.SerialiseLLSDReply(mapResponse); + + //Console.WriteLine(" Maplayer response is " + res); + + return res; + } + + /// + /// + /// + /// + protected LLSDMapLayer BuildLLSDMapLayerResponse() + { + LLSDMapLayer mapLayer = new LLSDMapLayer(); + mapLayer.Right = 5000; + mapLayer.Top = 5000; + mapLayer.ImageID = new LLUUID("00000000-0000-0000-9999-000000000006"); + + return mapLayer; + } + + public string ProcessEventQueue(string request, string path, string param) + { + // Console.WriteLine("event queue request " + request); + string res = ""; + int timer = 0; + + /*while ((timer < 200) || (this.CapsEventQueue.Count < 1)) + { + timer++; + }*/ + if (this.CapsEventQueue.Count > 0) + { + lock (this.CapsEventQueue) + { + string item = CapsEventQueue.Dequeue(); + res = item; + } + } + else + { + res = this.CreateEmptyEventResponse(); + } + return res; + } + + public string CreateEstablishAgentComms(string caps, string ipAddressPort) + { + string res = "id" + eventQueueCount + ""; + res += "events"; + res += "messageEstablishAgentCommunication"; + res += "body"; + res += "sim-ip-and-port" + ipAddressPort + ""; + res += "seed-capability" + caps + ""; + res += "agent-id" + this.agentID.ToStringHyphenated() + ""; + res += ""; + res += ""; + res += ""; + eventQueueCount++; + this.CapsEventQueue.Enqueue(res); + return res; + } + + public string CreateEmptyEventResponse() + { + string res = "id" + eventQueueCount + ""; + res += "events"; + res += ""; + res += ""; + eventQueueCount++; + return res; + } + + public string NewAgentInventory(string request, string path, string param) + { + //Console.WriteLine("received upload request:"+ request); + string res = ""; + LLUUID newAsset = LLUUID.Random(); + LLUUID newInvItem = LLUUID.Random(); + string uploaderPath = capsObjectPath + Util.RandomClass.Next(5000, 8000).ToString("0000"); + AssetUploader uploader = new AssetUploader(newAsset, newInvItem, uploaderPath, this.httpListener); + httpListener.AddRestHandler("POST", "/CAPS/" + uploaderPath, uploader.uploaderCaps); + string uploaderURL = "http://" + httpListenerAddress + ":" + httpListenPort.ToString() + "/CAPS/" + uploaderPath; + //Console.WriteLine("uploader url is " + uploaderURL); + res += ""; + res += "uploader" + uploaderURL + ""; + //res += "successtrue"; + res += "stateupload"; + res += ""; + uploader.OnUpLoad += this.UploadHandler; + return res; + } + + public void UploadHandler(LLUUID assetID, LLUUID inventoryItem, byte[] data) + { + // Console.WriteLine("upload handler called"); + AssetBase asset; + asset = new AssetBase(); + asset.FullID = assetID; + asset.Type = 0; + asset.InvType = 0; + asset.Name = "UploadedTexture" + Util.RandomClass.Next(1, 1000).ToString("000"); + asset.Data = data; + this.assetCache.AddAsset(asset); + } + + public class AssetUploader + { + public event UpLoadedTexture OnUpLoad; + + private string uploaderPath = ""; + private LLUUID newAssetID; + private LLUUID inventoryItemID; + private BaseHttpServer httpListener; + public AssetUploader(LLUUID assetID, LLUUID inventoryItem, string path, BaseHttpServer httpServer) + { + newAssetID = assetID; + inventoryItemID = inventoryItem; + uploaderPath = path; + httpListener = httpServer; + + } + + public string uploaderCaps(string request, string path, string param) + { + Encoding _enc = System.Text.Encoding.UTF8; + byte[] data = _enc.GetBytes(request); + //Console.WriteLine("recieved upload " + Util.FieldToString(data)); + LLUUID inv = this.inventoryItemID; + string res = ""; + res += ""; + res += "new_asset" + newAssetID.ToStringHyphenated() + ""; + res += "new_inventory_item" + inv.ToStringHyphenated() + ""; + res += "statecomplete"; + res += ""; + + // Console.WriteLine("asset " + newAssetID.ToStringHyphenated() + " , inventory item " + inv.ToStringHyphenated()); + httpListener.RemoveRestHandler("POST", "/CAPS/" + uploaderPath); + if (OnUpLoad != null) + { + OnUpLoad(newAssetID, inv, data); + } + + /*FileStream fs = File.Create("upload.jp2"); + BinaryWriter bw = new BinaryWriter(fs); + bw.Write(data); + bw.Close(); + fs.Close();*/ + return res; + } + } + } +} diff --git a/OpenSim/Region/Simulation/EstateManager.cs b/OpenSim/Region/Simulation/EstateManager.cs new file mode 100644 index 0000000..dcb5564 --- /dev/null +++ b/OpenSim/Region/Simulation/EstateManager.cs @@ -0,0 +1,301 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Types; +using OpenSim.Framework.Interfaces; +using OpenSim.Region; +using OpenSim.Region.Scenes; +using OpenSim; +using libsecondlife; +using libsecondlife.Packets; +using Avatar = OpenSim.Region.Scenes.ScenePresence; + + +namespace OpenSim.Region +{ + + /// + /// Processes requests regarding estates. Refer to EstateSettings.cs in OpenSim.Framework. Types for all of the core settings + /// + public class EstateManager + { + private Scene m_world; + private RegionInfo m_regInfo; + + public EstateManager(Scene world,RegionInfo reginfo) + { + m_world = world; //Estate settings found at world.m_regInfo.estateSettings + m_regInfo = reginfo; + } + + private bool convertParamStringToBool(byte[] field) + { + string s = Helpers.FieldToUTF8String(field); + if (s == "1" || s.ToLower() == "y" || s.ToLower() == "yes" || s.ToLower() == "t" || s.ToLower() == "true") + { + return true; + } + return false; + } + + public void handleEstateOwnerMessage(EstateOwnerMessagePacket packet, IClientAPI remote_client) + { + if (remote_client.AgentId == m_regInfo.MasterAvatarAssignedUUID) + { + switch (Helpers.FieldToUTF8String(packet.MethodData.Method)) + { + case "getinfo": + Console.WriteLine("GETINFO Requested"); + this.sendRegionInfoPacketToAll(); + + break; + case "setregioninfo": + if (packet.ParamList.Length != 9) + { + OpenSim.Framework.Console.MainLog.Instance.Error("EstateOwnerMessage: SetRegionInfo method has a ParamList of invalid length"); + } + else + { + m_regInfo.estateSettings.regionFlags = libsecondlife.Simulator.RegionFlags.None; + + if (convertParamStringToBool(packet.ParamList[0].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.BlockTerraform; + } + + if (convertParamStringToBool(packet.ParamList[1].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.NoFly; + } + + if (convertParamStringToBool(packet.ParamList[2].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.AllowDamage; + } + + if (convertParamStringToBool(packet.ParamList[3].Parameter) == false) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.BlockLandResell; + } + + + int tempMaxAgents = Convert.ToInt16(Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[4].Parameter))); + m_regInfo.estateSettings.maxAgents = (byte)tempMaxAgents; + + float tempObjectBonusFactor = (float)Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[5].Parameter)); + m_regInfo.estateSettings.objectBonusFactor = tempObjectBonusFactor; + + int tempMatureLevel = Convert.ToInt16(Helpers.FieldToUTF8String(packet.ParamList[6].Parameter)); + m_regInfo.estateSettings.simAccess = (libsecondlife.Simulator.SimAccess)tempMatureLevel; + + + if (convertParamStringToBool(packet.ParamList[7].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.RestrictPushObject; + } + + if (convertParamStringToBool(packet.ParamList[8].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | libsecondlife.Simulator.RegionFlags.AllowParcelChanges; + } + + sendRegionInfoPacketToAll(); + + } + break; + case "texturebase": + foreach (EstateOwnerMessagePacket.ParamListBlock block in packet.ParamList) + { + string s = Helpers.FieldToUTF8String(block.Parameter); + string[] splitField = s.Split(' '); + if (splitField.Length == 2) + { + LLUUID tempUUID = new LLUUID(splitField[1]); + switch (Convert.ToInt16(splitField[0])) + { + case 0: + m_regInfo.estateSettings.terrainBase0 = tempUUID; + break; + case 1: + m_regInfo.estateSettings.terrainBase1 = tempUUID; + break; + case 2: + m_regInfo.estateSettings.terrainBase2 = tempUUID; + break; + case 3: + m_regInfo.estateSettings.terrainBase3 = tempUUID; + break; + } + } + } + break; + case "texturedetail": + foreach (EstateOwnerMessagePacket.ParamListBlock block in packet.ParamList) + { + + string s = Helpers.FieldToUTF8String(block.Parameter); + string[] splitField = s.Split(' '); + if (splitField.Length == 2) + { + LLUUID tempUUID = new LLUUID(splitField[1]); + switch (Convert.ToInt16(splitField[0])) + { + case 0: + m_regInfo.estateSettings.terrainDetail0 = tempUUID; + break; + case 1: + m_regInfo.estateSettings.terrainDetail1 = tempUUID; + break; + case 2: + m_regInfo.estateSettings.terrainDetail2 = tempUUID; + break; + case 3: + m_regInfo.estateSettings.terrainDetail3 = tempUUID; + break; + } + } + } + break; + case "textureheights": + foreach (EstateOwnerMessagePacket.ParamListBlock block in packet.ParamList) + { + + string s = Helpers.FieldToUTF8String(block.Parameter); + string[] splitField = s.Split(' '); + if (splitField.Length == 3) + { + + float tempHeightLow = (float)Convert.ToDecimal(splitField[1]); + float tempHeightHigh = (float)Convert.ToDecimal(splitField[2]); + + switch (Convert.ToInt16(splitField[0])) + { + case 0: + m_regInfo.estateSettings.terrainStartHeight0 = tempHeightLow; + m_regInfo.estateSettings.terrainHeightRange0 = tempHeightHigh; + break; + case 1: + m_regInfo.estateSettings.terrainStartHeight1 = tempHeightLow; + m_regInfo.estateSettings.terrainHeightRange1 = tempHeightHigh; + break; + case 2: + m_regInfo.estateSettings.terrainStartHeight2 = tempHeightLow; + m_regInfo.estateSettings.terrainHeightRange2 = tempHeightHigh; + break; + case 3: + m_regInfo.estateSettings.terrainStartHeight3 = tempHeightLow; + m_regInfo.estateSettings.terrainHeightRange3 = tempHeightHigh; + break; + } + } + } + break; + case "texturecommit": + sendRegionHandshakeToAll(); + break; + case "setregionterrain": + if (packet.ParamList.Length != 9) + { + OpenSim.Framework.Console.MainLog.Instance.Error("EstateOwnerMessage: SetRegionTerrain method has a ParamList of invalid length"); + } + else + { + m_regInfo.estateSettings.waterHeight = (float)Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[0].Parameter)); + m_regInfo.estateSettings.terrainRaiseLimit = (float)Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[1].Parameter)); + m_regInfo.estateSettings.terrainLowerLimit = (float)Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[2].Parameter)); + m_regInfo.estateSettings.useFixedSun = this.convertParamStringToBool(packet.ParamList[4].Parameter); + m_regInfo.estateSettings.sunHour = (float)Convert.ToDecimal(Helpers.FieldToUTF8String(packet.ParamList[5].Parameter)); + + sendRegionInfoPacketToAll(); + } + break; + default: + OpenSim.Framework.Console.MainLog.Instance.Error("EstateOwnerMessage: Unknown method requested\n" + packet.ToString()); + break; + } + } + } + + public void sendRegionInfoPacketToAll() + { + List avatars = m_world.RequestAvatarList(); + + for (int i = 0; i < avatars.Count; i++) + { + this.sendRegionInfoPacket(avatars[i].ControllingClient); + } + } + + public void sendRegionHandshakeToAll() + { + List avatars = m_world.RequestAvatarList(); + + for (int i = 0; i < avatars.Count; i++) + { + this.sendRegionHandshake(avatars[i].ControllingClient); + } + } + + public void sendRegionInfoPacket(IClientAPI remote_client) + { + Encoding _enc = System.Text.Encoding.ASCII; + + AgentCircuitData circuitData = remote_client.RequestClientInfo(); + + RegionInfoPacket regionInfoPacket = new RegionInfoPacket(); + regionInfoPacket.AgentData.AgentID = circuitData.AgentID; + regionInfoPacket.AgentData.SessionID = circuitData.SessionID; + regionInfoPacket.RegionInfo.BillableFactor = m_regInfo.estateSettings.billableFactor; + regionInfoPacket.RegionInfo.EstateID = m_regInfo.estateSettings.estateID; + regionInfoPacket.RegionInfo.MaxAgents = m_regInfo.estateSettings.maxAgents; + regionInfoPacket.RegionInfo.ObjectBonusFactor = m_regInfo.estateSettings.objectBonusFactor; + regionInfoPacket.RegionInfo.ParentEstateID = m_regInfo.estateSettings.parentEstateID; + regionInfoPacket.RegionInfo.PricePerMeter = m_regInfo.estateSettings.pricePerMeter; + regionInfoPacket.RegionInfo.RedirectGridX = m_regInfo.estateSettings.redirectGridX; + regionInfoPacket.RegionInfo.RedirectGridY = m_regInfo.estateSettings.redirectGridY; + regionInfoPacket.RegionInfo.RegionFlags = (uint)m_regInfo.estateSettings.regionFlags; + regionInfoPacket.RegionInfo.SimAccess = (byte)m_regInfo.estateSettings.simAccess; + regionInfoPacket.RegionInfo.SimName = _enc.GetBytes( m_regInfo.RegionName); + regionInfoPacket.RegionInfo.SunHour = m_regInfo.estateSettings.sunHour; + regionInfoPacket.RegionInfo.TerrainLowerLimit = m_regInfo.estateSettings.terrainLowerLimit; + regionInfoPacket.RegionInfo.TerrainRaiseLimit = m_regInfo.estateSettings.terrainRaiseLimit; + regionInfoPacket.RegionInfo.UseEstateSun = !m_regInfo.estateSettings.useFixedSun; + regionInfoPacket.RegionInfo.WaterHeight = m_regInfo.estateSettings.waterHeight; + + remote_client.OutPacket(regionInfoPacket); + } + + public void sendRegionHandshake(IClientAPI remoteClient) + { + remoteClient.SendRegionHandshake(m_regInfo); + } + + } +} diff --git a/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj b/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj new file mode 100644 index 0000000..7811a55 --- /dev/null +++ b/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj @@ -0,0 +1,211 @@ + + + Local + 8.0.50727 + 2.0 + {C0DAB338-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Simulation + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Simulation + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\Axiom.MathLib.dll + False + + + ..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\..\bin\XMLRPC.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Communications + {CB52B7E7-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.GenericConfig.Xml + {C74E4A30-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Servers + {2CC71860-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Caches + {61FCCDB3-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Physics.Manager + {F4FF31EB-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Region.Terrain.BasicTerrain + {C9E0F891-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj.user b/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Simulation/OpenSim.Region.Simulation.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Simulation/ParcelManager.cs b/OpenSim/Region/Simulation/ParcelManager.cs new file mode 100644 index 0000000..d15d77d --- /dev/null +++ b/OpenSim/Region/Simulation/ParcelManager.cs @@ -0,0 +1,892 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Region.Scenes; +using Avatar = OpenSim.Region.Scenes.ScenePresence; + +namespace OpenSim.Region +{ + + + #region ParcelManager Class + /// + /// Handles Parcel objects and operations requiring information from other Parcel objects (divide, join, etc) + /// + public class ParcelManager : OpenSim.Framework.Interfaces.ILocalStorageParcelReceiver + { + + #region Constants + //Parcel types set with flags in ParcelOverlay. + //Only one of these can be used. + public const byte PARCEL_TYPE_PUBLIC = (byte)0; //Equals 00000000 + public const byte PARCEL_TYPE_OWNED_BY_OTHER = (byte)1; //Equals 00000001 + public const byte PARCEL_TYPE_OWNED_BY_GROUP = (byte)2; //Equals 00000010 + public const byte PARCEL_TYPE_OWNED_BY_REQUESTER = (byte)3; //Equals 00000011 + public const byte PARCEL_TYPE_IS_FOR_SALE = (byte)4; //Equals 00000100 + public const byte PARCEL_TYPE_IS_BEING_AUCTIONED = (byte)5; //Equals 00000101 + + + //Flags that when set, a border on the given side will be placed + //NOTE: North and East is assumable by the west and south sides (if parcel to east has a west border, then I have an east border; etc) + //This took forever to figure out -- jeesh. /blame LL for even having to send these + public const byte PARCEL_FLAG_PROPERTY_BORDER_WEST = (byte)64; //Equals 01000000 + public const byte PARCEL_FLAG_PROPERTY_BORDER_SOUTH = (byte)128; //Equals 10000000 + + //RequestResults (I think these are right, they seem to work): + public const int PARCEL_RESULT_ONE_PARCEL = 0; // The request they made contained only one parcel + public const int PARCEL_RESULT_MULTIPLE_PARCELS = 1; // The request they made contained more than one parcel + + //These are other constants. Yay! + public const int START_PARCEL_LOCAL_ID = 1; + #endregion + + #region Member Variables + public Dictionary parcelList = new Dictionary(); + private int lastParcelLocalID = START_PARCEL_LOCAL_ID - 1; + private int[,] parcelIDList = new int[64, 64]; + + private Scene m_world; + private RegionInfo m_regInfo; + + #endregion + + #region Constructors + public ParcelManager(Scene world, RegionInfo reginfo) + { + + m_world = world; + m_regInfo = reginfo; + parcelIDList.Initialize(); + + } + #endregion + + #region Member Functions + + #region Parcel From Storage Functions + public void ParcelFromStorage(ParcelData data) + { + Parcel new_parcel = new Parcel(data.ownerID, data.isGroupOwned, m_world); + new_parcel.parcelData = data.Copy(); + new_parcel.setParcelBitmapFromByteArray(); + addParcel(new_parcel); + + } + + public void NoParcelDataFromStorage() + { + resetSimParcels(); + } + #endregion + + #region Parcel Add/Remove/Get/Create + /// + /// Creates a basic Parcel object without an owner (a zeroed key) + /// + /// + public Parcel createBaseParcel() + { + return new Parcel(new LLUUID(), false, m_world); + } + + /// + /// Adds a parcel to the stored list and adds them to the parcelIDList to what they own + /// + /// The parcel being added + public void addParcel(Parcel new_parcel) + { + lastParcelLocalID++; + new_parcel.parcelData.localID = lastParcelLocalID; + parcelList.Add(lastParcelLocalID, new_parcel.Copy()); + + + bool[,] parcelBitmap = new_parcel.getParcelBitmap(); + int x, y; + for (x = 0; x < 64; x++) + { + for (y = 0; y < 64; y++) + { + if (parcelBitmap[x, y]) + { + parcelIDList[x, y] = lastParcelLocalID; + } + } + } + parcelList[lastParcelLocalID].forceUpdateParcelInfo(); + + + } + /// + /// Removes a parcel from the list. Will not remove if local_id is still owning an area in parcelIDList + /// + /// Parcel.localID of the parcel to remove. + public void removeParcel(int local_id) + { + int x, y; + for (x = 0; x < 64; x++) + { + for (y = 0; y < 64; y++) + { + if (parcelIDList[x, y] == local_id) + { + throw new Exception("Could not remove parcel. Still being used at " + x + ", " + y); + } + } + } + m_world.localStorage.RemoveParcel(parcelList[local_id].parcelData); + parcelList.Remove(local_id); + } + + private void performFinalParcelJoin(Parcel master, Parcel slave) + { + int x, y; + bool[,] parcelBitmapSlave = slave.getParcelBitmap(); + for (x = 0; x < 64; x++) + { + for (y = 0; y < 64; y++) + { + if (parcelBitmapSlave[x, y]) + { + parcelIDList[x, y] = master.parcelData.localID; + } + } + } + removeParcel(slave.parcelData.localID); + } + /// + /// Get the parcel at the specified point + /// + /// Value between 0 - 256 on the x axis of the point + /// Value between 0 - 256 on the y axis of the point + /// Parcel at the point supplied + public Parcel getParcel(int x, int y) + { + if (x > 256 || y > 256 || x < 0 || y < 0) + { + throw new Exception("Error: Parcel not found at point " + x + ", " + y); + } + else + { + return parcelList[parcelIDList[x / 4, y / 4]]; + } + + } + #endregion + + #region Parcel Modification + /// + /// Subdivides a parcel + /// + /// West Point + /// South Point + /// East Point + /// North Point + /// LLUUID of user who is trying to subdivide + /// Returns true if successful + private bool subdivide(int start_x, int start_y, int end_x, int end_y, LLUUID attempting_user_id) + { + //First, lets loop through the points and make sure they are all in the same parcel + //Get the parcel at start + Parcel startParcel = getParcel(start_x, start_y); + if (startParcel == null) return false; //No such parcel at the beginning + + //Loop through the points + try + { + int totalX = end_x - start_x; + int totalY = end_y - start_y; + int x, y; + for (y = 0; y < totalY; y++) + { + for (x = 0; x < totalX; x++) + { + Parcel tempParcel = getParcel(start_x + x, start_y + y); + if (tempParcel == null) return false; //No such parcel at that point + if (tempParcel != startParcel) return false; //Subdividing over 2 parcels; no-no + } + } + } + catch (Exception) + { + return false; //Exception. For now, lets skip subdivision + } + + //If we are still here, then they are subdividing within one parcel + //Check owner + if (startParcel.parcelData.ownerID != attempting_user_id) + { + return false; //They cant do this! + } + + //Lets create a new parcel with bitmap activated at that point (keeping the old parcels info) + Parcel newParcel = startParcel.Copy(); + newParcel.parcelData.parcelName = "Subdivision of " + newParcel.parcelData.parcelName; + newParcel.parcelData.globalID = LLUUID.Random(); + + newParcel.setParcelBitmap(Parcel.getSquareParcelBitmap(start_x, start_y, end_x, end_y)); + + //Now, lets set the subdivision area of the original to false + int startParcelIndex = startParcel.parcelData.localID; + parcelList[startParcelIndex].setParcelBitmap(Parcel.modifyParcelBitmapSquare(startParcel.getParcelBitmap(), start_x, start_y, end_x, end_y, false)); + parcelList[startParcelIndex].forceUpdateParcelInfo(); + + + //Now add the new parcel + addParcel(newParcel); + + + + + + return true; + } + /// + /// Join 2 parcels together + /// + /// x value in first parcel + /// y value in first parcel + /// x value in second parcel + /// y value in second parcel + /// LLUUID of the avatar trying to join the parcels + /// Returns true if successful + private bool join(int start_x, int start_y, int end_x, int end_y, LLUUID attempting_user_id) + { + end_x -= 4; + end_y -= 4; + + //NOTE: The following only connects the parcels in each corner and not all the parcels that are within the selection box! + //This should be fixed later -- somewhat "incomplete code" --Ming + Parcel startParcel, endParcel; + + try + { + startParcel = getParcel(start_x, start_y); + endParcel = getParcel(end_x, end_y); + } + catch (Exception) + { + return false; //Error occured when trying to get the start and end parcels + } + if (startParcel == endParcel) + { + return false; //Subdivision of the same parcel is not allowed + } + + //Check the parcel owners: + if (startParcel.parcelData.ownerID != endParcel.parcelData.ownerID) + { + return false; + } + if (startParcel.parcelData.ownerID != attempting_user_id) + { + //TODO: Group editing stuff. Avatar owner support for now + return false; + } + + //Same owners! Lets join them + //Merge them to startParcel + parcelList[startParcel.parcelData.localID].setParcelBitmap(Parcel.mergeParcelBitmaps(startParcel.getParcelBitmap(), endParcel.getParcelBitmap())); + performFinalParcelJoin(startParcel, endParcel); + + return true; + + + + } + #endregion + + #region Parcel Updating + /// + /// Where we send the ParcelOverlay packet to the client + /// + /// The object representing the client + public void sendParcelOverlay(IClientAPI remote_client) + { + const int PARCEL_BLOCKS_PER_PACKET = 1024; + int x, y = 0; + byte[] byteArray = new byte[PARCEL_BLOCKS_PER_PACKET]; + int byteArrayCount = 0; + int sequenceID = 0; + ParcelOverlayPacket packet; + + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) + { + byte tempByte = (byte)0; //This represents the byte for the current 4x4 + Parcel currentParcelBlock = getParcel(x * 4, y * 4); + + if (currentParcelBlock.parcelData.ownerID == remote_client.AgentId) + { + //Owner Flag + tempByte = Convert.ToByte(tempByte | PARCEL_TYPE_OWNED_BY_REQUESTER); + } + else if (currentParcelBlock.parcelData.salePrice > 0 && (currentParcelBlock.parcelData.authBuyerID == LLUUID.Zero || currentParcelBlock.parcelData.authBuyerID == remote_client.AgentId)) + { + //Sale Flag + tempByte = Convert.ToByte(tempByte | PARCEL_TYPE_IS_FOR_SALE); + } + else if (currentParcelBlock.parcelData.ownerID == LLUUID.Zero) + { + //Public Flag + tempByte = Convert.ToByte(tempByte | PARCEL_TYPE_PUBLIC); + } + else + { + //Other Flag + tempByte = Convert.ToByte(tempByte | PARCEL_TYPE_OWNED_BY_OTHER); + } + + + //Now for border control + if (x == 0) + { + tempByte = Convert.ToByte(tempByte | PARCEL_FLAG_PROPERTY_BORDER_WEST); + } + else if (getParcel((x - 1) * 4, y * 4) != currentParcelBlock) + { + tempByte = Convert.ToByte(tempByte | PARCEL_FLAG_PROPERTY_BORDER_WEST); + } + + if (y == 0) + { + tempByte = Convert.ToByte(tempByte | PARCEL_FLAG_PROPERTY_BORDER_SOUTH); + } + else if (getParcel(x * 4, (y - 1) * 4) != currentParcelBlock) + { + tempByte = Convert.ToByte(tempByte | PARCEL_FLAG_PROPERTY_BORDER_SOUTH); + } + + byteArray[byteArrayCount] = tempByte; + byteArrayCount++; + if (byteArrayCount >= PARCEL_BLOCKS_PER_PACKET) + { + byteArrayCount = 0; + packet = new ParcelOverlayPacket(); + packet.ParcelData.Data = byteArray; + packet.ParcelData.SequenceID = sequenceID; + remote_client.OutPacket((Packet)packet); + sequenceID++; + byteArray = new byte[PARCEL_BLOCKS_PER_PACKET]; + } + } + } + + packet = new ParcelOverlayPacket(); + packet.ParcelData.Data = byteArray; + packet.ParcelData.SequenceID = sequenceID; //Eh? + remote_client.OutPacket((Packet)packet); + } + + public void handleParcelPropertiesRequest(int start_x, int start_y, int end_x, int end_y, int sequence_id, bool snap_selection, IClientAPI remote_client) + { + //Get the parcels within the bounds + List temp = new List(); + int x, y, i; + int inc_x = end_x - start_x; + int inc_y = end_y - start_y; + for (x = 0; x < inc_x; x++) + { + for (y = 0; y < inc_y; y++) + { + OpenSim.Region.Parcel currentParcel = getParcel(start_x + x, start_y + y); + if (!temp.Contains(currentParcel)) + { + currentParcel.forceUpdateParcelInfo(); + temp.Add(currentParcel); + } + } + } + + int requestResult = ParcelManager.PARCEL_RESULT_ONE_PARCEL; + if (temp.Count > 1) + { + requestResult = ParcelManager.PARCEL_RESULT_MULTIPLE_PARCELS; + } + + for (i = 0; i < temp.Count; i++) + { + temp[i].sendParcelProperties(sequence_id, snap_selection, requestResult, remote_client); + } + + + sendParcelOverlay(remote_client); + } + + public void handleParcelPropertiesUpdateRequest(ParcelPropertiesUpdatePacket packet, IClientAPI remote_client) + { + if (parcelList.ContainsKey(packet.ParcelData.LocalID)) + { + parcelList[packet.ParcelData.LocalID].updateParcelProperties(packet, remote_client); + } + } + public void handleParcelDivideRequest(int west, int south, int east, int north, IClientAPI remote_client) + { + subdivide(west, south, east, north, remote_client.AgentId); + } + public void handleParcelJoinRequest(int west, int south, int east, int north, IClientAPI remote_client) + { + join(west, south, east, north, remote_client.AgentId); + + } + #endregion + + /// + /// Resets the sim to the default parcel (full sim parcel owned by the default user) + /// + public void resetSimParcels() + { + //Remove all the parcels in the sim and add a blank, full sim parcel set to public + parcelList.Clear(); + lastParcelLocalID = START_PARCEL_LOCAL_ID - 1; + parcelIDList.Initialize(); + + Parcel fullSimParcel = new Parcel(LLUUID.Zero, false, m_world); + + fullSimParcel.setParcelBitmap(Parcel.getSquareParcelBitmap(0, 0, 256, 256)); + fullSimParcel.parcelData.parcelName = "Your Sim Parcel"; + fullSimParcel.parcelData.parcelDesc = ""; + + fullSimParcel.parcelData.ownerID = m_regInfo.MasterAvatarAssignedUUID; + fullSimParcel.parcelData.salePrice = 1; + fullSimParcel.parcelData.parcelFlags = libsecondlife.Parcel.ParcelFlags.ForSale; + fullSimParcel.parcelData.parcelStatus = libsecondlife.Parcel.ParcelStatus.Leased; + + addParcel(fullSimParcel); + + } + #endregion + } + #endregion + + + #region Parcel Class + /// + /// Keeps track of a specific parcel's information + /// + public class Parcel + { + #region Member Variables + public ParcelData parcelData = new ParcelData(); + public Scene m_world; + + private bool[,] parcelBitmap = new bool[64, 64]; + + #endregion + + + #region Constructors + public Parcel(LLUUID owner_id, bool is_group_owned, Scene world) + { + m_world = world; + parcelData.ownerID = owner_id; + parcelData.isGroupOwned = is_group_owned; + + } + #endregion + + + #region Member Functions + + #region General Functions + /// + /// Checks to see if this parcel contains a point + /// + /// + /// + /// Returns true if the parcel contains the specified point + public bool containsPoint(int x, int y) + { + if (x >= 0 && y >= 0 && x <= 256 && x <= 256) + { + return (parcelBitmap[x / 4, y / 4] == true); + } + else + { + return false; + } + } + + public Parcel Copy() + { + Parcel newParcel = new Parcel(this.parcelData.ownerID, this.parcelData.isGroupOwned, m_world); + + //Place all new variables here! + newParcel.parcelBitmap = (bool[,])(this.parcelBitmap.Clone()); + newParcel.parcelData = parcelData.Copy(); + + return newParcel; + } + + #endregion + + + #region Packet Request Handling + /// + /// Sends parcel properties as requested + /// + /// ID sent by client for them to keep track of + /// Bool sent by client for them to use + /// Object representing the client + public void sendParcelProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client) + { + + ParcelPropertiesPacket updatePacket = new ParcelPropertiesPacket(); + updatePacket.ParcelData.AABBMax = parcelData.AABBMax; + updatePacket.ParcelData.AABBMin = parcelData.AABBMin; + updatePacket.ParcelData.Area = parcelData.area; + updatePacket.ParcelData.AuctionID = parcelData.auctionID; + updatePacket.ParcelData.AuthBuyerID = parcelData.authBuyerID; //unemplemented + + updatePacket.ParcelData.Bitmap = parcelData.parcelBitmapByteArray; + + updatePacket.ParcelData.Desc = libsecondlife.Helpers.StringToField(parcelData.parcelDesc); + updatePacket.ParcelData.Category = (byte)parcelData.category; + updatePacket.ParcelData.ClaimDate = parcelData.claimDate; + updatePacket.ParcelData.ClaimPrice = parcelData.claimPrice; + updatePacket.ParcelData.GroupID = parcelData.groupID; + updatePacket.ParcelData.GroupPrims = parcelData.groupPrims; + updatePacket.ParcelData.IsGroupOwned = parcelData.isGroupOwned; + updatePacket.ParcelData.LandingType = (byte)parcelData.landingType; + updatePacket.ParcelData.LocalID = parcelData.localID; + updatePacket.ParcelData.MaxPrims = 1000; //unemplemented + updatePacket.ParcelData.MediaAutoScale = parcelData.mediaAutoScale; + updatePacket.ParcelData.MediaID = parcelData.mediaID; + updatePacket.ParcelData.MediaURL = Helpers.StringToField(parcelData.mediaURL); + updatePacket.ParcelData.MusicURL = Helpers.StringToField(parcelData.musicURL); + updatePacket.ParcelData.Name = Helpers.StringToField(parcelData.parcelName); + updatePacket.ParcelData.OtherCleanTime = 0; //unemplemented + updatePacket.ParcelData.OtherCount = 0; //unemplemented + updatePacket.ParcelData.OtherPrims = 0; //unemplented + updatePacket.ParcelData.OwnerID = parcelData.ownerID; + updatePacket.ParcelData.OwnerPrims = 0; //unemplemented + updatePacket.ParcelData.ParcelFlags = (uint)parcelData.parcelFlags; //unemplemented + updatePacket.ParcelData.ParcelPrimBonus = (float)1.0; //unemplemented + updatePacket.ParcelData.PassHours = parcelData.passHours; + updatePacket.ParcelData.PassPrice = parcelData.passPrice; + updatePacket.ParcelData.PublicCount = 0; //unemplemented + updatePacket.ParcelData.RegionDenyAnonymous = false; //unemplemented + updatePacket.ParcelData.RegionDenyIdentified = false; //unemplemented + updatePacket.ParcelData.RegionDenyTransacted = false; //unemplemented + updatePacket.ParcelData.RegionPushOverride = true; //unemplemented + updatePacket.ParcelData.RentPrice = 0; //?? + updatePacket.ParcelData.RequestResult = request_result; + updatePacket.ParcelData.SalePrice = parcelData.salePrice; //unemplemented + updatePacket.ParcelData.SelectedPrims = 0; //unemeplemented + updatePacket.ParcelData.SelfCount = 0;//unemplemented + updatePacket.ParcelData.SequenceID = sequence_id; + updatePacket.ParcelData.SimWideMaxPrims = 15000; //unemplemented + updatePacket.ParcelData.SimWideTotalPrims = 0; //unemplemented + updatePacket.ParcelData.SnapSelection = snap_selection; + updatePacket.ParcelData.SnapshotID = parcelData.snapshotID; + updatePacket.ParcelData.Status = (byte)parcelData.parcelStatus; + updatePacket.ParcelData.TotalPrims = 0; //unemplemented + updatePacket.ParcelData.UserLocation = parcelData.userLocation; + updatePacket.ParcelData.UserLookAt = parcelData.userLookAt; + remote_client.OutPacket((Packet)updatePacket); + } + + public void updateParcelProperties(ParcelPropertiesUpdatePacket packet, IClientAPI remote_client) + { + if (remote_client.AgentId == parcelData.ownerID) + { + //Needs later group support + parcelData.authBuyerID = packet.ParcelData.AuthBuyerID; + parcelData.category = (libsecondlife.Parcel.ParcelCategory)packet.ParcelData.Category; + parcelData.parcelDesc = Helpers.FieldToUTF8String(packet.ParcelData.Desc); + parcelData.groupID = packet.ParcelData.GroupID; + parcelData.landingType = packet.ParcelData.LandingType; + parcelData.mediaAutoScale = packet.ParcelData.MediaAutoScale; + parcelData.mediaID = packet.ParcelData.MediaID; + parcelData.mediaURL = Helpers.FieldToUTF8String(packet.ParcelData.MediaURL); + parcelData.musicURL = Helpers.FieldToUTF8String(packet.ParcelData.MusicURL); + parcelData.parcelName = libsecondlife.Helpers.FieldToUTF8String(packet.ParcelData.Name); + parcelData.parcelFlags = (libsecondlife.Parcel.ParcelFlags)packet.ParcelData.ParcelFlags; + parcelData.passHours = packet.ParcelData.PassHours; + parcelData.passPrice = packet.ParcelData.PassPrice; + parcelData.salePrice = packet.ParcelData.SalePrice; + parcelData.snapshotID = packet.ParcelData.SnapshotID; + parcelData.userLocation = packet.ParcelData.UserLocation; + parcelData.userLookAt = packet.ParcelData.UserLookAt; + + List avatars = m_world.RequestAvatarList(); + + for (int i = 0; i < avatars.Count; i++) + { + Parcel over = m_world.parcelManager.getParcel((int)Math.Round(avatars[i].Pos.X), (int)Math.Round(avatars[i].Pos.Y)); + if (over == this) + { + sendParcelProperties(0, false, 0, avatars[i].ControllingClient); + } + } + + } + } + #endregion + + + #region Update Functions + /// + /// Updates the AABBMin and AABBMax values after area/shape modification of parcel + /// + private void updateAABBAndAreaValues() + { + int min_x = 64; + int min_y = 64; + int max_x = 0; + int max_y = 0; + int tempArea = 0; + int x, y; + for (x = 0; x < 64; x++) + { + for (y = 0; y < 64; y++) + { + if (parcelBitmap[x, y] == true) + { + if (min_x > x) min_x = x; + if (min_y > y) min_y = y; + if (max_x < x) max_x = x; + if (max_y < y) max_y = y; + tempArea += 16; //16sqm parcel + } + } + } + parcelData.AABBMin = new LLVector3((float)(min_x * 4), (float)(min_y * 4), m_world.Terrain[(min_x * 4), (min_y * 4)]); + parcelData.AABBMax = new LLVector3((float)(max_x * 4), (float)(max_y * 4), m_world.Terrain[(max_x * 4), (max_y * 4)]); + parcelData.area = tempArea; + } + + public void updateParcelBitmapByteArray() + { + parcelData.parcelBitmapByteArray = convertParcelBitmapToBytes(); + } + + /// + /// Update all settings in parcel such as area, bitmap byte array, etc + /// + public void forceUpdateParcelInfo() + { + this.updateAABBAndAreaValues(); + this.updateParcelBitmapByteArray(); + } + + public void setParcelBitmapFromByteArray() + { + parcelBitmap = convertBytesToParcelBitmap(); + } + #endregion + + + #region Parcel Bitmap Functions + /// + /// Sets the parcel's bitmap manually + /// + /// 64x64 block representing where this parcel is on a map + public void setParcelBitmap(bool[,] bitmap) + { + if (bitmap.GetLength(0) != 64 || bitmap.GetLength(1) != 64 || bitmap.Rank != 2) + { + //Throw an exception - The bitmap is not 64x64 + throw new Exception("Error: Invalid Parcel Bitmap"); + } + else + { + //Valid: Lets set it + parcelBitmap = bitmap; + forceUpdateParcelInfo(); + + } + } + /// + /// Gets the parcels bitmap manually + /// + /// + public bool[,] getParcelBitmap() + { + return parcelBitmap; + } + /// + /// Converts the parcel bitmap to a packet friendly byte array + /// + /// + private byte[] convertParcelBitmapToBytes() + { + byte[] tempConvertArr = new byte[512]; + byte tempByte = 0; + int x, y, i, byteNum = 0; + i = 0; + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) + { + tempByte = Convert.ToByte(tempByte | Convert.ToByte(parcelBitmap[x, y]) << (i++ % 8)); + if (i % 8 == 0) + { + tempConvertArr[byteNum] = tempByte; + tempByte = (byte)0; + i = 0; + byteNum++; + } + } + } + return tempConvertArr; + } + + private bool[,] convertBytesToParcelBitmap() + { + bool[,] tempConvertMap = new bool[64, 64]; + tempConvertMap.Initialize(); + byte tempByte = 0; + int x = 0, y = 0, i = 0, bitNum = 0; + for (i = 0; i < 512; i++) + { + tempByte = parcelData.parcelBitmapByteArray[i]; + for (bitNum = 0; bitNum < 8; bitNum++) + { + bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte)1); + tempConvertMap[x, y] = bit; + x++; + if (x > 63) + { + x = 0; + y++; + } + + } + + } + return tempConvertMap; + } + /// + /// Full sim parcel creation + /// + /// + public static bool[,] basicFullRegionParcelBitmap() + { + return getSquareParcelBitmap(0, 0, 256, 256); + } + + /// + /// Used to modify the bitmap between the x and y points. Points use 64 scale + /// + /// + /// + /// + /// + /// + public static bool[,] getSquareParcelBitmap(int start_x, int start_y, int end_x, int end_y) + { + + bool[,] tempBitmap = new bool[64, 64]; + tempBitmap.Initialize(); + + tempBitmap = modifyParcelBitmapSquare(tempBitmap, start_x, start_y, end_x, end_y, true); + return tempBitmap; + } + + /// + /// Change a parcel's bitmap at within a square and set those points to a specific value + /// + /// + /// + /// + /// + /// + /// + /// + public static bool[,] modifyParcelBitmapSquare(bool[,] parcel_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value) + { + if (parcel_bitmap.GetLength(0) != 64 || parcel_bitmap.GetLength(1) != 64 || parcel_bitmap.Rank != 2) + { + //Throw an exception - The bitmap is not 64x64 + throw new Exception("Error: Invalid Parcel Bitmap in modifyParcelBitmapSquare()"); + } + + int x, y; + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) + { + if (x >= start_x / 4 && x < end_x / 4 + && y >= start_y / 4 && y < end_y / 4) + { + parcel_bitmap[x, y] = set_value; + } + } + } + return parcel_bitmap; + } + /// + /// Join the true values of 2 bitmaps together + /// + /// + /// + /// + public static bool[,] mergeParcelBitmaps(bool[,] bitmap_base, bool[,] bitmap_add) + { + if (bitmap_base.GetLength(0) != 64 || bitmap_base.GetLength(1) != 64 || bitmap_base.Rank != 2) + { + //Throw an exception - The bitmap is not 64x64 + throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_base in mergeParcelBitmaps"); + } + if (bitmap_add.GetLength(0) != 64 || bitmap_add.GetLength(1) != 64 || bitmap_add.Rank != 2) + { + //Throw an exception - The bitmap is not 64x64 + throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_add in mergeParcelBitmaps"); + + } + + int x, y; + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) + { + if (bitmap_add[x, y]) + { + bitmap_base[x, y] = true; + } + } + } + return bitmap_base; + } + #endregion + + #endregion + + + } + #endregion + + +} diff --git a/OpenSim/Region/Simulation/RegionManager.cs b/OpenSim/Region/Simulation/RegionManager.cs new file mode 100644 index 0000000..a317f0f --- /dev/null +++ b/OpenSim/Region/Simulation/RegionManager.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenGrid.Framework.Communications; +using OpenSim.Framework; +using OpenSim.Framework.Types; +using OpenSim.Servers; + +namespace OpenSim.Region +{ + public class RegionManager //needs renaming , but first we need to rename the namespace + { + protected AuthenticateSessionsBase authenticateHandler; + protected RegionCommsListener regionCommsHost; + protected CommunicationsManager commsManager; + protected List capsHandlers = new List(); + protected BaseHttpServer httpListener; + + protected Scenes.Scene m_Scene; + + public ParcelManager parcelManager; + public EstateManager estateManager; + + public RegionManager() + { + + } + + } +} diff --git a/OpenSim/Region/Simulation/Scenes/Entity.cs b/OpenSim/Region/Simulation/Scenes/Entity.cs new file mode 100644 index 0000000..f8754f5 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/Entity.cs @@ -0,0 +1,194 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using Axiom.MathLib; +using OpenSim.Physics.Manager; +using libsecondlife; +using OpenSim.Region.Scripting; + +namespace OpenSim.Region.Scenes +{ + public abstract class Entity : IScriptReadonlyEntity + { + public libsecondlife.LLUUID uuid; + public Quaternion rotation; + protected List children; + + protected PhysicsActor _physActor; + protected Scene m_world; + protected string m_name; + + /// + /// + /// + public virtual string Name + { + get { return m_name; } + } + + protected LLVector3 m_pos; + /// + /// + /// + public virtual LLVector3 Pos + { + get + { + if (this._physActor != null) + { + m_pos.X = _physActor.Position.X; + m_pos.Y = _physActor.Position.Y; + m_pos.Z = _physActor.Position.Z; + } + + return m_pos; + } + set + { + if (this._physActor != null) + { + try + { + lock (this.m_world.SyncRoot) + { + + this._physActor.Position = new PhysicsVector(value.X, value.Y, value.Z); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + + m_pos = value; + } + } + + public LLVector3 velocity; + + /// + /// + /// + public virtual LLVector3 Velocity + { + get + { + if (this._physActor != null) + { + velocity.X = _physActor.Velocity.X; + velocity.Y = _physActor.Velocity.Y; + velocity.Z = _physActor.Velocity.Z; + } + + return velocity; + } + set + { + if (this._physActor != null) + { + try + { + lock (this.m_world.SyncRoot) + { + + this._physActor.Velocity = new PhysicsVector(value.X, value.Y, value.Z); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + + velocity = value; + } + } + + protected uint m_localId; + + public uint LocalId + { + get { return m_localId; } + } + + /// + /// Creates a new Entity (should not occur on it's own) + /// + public Entity() + { + uuid = new libsecondlife.LLUUID(); + + m_pos = new LLVector3(); + velocity = new LLVector3(); + rotation = new Quaternion(); + m_name = "(basic entity)"; + children = new List(); + } + + /// + /// + /// + public virtual void updateMovement() + { + foreach (Entity child in children) + { + child.updateMovement(); + } + } + + /// + /// Performs any updates that need to be done at each frame. This function is overridable from it's children. + /// + public virtual void update() { + // Do any per-frame updates needed that are applicable to every type of entity + foreach (Entity child in children) + { + child.update(); + } + } + + /// + /// Called at a set interval to inform entities that they should back themsleves up to the DB + /// + public virtual void BackUp() + { + + } + + /// + /// Infoms the entity that the land (heightmap) has changed + /// + public virtual void LandRenegerated() + { + + } + } +} diff --git a/OpenSim/Region/Simulation/Scenes/IScenePresenceBody.cs b/OpenSim/Region/Simulation/Scenes/IScenePresenceBody.cs new file mode 100644 index 0000000..65077e6 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/IScenePresenceBody.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Scenes +{ + public interface IScenePresenceBody + { + void processMovement(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation); + void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam); + void SendOurAppearance(IClientAPI OurClient); + void SendAppearanceToOtherAgent(ScenePresence avatarInfo); + } +} diff --git a/OpenSim/Region/Simulation/Scenes/Primitive.cs b/OpenSim/Region/Simulation/Scenes/Primitive.cs new file mode 100644 index 0000000..e04c711 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/Primitive.cs @@ -0,0 +1,582 @@ + +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; + +namespace OpenSim.Region.Scenes +{ + public class Primitive : Entity + { + internal PrimData primData; + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + // private Dictionary m_clientThreads; + private ulong m_regionHandle; + private const uint FULL_MASK_PERMISSIONS = 2147483647; + private bool physicsEnabled = false; + private byte updateFlag = 0; + private uint flags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456 + 128; + + private Dictionary inventoryItems; + + #region Properties + + public LLVector3 Scale + { + set + { + this.primData.Scale = value; + //this.dirtyFlag = true; + } + get + { + return this.primData.Scale; + } + } + + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + } + + public override LLVector3 Pos + { + get + { + return base.Pos; + } + set + { + base.Pos = value; + } + } + #endregion + + /// + /// + /// + /// + /// + /// + public Primitive( ulong regionHandle, Scene world) + { + // m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public Primitive(ulong regionHandle, Scene world, ObjectAddPacket addPacket, LLUUID ownerID, uint localID) + { + // m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + this.CreateFromPacket(addPacket, ownerID, localID); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public Primitive( ulong regionHandle, Scene world, LLUUID owner, LLUUID fullID, uint localID) + { + // m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + this.primData = new PrimData(); + this.primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + this.primData.OwnerID = owner; + this.primData.FullID = this.uuid = fullID; + this.primData.LocalID = m_localId = localID; + } + + /// + /// Constructor to create a default cube + /// + /// + /// + /// + /// + /// + /// + public Primitive( ulong regionHandle, Scene world, LLUUID owner, uint localID, LLVector3 position) + { + //m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + this.primData = PrimData.DefaultCube(); + this.primData.OwnerID = owner; + this.primData.LocalID = m_localId = localID; + this.Pos = this.primData.Position = position; + + this.updateFlag = 1; + } + + /// + /// + /// + /// + public byte[] GetByteArray() + { + byte[] result = null; + List dataArrays = new List(); + dataArrays.Add(primData.ToBytes()); + foreach (Entity child in children) + { + if (child is OpenSim.Region.Scenes.Primitive) + { + dataArrays.Add(((OpenSim.Region.Scenes.Primitive)child).GetByteArray()); + } + } + byte[] primstart = Helpers.StringToField(""); + byte[] primend = Helpers.StringToField(""); + int totalLength = primstart.Length + primend.Length; + for (int i = 0; i < dataArrays.Count; i++) + { + totalLength += dataArrays[i].Length; + } + + result = new byte[totalLength]; + int arraypos = 0; + Array.Copy(primstart, 0, result, 0, primstart.Length); + arraypos += primstart.Length; + for (int i = 0; i < dataArrays.Count; i++) + { + Array.Copy(dataArrays[i], 0, result, arraypos, dataArrays[i].Length); + arraypos += dataArrays[i].Length; + } + Array.Copy(primend, 0, result, arraypos, primend.Length); + + return result; + } + + #region Overridden Methods + + /// + /// + /// + public override void update() + { + if (this.updateFlag == 1) // is a new prim just been created/reloaded + { + this.SendFullUpdateToAllClients(); + this.updateFlag = 0; + } + if (this.updateFlag == 2) //some change has been made so update the clients + { + this.SendTerseUpdateToALLClients(); + this.updateFlag = 0; + } + } + + /// + /// + /// + public override void BackUp() + { + + } + + #endregion + + #region Packet handlers + + /// + /// + /// + /// + public void UpdatePosition(LLVector3 pos) + { + this.Pos = new LLVector3(pos.X, pos.Y, pos.Z); + this.updateFlag = 2; + } + + /// + /// + /// + /// + public void UpdateShape(ObjectShapePacket.ObjectDataBlock updatePacket) + { + this.primData.PathBegin = updatePacket.PathBegin; + this.primData.PathEnd = updatePacket.PathEnd; + this.primData.PathScaleX = updatePacket.PathScaleX; + this.primData.PathScaleY = updatePacket.PathScaleY; + this.primData.PathShearX = updatePacket.PathShearX; + this.primData.PathShearY = updatePacket.PathShearY; + this.primData.PathSkew = updatePacket.PathSkew; + this.primData.ProfileBegin = updatePacket.ProfileBegin; + this.primData.ProfileEnd = updatePacket.ProfileEnd; + this.primData.PathCurve = updatePacket.PathCurve; + this.primData.ProfileCurve = updatePacket.ProfileCurve; + this.primData.ProfileHollow = updatePacket.ProfileHollow; + this.primData.PathRadiusOffset = updatePacket.PathRadiusOffset; + this.primData.PathRevolutions = updatePacket.PathRevolutions; + this.primData.PathTaperX = updatePacket.PathTaperX; + this.primData.PathTaperY = updatePacket.PathTaperY; + this.primData.PathTwist = updatePacket.PathTwist; + this.primData.PathTwistBegin = updatePacket.PathTwistBegin; + } + + /// + /// + /// + /// + public void UpdateTexture(byte[] tex) + { + this.primData.TextureEntry = tex; + } + + /// + /// + /// + /// + public void UpdateObjectFlags(ObjectFlagUpdatePacket pack) + { + + } + + /// + /// + /// + /// + public void AssignToParent(Primitive prim) + { + + } + + #endregion + + # region Inventory Methods + /// + /// + /// + /// + /// + public bool AddToInventory(InventoryItem item) + { + return false; + } + + /// + /// + /// + /// + /// + public InventoryItem RemoveFromInventory(LLUUID itemID) + { + return null; + } + + /// + /// + /// + /// + /// + public void RequestInventoryInfo(IClientAPI simClient, RequestTaskInventoryPacket packet) + { + + } + + /// + /// + /// + /// + /// + public void RequestXferInventory(IClientAPI simClient, ulong xferID) + { + //will only currently work if the total size of the inventory data array is under about 1000 bytes + SendXferPacketPacket send = new SendXferPacketPacket(); + + send.XferID.ID = xferID; + send.XferID.Packet = 1 + 2147483648; + send.DataPacket.Data = this.ConvertInventoryToBytes(); + + simClient.OutPacket(send); + } + + /// + /// + /// + /// + public byte[] ConvertInventoryToBytes() + { + System.Text.Encoding enc = System.Text.Encoding.ASCII; + byte[] result = new byte[0]; + List inventoryData = new List(); + int totallength = 0; + foreach (InventoryItem invItem in inventoryItems.Values) + { + byte[] data = enc.GetBytes(invItem.ExportString()); + inventoryData.Add(data); + totallength += data.Length; + } + //TODO: copy arrays into the single result array + + return result; + } + + /// + /// + /// + /// + public void CreateInventoryFromBytes(byte[] data) + { + + } + + #endregion + + #region Update viewers Methods + + /// + /// + /// + /// + public void SendFullUpdateForAllChildren(IClientAPI remoteClient) + { + this.SendFullUpdateToClient(remoteClient); + for (int i = 0; i < this.children.Count; i++) + { + if (this.children[i] is Primitive) + { + ((Primitive)this.children[i]).SendFullUpdateForAllChildren(remoteClient); + } + } + } + + /// + /// + /// + /// + public void SendFullUpdateToClient(IClientAPI remoteClient) + { + LLVector3 lPos; + if (this._physActor != null && this.physicsEnabled) + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + } + else + { + lPos = this.Pos; + } + + remoteClient.SendPrimitiveToClient(this.m_regionHandle, 64096, this.LocalId, this.primData, lPos, new LLUUID("00000000-0000-0000-9999-000000000005"), this.flags); + } + + /// + /// + /// + public void SendFullUpdateToAllClients() + { + List avatars = this.m_world.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + this.SendFullUpdateToClient(avatars[i].ControllingClient); + } + } + + /// + /// + /// + /// + public void SendTerseUpdateToClient(IClientAPI RemoteClient) + { + LLVector3 lPos; + Axiom.MathLib.Quaternion lRot; + if (this._physActor != null && this.physicsEnabled) //is this needed ? doesn't the property fields do this for us? + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + lRot = this._physActor.Orientation; + } + else + { + lPos = this.Pos; + lRot = this.rotation; + } + LLQuaternion mRot = new LLQuaternion(lRot.x, lRot.y, lRot.z, lRot.w); + RemoteClient.SendPrimTerseUpdate(this.m_regionHandle, 64096, this.LocalId, lPos, mRot); + } + + /// + /// + /// + public void SendTerseUpdateToALLClients() + { + List avatars = this.m_world.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + this.SendTerseUpdateToClient(avatars[i].ControllingClient); + } + } + + #endregion + + #region Create Methods + + /// + /// + /// + /// + /// + /// + public void CreateFromPacket(ObjectAddPacket addPacket, LLUUID ownerID, uint localID) + { + PrimData PData = new PrimData(); + this.primData = PData; + this.primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + + PData.OwnerID = ownerID; + PData.PCode = addPacket.ObjectData.PCode; + PData.PathBegin = addPacket.ObjectData.PathBegin; + PData.PathEnd = addPacket.ObjectData.PathEnd; + PData.PathScaleX = addPacket.ObjectData.PathScaleX; + PData.PathScaleY = addPacket.ObjectData.PathScaleY; + PData.PathShearX = addPacket.ObjectData.PathShearX; + PData.PathShearY = addPacket.ObjectData.PathShearY; + PData.PathSkew = addPacket.ObjectData.PathSkew; + PData.ProfileBegin = addPacket.ObjectData.ProfileBegin; + PData.ProfileEnd = addPacket.ObjectData.ProfileEnd; + PData.Scale = addPacket.ObjectData.Scale; + PData.PathCurve = addPacket.ObjectData.PathCurve; + PData.ProfileCurve = addPacket.ObjectData.ProfileCurve; + PData.ParentID = 0; + PData.ProfileHollow = addPacket.ObjectData.ProfileHollow; + PData.PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; + PData.PathRevolutions = addPacket.ObjectData.PathRevolutions; + PData.PathTaperX = addPacket.ObjectData.PathTaperX; + PData.PathTaperY = addPacket.ObjectData.PathTaperY; + PData.PathTwist = addPacket.ObjectData.PathTwist; + PData.PathTwistBegin = addPacket.ObjectData.PathTwistBegin; + LLVector3 pos1 = addPacket.ObjectData.RayEnd; + this.primData.FullID = this.uuid = LLUUID.Random(); + this.primData.LocalID = m_localId = (uint)(localID); + this.primData.Position = this.Pos = pos1; + + this.updateFlag = 1; + } + + /// + /// + /// + /// + public void CreateFromBytes(byte[] data) + { + + } + + /// + /// + /// + /// + public void CreateFromPrimData(PrimData primData) + { + this.CreateFromPrimData(primData, primData.Position, primData.LocalID, false); + } + + /// + /// + /// + /// + /// + /// + /// + public void CreateFromPrimData(PrimData primData, LLVector3 posi, uint localID, bool newprim) + { + + } + + public void GrapMovement(LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) + { + // Console.WriteLine("moving prim to new location " + pos.X + " , " + pos.Y + " , " + pos.Z); + this.Pos = pos; + this.SendTerseUpdateToALLClients(); + } + + public void GetProperites(IClientAPI client) + { + //needs changing + ObjectPropertiesPacket proper = new ObjectPropertiesPacket(); + proper.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[1]; + proper.ObjectData[0] = new ObjectPropertiesPacket.ObjectDataBlock(); + proper.ObjectData[0].ItemID = LLUUID.Zero; + proper.ObjectData[0].CreationDate = (ulong)primData.CreationDate; + proper.ObjectData[0].CreatorID = primData.OwnerID; + proper.ObjectData[0].FolderID = LLUUID.Zero; + proper.ObjectData[0].FromTaskID = LLUUID.Zero; + proper.ObjectData[0].GroupID = LLUUID.Zero; + proper.ObjectData[0].InventorySerial = 0; + proper.ObjectData[0].LastOwnerID = LLUUID.Zero; + proper.ObjectData[0].ObjectID = this.uuid; + proper.ObjectData[0].OwnerID = primData.OwnerID; + proper.ObjectData[0].TouchName = new byte[0]; + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = new byte[0]; + proper.ObjectData[0].Name = new byte[0]; + proper.ObjectData[0].Description = new byte[0]; + proper.ObjectData[0].OwnerMask = primData.OwnerMask; + proper.ObjectData[0].NextOwnerMask = primData.NextOwnerMask; + proper.ObjectData[0].GroupMask = primData.GroupMask; + proper.ObjectData[0].EveryoneMask = primData.EveryoneMask; + proper.ObjectData[0].BaseMask = primData.BaseMask; + + client.OutPacket(proper); + + } + + #endregion + + } +} diff --git a/OpenSim/Region/Simulation/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Simulation/Scenes/Scene.PacketHandlers.cs new file mode 100644 index 0000000..d1a2717 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/Scene.PacketHandlers.cs @@ -0,0 +1,305 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Region.Scenes +{ + public partial class Scene + { + /// + /// Modifies terrain using the specified information + /// + /// The height at which the user started modifying the terrain + /// The number of seconds the modify button was pressed + /// The size of the brush used + /// The action to be performed + /// Distance from the north border where the cursor is located + /// Distance from the west border where the cursor is located + public void ModifyTerrain(float height, float seconds, byte brushsize, byte action, float north, float west) + { + // Shiny. + double size = (double)(1 << brushsize); + + switch (action) + { + case 0: + // flatten terrain + Terrain.flatten(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 1: + // raise terrain + Terrain.raise(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 2: + //lower terrain + Terrain.lower(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 3: + // smooth terrain + Terrain.smooth(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 4: + // noise + Terrain.noise(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 5: + // revert + Terrain.revert(north, west, size, (double)seconds / 100.0); + RegenerateTerrain(true, (int)north, (int)west); + break; + + // CLIENT EXTENSIONS GO HERE + case 128: + // erode-thermal + break; + case 129: + // erode-aerobic + break; + case 130: + // erode-hydraulic + break; + } + return; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SimChat(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + Console.WriteLine("Chat message"); + ScenePresence avatar = null; + foreach (IClientAPI client in m_clientThreads.Values) + { + int dis = -1000; + if (this.Avatars.ContainsKey(client.AgentId)) + { + + avatar = this.Avatars[client.AgentId]; + // int dis = Util.fast_distance2d((int)(client.ClientAvatar.Pos.X - simClient.ClientAvatar.Pos.X), (int)(client.ClientAvatar.Pos.Y - simClient.ClientAvatar.Pos.Y)); + dis= (int)avatar.Pos.GetDistanceTo(fromPos); + Console.WriteLine("found avatar at " +dis); + + } + + switch (type) + { + case 0: // Whisper + if ((dis < 10) && (dis > -10)) + { + //should change so the message is sent through the avatar rather than direct to the ClientView + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + case 1: // Say + if ((dis < 30) && (dis > -30)) + { + Console.WriteLine("sending chat"); + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + case 2: // Shout + if ((dis < 100) && (dis > -100)) + { + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + + case 0xff: // Broadcast + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + break; + } + + } + } + + /// + /// + /// + /// + /// + public void RezObject(AssetBase primAsset, LLVector3 pos) + { + + } + + /// + /// + /// + /// + /// + public void DeRezObject(Packet packet, IClientAPI simClient) + { + + } + + /// + /// + /// + /// + public void SendAvatarsToClient(IClientAPI remoteClient) + { + + } + + /// + /// + /// + /// + /// + public void LinkObjects(uint parentPrim, List childPrims) + { + + + } + + /// + /// + /// + /// + /// + public void UpdatePrimShape(uint primLocalID, ObjectShapePacket.ObjectDataBlock shapeBlock) + { + + } + + /// + /// + /// + /// + /// + public void SelectPrim(uint primLocalID, IClientAPI remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.LocalId == primLocalID) + { + ((OpenSim.Region.Scenes.Primitive)ent).GetProperites(remoteClient); + break; + } + } + } + + public void MoveObject(LLUUID objectID, LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) + { + if (this.Entities.ContainsKey(objectID)) + { + ((Primitive)this.Entities[objectID]).GrapMovement(offset, pos, remoteClient); + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimFlags(uint localID, Packet packet, IClientAPI remoteClient) + { + + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient) + { + + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimPosition(uint localID, LLVector3 pos, IClientAPI remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.LocalId == localID) + { + ((OpenSim.Region.Scenes.Primitive)ent).UpdatePosition(pos); + break; + } + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient) + { + + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimScale(uint localID, LLVector3 scale, IClientAPI remoteClient) + { + } + + /// + /// Sends prims to a client + /// + /// Client to send to + public void GetInitialPrims(IClientAPI RemoteClient) + { + + } + } +} diff --git a/OpenSim/Region/Simulation/Scenes/Scene.Scripting.cs b/OpenSim/Region/Simulation/Scenes/Scene.Scripting.cs new file mode 100644 index 0000000..7b53388 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/Scene.Scripting.cs @@ -0,0 +1,184 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Reflection; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using libsecondlife; + +namespace OpenSim.Region.Scenes +{ + public partial class Scene + { + private Dictionary scriptEngines = new Dictionary(); + + /// + /// + /// + private void LoadScriptEngines() + { + this.LoadScriptPlugins(); + } + + /// + /// + /// + public void LoadScriptPlugins() + { + string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ScriptEngines"); + string[] pluginFiles = Directory.GetFiles(path, "*.dll"); + + + for (int i = 0; i < pluginFiles.Length; i++) + { + this.AddPlugin(pluginFiles[i]); + } + } + + /// + /// + /// + /// + private void AddPlugin(string FileName) + { + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IScriptEngine", true); + + if (typeInterface != null) + { + IScriptEngine plug = (IScriptEngine)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Init(this); + this.scriptEngines.Add(plug.GetName(), plug); + + } + + typeInterface = null; + } + } + } + + pluginAssembly = null; + } + + /// + /// + /// + /// + /// + /// + /// + public void LoadScript(string scriptType, string scriptName, string script, Entity ent) + { + if(this.scriptEngines.ContainsKey(scriptType)) + { + this.scriptEngines[scriptType].LoadScript(script, scriptName, ent.LocalId); + } + } + + #region IScriptAPI Methods + + /// + /// + /// + /// + /// + public LLVector3 GetEntityPosition(uint localID) + { + LLVector3 res = new LLVector3(); + // Console.WriteLine("script- getting entity " + localID + " position"); + foreach (Entity entity in this.Entities.Values) + { + if (entity.LocalId == localID) + { + res.X = entity.Pos.X; + res.Y = entity.Pos.Y; + res.Z = entity.Pos.Z; + } + } + return res; + } + + /// + /// + /// + /// + /// + /// + /// + public void SetEntityPosition(uint localID, float x , float y, float z) + { + foreach (Entity entity in this.Entities.Values) + { + if (entity.LocalId == localID && entity is Primitive) + { + LLVector3 pos = entity.Pos; + pos.X = x; + pos.Y = y; + Primitive prim = entity as Primitive; + // Of course, we really should have asked the physEngine if this is possible, and if not, returned false. + //prim.UpdatePosition(pos); + // Console.WriteLine("script- setting entity " + localID + " positon"); + } + } + + } + + /// + /// + /// + /// + public uint GetRandomAvatarID() + { + //Console.WriteLine("script- getting random avatar id"); + uint res = 0; + foreach (Entity entity in this.Entities.Values) + { + if (entity is ScenePresence) + { + res = entity.LocalId; + } + } + return res; + } + + #endregion + + + } +} diff --git a/OpenSim/Region/Simulation/Scenes/Scene.cs b/OpenSim/Region/Simulation/Scenes/Scene.cs new file mode 100644 index 0000000..bf2244e --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/Scene.cs @@ -0,0 +1,795 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using libsecondlife; +using libsecondlife.Packets; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework; +using OpenSim.Region.Scripting; +using OpenSim.Terrain; +using OpenGrid.Framework.Communications; +using OpenSim.Caches; +using OpenSim.Region; +using OpenSim.Servers; + +namespace OpenSim.Region.Scenes +{ + public delegate bool FilterAvatarList(ScenePresence avatar); + + public partial class Scene : SceneBase, ILocalStorageReceiver, IScriptAPI + { + protected System.Timers.Timer m_heartbeatTimer = new System.Timers.Timer(); + protected Dictionary Avatars; + protected Dictionary Prims; + private PhysicsScene phyScene; + private float timeStep = 0.1f; + private Random Rand = new Random(); + private uint _primCount = 702000; + private int storageCount; + private Dictionary m_scriptHandlers; + private Dictionary m_scripts; + private Mutex updateLock; + + protected AuthenticateSessionsBase authenticateHandler; + protected RegionCommsListener regionCommsHost; + protected CommunicationsManager commsManager; + + protected Dictionary capsHandlers = new Dictionary(); + protected BaseHttpServer httpListener; + + public ParcelManager parcelManager; + public EstateManager estateManager; + public EventManager eventManager; + + #region Properties + /// + /// + /// + public PhysicsScene PhysScene + { + set + { + this.phyScene = value; + } + get + { + return (this.phyScene); + } + } + + #endregion + + #region Constructors + /// + /// Creates a new World class, and a region to go with it. + /// + /// Dictionary to contain client threads + /// Region Handle for this region + /// Region Name for this region + public Scene(Dictionary clientThreads, RegionInfo regInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, BaseHttpServer httpServer) + { + try + { + updateLock = new Mutex(false); + this.authenticateHandler = authen; + this.commsManager = commsMan; + this.assetCache = assetCach; + m_clientThreads = clientThreads; + m_regInfo = regInfo; + m_regionHandle = m_regInfo.RegionHandle; + m_regionName = m_regInfo.RegionName; + this.m_datastore = m_regInfo.DataStore; + this.RegisterRegionWithComms(); + + parcelManager = new ParcelManager(this, this.m_regInfo); + estateManager = new EstateManager(this, this.m_regInfo); + + eventManager = new EventManager(); + + m_scriptHandlers = new Dictionary(); + m_scripts = new Dictionary(); + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs - creating new entitities instance"); + Entities = new Dictionary(); + Avatars = new Dictionary(); + Prims = new Dictionary(); + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs - creating LandMap"); + Terrain = new TerrainEngine(); + + ScenePresence.LoadAnims(); + this.httpListener = httpServer; + + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Error( "World.cs: Constructor failed with exception " + e.ToString()); + } + } + #endregion + + /// + /// + /// + public void StartTimer() + { + m_heartbeatTimer.Enabled = true; + m_heartbeatTimer.Interval = 100; + m_heartbeatTimer.Elapsed += new ElapsedEventHandler(this.Heartbeat); + } + + + #region Update Methods + + + /// + /// Performs per-frame updates regularly + /// + /// + /// + void Heartbeat(object sender, System.EventArgs e) + { + this.Update(); + } + + /// + /// Performs per-frame updates on the world, this should be the central world loop + /// + public override void Update() + { + updateLock.WaitOne(); + try + { + if (this.phyScene.IsThreaded) + { + this.phyScene.GetResults(); + + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].updateMovement(); + } + + lock (this.m_syncRoot) + { + this.phyScene.Simulate(timeStep); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].update(); + } + + // New + eventManager.TriggerOnFrame(); + + // TODO: Obsolete - Phase out + foreach (ScriptHandler scriptHandler in m_scriptHandlers.Values) + { + scriptHandler.OnFrame(); + } + foreach (IScriptEngine scripteng in this.scriptEngines.Values) + { + scripteng.OnFrame(); + } + + //backup world data + this.storageCount++; + if (storageCount > 1200) //set to how often you want to backup + { + this.Backup(); + storageCount = 0; + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: Update() - Failed with exception " + e.ToString()); + } + updateLock.ReleaseMutex(); + + } + + /// + /// + /// + /// + public bool Backup() + { + /* + try + { + // Terrain backup routines + if (Terrain.tainted > 0) + { + Terrain.tainted = 0; + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs: Backup() - Terrain tainted, saving."); + localStorage.SaveMap(Terrain.getHeights1D()); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs: Backup() - Terrain saved, informing Physics."); + lock (this.m_syncRoot) + { + phyScene.SetTerrain(Terrain.getHeights1D()); + } + } + + // Primitive backup routines + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs: Backup() - Backing up Primitives"); + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].BackUp(); + } + + //Parcel backup routines + ParcelData[] parcels = new ParcelData[parcelManager.parcelList.Count]; + int i = 0; + foreach (OpenSim.Region.Parcel parcel in parcelManager.parcelList.Values) + { + parcels[i] = parcel.parcelData; + i++; + } + localStorage.SaveParcels(parcels); + + // Backup successful + return true; + } + catch (Exception e) + { + // Backup failed + OpenSim.Framework.Console.MainLog.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "World.cs: Backup() - Backup Failed with exception " + e.ToString()); + return false; + } + */ + return true; + } + #endregion + + #region Regenerate Terrain + + /// + /// Rebuilds the terrain using a procedural algorithm + /// + public void RegenerateTerrain() + { + try + { + Terrain.hills(); + + lock (this.m_syncRoot) + { + this.phyScene.SetTerrain(Terrain.getHeights1D()); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + + foreach (IClientAPI client in m_clientThreads.Values) + { + this.SendLayerData(client); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); + } + } + + /// + /// Rebuilds the terrain using a 2D float array + /// + /// 256,256 float array containing heights + public void RegenerateTerrain(float[,] newMap) + { + try + { + this.Terrain.setHeights2D(newMap); + lock (this.m_syncRoot) + { + this.phyScene.SetTerrain(this.Terrain.getHeights1D()); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + + foreach (IClientAPI client in m_clientThreads.Values) + { + this.SendLayerData(client); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); + } + } + + /// + /// Rebuilds the terrain assuming changes occured at a specified point[?] + /// + /// ??? + /// ??? + /// ??? + public void RegenerateTerrain(bool changes, int pointx, int pointy) + { + try + { + if (changes) + { + /* Dont save here, rely on tainting system instead */ + + foreach (IClientAPI client in m_clientThreads.Values) + { + this.SendLayerData(pointx, pointy, client); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Load Terrain + /// + /// Loads the World heightmap + /// + /// + public override void LoadWorldMap() + { + try + { + float[] map = this.localStorage.LoadWorld(); + if (map == null) + { + if (string.IsNullOrEmpty(this.m_regInfo.estateSettings.terrainFile)) + { + Console.WriteLine("No default terrain, procedurally generating..."); + this.Terrain.hills(); + + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + } + else + { + try + { + this.Terrain.loadFromFileF32(this.m_regInfo.estateSettings.terrainFile); + this.Terrain *= this.m_regInfo.estateSettings.terrainMultiplier; + } + catch + { + Console.WriteLine("Unable to load default terrain, procedurally generating instead..."); + Terrain.hills(); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + } + } + else + { + this.Terrain.setHeights1D(map); + } + + CreateTerrainTexture(); + + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: LoadWorldMap() - Failed with exception " + e.ToString()); + } + } + + /// + /// + /// + private void CreateTerrainTexture() + { + //create a texture asset of the terrain + byte[] data = this.Terrain.exportJpegImage("defaultstripe.png"); + this.m_regInfo.estateSettings.terrainImageID = LLUUID.Random(); + AssetBase asset = new AssetBase(); + asset.FullID = this.m_regInfo.estateSettings.terrainImageID; + asset.Data = data; + asset.Name = "terrainImage"; + asset.Type = 0; + this.assetCache.AddAsset(asset); + } + #endregion + + #region Primitives Methods + + + /// + /// Loads the World's objects + /// + public void LoadPrimsFromStorage() + { + try + { + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs: LoadPrimsFromStorage() - Loading primitives"); + this.localStorage.LoadPrimitives(this); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: LoadPrimsFromStorage() - Failed with exception " + e.ToString()); + } + } + + /// + /// Loads a specific object from storage + /// + /// The object to load + public void PrimFromStorage(PrimData prim) + { + + } + + /// + /// + /// + /// + /// + public void AddNewPrim(Packet addPacket, IClientAPI agentClient) + { + AddNewPrim((ObjectAddPacket)addPacket, agentClient.AgentId); + } + + /// + /// + /// + /// + /// + public void AddNewPrim(ObjectAddPacket addPacket, LLUUID ownerID) + { + try + { + Primitive prim = new Primitive(m_regionHandle, this, addPacket, ownerID, this._primCount); + + this.Entities.Add(prim.uuid, prim); + this._primCount++; + + // Trigger event for listeners + eventManager.TriggerOnNewPrimitive(prim); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: AddNewPrim() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Add/Remove Avatar Methods + + /// + /// + /// + /// + /// + public override void AddNewClient(IClientAPI remoteClient, LLUUID agentID, bool child) + { + remoteClient.OnRegionHandShakeReply += this.SendLayerData; + //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims); + remoteClient.OnChatFromViewer += this.SimChat; + remoteClient.OnRequestWearables += this.InformClientOfNeighbours; + remoteClient.OnAddPrim += this.AddNewPrim; + remoteClient.OnUpdatePrimPosition += this.UpdatePrimPosition; + remoteClient.OnRequestMapBlocks += this.RequestMapBlocks; + remoteClient.OnTeleportLocationRequest += this.RequestTeleportLocation; + //remoteClient.OnObjectSelect += this.SelectPrim; + remoteClient.OnGrapUpdate += this.MoveObject; + + /* remoteClient.OnParcelPropertiesRequest += new ParcelPropertiesRequest(parcelManager.handleParcelPropertiesRequest); + remoteClient.OnParcelDivideRequest += new ParcelDivideRequest(parcelManager.handleParcelDivideRequest); + remoteClient.OnParcelJoinRequest += new ParcelJoinRequest(parcelManager.handleParcelJoinRequest); + remoteClient.OnParcelPropertiesUpdateRequest += new ParcelPropertiesUpdateRequest(parcelManager.handleParcelPropertiesUpdateRequest); + remoteClient.OnEstateOwnerMessage += new EstateOwnerMessageRequest(estateManager.handleEstateOwnerMessage); + */ + + ScenePresence newAvatar = null; + try + { + + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs:AddViewerAgent() - Creating new avatar for remote viewer agent"); + newAvatar = new ScenePresence(remoteClient, this, this.m_regInfo); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs:AddViewerAgent() - Adding new avatar to world"); + OpenSim.Framework.Console.MainLog.Instance.Verbose( "World.cs:AddViewerAgent() - Starting RegionHandshake "); + + //newAvatar.SendRegionHandshake(); + this.estateManager.sendRegionHandshake(remoteClient); + + PhysicsVector pVec = new PhysicsVector(newAvatar.Pos.X, newAvatar.Pos.Y, newAvatar.Pos.Z); + lock (this.m_syncRoot) + { + newAvatar.PhysActor = this.phyScene.AddAvatar(pVec); + } + + lock (Entities) + { + if (!Entities.ContainsKey(agentID)) + { + this.Entities.Add(agentID, newAvatar); + } + else + { + Entities[agentID] = newAvatar; + } + } + lock (Avatars) + { + if (Avatars.ContainsKey(agentID)) + { + Avatars[agentID] = newAvatar; + } + else + { + this.Avatars.Add(agentID, newAvatar); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: AddViewerAgent() - Failed with exception " + e.ToString()); + } + return; + } + + + + /// + /// + /// + /// + public override void RemoveClient(LLUUID agentID) + { + eventManager.TriggerOnRemovePresence(agentID); + + return; + } + #endregion + + #region Request Avatars List Methods + //The idea is to have a group of method that return a list of avatars meeting some requirement + // ie it could be all Avatars within a certain range of the calling prim/avatar. + + /// + /// Request a List of all Avatars in this World + /// + /// + public List RequestAvatarList() + { + List result = new List(); + + foreach (ScenePresence avatar in Avatars.Values) + { + result.Add(avatar); + } + + return result; + } + + /// + /// Request a filtered list of Avatars in this World + /// + /// + public List RequestAvatarList(FilterAvatarList filter) + { + List result = new List(); + + foreach (ScenePresence avatar in Avatars.Values) + { + if (filter(avatar)) + { + result.Add(avatar); + } + } + + return result; + } + + /// + /// Request a Avatar by UUID + /// + /// + /// + public ScenePresence RequestAvatar(LLUUID avatarID) + { + if (this.Avatars.ContainsKey(avatarID)) + { + return Avatars[avatarID]; + } + return null; + } + #endregion + + + #region RegionCommsHost + + /// + /// + /// + public void RegisterRegionWithComms() + { + GridInfo gridSettings = new GridInfo(); + this.regionCommsHost = this.commsManager.GridServer.RegisterRegion(this.m_regInfo,gridSettings); + if (this.regionCommsHost != null) + { + this.regionCommsHost.OnExpectUser += new ExpectUserDelegate(this.NewUserConnection); + this.regionCommsHost.OnAvatarCrossingIntoRegion += new AgentCrossing(this.AgentCrossing); + } + } + + /// + /// + /// + /// + /// + public void NewUserConnection(ulong regionHandle, AgentCircuitData agent) + { + // Console.WriteLine("World.cs - add new user connection"); + //should just check that its meant for this region + if (regionHandle == this.m_regInfo.RegionHandle) + { + if (agent.CapsPath != "") + { + //Console.WriteLine("new user, so creating caps handler for it"); + Caps cap = new Caps(this.assetCache, httpListener, this.m_regInfo.CommsIPListenAddr, 9000, agent.CapsPath, agent.AgentID); + cap.RegisterHandlers(); + this.capsHandlers.Add(agent.AgentID, cap); + } + this.authenticateHandler.AddNewCircuit(agent.circuitcode, agent); + } + } + + public void AgentCrossing(ulong regionHandle, libsecondlife.LLUUID agentID, libsecondlife.LLVector3 position) + { + if (regionHandle == this.m_regInfo.RegionHandle) + { + if (this.Avatars.ContainsKey(agentID)) + { + this.Avatars[agentID].MakeAvatar(position); + } + } + } + + /// + /// + /// + public void InformClientOfNeighbours(IClientAPI remoteClient) + { + // Console.WriteLine("informing client of neighbouring regions"); + List neighbours = this.commsManager.GridServer.RequestNeighbours(this.m_regInfo); + + //Console.WriteLine("we have " + neighbours.Count + " neighbouring regions"); + if (neighbours != null) + { + for (int i = 0; i < neighbours.Count; i++) + { + // Console.WriteLine("sending neighbours data"); + AgentCircuitData agent = remoteClient.RequestClientInfo(); + agent.BaseFolder = LLUUID.Zero; + agent.InventoryFolder = LLUUID.Zero; + agent.startpos = new LLVector3(128, 128, 70); + agent.child = true; + this.commsManager.InterRegion.InformRegionOfChildAgent(neighbours[i].RegionHandle, agent); + remoteClient.InformClientOfNeighbour(neighbours[i].RegionHandle, System.Net.IPAddress.Parse(neighbours[i].CommsIPListenAddr), (ushort)neighbours[i].CommsIPListenPort); + //this.capsHandlers[remoteClient.AgentId].CreateEstablishAgentComms("", System.Net.IPAddress.Parse(neighbours[i].CommsIPListenAddr) + ":" + neighbours[i].CommsIPListenPort); + } + } + } + + /// + /// + /// + /// + /// + public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle) + { + return this.commsManager.GridServer.RequestNeighbourInfo(regionHandle); + } + + /// + /// + /// + /// + /// + /// + /// + public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY) + { + List mapBlocks; + mapBlocks = this.commsManager.GridServer.RequestNeighbourMapBlocks(minX, minY, maxX, maxY); + remoteClient.SendMapBlock(mapBlocks); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, LLVector3 position, LLVector3 lookAt, uint flags) + { + if (regionHandle == this.m_regionHandle) + { + if (this.Avatars.ContainsKey(remoteClient.AgentId)) + { + remoteClient.SendTeleportLocationStart(); + remoteClient.SendLocalTeleport(position, lookAt, flags); + this.Avatars[remoteClient.AgentId].Teleport(position); + } + } + else + { + RegionInfo reg = this.RequestNeighbouringRegionInfo(regionHandle); + if (reg != null) + { + remoteClient.SendTeleportLocationStart(); + AgentCircuitData agent = remoteClient.RequestClientInfo(); + agent.BaseFolder = LLUUID.Zero; + agent.InventoryFolder = LLUUID.Zero; + agent.startpos = new LLVector3(128, 128, 70); + agent.child = true; + this.commsManager.InterRegion.InformRegionOfChildAgent(regionHandle, agent); + this.commsManager.InterRegion.ExpectAvatarCrossing(regionHandle, remoteClient.AgentId, position); + remoteClient.SendRegionTeleport(regionHandle, 13, reg.CommsIPListenAddr, (ushort)reg.CommsIPListenPort, 4, (1 << 4)); + } + //remoteClient.SendTeleportCancel(); + } + } + + /// + /// + /// + /// + /// + /// + public bool InformNeighbourOfCrossing(ulong regionhandle, LLUUID agentID, LLVector3 position) + { + return this.commsManager.InterRegion.ExpectAvatarCrossing(regionhandle, agentID, position); + } + + #endregion + } +} diff --git a/OpenSim/Region/Simulation/Scenes/SceneBase.cs b/OpenSim/Region/Simulation/Scenes/SceneBase.cs new file mode 100644 index 0000000..4dbd374 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/SceneBase.cs @@ -0,0 +1,201 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using libsecondlife; +using libsecondlife.Packets; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Threading; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Region.Scripting; +using OpenSim.Terrain; +using OpenSim.Caches; + +namespace OpenSim.Region.Scenes +{ + public abstract class SceneBase : IWorld + { + public Dictionary Entities; + protected Dictionary m_clientThreads; + protected ulong m_regionHandle; + protected string m_regionName; + protected RegionInfo m_regInfo; + + public TerrainEngine Terrain; + + public string m_datastore; + public ILocalStorage localStorage; + + protected object m_syncRoot = new object(); + private uint m_nextLocalId = 8880000; + protected AssetCache assetCache; + + #region Update Methods + /// + /// Normally called once every frame/tick to let the world preform anything required (like running the physics simulation) + /// + public abstract void Update(); + + #endregion + + #region Terrain Methods + + /// + /// Loads the World heightmap + /// + public abstract void LoadWorldMap(); + + /// + /// Loads a new storage subsystem from a named library + /// + /// Storage Library + /// Successful or not + public bool LoadStorageDLL(string dllName) + { + try + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + ILocalStorage store = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("ILocalStorage", true); + + if (typeInterface != null) + { + ILocalStorage plug = (ILocalStorage)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + store = plug; + + store.Initialise(this.m_datastore); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + this.localStorage = store; + return (store == null); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("World.cs: LoadStorageDLL() - Failed with exception " + e.ToString()); + return false; + } + } + + + /// + /// Send the region heightmap to the client + /// + /// Client to send to + public virtual void SendLayerData(IClientAPI RemoteClient) + { + RemoteClient.SendLayerData(Terrain.getHeights1D()); + } + + /// + /// Sends a specified patch to a client + /// + /// Patch coordinate (x) 0..16 + /// Patch coordinate (y) 0..16 + /// The client to send to + public virtual void SendLayerData(int px, int py, IClientAPI RemoteClient) + { + RemoteClient.SendLayerData(px, py, Terrain.getHeights1D()); + } + + #endregion + + #region Add/Remove Agent/Avatar + /// + /// + /// + /// + /// + /// + public abstract void AddNewClient(IClientAPI remoteClient, LLUUID agentID, bool child); + + /// + /// + /// + /// + public abstract void RemoveClient(LLUUID agentID); + + #endregion + + /// + /// + /// + /// + public virtual RegionInfo RegionInfo + { + get { return this.m_regInfo; } + } + + public object SyncRoot + { + get { return m_syncRoot; } + } + + public uint NextLocalId + { + get { return m_nextLocalId++; } + } + + #region Shutdown + /// + /// Tidy before shutdown + /// + public virtual void Close() + { + try + { + this.localStorage.ShutDown(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "World.cs: Close() - Failed with exception " + e.ToString()); + } + } + + #endregion + + + } +} diff --git a/OpenSim/Region/Simulation/Scenes/SceneEvents.cs b/OpenSim/Region/Simulation/Scenes/SceneEvents.cs new file mode 100644 index 0000000..2898578 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/SceneEvents.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scenes +{ + /// + /// A class for triggering remote scene events. + /// + public class EventManager + { + public delegate void OnFrameDelegate(); + public event OnFrameDelegate OnFrame; + + public delegate void OnNewPresenceDelegate(ScenePresence presence); + public event OnNewPresenceDelegate OnNewPresence; + + public delegate void OnNewPrimitiveDelegate(Primitive prim); + public event OnNewPrimitiveDelegate OnNewPrimitive; + + public delegate void OnRemovePresenceDelegate(libsecondlife.LLUUID uuid); + public event OnRemovePresenceDelegate OnRemovePresence; + + public void TriggerOnFrame() + { + if (OnFrame != null) + { + OnFrame(); + } + } + + public void TriggerOnNewPrimitive(Primitive prim) + { + if (OnNewPrimitive != null) + OnNewPrimitive(prim); + } + + public void TriggerOnNewPresence(ScenePresence presence) + { + if (OnNewPresence != null) + OnNewPresence(presence); + } + + public void TriggerOnRemovePresence(libsecondlife.LLUUID uuid) + { + if (OnRemovePresence != null) + { + OnRemovePresence(uuid); + } + } + } +} diff --git a/OpenSim/Region/Simulation/Scenes/SceneObject.cs b/OpenSim/Region/Simulation/Scenes/SceneObject.cs new file mode 100644 index 0000000..5df87bf --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/SceneObject.cs @@ -0,0 +1,128 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; + +namespace OpenSim.Region.Scenes +{ + public class SceneObject : Entity + { + private LLUUID rootUUID; + //private Dictionary ChildPrimitives = new Dictionary(); + protected Primitive rootPrimitive; + private Scene m_world; + protected ulong regionHandle; + + /// + /// + /// + public SceneObject() + { + + } + + /// + /// + /// + /// + /// + /// + public void CreateFromPacket(ObjectAddPacket addPacket, LLUUID agentID, uint localID) + { + this.rootPrimitive = new Primitive( this.regionHandle, this.m_world, addPacket, agentID, localID); + } + + /// + /// + /// + /// + public void CreateFromBytes(byte[] data) + { + + } + + /// + /// + /// + public override void update() + { + + } + + /// + /// + /// + public override void BackUp() + { + + } + + /// + /// + /// + /// + public void GetProperites(IClientAPI client) + { + //needs changing + ObjectPropertiesPacket proper = new ObjectPropertiesPacket(); + proper.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[1]; + proper.ObjectData[0] = new ObjectPropertiesPacket.ObjectDataBlock(); + proper.ObjectData[0].ItemID = LLUUID.Zero; + proper.ObjectData[0].CreationDate = (ulong)this.rootPrimitive.primData.CreationDate; + proper.ObjectData[0].CreatorID = this.rootPrimitive.primData.OwnerID; + proper.ObjectData[0].FolderID = LLUUID.Zero; + proper.ObjectData[0].FromTaskID = LLUUID.Zero; + proper.ObjectData[0].GroupID = LLUUID.Zero; + proper.ObjectData[0].InventorySerial = 0; + proper.ObjectData[0].LastOwnerID = LLUUID.Zero; + proper.ObjectData[0].ObjectID = this.uuid; + proper.ObjectData[0].OwnerID = this.rootPrimitive.primData.OwnerID; + proper.ObjectData[0].TouchName = new byte[0]; + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = new byte[0]; + proper.ObjectData[0].Name = new byte[0]; + proper.ObjectData[0].Description = new byte[0]; + proper.ObjectData[0].OwnerMask = this.rootPrimitive.primData.OwnerMask; + proper.ObjectData[0].NextOwnerMask = this.rootPrimitive.primData.NextOwnerMask; + proper.ObjectData[0].GroupMask = this.rootPrimitive.primData.GroupMask; + proper.ObjectData[0].EveryoneMask = this.rootPrimitive.primData.EveryoneMask; + proper.ObjectData[0].BaseMask = this.rootPrimitive.primData.BaseMask; + + client.OutPacket(proper); + + } + + } +} diff --git a/OpenSim/Region/Simulation/Scenes/ScenePresence.Animations.cs b/OpenSim/Region/Simulation/Scenes/ScenePresence.Animations.cs new file mode 100644 index 0000000..f0a8721 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/ScenePresence.Animations.cs @@ -0,0 +1,76 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using System.Xml; + +namespace OpenSim.Region.Scenes +{ + partial class ScenePresence + { + public class AvatarAnimations + { + + public Dictionary AnimsLLUUID = new Dictionary(); + public Dictionary AnimsNames = new Dictionary(); + + public AvatarAnimations() + { + } + + public void LoadAnims() + { + //OpenSim.Framework.Console.MainLog.Instance.Verbose("Avatar.cs:LoadAnims() - Loading avatar animations"); + XmlTextReader reader = new XmlTextReader("data/avataranimations.xml"); + + XmlDocument doc = new XmlDocument(); + doc.Load(reader); + foreach (XmlNode nod in doc.DocumentElement.ChildNodes) + { + + if (nod.Attributes["name"] != null) + { + AnimsLLUUID.Add(nod.Attributes["name"].Value, nod.InnerText); + } + + } + + reader.Close(); + + // OpenSim.Framework.Console.MainLog.Instance.Verbose("Loaded " + AnimsLLUUID.Count.ToString() + " animation(s)"); + + foreach (KeyValuePair kp in OpenSim.Region.Scenes.ScenePresence.Animations.AnimsLLUUID) + { + AnimsNames.Add(kp.Value, kp.Key); + } + } + } + } +} diff --git a/OpenSim/Region/Simulation/Scenes/ScenePresence.Body.cs b/OpenSim/Region/Simulation/Scenes/ScenePresence.Body.cs new file mode 100644 index 0000000..d21b11f --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/ScenePresence.Body.cs @@ -0,0 +1,90 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Scenes +{ + partial class ScenePresence + { + public class Avatar : IScenePresenceBody + { + public Avatar() + { + + } + + public void processMovement(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation) + { + } + + public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + { + } + + public void SendOurAppearance(IClientAPI OurClient) + { + } + + public void SendAppearanceToOtherAgent(ScenePresence avatarInfo) + { + } + } + + public class ChildAgent : IScenePresenceBody //is a ghost + { + public ChildAgent() + { + + } + + public void processMovement(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation) + { + } + + public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + { + } + + public void SendOurAppearance(IClientAPI OurClient) + { + } + + public void SendAppearanceToOtherAgent(ScenePresence avatarInfo) + { + } + } + } + +} diff --git a/OpenSim/Region/Simulation/Scenes/ScenePresence.cs b/OpenSim/Region/Simulation/Scenes/ScenePresence.cs new file mode 100644 index 0000000..45d3fed --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/ScenePresence.cs @@ -0,0 +1,525 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using Axiom.MathLib; + +namespace OpenSim.Region.Scenes +{ + public partial class ScenePresence : Entity + { + public static bool PhysicsEngineFlying = false; + public static AvatarAnimations Animations; + public static byte[] DefaultTexture; + public string firstname; + public string lastname; + public IClientAPI ControllingClient; + public LLUUID current_anim; + public int anim_seq; + private bool updateflag = false; + private byte movementflag = 0; + private List forcesList = new List(); + private short _updateCount = 0; + private Axiom.MathLib.Quaternion bodyRot; + private LLObject.TextureEntry avatarAppearanceTexture = null; + private byte[] visualParams; + private AvatarWearable[] Wearables; + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + private ulong m_regionHandle; + private bool childAgent = false; + private bool newForce = false; + private bool newAvatar = false; + private IScenePresenceBody m_body; + + protected RegionInfo m_regionInfo; + + #region Properties + /// + /// + /// + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + get + { + return _physActor; + } + } + #endregion + + #region Constructor(s) + /// + /// + /// + /// + /// + /// + /// + public ScenePresence(IClientAPI theClient, Scene world, RegionInfo reginfo) + { + + m_world = world; + this.uuid = theClient.AgentId; + + m_regionInfo = reginfo; + m_regionHandle = reginfo.RegionHandle; + OpenSim.Framework.Console.MainLog.Instance.Verbose("Avatar.cs "); + ControllingClient = theClient; + this.firstname = ControllingClient.FirstName; + this.lastname = ControllingClient.LastName; + m_localId = m_world.NextLocalId; + Pos = ControllingClient.StartPos; + visualParams = new byte[218]; + for (int i = 0; i < 218; i++) + { + visualParams[i] = 100; + } + + Wearables = AvatarWearable.DefaultWearables; + + this.avatarAppearanceTexture = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + + //register for events + ControllingClient.OnRequestWearables += this.SendOurAppearance; + //ControllingClient.OnSetAppearance += new SetAppearance(this.SetAppearance); + ControllingClient.OnCompleteMovementToRegion += this.CompleteMovement; + ControllingClient.OnCompleteMovementToRegion += this.SendInitialData; + ControllingClient.OnAgentUpdate += this.HandleAgentUpdate; + // ControllingClient.OnStartAnim += new StartAnim(this.SendAnimPack); + // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange); + //ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement); + + } + #endregion + + #region Status Methods + /// + /// Not Used, most likely can be deleted + /// + /// + public void ChildStatusChange(bool status) + { + this.childAgent = status; + + if (this.childAgent == true) + { + this.Velocity = new LLVector3(0, 0, 0); + this.Pos = new LLVector3(128, 128, 70); + + } + } + + /// + /// + /// + /// + public void MakeAvatar(LLVector3 pos) + { + //this.childAvatar = false; + this.Pos = pos; + this.newAvatar = true; + this.childAgent = false; + } + + protected void MakeChildAgent() + { + this.Velocity = new LLVector3(0, 0, 0); + this.Pos = new LLVector3(128, 128, 70); + this.childAgent = true; + } + + /// + /// + /// + /// + public void Teleport(LLVector3 pos) + { + this.Pos = pos; + this.SendTerseUpdateToALLClients(); + } + + /// + /// + /// + public void StopMovement() + { + + } + #endregion + + #region Event Handlers + /// + /// + /// + /// + /// + public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + { + + } + + /// + /// Complete Avatar's movement into the region + /// + public void CompleteMovement() + { + LLVector3 look = this.Velocity; + if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) + { + look = new LLVector3(0.99f, 0.042f, 0); + } + this.ControllingClient.MoveAgentIntoRegion(m_regionInfo, Pos, look); + if (this.childAgent) + { + this.childAgent = false; + } + } + + /// + /// + /// + /// + public void HandleAgentUpdate(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation) + { + if ((flags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_AT_POS) != 0) + { + Axiom.MathLib.Quaternion q = new Axiom.MathLib.Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); + if (((movementflag & 1) == 0) || (q != this.bodyRot)) + { + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(1, 0, 0); + this.AddNewMovement(v3, q); + movementflag = 1; + this.bodyRot = q; + } + } + else if ((flags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_AT_NEG) != 0) + { + Axiom.MathLib.Quaternion q = new Axiom.MathLib.Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); + if (((movementflag & 2) == 0) || (q != this.bodyRot)) + { + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(-1, 0, 0); + this.AddNewMovement(v3, q); + movementflag = 2; + this.bodyRot = q; + } + } + else + { + if ((movementflag) != 0) + { + NewForce newVelocity = new NewForce(); + newVelocity.X = 0; + newVelocity.Y = 0; + newVelocity.Z = 0; + this.forcesList.Add(newVelocity); + movementflag = 0; + } + } + + } + + protected void AddNewMovement(Axiom.MathLib.Vector3 vec, Axiom.MathLib.Quaternion rotation) + { + NewForce newVelocity = new NewForce(); + Axiom.MathLib.Vector3 direc = rotation * vec; + direc.Normalize(); + + direc = direc * ((0.03f) * 128f); + if (this._physActor.Flying) + direc *= 4; + + newVelocity.X = direc.x; + newVelocity.Y = direc.y; + newVelocity.Z = direc.z; + this.forcesList.Add(newVelocity); + } + + #endregion + + #region Overridden Methods + /// + /// + /// + public override void LandRenegerated() + { + + } + + /// + /// + /// + public override void update() + { + if (this.childAgent == false) + { + if (this.newForce) + { + this.SendTerseUpdateToALLClients(); + _updateCount = 0; + } + else if (movementflag != 0) + { + _updateCount++; + if (_updateCount > 3) + { + this.SendTerseUpdateToALLClients(); + _updateCount = 0; + } + } + + this.CheckForBorderCrossing(); + } + } + #endregion + + #region Update Client(s) + /// + /// + /// + /// + public void SendTerseUpdateToClient(IClientAPI RemoteClient) + { + LLVector3 pos = this.Pos; + LLVector3 vel = this.Velocity; + RemoteClient.SendAvatarTerseUpdate(this.m_regionHandle, 64096, this.LocalId, new LLVector3(pos.X, pos.Y, pos.Z), new LLVector3(vel.X, vel.Y, vel.Z)); + } + + /// + /// + /// + public void SendTerseUpdateToALLClients() + { + List avatars = this.m_world.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + this.SendTerseUpdateToClient(avatars[i].ControllingClient); + } + } + + /// + /// + /// + /// + public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar) + { + remoteAvatar.ControllingClient.SendAvatarData(m_regionInfo.RegionHandle, this.firstname, this.lastname, this.uuid, this.LocalId, this.Pos, DefaultTexture); + } + + /// + /// + /// + public void SendInitialData() + { + this.ControllingClient.SendAvatarData(m_regionInfo.RegionHandle, this.firstname, this.lastname, this.uuid, this.LocalId, this.Pos, DefaultTexture); + if (this.newAvatar) + { + this.m_world.InformClientOfNeighbours(this.ControllingClient); + this.newAvatar = false; + } + } + + /// + /// + /// + /// + public void SendOurAppearance(IClientAPI OurClient) + { + this.ControllingClient.SendWearables(this.Wearables); + } + + /// + /// + /// + /// + public void SendAppearanceToOtherAgent(ScenePresence avatarInfo) + { + + } + + /// + /// + /// + /// + /// + public void SendAnimPack(LLUUID animID, int seq) + { + + + } + + /// + /// + /// + public void SendAnimPack() + { + + } + #endregion + + #region Border Crossing Methods + /// + /// + /// + protected void CheckForBorderCrossing() + { + LLVector3 pos2 = this.Pos; + LLVector3 vel = this.Velocity; + + float timeStep = 0.2f; + pos2.X = pos2.X + (vel.X * timeStep); + pos2.Y = pos2.Y + (vel.Y * timeStep); + pos2.Z = pos2.Z + (vel.Z * timeStep); + + if ((pos2.X < 0) || (pos2.X > 256)) + { + this.CrossToNewRegion(); + } + + if ((pos2.Y < 0) || (pos2.Y > 256)) + { + this.CrossToNewRegion(); + } + } + + /// + /// + /// + protected void CrossToNewRegion() + { + LLVector3 pos = this.Pos; + LLVector3 newpos = new LLVector3(pos.X, pos.Y, pos.Z); + uint neighbourx = this.m_regionInfo.RegionLocX; + uint neighboury = this.m_regionInfo.RegionLocY; + + if (pos.X < 2) + { + neighbourx -= 1; + newpos.X = 254; + } + if (pos.X > 253) + { + neighbourx += 1; + newpos.X = 1; + } + if (pos.Y < 2) + { + neighboury -= 1; + newpos.Y = 254; + } + if (pos.Y > 253) + { + neighboury += 1; + newpos.Y = 1; + } + + LLVector3 vel = this.velocity; + ulong neighbourHandle = Helpers.UIntsToLong((uint)(neighbourx * 256), (uint)(neighboury * 256)); + RegionInfo neighbourRegion = this.m_world.RequestNeighbouringRegionInfo(neighbourHandle); + if (neighbourRegion != null) + { + bool res = this.m_world.InformNeighbourOfCrossing(neighbourHandle, this.ControllingClient.AgentId, newpos); + if (res) + { + this.MakeChildAgent(); + this.ControllingClient.CrossRegion(neighbourHandle, newpos, vel, System.Net.IPAddress.Parse(neighbourRegion.CommsIPListenAddr), (ushort)neighbourRegion.CommsIPListenPort); + } + } + } + #endregion + + /// + /// + /// + public static void LoadAnims() + { + + } + + /// + /// + /// + public override void updateMovement() + { + newForce = false; + lock (this.forcesList) + { + if (this.forcesList.Count > 0) + { + for (int i = 0; i < this.forcesList.Count; i++) + { + NewForce force = this.forcesList[i]; + + this.updateflag = true; + this.Velocity = new LLVector3(force.X, force.Y, force.Z); + this.newForce = true; + } + for (int i = 0; i < this.forcesList.Count; i++) + { + this.forcesList.RemoveAt(0); + } + } + } + } + + public static void LoadTextureFile(string name) + { + FileInfo fInfo = new FileInfo(name); + long numBytes = fInfo.Length; + FileStream fStream = new FileStream(name, FileMode.Open, FileAccess.Read); + BinaryReader br = new BinaryReader(fStream); + byte[] data1 = br.ReadBytes((int)numBytes); + br.Close(); + fStream.Close(); + DefaultTexture = data1; + } + + public class NewForce + { + public float X; + public float Y; + public float Z; + + public NewForce() + { + + } + } + } + +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/IScriptContext.cs b/OpenSim/Region/Simulation/Scenes/scripting/IScriptContext.cs new file mode 100644 index 0000000..daa1b92 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/IScriptContext.cs @@ -0,0 +1,40 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Region.Scripting +{ + public interface IScriptContext + { + IScriptEntity Entity { get; } + bool TryGetRandomAvatar(out IScriptReadonlyEntity avatar); + } +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/IScriptEntity.cs b/OpenSim/Region/Simulation/Scenes/scripting/IScriptEntity.cs new file mode 100644 index 0000000..44b886f --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/IScriptEntity.cs @@ -0,0 +1,46 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Region.Scripting +{ + public interface IScriptReadonlyEntity + { + LLVector3 Pos { get; } + string Name { get; } + } + + public interface IScriptEntity + { + LLVector3 Pos { get; set; } + string Name { get; } + } +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/IScriptHandler.cs b/OpenSim/Region/Simulation/Scenes/scripting/IScriptHandler.cs new file mode 100644 index 0000000..797998d --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/IScriptHandler.cs @@ -0,0 +1,126 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Physics.Manager; +using OpenSim.Region; +using OpenSim.Region.Scenes; +using Avatar=OpenSim.Region.Scenes.ScenePresence; +using Primitive = OpenSim.Region.Scenes.Primitive; + +namespace OpenSim.Region.Scripting +{ + public delegate void ScriptEventHandler(IScriptContext context); + + public class ScriptHandler : IScriptContext, IScriptEntity, IScriptReadonlyEntity + { + private Scene m_world; + private Script m_script; + private Entity m_entity; + + public LLUUID ScriptId + { + get + { + return m_script.ScriptId; + } + } + + public void OnFrame() + { + m_script.OnFrame(this); + } + + public ScriptHandler(Script script, Entity entity, Scene world) + { + m_script = script; + m_entity = entity; + m_world = world; + } + + #region IScriptContext Members + + IScriptEntity IScriptContext.Entity + { + get + { + return this; + } + } + + bool IScriptContext.TryGetRandomAvatar(out IScriptReadonlyEntity avatar) + { + foreach (Entity entity in m_world.Entities.Values ) + { + if( entity is Avatar ) + { + avatar = entity; + return true; + } + } + + avatar = null; + return false; + } + + #endregion + + #region IScriptEntity and IScriptReadonlyEntity Members + + public string Name + { + get + { + return m_entity.Name; + } + } + + public LLVector3 Pos + { + get + { + return m_entity.Pos; + } + + set + { + if (m_entity is Primitive) + { + Primitive prim = m_entity as Primitive; + // Of course, we really should have asked the physEngine if this is possible, and if not, returned false. + // prim.UpdatePosition( value ); + } + } + } + + #endregion + } + +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/Script.cs b/OpenSim/Region/Simulation/Scenes/scripting/Script.cs new file mode 100644 index 0000000..1d01f3c --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/Script.cs @@ -0,0 +1,53 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Region.Scripting +{ + public class Script + { + private LLUUID m_scriptId; + public virtual LLUUID ScriptId + { + get + { + return m_scriptId; + } + } + + public Script( LLUUID scriptId ) + { + m_scriptId = scriptId; + } + + public ScriptEventHandler OnFrame; + } +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/ScriptFactory.cs b/OpenSim/Region/Simulation/Scenes/scripting/ScriptFactory.cs new file mode 100644 index 0000000..32ef046 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/ScriptFactory.cs @@ -0,0 +1,35 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting +{ + public delegate Script ScriptFactory(); +} diff --git a/OpenSim/Region/Simulation/Scenes/scripting/Scripts/FollowRandomAvatar.cs b/OpenSim/Region/Simulation/Scenes/scripting/Scripts/FollowRandomAvatar.cs new file mode 100644 index 0000000..21f07a8 --- /dev/null +++ b/OpenSim/Region/Simulation/Scenes/scripting/Scripts/FollowRandomAvatar.cs @@ -0,0 +1,64 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Region.Scripting +{ + public class FollowRandomAvatar : Script + { + public FollowRandomAvatar() + : base(LLUUID.Random()) + { + OnFrame += MyOnFrame; + } + + private void MyOnFrame(IScriptContext context) + { + LLVector3 pos = context.Entity.Pos; + + IScriptReadonlyEntity avatar; + + if (context.TryGetRandomAvatar(out avatar)) + { + LLVector3 avatarPos = avatar.Pos; + + float x = pos.X + ((float)avatarPos.X.CompareTo(pos.X)) / 2; + float y = pos.Y + ((float)avatarPos.Y.CompareTo(pos.Y)) / 2; + + LLVector3 newPos = new LLVector3(x, y, pos.Z); + + context.Entity.Pos = newPos; + } + } + } + + +} diff --git a/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs new file mode 100644 index 0000000..ab3c34c --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs @@ -0,0 +1,117 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +// BDB Support +// Apparently broken on Mono + +using System; +using System.Collections.Generic; +using System.Data; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using BerkeleyDb; +using Kds.Serialization; +using Kds.Serialization.Buffer; + +namespace OpenSim.Storage.LocalStorageBDB +{ + public class BDBLocalStorage : ILocalStorage + { + const string simDbName = "localsim.db"; + + DbHash sim; + Db DB; + //BEFormatter formatter; + + public BDBLocalStorage() + { + DB = new Db(DbCreateFlags.None); + sim = (DbHash)DB.Open(null, simDbName, null, BerkeleyDb.DbType.Hash, Db.OpenFlags.Create, 0); + //vendorDb = (DbBTree)db.Open(null, VendorDbName, null, DbType.BTree, Db.OpenFlags.Create, 0); + } + + public void Initialise(string file) + { + // Blank + } + + public void StorePrim(PrimData prim) + { + DbEntry key = new DbEntry(); + DbEntry data = new DbEntry(); + lock (sim) + { + sim.PutUnique(null, ref key, ref data, DbFile.WriteFlags.AutoCommit); + } + } + public void RemovePrim(LLUUID primID) + { + + } + public void LoadPrimitives(ILocalStorageReceiver receiver) + { + + } + public float[] LoadWorld() + { + return new float[65536]; + } + public void SaveMap(float[] heightmap) + { + + } + + public void SaveParcels(ParcelData[] parcel_data) + { + } + + public void SaveParcel(ParcelData parcel) + { + } + + public void RemoveParcel(ParcelData parcel) + { + } + + public void RemoveAllParcels() + { + } + + public void LoadParcels(ILocalStorageParcelReceiver recv) + { + recv.NoParcelDataFromStorage(); + } + + public void ShutDown() + { + sim.GetDb().Close(); + DB.Close(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj new file mode 100644 index 0000000..b956c9b --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {A4691E59-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Storage.LocalStorageBerkeleyDB + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Storage.LocalStorageBerkeleyDB + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Kds.Serialization.dll + False + + + ..\..\..\..\bin\libdb_dotNET43.dll + False + + + ..\..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj.user b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Region.Storage.LocalStorageBerkeleyDB.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build new file mode 100644 index 0000000..bc2d8ec --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs b/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs new file mode 100644 index 0000000..ea2b62e --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("Db4LocalStorage")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Db4LocalStorage")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs b/OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs new file mode 100644 index 0000000..8e6b04d --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs @@ -0,0 +1,271 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; + +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Console; + + +namespace OpenSim.Storage.LocalStorageDb4o +{ + /// + /// + /// + public class Db4LocalStorage : ILocalStorage + { + private IObjectContainer db; + private string datastore; + + public Db4LocalStorage() + { + + } + + public void Initialise(string dfile) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Db4LocalStorage Opening " + dfile); + datastore = dfile; + try + { + db = Db4oFactory.OpenFile(datastore); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Db4LocalStorage creation"); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainLog.Instance.Warn("Db4LocalStorage :Constructor - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + } + + public void StorePrim(PrimData prim) + { + IObjectSet result = db.Query(new UUIDPrimQuery(prim.FullID)); + if (result.Count > 0) + { + //prim already in storage + //so update it + PrimData found = (PrimData)result.Next(); + found.PathBegin = prim.PathBegin; + found.PathCurve = prim.PathCurve; + found.PathEnd = prim.PathEnd; + found.PathRadiusOffset = prim.PathRadiusOffset; + found.PathRevolutions = prim.PathRevolutions; + found.PathScaleX = prim.PathScaleX; + found.PathScaleY = prim.PathScaleY; + found.PathShearX = prim.PathShearX; + found.PathShearY = prim.PathShearY; + found.PathSkew = prim.PathSkew; + found.PathTaperX = prim.PathTaperX; + found.PathTaperY = prim.PathTaperY; + found.PathTwist = prim.PathTwist; + found.PathTwistBegin = prim.PathTwistBegin; + found.PCode = prim.PCode; + found.ProfileBegin = prim.ProfileBegin; + found.ProfileCurve = prim.ProfileCurve; + found.ProfileEnd = prim.ProfileEnd; + found.ProfileHollow = prim.ProfileHollow; + found.Position = prim.Position; + found.Rotation = prim.Rotation; + found.TextureEntry = prim.TextureEntry; + db.Set(found); + db.Commit(); + } + else + { + //not in storage + db.Set(prim); + db.Commit(); + } + } + + public void RemovePrim(LLUUID primID) + { + IObjectSet result = db.Query(new UUIDPrimQuery(primID)); + if (result.Count > 0) + { + PrimData found = (PrimData)result.Next(); + db.Delete(found); + } + } + + + public void LoadPrimitives(ILocalStorageReceiver receiver) + { + IObjectSet result = db.Get(typeof(PrimData)); + OpenSim.Framework.Console.MainLog.Instance.Verbose("Db4LocalStorage.cs: LoadPrimitives() - number of prims in storages is " + result.Count); + foreach (PrimData prim in result) + { + receiver.PrimFromStorage(prim); + } + } + + public float[] LoadWorld() + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("LoadWorld() - Loading world...."); + float[] heightmap = null; + OpenSim.Framework.Console.MainLog.Instance.Verbose("LoadWorld() - Looking for a heightmap in local DB"); + IObjectSet world_result = db.Get(typeof(MapStorage)); + if (world_result.Count > 0) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("LoadWorld() - Found a heightmap in local database, loading"); + MapStorage map = (MapStorage)world_result.Next(); + //blank.LandMap = map.Map; + heightmap = map.Map; + } + return heightmap; + } + + public void SaveMap(float[] heightmap) + { + IObjectSet world_result = db.Get(typeof(MapStorage)); + if (world_result.Count > 0) + { + OpenSim.Framework.Console.MainLog.Instance.Verbose("SaveWorld() - updating saved copy of heightmap in local database"); + MapStorage map = (MapStorage)world_result.Next(); + db.Delete(map); + } + MapStorage map1 = new MapStorage(); + map1.Map = heightmap; //OpenSim_Main.local_world.LandMap; + db.Set(map1); + db.Commit(); + } + + public void SaveParcel(ParcelData parcel) + { + IObjectSet result = db.Query(new UUIDParcelQuery(parcel.globalID)); + if (result.Count > 0) + { + //Old Parcel + ParcelData updateParcel = (ParcelData)result.Next(); + updateParcel.AABBMax = parcel.AABBMax; + updateParcel.AABBMin = parcel.AABBMin; + updateParcel.area = parcel.area; + updateParcel.auctionID = parcel.auctionID; + updateParcel.authBuyerID = parcel.authBuyerID; + updateParcel.category = parcel.category; + updateParcel.claimDate = parcel.claimDate; + updateParcel.claimPrice = parcel.claimPrice; + updateParcel.groupID = parcel.groupID; + updateParcel.groupPrims = parcel.groupPrims; + updateParcel.isGroupOwned = parcel.isGroupOwned; + updateParcel.landingType = parcel.landingType; + updateParcel.mediaAutoScale = parcel.mediaAutoScale; + updateParcel.mediaID = parcel.mediaID; + updateParcel.mediaURL = parcel.mediaURL; + updateParcel.musicURL = parcel.musicURL; + updateParcel.localID = parcel.localID; + updateParcel.ownerID = parcel.ownerID; + updateParcel.passHours = parcel.passHours; + updateParcel.passPrice = parcel.passPrice; + updateParcel.parcelBitmapByteArray = (byte[])parcel.parcelBitmapByteArray.Clone(); + updateParcel.parcelDesc = parcel.parcelDesc; + updateParcel.parcelFlags = parcel.parcelFlags; + updateParcel.parcelName = parcel.parcelName; + updateParcel.parcelStatus = parcel.parcelStatus; + updateParcel.salePrice = parcel.salePrice; + updateParcel.snapshotID = parcel.snapshotID; + updateParcel.userLocation = parcel.userLocation; + updateParcel.userLookAt = parcel.userLookAt; + + db.Set(updateParcel); + } + else + { + db.Set(parcel); + } + db.Commit(); + } + + public void SaveParcels(ParcelData[] parcel_data) + { + MainLog.Instance.Notice("Parcel Backup: Saving Parcels..."); + int i; + for (i = 0; i < parcel_data.GetLength(0); i++) + { + + SaveParcel(parcel_data[i]); + + } + MainLog.Instance.Notice("Parcel Backup: Parcel Save Complete"); + } + + public void RemoveParcel(ParcelData parcel) + { + IObjectSet result = db.Query(new UUIDParcelQuery(parcel.globalID)); + if (result.Count > 0) + { + db.Delete(result[0]); + } + db.Commit(); + } + public void RemoveAllParcels() + { + MainLog.Instance.Notice("Parcel Backup: Removing all parcels..."); + IObjectSet result = db.Get(typeof(ParcelData)); + if (result.Count > 0) + { + foreach (ParcelData parcelData in result) + { + RemoveParcel(parcelData); + } + } + } + + public void LoadParcels(ILocalStorageParcelReceiver recv) + { + MainLog.Instance.Notice("Parcel Backup: Loading Parcels..."); + IObjectSet result = db.Get(typeof(ParcelData)); + if (result.Count > 0) + { + MainLog.Instance.Notice("Parcel Backup: Parcels exist in database."); + foreach (ParcelData parcelData in result) + { + + recv.ParcelFromStorage(parcelData); + } + } + else + { + MainLog.Instance.Notice("Parcel Backup: No parcels exist. Creating basic parcel."); + recv.NoParcelDataFromStorage(); + } + MainLog.Instance.Notice("Parcel Backup: Parcels Restored"); + } + public void ShutDown() + { + db.Commit(); + db.Close(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs b/OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs new file mode 100644 index 0000000..56387ac --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs @@ -0,0 +1,43 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + public class MapStorage + { + public float[] Map; + + public MapStorage() + { + + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj b/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj new file mode 100644 index 0000000..147158c --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj @@ -0,0 +1,116 @@ + + + Local + 8.0.50727 + 2.0 + {43DB702D-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Storage.LocalStorageDb4o + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Storage.LocalStorageDb4o + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj.user b/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/OpenSim.Region.Storage.LocalStorageDb4o.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs new file mode 100644 index 0000000..d24fb5f --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs @@ -0,0 +1,52 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + public class UUIDParcelQuery : Predicate + { + private LLUUID globalIDSearch; + + public UUIDParcelQuery(LLUUID find) + { + globalIDSearch = find; + } + public bool Match(ParcelData parcel) + { + return (parcel.globalID == globalIDSearch); + } + } +} diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs new file mode 100644 index 0000000..b2e8a91 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs @@ -0,0 +1,52 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + public class UUIDPrimQuery : Predicate + { + private LLUUID _findID; + + public UUIDPrimQuery(LLUUID find) + { + _findID = find; + } + public bool Match(PrimData prim) + { + return (prim.FullID == _findID); + } + } +} diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj new file mode 100644 index 0000000..d1353a5 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj @@ -0,0 +1,111 @@ + + + Local + 8.0.50727 + 2.0 + {477B9270-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Storage.LocalStorageSQLite + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Storage.LocalStorageSQLite + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\..\bin\libsecondlife.dll + False + + + System.dll + False + + + System.Data.dll + False + + + ..\..\..\..\bin\System.Data.SQLite.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj.user b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Region.Storage.LocalStorageSQLite.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build new file mode 100644 index 0000000..bd4c731 --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs b/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b45debf --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs @@ -0,0 +1,62 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Storage.LocalStorageSQLite")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Storage.LocalStorageSQLite")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ecd6e0c1-7909-413e-9e3f-659678ac3bc3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.*")] +[assembly: AssemblyFileVersion("1.0.0.*")] diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs b/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs new file mode 100644 index 0000000..8a7893e --- /dev/null +++ b/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs @@ -0,0 +1,198 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +// SQLite Support +// A bad idea, but the IRC people told me to! + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SQLite; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Storage.LocalStorageSQLite +{ + public class SQLiteLocalStorage : ILocalStorage + { + IDbConnection db; + + public SQLiteLocalStorage() + { + try + { + string connectionstring = "URI=file:localsim.sdb"; + db = (IDbConnection)new SQLiteConnection(connectionstring); + db.Open(); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainLog.Instance.Warn("SQLiteLocalStorage :Constructor - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + } + + public void Initialise(string file) + { + // Blank + } + + public void StorePrim(PrimData prim) + { + IDbCommand cmd = db.CreateCommand(); + + //SECURITY WARNING: + // These parameters wont produce SQL injections since they are all integer based, however. + // if inserting strings such as name or description, you will need to use appropriate + // measures to prevent SQL injection (although the value of SQL injection in this is limited). + + string sql = "REPLACE INTO prim (OwnerID,PCode,PathBegin,PathEnd,PathScaleX,PathScaleY,PathShearX,PathShearY,PathSkew,ProfileBegin,ProfileEnd,Scale,PathCurve,ProfileCurve,ParentID,ProfileHollow,PathRadiusOffset,PathRevolutions,PathTaperX,PathTaperY,PathTwist,PathTwistBegin,Texture,CreationDate,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,Position,Rotation,LocalID,FullID) "; + sql += "VALUES ("; + sql += "\"" + prim.OwnerID.ToStringHyphenated() + "\","; // KILL ME NOW! + sql += "\"" + prim.PCode.ToString() + "\","; + sql += "\"" + prim.PathBegin.ToString() + "\","; + sql += "\"" + prim.PathEnd.ToString() + "\","; + sql += "\"" + prim.PathScaleX.ToString() + "\","; + sql += "\"" + prim.PathScaleY.ToString() + "\","; + sql += "\"" + prim.PathShearX.ToString() + "\","; + sql += "\"" + prim.PathShearY.ToString() + "\","; + sql += "\"" + prim.PathSkew.ToString() + "\","; + sql += "\"" + prim.ProfileBegin.ToString() + "\","; + sql += "\"" + prim.ProfileEnd.ToString() + "\","; + sql += "\"" + prim.Scale.ToString() + "\","; + sql += "\"" + prim.PathCurve.ToString() + "\","; + sql += "\"" + prim.ProfileCurve.ToString() + "\","; + sql += "\"" + prim.ParentID.ToString() + "\","; + sql += "\"" + prim.ProfileHollow.ToString() + "\","; + sql += "\"" + prim.PathRadiusOffset.ToString() + "\","; + sql += "\"" + prim.PathRevolutions.ToString() + "\","; + sql += "\"" + prim.PathTaperX.ToString() + "\","; + sql += "\"" + prim.PathTaperY.ToString() + "\","; + sql += "\"" + prim.PathTwist.ToString() + "\","; + sql += "\"" + prim.PathTwistBegin.ToString() + "\","; + sql += "\"" + prim.TextureEntry.ToString() + "\","; + sql += "\"" + prim.CreationDate.ToString() + "\","; + sql += "\"" + prim.OwnerMask.ToString() + "\","; + sql += "\"" + prim.NextOwnerMask.ToString() + "\","; + sql += "\"" + prim.GroupMask.ToString() + "\","; + sql += "\"" + prim.EveryoneMask.ToString() + "\","; + sql += "\"" + prim.BaseMask.ToString() + "\","; + sql += "\"" + prim.Position.ToString() + "\","; + sql += "\"" + prim.Rotation.ToString() + "\","; + sql += "\"" + prim.LocalID.ToString() + "\","; + sql += "\"" + prim.FullID.ToString() + "\")"; + + cmd.CommandText = sql; + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("SQLiteLocalStorage :StorePrim - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + + cmd.Dispose(); + cmd = null; + } + + public void RemovePrim(LLUUID primID) + { + IDbCommand cmd = db.CreateCommand(); + + //SECURITY WARNING: + // These parameters wont produce SQL injections since they are all integer based, however. + // if inserting strings such as name or description, you will need to use appropriate + // measures to prevent SQL injection (although the value of SQL injection in this is limited). + + string sql = "DELETE FROM prim WHERE FullID = \"" + primID.ToStringHyphenated() + "\""; + + cmd.CommandText = sql; + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("SQLiteLocalStorage :RemovePrim - Exception occured"); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + + cmd.Dispose(); + cmd = null; + } + + public void LoadPrimitives(ILocalStorageReceiver receiver) + { + + } + + public float[] LoadWorld() + { + return new float[65536]; + } + + public void SaveMap(float[] heightmap) + { + + } + + public void SaveParcels(ParcelData[] parcel_manager) + { + + } + + public void SaveParcel(ParcelData parcel) + { + } + + public void RemoveParcel(ParcelData parcel) + { + } + + public void RemoveAllParcels() + { + } + + public void LoadParcels(ILocalStorageParcelReceiver recv) + { + recv.NoParcelDataFromStorage(); + } + + public void ShutDown() + { + db.Close(); + db = null; + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj b/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj new file mode 100644 index 0000000..24667e5 --- /dev/null +++ b/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj @@ -0,0 +1,110 @@ + + + Local + 8.0.50727 + 2.0 + {C9E0F891-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Region.Terrain.BasicTerrain + JScript + Grid + IE50 + false + Library + + OpenSim.Region.Terrain.BasicTerrain + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\..\bin\ + False + False + False + 4 + + + + + ..\..\..\bin\libTerrain-BSD.dll + False + + + Microsoft.JScript.dll + False + + + ..\..\..\bin\openjpegnet.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Drawing.dll + False + + + System.Xml.dll + False + + + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj.user b/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj.user new file mode 100644 index 0000000..6841907 --- /dev/null +++ b/OpenSim/Region/Terrain.BasicTerrain/OpenSim.Region.Terrain.BasicTerrain.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-06\NameSpaceChanges\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs b/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..827c68f --- /dev/null +++ b/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs @@ -0,0 +1,62 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Terrain.BasicTerrain")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Terrain.BasicTerrain")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3263f5b5-0a41-4ed5-91a2-9baaaeecc849")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs b/OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs new file mode 100644 index 0000000..4f989fa --- /dev/null +++ b/OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs @@ -0,0 +1,786 @@ +/* +* Copyright (c) Contributors, http://www.openmetaverse.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using libTerrain; +using OpenJPEGNet; + +namespace OpenSim.Terrain +{ + public class TerrainCommand + { + public virtual bool run(string[] cmdargs, ref string output) + { + return false; + } + + public string args; + public string help; + } + + public class TerrainEngine + { + /// + /// Plugin library for scripts + /// + public FilterHost customFilters = new FilterHost(); + + /// + /// A [normally] 256x256 heightmap + /// + public Channel heightmap; + + /// + /// A copy of heightmap at the last save point (for reverting) + /// + public Channel revertmap; + + /// + /// Water heightmap (needs clientside mods to work) + /// + public Channel watermap; + + /// + /// Whether or not the terrain has been modified since it was last saved and sent to the Physics engine. + /// Counts the number of modifications since the last save. (0 = Untainted) + /// + public int tainted; + + int w, h; + + /// + /// Generate a new TerrainEngine instance and creates a new heightmap + /// + public TerrainEngine() + { + w = 256; + h = 256; + heightmap = new Channel(w, h); + + tainted++; + } + + /// + /// Converts the heightmap to a 65536 value 1D floating point array + /// + /// A float[65536] array containing the heightmap + public float[] getHeights1D() + { + float[] heights = new float[w * h]; + int i; + + for (i = 0; i < w * h; i++) + { + heights[i] = (float)heightmap.map[i / w, i % w]; + } + + return heights; + } + + /// + /// Converts the heightmap to a 256x256 value 2D floating point array. + /// + /// An array of 256,256 values containing the heightmap + public float[,] getHeights2D() + { + float[,] heights = new float[w, h]; + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heights[x, y] = (float)heightmap.map[x, y]; + } + } + return heights; + } + + /// + /// Imports a 1D floating point array into the 2D heightmap array + /// + /// The array to import (must have 65536 members) + public void setHeights1D(float[] heights) + { + int i; + for (i = 0; i < w * h; i++) + { + heightmap.map[i / w, i % w] = heights[i]; + } + + tainted++; + } + + /// + /// Loads a 2D array of values into the heightmap + /// + /// An array of 256,256 float values + public void setHeights2D(float[,] heights) + { + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.set(x, y, (double)heights[x, y]); + } + } + tainted++; + } + + /// + /// Swaps the two heightmap buffers (the 'revert map' and the heightmap) + /// + public void swapRevertMaps() + { + Channel backup = heightmap.copy(); + heightmap = revertmap; + revertmap = backup; + } + + /// + /// Saves the current heightmap into the revertmap + /// + public void saveRevertMap() + { + revertmap = heightmap.copy(); + } + + /// + /// Processes a terrain-specific command + /// + /// Commandline arguments (space seperated) + /// Reference that returns error or help text if returning false + /// If the operation was successful (if not, the error is placed into resultText) + public bool RunTerrainCmd(string[] args, ref string resultText) + { + string command = args[0]; + + try + { + + switch (command) + { + case "help": + resultText += "terrain regenerate - rebuilds the sims terrain using a default algorithm\n"; + resultText += "terrain voronoi - generates a worley fractal with X points per block"; + resultText += "terrain seed - sets the random seed value to \n"; + resultText += "terrain load - loads a terrain from disk, type can be 'F32', 'F64', 'RAW' or 'IMG'\n"; + resultText += "terrain save - saves a terrain to disk, type can be 'F32', 'F64' or 'PNG'\n"; + resultText += "terrain save grdmap - creates a PNG snapshot of the region using a named gradient map\n"; + resultText += "terrain rescale - rescales a terrain to be between and meters high\n"; + resultText += "terrain erode aerobic \n"; + resultText += "terrain erode thermal \n"; + resultText += "terrain multiply - multiplies a terrain by \n"; + resultText += "terrain revert - reverts the terrain to the stored original\n"; + resultText += "terrain bake - saves the current terrain into the revert map\n"; + resultText += "terrain csfilter - loads a new filter from the specified .cs file\n"; + resultText += "terrain jsfilter - loads a new filter from the specified .js file\n"; + foreach (KeyValuePair filter in customFilters.filters) + { + resultText += filter.Value.Help(); + } + + return false; + + case "revert": + swapRevertMaps(); + saveRevertMap(); + break; + + case "bake": + saveRevertMap(); + break; + + case "seed": + setSeed(Convert.ToInt32(args[1])); + break; + + case "erode": + return consoleErosion(args, ref resultText); + + case "voronoi": + double[] c = new double[2]; + c[0] = -1; + c[1] = 1; + heightmap.voronoiDiagram(Convert.ToInt32(args[1]), Convert.ToInt32(args[2]), c); + break; + + case "hills": + return consoleHills(args, ref resultText); + + case "regenerate": + hills(); + break; + + case "rescale": + setRange(Convert.ToSingle(args[1]), Convert.ToSingle(args[2])); + break; + + case "multiply": + heightmap *= Convert.ToDouble(args[1]); + break; + + case "load": + switch (args[1].ToLower()) + { + case "f32": + loadFromFileF32(args[2]); + break; + + case "f64": + loadFromFileF64(args[2]); + break; + + case "raw": + loadFromFileSLRAW(args[2]); + break; + + case "img": + heightmap.loadImage(args[2]); + return false; + + default: + resultText = "Unknown image or data format"; + return false; + } + break; + + case "save": + switch (args[1].ToLower()) + { + case "f32": + writeToFileF32(args[2]); + break; + + case "f64": + writeToFileF64(args[2]); + break; + + case "grdmap": + exportImage(args[2], args[3]); + break; + + case "png": + heightmap.saveImage(args[2]); + break; + + default: + resultText = "Unknown image or data format"; + return false; + } + break; + + case "csfilter": + customFilters.LoadFilterCSharp(args[1]); + break; + case "jsfilter": + customFilters.LoadFilterJScript(args[1]); + break; + + default: + // Run any custom registered filters + if (customFilters.filters.ContainsKey(command)) + { + customFilters.filters[command].Filter(heightmap, args); + break; + } + else + { + resultText = "Unknown terrain command"; + return false; + } + } + return true; + } + catch (Exception e) + { + resultText = "Error running terrain command: " + e.ToString(); + return false; + } + } + + private bool consoleErosion(string[] args, ref string resultText) + { + switch (args[1].ToLower()) + { + case "aerobic": + // WindSpeed, PickupMinimum,DropMinimum,Carry,Rounds,Lowest + heightmap.AerobicErosion(Convert.ToDouble(args[2]), Convert.ToDouble(args[3]), Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToInt32(args[6]), Convert.ToBoolean(args[7])); + break; + case "thermal": + heightmap.thermalWeathering(Convert.ToDouble(args[2]), Convert.ToInt32(args[3]), Convert.ToDouble(args[4])); + break; + default: + resultText = "Unknown erosion type"; + return false; + } + return true; + } + + private bool consoleHills(string[] args, ref string resultText) + { + int count; + double sizeMin; + double sizeRange; + bool island; + bool additive; + bool noisy; + + if (args.GetLength(0) > 2) + { + count = Convert.ToInt32(args[2]); + sizeMin = Convert.ToDouble(args[3]); + sizeRange = Convert.ToDouble(args[4]); + island = Convert.ToBoolean(args[5]); + additive = Convert.ToBoolean(args[6]); + noisy = Convert.ToBoolean(args[7]); + } + else + { + count = 200; + sizeMin = 20; + sizeRange = 40; + island = true; + additive = true; + noisy = false; + } + + switch (args[1].ToLower()) + { + case "blocks": + heightmap.hillsBlocks(count, sizeMin, sizeRange, island, additive, noisy); + break; + case "cones": + heightmap.hillsCones(count, sizeMin, sizeRange, island, additive, noisy); + break; + case "spheres": + heightmap.hillsSpheres(count, sizeMin, sizeRange, island, additive, noisy); + break; + case "squared": + heightmap.hillsSquared(count, sizeMin, sizeRange, island, additive, noisy); + break; + default: + resultText = "Unknown hills type"; + return false; + } + return true; + } + + /// + /// Renormalises the array between min and max + /// + /// Minimum value of the new array + /// Maximum value of the new array + public void setRange(float min, float max) + { + heightmap.normalise((double)min, (double)max); + tainted++; + } + + /// + /// Loads a file consisting of 256x256 doubles and imports it as an array into the map. + /// + /// TODO: Move this to libTerrain itself + /// The filename of the double array to import + public void loadFromFileF64(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); + System.IO.BinaryReader bs = new System.IO.BinaryReader(s); + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.map[x, y] = bs.ReadDouble(); + } + } + + bs.Close(); + s.Close(); + + tainted++; + } + + /// + /// Loads a file consisting of 256x256 floats and imports it as an array into the map. + /// + /// TODO: Move this to libTerrain itself + /// The filename of the float array to import + public void loadFromFileF32(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); + System.IO.BinaryReader bs = new System.IO.BinaryReader(s); + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.map[x, y] = (double)bs.ReadSingle(); + } + } + + bs.Close(); + s.Close(); + + tainted++; + } + + /// + /// Loads a file formatted in the SL .RAW Format used on the main grid + /// + /// This file format stinks and is best avoided. + /// A path to the .RAW format + public void loadFromFileSLRAW(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); + System.IO.BinaryReader bs = new System.IO.BinaryReader(s); + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.map[x, y] = (double)bs.ReadByte() * ((double)bs.ReadByte() / 127.0); + bs.ReadBytes(11); // Advance the stream to next bytes. + } + } + + bs.Close(); + s.Close(); + + tainted++; + } + + /// + /// Writes the current terrain heightmap to disk, in the format of a 65536 entry double[] array. + /// + /// The desired output filename + public void writeToFileF64(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); + System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s); + + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + bs.Write(heightmap.get(x, y)); + } + } + + bs.Close(); + s.Close(); + } + + /// + /// Writes the current terrain heightmap to disk, in the format of a 65536 entry float[] array + /// + /// The desired output filename + public void writeToFileF32(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); + System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s); + + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + bs.Write((float)heightmap.get(x, y)); + } + } + + bs.Close(); + s.Close(); + } + + /// + /// Sets the random seed to be used by procedural functions which involve random numbers. + /// + /// The desired seed + public void setSeed(int val) + { + heightmap.seed = val; + } + + /// + /// Raises land in a sphere around the specified coordinates + /// + /// Center of the sphere on the X axis + /// Center of the sphere on the Y axis + /// The radius of the sphere + /// Scale the height of the sphere by this amount (recommended 0..2) + public void raise(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + heightmap.raise(rx, ry, size, amount); + } + + tainted++; + } + + /// + /// Lowers the land in a sphere around the specified coordinates + /// + /// The center of the sphere at the X axis + /// The center of the sphere at the Y axis + /// The radius of the sphere in meters + /// Scale the height of the sphere by this amount (recommended 0..2) + public void lower(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + heightmap.lower(rx, ry, size, amount); + } + + tainted++; + } + + /// + /// Flattens the land under the brush of specified coordinates (spherical mask) + /// + /// Center of sphere + /// Center of sphere + /// Radius of the sphere + /// Thickness of the mask (0..2 recommended) + public void flatten(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + heightmap.flatten(rx, ry, size, amount); + } + + tainted++; + } + + /// + /// Creates noise within the specified bounds + /// + /// Center of the bounding sphere + /// Center of the bounding sphere + /// The radius of the sphere + /// Strength of the mask (0..2) recommended + public void noise(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + Channel smoothed = new Channel(); + smoothed.noise(); + + Channel mask = new Channel(); + mask.raise(rx, ry, size, amount); + + heightmap.blend(smoothed, mask); + } + + tainted++; + } + + /// + /// Reverts land within the specified bounds + /// + /// Center of the bounding sphere + /// Center of the bounding sphere + /// The radius of the sphere + /// Strength of the mask (0..2) recommended + public void revert(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + Channel mask = new Channel(); + mask.raise(rx, ry, size, amount); + + heightmap.blend(revertmap, mask); + } + + tainted++; + } + + /// + /// Smooths land under the brush of specified coordinates (spherical mask) + /// + /// Center of the sphere + /// Center of the sphere + /// Radius of the sphere + /// Thickness of the mask (0..2 recommended) + public void smooth(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + Channel smoothed = heightmap.copy(); + smoothed.smooth(amount); + + Channel mask = new Channel(); + mask.raise(rx,ry,size,amount); + + heightmap.blend(smoothed, mask); + } + + tainted++; + } + + /// + /// Generates a simple set of hills in the shape of an island + /// + public void hills() + { + lock (heightmap) + { + heightmap.hillsSpheres(200, 20, 40, true, true, false); + heightmap.normalise(); + heightmap *= 60.0; // Raise to 60m + } + + tainted++; + } + + /// + /// Multiplies the heightfield by val + /// + /// The heightfield + /// The multiplier + /// + public static TerrainEngine operator *(TerrainEngine meep, Double val) + { + meep.heightmap *= val; + meep.tainted++; + return meep; + } + + /// + /// Returns the height at the coordinates x,y + /// + /// X Coordinate + /// Y Coordinate + /// + public float this[int x, int y] + { + get + { + return (float)heightmap.get(x, y); + } + set + { + tainted++; + heightmap.set(x, y, (double)value); + } + } + + /// + /// Exports the current heightmap to a PNG file + /// + /// The destination filename for the image + /// A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal. + public void exportImage(string filename, string gradientmap) + { + try + { + Bitmap gradientmapLd = new Bitmap(gradientmap); + + int pallete = gradientmapLd.Height; + + Bitmap bmp = new Bitmap(heightmap.w, heightmap.h); + Color[] colours = new Color[pallete]; + + for (int i = 0; i < pallete; i++) + { + colours[i] = gradientmapLd.GetPixel(0, i); + } + + Channel copy = heightmap.copy(); + for (int x = 0; x < copy.w; x++) + { + for (int y = 0; y < copy.h; y++) + { + // 512 is the largest possible height before colours clamp + int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(x, y) / 512.0), 0.0) * pallete); + bmp.SetPixel(x, y, colours[colorindex]); + } + } + + bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png); + } + catch (Exception e) + { + Console.WriteLine("Failed generating terrain map: " + e.ToString()); + } + } + + /// + /// Exports the current heightmap in Jpeg2000 format to a byte[] + /// + /// A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal. + public byte[] exportJpegImage(string gradientmap) + { + byte[] imageData = null; + try + { + Bitmap gradientmapLd = new Bitmap(gradientmap); + + int pallete = gradientmapLd.Height; + + Bitmap bmp = new Bitmap(heightmap.w, heightmap.h); + Color[] colours = new Color[pallete]; + + for (int i = 0; i < pallete; i++) + { + colours[i] = gradientmapLd.GetPixel(0, i); + } + + Channel copy = heightmap.copy(); + for (int x = 0; x < copy.w; x++) + { + for (int y = 0; y < copy.h; y++) + { + // 512 is the largest possible height before colours clamp + int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(copy.h - y, x) / 512.0), 0.0) * pallete); + bmp.SetPixel(x, y, colours[colorindex]); + } + } + + //bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png); + imageData = OpenJPEGNet.OpenJPEG.EncodeFromImage(bmp, "map"); + + } + catch (Exception e) + { + Console.WriteLine("Failed generating terrain map: " + e.ToString()); + } + + return imageData; + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs b/OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs new file mode 100644 index 0000000..689375d --- /dev/null +++ b/OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using System.CodeDom.Compiler; +using System.CodeDom; +using Microsoft.CSharp; +using Microsoft.JScript; + +using libTerrain; + +namespace OpenSim.Terrain +{ + public interface ITerrainFilter + { + void Filter(Channel heightmap, string[] args); + string Register(); + string Help(); + } + + public class TestFilter : ITerrainFilter + { + public void Filter(Channel heightmap, string[] args) + { + Console.WriteLine("Hello world"); + } + + public string Register() + { + return "demofilter"; + } + + public string Help() + { + return "demofilter - Does nothing"; + } + } + + public class FilterHost + { + public Dictionary filters = new Dictionary(); + + private void LoadFilter(ICodeCompiler compiler, string filename) + { + CompilerParameters compilerParams = new CompilerParameters(); + CompilerResults compilerResults; + compilerParams.GenerateExecutable = false; + compilerParams.GenerateInMemory = true; + compilerParams.IncludeDebugInformation = false; + compilerParams.ReferencedAssemblies.Add("libTerrain-BSD.dll"); + compilerParams.ReferencedAssemblies.Add("OpenSim.Terrain.BasicTerrain.dll"); + compilerParams.ReferencedAssemblies.Add("System.dll"); + + compilerResults = compiler.CompileAssemblyFromFile(compilerParams, filename); + + if (compilerResults.Errors.Count > 0) + { + Console.WriteLine("Compile errors:"); + foreach (CompilerError error in compilerResults.Errors) + { + Console.WriteLine(error.Line.ToString() + ": " + error.ErrorText.ToString()); + } + } + else + { + foreach (Type pluginType in compilerResults.CompiledAssembly.GetExportedTypes()) + { + Type testInterface = pluginType.GetInterface("ITerrainFilter",true); + + if (testInterface != null) + { + ITerrainFilter filter = (ITerrainFilter)compilerResults.CompiledAssembly.CreateInstance(pluginType.ToString()); + + string filterName = filter.Register(); + Console.WriteLine("Plugin: " + filterName + " loaded."); + + if (!filters.ContainsKey(filterName)) + { + filters.Add(filterName, filter); + } + else + { + filters[filterName] = filter; + } + } + } + } + + } + + public void LoadFilterCSharp(string filename) + { + CSharpCodeProvider compiler = new CSharpCodeProvider(); + LoadFilter(compiler.CreateCompiler(), filename); + } + + public void LoadFilterJScript(string filename) + { + JScriptCodeProvider compiler = new JScriptCodeProvider(); + LoadFilter(compiler.CreateCompiler(), filename); + } + } +} -- cgit v1.1