From 2a3c79df83e800d5dfe75a1a3b140ed81da2b1d6 Mon Sep 17 00:00:00 2001 From: Sean Dague Date: Mon, 16 Jul 2007 15:40:11 +0000 Subject: changed to native line ending encoding --- .../Communications/CommunicationsManager.cs | 142 +- OpenSim/Framework/Communications/IGridServices.cs | 82 +- .../Communications/IInterRegionCommunications.cs | 76 +- .../Framework/Communications/IInventoryServices.cs | 34 +- OpenSim/Framework/Communications/IUserServices.cs | 86 +- .../Communications/Properties/AssemblyInfo.cs | 120 +- .../Communications/caches/CachedUserInfo.cs | 154 +- .../Communications/caches/InventoryFolder.cs | 102 +- .../Communications/caches/UserProfileCache.cs | 214 +- OpenSim/Framework/Console/AssemblyInfo.cs | 112 +- OpenSim/Framework/Console/ConsoleCallbacksBase.cs | 70 +- OpenSim/Framework/Console/LogBase.cs | 564 ++--- OpenSim/Framework/Console/MainLog.cs | 94 +- OpenSim/Framework/Data.DB4o/DB4oGridData.cs | 324 +-- OpenSim/Framework/Data.DB4o/DB4oManager.cs | 326 +-- OpenSim/Framework/Data.DB4o/DB4oUserData.cs | 404 ++-- .../Framework/Data.DB4o/Properties/AssemblyInfo.cs | 66 +- OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs | 388 ++-- OpenSim/Framework/Data.MSSQL/MSSQLManager.cs | 422 ++-- .../Data.MSSQL/Properties/AssemblyInfo.cs | 66 +- OpenSim/Framework/Data.MySQL/MySQLGridData.cs | 574 ++--- OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs | 618 ++--- OpenSim/Framework/Data.MySQL/MySQLLogData.cs | 210 +- OpenSim/Framework/Data.MySQL/MySQLManager.cs | 1212 +++++----- OpenSim/Framework/Data.MySQL/MySQLUserData.cs | 512 ++--- .../Data.MySQL/Properties/AssemblyInfo.cs | 66 +- .../Data.SQLite/Properties/AssemblyInfo.cs | 66 +- OpenSim/Framework/Data.SQLite/SQLiteGridData.cs | 394 ++-- OpenSim/Framework/Data.SQLite/SQLiteManager.cs | 412 ++-- OpenSim/Framework/Data/GridData.cs | 222 +- OpenSim/Framework/Data/ILogData.cs | 180 +- OpenSim/Framework/Data/IniConfig.cs | 192 +- OpenSim/Framework/Data/InventoryData.cs | 394 ++-- OpenSim/Framework/Data/Properties/AssemblyInfo.cs | 66 +- OpenSim/Framework/Data/ReservationData.cs | 94 +- OpenSim/Framework/Data/SimProfileData.cs | 384 ++-- OpenSim/Framework/Data/UserData.cs | 256 +-- OpenSim/Framework/Data/UserProfileData.cs | 360 +-- OpenSim/Framework/General/AgentInventory.cs | 530 ++--- .../Framework/General/AuthenticateSessionBase.cs | 258 +-- OpenSim/Framework/General/BlockingQueue.cs | 116 +- OpenSim/Framework/General/ClientManager.cs | 72 +- OpenSim/Framework/General/IRegionCommsListener.cs | 92 +- .../General/Interfaces/AuthenticateResponse.cs | 86 +- .../General/Interfaces/Config/IGenericConfig.cs | 76 +- .../General/Interfaces/Config/IGridConfig.cs | 118 +- .../General/Interfaces/Config/IUserConfig.cs | 106 +- .../Framework/General/Interfaces/IAssetServer.cs | 128 +- OpenSim/Framework/General/Interfaces/IClientAPI.cs | 390 ++-- .../Framework/General/Interfaces/ILocalStorage.cs | 142 +- .../Framework/General/Interfaces/IUserServer.cs | 78 +- OpenSim/Framework/General/Interfaces/IWorld.cs | 84 +- OpenSim/Framework/General/NpcClientBase.cs | 254 +-- .../Framework/General/Properties/AssemblyInfo.cs | 62 +- OpenSim/Framework/General/RegionCommsListener.cs | 206 +- OpenSim/Framework/General/Remoting.cs | 270 +-- OpenSim/Framework/General/Types/AgentCiruitData.cs | 98 +- OpenSim/Framework/General/Types/AgentWearable.cs | 114 +- OpenSim/Framework/General/Types/AssetBase.cs | 92 +- OpenSim/Framework/General/Types/AssetLandmark.cs | 118 +- OpenSim/Framework/General/Types/AssetStorage.cs | 94 +- OpenSim/Framework/General/Types/EstateSettings.cs | 186 +- OpenSim/Framework/General/Types/Login.cs | 98 +- OpenSim/Framework/General/Types/MapBlockData.cs | 46 +- OpenSim/Framework/General/Types/NeighbourInfo.cs | 84 +- .../Framework/General/Types/NetworkServersInfo.cs | 438 ++-- OpenSim/Framework/General/Types/ParcelData.cs | 240 +- OpenSim/Framework/General/Types/PrimData.cs | 456 ++-- .../Framework/General/Types/PrimitiveBaseShape.cs | 218 +- OpenSim/Framework/General/Types/RegionHandle.cs | 242 +- OpenSim/Framework/General/Types/RegionInfo.cs | 684 +++--- OpenSim/Framework/General/Types/UUID.cs | 254 +-- OpenSim/Framework/General/UserProfile.cs | 174 +- OpenSim/Framework/General/Util.cs | 368 +-- .../GenericConfig/Xml/Properties/AssemblyInfo.cs | 66 +- OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs | 244 +- OpenSim/Framework/Servers/BaseHttpServer.cs | 448 ++-- OpenSim/Framework/Servers/BaseStreamHandler.cs | 80 +- OpenSim/Framework/Servers/BinaryStreamHandler.cs | 98 +- OpenSim/Framework/Servers/CheckSumServer.cs | 252 +- OpenSim/Framework/Servers/IStreamHandler.cs | 44 +- OpenSim/Framework/Servers/RestMethod.cs | 62 +- OpenSim/Framework/Servers/RestStreamHandler.cs | 62 +- OpenSim/Framework/Servers/UDPServerBase.cs | 174 +- OpenSim/Framework/Servers/XmlRpcMethod.cs | 66 +- OpenSim/Framework/UserManager/LoginResponse.cs | 1286 +++++------ OpenSim/Framework/UserManager/UserManagerBase.cs | 1262 +++++----- OpenSim/Grid/AssetServer/Main.cs | 812 +++---- .../Grid/AssetServer/Properties/AssemblyInfo.cs | 116 +- .../Grid/Framework.Manager/GridManagementAgent.cs | 276 +-- .../Grid/Framework.Manager/GridServerManager.cs | 186 +- OpenSim/Grid/GridServer.Config/AssemblyInfo.cs | 112 +- OpenSim/Grid/GridServer.Config/DbGridConfig.cs | 320 +-- OpenSim/Grid/GridServer/GridManager.cs | 1420 ++++++------ OpenSim/Grid/GridServer/Main.cs | 516 ++--- OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs | 116 +- OpenSim/Grid/InventoryServer/InventoryManager.cs | 250 +- OpenSim/Grid/InventoryServer/Main.cs | 174 +- .../OpenGridServices.Manager/BlockingQueue.cs | 66 +- .../Grid/Manager/OpenGridServices.Manager/Util.cs | 266 +-- OpenSim/Grid/UserServer.Config/AssemblyInfo.cs | 112 +- OpenSim/Grid/UserServer.Config/DbUserConfig.cs | 190 +- OpenSim/Grid/UserServer/Main.cs | 428 ++-- OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs | 62 +- OpenSim/Grid/UserServer/UserManager.cs | 200 +- OpenSim/Region/Application/Application.cs | 250 +- OpenSim/Region/Application/OpenSimMain.cs | 992 ++++---- OpenSim/Region/Application/VersionInfo.cs | 72 +- OpenSim/Region/Caches/AssetCache.cs | 1338 +++++------ OpenSim/Region/Caches/Properties/AssemblyInfo.cs | 66 +- OpenSim/Region/Capabilities/Caps.cs | 626 ++--- OpenSim/Region/Capabilities/LLSDArray.cs | 84 +- .../Region/Capabilities/LLSDAssetUploadComplete.cs | 88 +- .../Region/Capabilities/LLSDAssetUploadRequest.cs | 42 +- .../Region/Capabilities/LLSDAssetUploadResponse.cs | 36 +- OpenSim/Region/Capabilities/LLSDCapEvent.cs | 82 +- OpenSim/Region/Capabilities/LLSDCapsDetails.cs | 34 +- OpenSim/Region/Capabilities/LLSDEmpty.cs | 76 +- OpenSim/Region/Capabilities/LLSDHelpers.cs | 328 +-- OpenSim/Region/Capabilities/LLSDMapLayer.cs | 92 +- .../Region/Capabilities/LLSDMapLayerResponse.cs | 82 +- OpenSim/Region/Capabilities/LLSDMapRequest.cs | 26 +- OpenSim/Region/Capabilities/LLSDMethod.cs | 16 +- OpenSim/Region/Capabilities/LLSDStreamHandler.cs | 84 +- OpenSim/Region/Capabilities/LLSDTest.cs | 82 +- OpenSim/Region/Capabilities/LLSDType.cs | 118 +- .../Region/ClientStack/Assets/InventoryCache.cs | 676 +++--- .../ClientStack/ClientStackNetworkHandler.cs | 80 +- OpenSim/Region/ClientStack/ClientView.API.cs | 2360 +++++++++---------- .../ClientStack/ClientView.AgentAssetUpload.cs | 714 +++--- .../ClientStack/ClientView.PacketHandlers.cs | 472 ++-- .../ClientStack/ClientView.ProcessPackets.cs | 1294 +++++------ OpenSim/Region/ClientStack/ClientView.cs | 586 ++--- OpenSim/Region/ClientStack/ClientViewBase.cs | 652 +++--- OpenSim/Region/ClientStack/PacketServer.cs | 368 +-- .../Region/ClientStack/RegionApplicationBase.cs | 236 +- OpenSim/Region/ClientStack/UDPServer.cs | 390 ++-- .../Communications/Local/CommunicationsLocal.cs | 110 +- .../Communications/Local/LocalBackEndServices.cs | 412 ++-- .../Communications/Local/LocalUserServices.cs | 284 +-- .../Local/Properties/AssemblyInfo.cs | 66 +- .../Communications/OGS1/CommunicationsOGS1.cs | 36 +- .../Region/Communications/OGS1/OGS1GridServices.cs | 862 +++---- .../Communications/OGS1/OGS1InterSimComms.cs | 138 +- .../Region/Communications/OGS1/OGS1UserServices.cs | 202 +- .../Communications/OGS1/Properties/AssemblyInfo.cs | 66 +- OpenSim/Region/Environment/EstateManager.cs | 598 ++--- .../Environment/Interfaces/IRegionDataStore.cs | 124 +- OpenSim/Region/Environment/ParcelManager.cs | 2412 ++++++++++---------- OpenSim/Region/Environment/RegionManager.cs | 58 +- OpenSim/Region/Environment/Scenes/Entity.cs | 230 +- OpenSim/Region/Environment/Scenes/EntityBase.cs | 284 +-- .../Environment/Scenes/IScenePresenceBody.cs | 28 +- OpenSim/Region/Environment/Scenes/Primitive.cs | 1296 +++++------ .../Environment/Scenes/Scene.PacketHandlers.cs | 1236 +++++----- OpenSim/Region/Environment/Scenes/Scene.cs | 1838 +++++++-------- OpenSim/Region/Environment/Scenes/SceneBase.cs | 390 ++-- OpenSim/Region/Environment/Scenes/SceneEvents.cs | 164 +- OpenSim/Region/Environment/Scenes/SceneObject.cs | 618 ++--- .../Environment/Scenes/ScenePresence.Animations.cs | 148 +- .../Environment/Scenes/ScenePresence.Body.cs | 170 +- OpenSim/Region/Environment/Scenes/ScenePresence.cs | 1246 +++++----- .../Engines/CSharpEngine/CSharpScriptEngine.cs | 204 +- .../CSharpEngine/Examples/ExportRegionToLSL.cs | 138 +- .../Engines/JScriptEngine/JScriptEngine.cs | 204 +- .../Engines/JVMEngine/JVM/ClassInstance.cs | 90 +- .../scripting/Engines/JVMEngine/JVM/ClassRecord.cs | 1006 ++++---- .../Scenes/scripting/Engines/JVMEngine/JVM/Heap.cs | 86 +- .../Engines/JVMEngine/JVM/Interpreter.Logic.cs | 854 +++---- .../Engines/JVMEngine/JVM/Interpreter.Methods.cs | 192 +- .../Engines/JVMEngine/JVM/Interpreter.Return.cs | 80 +- .../scripting/Engines/JVMEngine/JVM/Interpreter.cs | 270 +-- .../scripting/Engines/JVMEngine/JVM/MainMemory.cs | 90 +- .../Engines/JVMEngine/JVM/MethodMemory.cs | 92 +- .../scripting/Engines/JVMEngine/JVM/Object.cs | 74 +- .../scripting/Engines/JVMEngine/JVM/Stack.cs | 84 +- .../scripting/Engines/JVMEngine/JVM/StackFrame.cs | 98 +- .../scripting/Engines/JVMEngine/JVM/Thread.cs | 238 +- .../scripting/Engines/JVMEngine/JavaEngine.cs | 58 +- .../scripting/Engines/JVMEngine/OpenSimJVM.cs | 340 +-- .../Engines/JVMEngine/Types/ArrayReference.cs | 20 +- .../scripting/Engines/JVMEngine/Types/BaseType.cs | 20 +- .../Engines/JVMEngine/Types/ObjectReference.cs | 32 +- .../Engines/JVMEngine/Types/PrimitiveTypes/Byte.cs | 20 +- .../Engines/JVMEngine/Types/PrimitiveTypes/Char.cs | 20 +- .../JVMEngine/Types/PrimitiveTypes/Float.cs | 32 +- .../Engines/JVMEngine/Types/PrimitiveTypes/Int.cs | 32 +- .../Engines/LSLEngine/LSLHandler/Engine.cs | 280 +-- .../LSLEngine/LSLHandler/LSL_CLRInterface.cs | 102 +- .../Engines/LSLEngine/LSLHandler/LSO_Enums.cs | 970 ++++---- .../Engines/LSLEngine/LSLHandler/LSO_Parser.cs | 1216 +++++----- .../Engines/LSLEngine/LSLHandler/LSO_Struct.cs | 210 +- .../Region/Environment/Scenes/scripting/Script.cs | 128 +- .../Environment/Scenes/scripting/ScriptAPI.cs | 64 +- .../Environment/Scenes/scripting/ScriptInfo.cs | 116 +- .../Scenes/scripting/ScriptInterpretedAPI.cs | 412 ++-- .../Scenes/scripting/ScriptInterpretedEvents.cs | 32 +- .../Environment/Scenes/scripting/ScriptManager.cs | 214 +- OpenSim/Region/Environment/StorageManager.cs | 120 +- .../Region/Examples/SimpleApp/MyNpcCharacter.cs | 368 +-- OpenSim/Region/Examples/SimpleApp/MySceneObject.cs | 80 +- OpenSim/Region/Examples/SimpleApp/MyWorld.cs | 194 +- OpenSim/Region/Examples/SimpleApp/Program.cs | 252 +- .../Examples/SimpleApp/Properties/AssemblyInfo.cs | 62 +- .../Region/GridInterfaces/Local/AssemblyInfo.cs | 112 +- .../GridInterfaces/Local/LocalAssetServer.cs | 622 ++--- .../Region/GridInterfaces/Remote/AssemblyInfo.cs | 112 +- .../GridInterfaces/Remote/RemoteAssetServer.cs | 266 +-- .../Physics/BasicPhysicsPlugin/AssemblyInfo.cs | 112 +- .../BasicPhysicsPlugin/BasicPhysicsPlugin.cs | 602 ++--- .../Region/Physics/BulletXPlugin/AssemblyInfo.cs | 112 +- .../Region/Physics/BulletXPlugin/BulletXPlugin.cs | 1068 ++++----- OpenSim/Region/Physics/Manager/AssemblyInfo.cs | 112 +- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 334 +-- OpenSim/Region/Physics/Manager/PhysicsManager.cs | 230 +- OpenSim/Region/Physics/Manager/PhysicsScene.cs | 220 +- OpenSim/Region/Physics/Manager/PhysicsVector.cs | 110 +- OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs | 112 +- OpenSim/Region/Physics/OdePlugin/OdePlugin.cs | 914 ++++---- OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs | 112 +- OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs | 850 +++---- .../Region/Scripting/Properties/AssemblyInfo.cs | 70 +- OpenSim/Region/Scripting/Script.cs | 64 +- OpenSim/Region/Scripting/ScriptAccess.cs | 62 +- .../LocalStorageBerkeleyDB/BDBLocalStorage.cs | 222 +- .../Storage/LocalStorageDb4o/AssemblyInfo.cs | 112 +- .../Storage/LocalStorageDb4o/Db4LocalStorage.cs | 532 ++--- .../Region/Storage/LocalStorageDb4o/MapStorage.cs | 76 +- .../Storage/LocalStorageDb4o/UUIDParcelQuery.cs | 94 +- .../Storage/LocalStorageDb4o/UUIDPrimQuery.cs | 94 +- .../LocalStorageSQLite/Properties/AssemblyInfo.cs | 120 +- .../LocalStorageSQLite/SQLiteLocalStorage.cs | 394 ++-- .../OpenSim.DataStore.NullStorage/NullDataStore.cs | 131 +- .../Properties/AssemblyInfo.cs | 70 +- .../Properties/AssemblyInfo.cs | 120 +- .../Region/Terrain.BasicTerrain/TerrainEngine.cs | 1906 ++++++++-------- .../Region/Terrain.BasicTerrain/TerrainFilter.cs | 252 +- 237 files changed, 35934 insertions(+), 35933 deletions(-) (limited to 'OpenSim') diff --git a/OpenSim/Framework/Communications/CommunicationsManager.cs b/OpenSim/Framework/Communications/CommunicationsManager.cs index 550372f..db34d1b 100644 --- a/OpenSim/Framework/Communications/CommunicationsManager.cs +++ b/OpenSim/Framework/Communications/CommunicationsManager.cs @@ -1,71 +1,71 @@ -/* -* 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.Text; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Data; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Communications.Caches; - -namespace OpenSim.Framework.Communications -{ - - public class CommunicationsManager - { - public IUserServices UserServer; - public IGridServices GridServer; - public IInventoryServices InventoryServer; - public IInterRegionCommunications InterRegion; - public UserProfileCache UserProfilesCache; - - public NetworkServersInfo ServersInfo; - public CommunicationsManager(NetworkServersInfo serversInfo, BaseHttpServer httpServer) - { - ServersInfo = serversInfo; - UserProfilesCache = new UserProfileCache(this); - } - - #region Packet Handlers - public void HandleUUIDNameRequest(LLUUID uuid, IClientAPI remote_client) - { - UserProfileData profileData = this.UserServer.GetUserProfile(uuid); - if (profileData != null) - { - LLUUID profileId = profileData.UUID; - string firstname = profileData.username; - string lastname = profileData.surname; - - remote_client.SendNameReply(profileId, firstname, lastname); - } - } - - #endregion - } -} +/* +* 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.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Data; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Communications.Caches; + +namespace OpenSim.Framework.Communications +{ + + public class CommunicationsManager + { + public IUserServices UserServer; + public IGridServices GridServer; + public IInventoryServices InventoryServer; + public IInterRegionCommunications InterRegion; + public UserProfileCache UserProfilesCache; + + public NetworkServersInfo ServersInfo; + public CommunicationsManager(NetworkServersInfo serversInfo, BaseHttpServer httpServer) + { + ServersInfo = serversInfo; + UserProfilesCache = new UserProfileCache(this); + } + + #region Packet Handlers + public void HandleUUIDNameRequest(LLUUID uuid, IClientAPI remote_client) + { + UserProfileData profileData = this.UserServer.GetUserProfile(uuid); + if (profileData != null) + { + LLUUID profileId = profileData.UUID; + string firstname = profileData.username; + string lastname = profileData.surname; + + remote_client.SendNameReply(profileId, firstname, lastname); + } + } + + #endregion + } +} diff --git a/OpenSim/Framework/Communications/IGridServices.cs b/OpenSim/Framework/Communications/IGridServices.cs index d2e5ab6..1cfe2b6 100644 --- a/OpenSim/Framework/Communications/IGridServices.cs +++ b/OpenSim/Framework/Communications/IGridServices.cs @@ -1,41 +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.Collections.Generic; -using OpenSim.Framework.Types; - -namespace OpenSim.Framework.Communications -{ - public interface IGridServices - { - RegionCommsListener RegisterRegion(RegionInfo regionInfos); - List RequestNeighbours(RegionInfo regionInfo); - RegionInfo RequestNeighbourInfo(ulong regionHandle); - List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY); - } -} +/* +* 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.Collections.Generic; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Communications +{ + public interface IGridServices + { + RegionCommsListener RegisterRegion(RegionInfo regionInfos); + 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 index 55f12ac..7758f2b 100644 --- a/OpenSim/Framework/Communications/IInterRegionCommunications.cs +++ b/OpenSim/Framework/Communications/IInterRegionCommunications.cs @@ -1,38 +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 libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Framework.Communications -{ - public interface IInterRegionCommunications - { - bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData); - bool ExpectAvatarCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position); - } -} +/* +* 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 libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Communications +{ + public interface IInterRegionCommunications + { + bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData); + bool ExpectAvatarCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position); + } +} diff --git a/OpenSim/Framework/Communications/IInventoryServices.cs b/OpenSim/Framework/Communications/IInventoryServices.cs index 0b05834..807952c 100644 --- a/OpenSim/Framework/Communications/IInventoryServices.cs +++ b/OpenSim/Framework/Communications/IInventoryServices.cs @@ -1,17 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Framework.Data; -using libsecondlife; -using OpenSim.Framework.Communications.Caches; - -namespace OpenSim.Framework.Communications -{ - public delegate void InventoryFolderInfo(LLUUID userID, InventoryFolder folderInfo); - public delegate void InventoryItemInfo(LLUUID userID, InventoryItemBase itemInfo); - - public interface IInventoryServices - { - void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack, InventoryItemInfo itemCallBack); - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Data; +using libsecondlife; +using OpenSim.Framework.Communications.Caches; + +namespace OpenSim.Framework.Communications +{ + public delegate void InventoryFolderInfo(LLUUID userID, InventoryFolder folderInfo); + public delegate void InventoryItemInfo(LLUUID userID, InventoryItemBase itemInfo); + + public interface IInventoryServices + { + void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack, InventoryItemInfo itemCallBack); + } +} diff --git a/OpenSim/Framework/Communications/IUserServices.cs b/OpenSim/Framework/Communications/IUserServices.cs index 0b1f86c..cd97b52 100644 --- a/OpenSim/Framework/Communications/IUserServices.cs +++ b/OpenSim/Framework/Communications/IUserServices.cs @@ -1,43 +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 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); - - UserProfileData SetupMasterUser(string firstName, string lastName); - UserProfileData SetupMasterUser(string firstName, string lastName, string password); - - } -} +/* +* 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 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); + + UserProfileData SetupMasterUser(string firstName, string lastName); + UserProfileData SetupMasterUser(string firstName, string lastName, string password); + + } +} diff --git a/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs b/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs index 09f6473..79f3e30 100644 --- a/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Communications/Properties/AssemblyInfo.cs @@ -1,60 +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.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")] +/* +* 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.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/Communications/caches/CachedUserInfo.cs b/OpenSim/Framework/Communications/caches/CachedUserInfo.cs index 1c779e9..b8d8847 100644 --- a/OpenSim/Framework/Communications/caches/CachedUserInfo.cs +++ b/OpenSim/Framework/Communications/caches/CachedUserInfo.cs @@ -1,77 +1,77 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Framework.Data; -using libsecondlife; - -namespace OpenSim.Framework.Communications.Caches -{ - public class CachedUserInfo - { - public UserProfileData UserProfile; - //public Dictionary Folders = new Dictionary(); - public InventoryFolder RootFolder; - - public CachedUserInfo() - { - - } - - /// - /// - /// - /// - /// - public void FolderReceive(LLUUID userID, InventoryFolder folderInfo) - { - if (userID == UserProfile.UUID) - { - if (this.RootFolder == null) - { - if (folderInfo.parentID == LLUUID.Zero) - { - this.RootFolder = folderInfo; - } - } - else - { - if (this.RootFolder.folderID == folderInfo.parentID) - { - this.RootFolder.SubFolders.Add(folderInfo.folderID, folderInfo); - } - else - { - InventoryFolder pFolder = this.RootFolder.HasSubFolder(folderInfo.parentID); - if (pFolder != null) - { - pFolder.SubFolders.Add(folderInfo.folderID, folderInfo); - } - } - } - } - } - - public void ItemReceive(LLUUID userID, InventoryItemBase itemInfo) - { - if (userID == UserProfile.UUID) - { - if (this.RootFolder != null) - { - if (itemInfo.parentFolderID == this.RootFolder.folderID) - { - this.RootFolder.Items.Add(itemInfo.inventoryID, itemInfo); - } - else - { - InventoryFolder pFolder = this.RootFolder.HasSubFolder(itemInfo.parentFolderID); - if (pFolder != null) - { - pFolder.Items.Add(itemInfo.inventoryID, itemInfo); - } - } - } - - } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Data; +using libsecondlife; + +namespace OpenSim.Framework.Communications.Caches +{ + public class CachedUserInfo + { + public UserProfileData UserProfile; + //public Dictionary Folders = new Dictionary(); + public InventoryFolder RootFolder; + + public CachedUserInfo() + { + + } + + /// + /// + /// + /// + /// + public void FolderReceive(LLUUID userID, InventoryFolder folderInfo) + { + if (userID == UserProfile.UUID) + { + if (this.RootFolder == null) + { + if (folderInfo.parentID == LLUUID.Zero) + { + this.RootFolder = folderInfo; + } + } + else + { + if (this.RootFolder.folderID == folderInfo.parentID) + { + this.RootFolder.SubFolders.Add(folderInfo.folderID, folderInfo); + } + else + { + InventoryFolder pFolder = this.RootFolder.HasSubFolder(folderInfo.parentID); + if (pFolder != null) + { + pFolder.SubFolders.Add(folderInfo.folderID, folderInfo); + } + } + } + } + } + + public void ItemReceive(LLUUID userID, InventoryItemBase itemInfo) + { + if (userID == UserProfile.UUID) + { + if (this.RootFolder != null) + { + if (itemInfo.parentFolderID == this.RootFolder.folderID) + { + this.RootFolder.Items.Add(itemInfo.inventoryID, itemInfo); + } + else + { + InventoryFolder pFolder = this.RootFolder.HasSubFolder(itemInfo.parentFolderID); + if (pFolder != null) + { + pFolder.Items.Add(itemInfo.inventoryID, itemInfo); + } + } + } + + } + } + } +} diff --git a/OpenSim/Framework/Communications/caches/InventoryFolder.cs b/OpenSim/Framework/Communications/caches/InventoryFolder.cs index eaddf19..af38b12 100644 --- a/OpenSim/Framework/Communications/caches/InventoryFolder.cs +++ b/OpenSim/Framework/Communications/caches/InventoryFolder.cs @@ -1,51 +1,51 @@ -using System; -using System.Collections.Generic; -using System.Text; -using libsecondlife; -using OpenSim.Framework.Data; - -namespace OpenSim.Framework.Communications.Caches -{ - public class InventoryFolder : InventoryFolderBase - { - public Dictionary SubFolders = new Dictionary(); - public Dictionary Items = new Dictionary(); - - public InventoryFolder() - { - } - - public InventoryFolder HasSubFolder(LLUUID folderID) - { - InventoryFolder returnFolder = null; - if (this.SubFolders.ContainsKey(folderID)) - { - returnFolder = this.SubFolders[folderID]; - } - else - { - foreach (InventoryFolder folder in this.SubFolders.Values) - { - returnFolder = folder.HasSubFolder(folderID); - if (returnFolder != null) - { - break; - } - } - } - return returnFolder; - } - - public InventoryFolder CreateNewSubFolder(LLUUID folderID, string folderName, ushort type) - { - InventoryFolder subFold = new InventoryFolder(); - subFold.name = folderName; - subFold.folderID = folderID; - subFold.type = type; - subFold.parentID = this.folderID; - subFold.agentID = this.agentID; - this.SubFolders.Add(subFold.folderID, subFold); - return subFold; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Data; + +namespace OpenSim.Framework.Communications.Caches +{ + public class InventoryFolder : InventoryFolderBase + { + public Dictionary SubFolders = new Dictionary(); + public Dictionary Items = new Dictionary(); + + public InventoryFolder() + { + } + + public InventoryFolder HasSubFolder(LLUUID folderID) + { + InventoryFolder returnFolder = null; + if (this.SubFolders.ContainsKey(folderID)) + { + returnFolder = this.SubFolders[folderID]; + } + else + { + foreach (InventoryFolder folder in this.SubFolders.Values) + { + returnFolder = folder.HasSubFolder(folderID); + if (returnFolder != null) + { + break; + } + } + } + return returnFolder; + } + + public InventoryFolder CreateNewSubFolder(LLUUID folderID, string folderName, ushort type) + { + InventoryFolder subFold = new InventoryFolder(); + subFold.name = folderName; + subFold.folderID = folderID; + subFold.type = type; + subFold.parentID = this.folderID; + subFold.agentID = this.agentID; + this.SubFolders.Add(subFold.folderID, subFold); + return subFold; + } + } +} diff --git a/OpenSim/Framework/Communications/caches/UserProfileCache.cs b/OpenSim/Framework/Communications/caches/UserProfileCache.cs index 0ee63ba..f651b8a 100644 --- a/OpenSim/Framework/Communications/caches/UserProfileCache.cs +++ b/OpenSim/Framework/Communications/caches/UserProfileCache.cs @@ -1,107 +1,107 @@ -using System; -using System.Collections.Generic; -using System.Text; -using libsecondlife; -using OpenSim.Framework.Data; -using OpenSim.Framework.Communications; - -namespace OpenSim.Framework.Communications.Caches -{ - public class UserProfileCache - { - public Dictionary UserProfiles = new Dictionary(); - - private CommunicationsManager m_parent; - - public UserProfileCache(CommunicationsManager parent) - { - m_parent = parent; - } - - /// - /// A new user has moved into a region in this instance - /// so get info from servers - /// - /// - public void AddNewUser(LLUUID userID) - { - if (!this.UserProfiles.ContainsKey(userID)) - { - CachedUserInfo userInfo = new CachedUserInfo(); - userInfo.UserProfile = this.RequestUserProfileForUser(userID); - this.m_parent.InventoryServer.RequestInventoryForUser(userID, userInfo.FolderReceive, userInfo.ItemReceive); - if (userInfo.UserProfile != null) - { - this.UserProfiles.Add(userID, userInfo); - } - else - { - //no profile for this user, what do we do now? - } - } - else - { - //already have a cached profile for this user - //we should make sure its upto date with the user server version - } - } - - /// - /// A new user has moved into a region in this instance - /// so get info from servers - /// - /// - /// - public void AddNewUser(string firstName, string lastName) - { - - } - - /// - /// A user has left this instance - /// so make sure servers have been updated - /// Then remove cached info - /// - /// - public void UserLogOut(LLUUID userID) - { - - } - - /// - /// Request the user profile from User server - /// - /// - private UserProfileData RequestUserProfileForUser(LLUUID userID) - { - return this.m_parent.UserServer.GetUserProfile(userID); - } - - /// - /// Request Iventory Info from Inventory server - /// - /// - private void RequestInventoryForUser(LLUUID userID) - { - - } - - /// - /// Make sure UserProfile is updated on user server - /// - /// - private void UpdateUserProfileToServer(LLUUID userID) - { - - } - - /// - /// Update Inventory data to Inventory server - /// - /// - private void UpdateInventoryToServer(LLUUID userID) - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Data; +using OpenSim.Framework.Communications; + +namespace OpenSim.Framework.Communications.Caches +{ + public class UserProfileCache + { + public Dictionary UserProfiles = new Dictionary(); + + private CommunicationsManager m_parent; + + public UserProfileCache(CommunicationsManager parent) + { + m_parent = parent; + } + + /// + /// A new user has moved into a region in this instance + /// so get info from servers + /// + /// + public void AddNewUser(LLUUID userID) + { + if (!this.UserProfiles.ContainsKey(userID)) + { + CachedUserInfo userInfo = new CachedUserInfo(); + userInfo.UserProfile = this.RequestUserProfileForUser(userID); + this.m_parent.InventoryServer.RequestInventoryForUser(userID, userInfo.FolderReceive, userInfo.ItemReceive); + if (userInfo.UserProfile != null) + { + this.UserProfiles.Add(userID, userInfo); + } + else + { + //no profile for this user, what do we do now? + } + } + else + { + //already have a cached profile for this user + //we should make sure its upto date with the user server version + } + } + + /// + /// A new user has moved into a region in this instance + /// so get info from servers + /// + /// + /// + public void AddNewUser(string firstName, string lastName) + { + + } + + /// + /// A user has left this instance + /// so make sure servers have been updated + /// Then remove cached info + /// + /// + public void UserLogOut(LLUUID userID) + { + + } + + /// + /// Request the user profile from User server + /// + /// + private UserProfileData RequestUserProfileForUser(LLUUID userID) + { + return this.m_parent.UserServer.GetUserProfile(userID); + } + + /// + /// Request Iventory Info from Inventory server + /// + /// + private void RequestInventoryForUser(LLUUID userID) + { + + } + + /// + /// Make sure UserProfile is updated on user server + /// + /// + private void UpdateUserProfileToServer(LLUUID userID) + { + + } + + /// + /// Update Inventory data to Inventory server + /// + /// + private void UpdateInventoryToServer(LLUUID userID) + { + + } + } +} diff --git a/OpenSim/Framework/Console/AssemblyInfo.cs b/OpenSim/Framework/Console/AssemblyInfo.cs index 30f6167..61bd423 100644 --- a/OpenSim/Framework/Console/AssemblyInfo.cs +++ b/OpenSim/Framework/Console/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index 346cfe6..1dea251 100644 --- a/OpenSim/Framework/Console/ConsoleCallbacksBase.cs +++ b/OpenSim/Framework/Console/ConsoleCallbacksBase.cs @@ -1,35 +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. -* -*/ -namespace OpenSim.Framework.Console -{ - public interface conscmd_callback - { - void RunCmd(string cmd, string[] cmdparams); - void Show(string ShowWhat); - } -} +/* +* 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. +* +*/ +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 index f73e15e..1eb6ff0 100644 --- a/OpenSim/Framework/Console/LogBase.cs +++ b/OpenSim/Framework/Console/LogBase.cs @@ -1,282 +1,282 @@ -/* -* 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.Net; - -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(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 (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; - } - - public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue) - { - IPAddress address; - string addressStr; - - while (true) - { - addressStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); - if (IPAddress.TryParse(addressStr, out address)) - { - break; - } - else - { - MainLog.Instance.Error("Illegal address. Please re-enter."); - } - } - - return address; - } - - public int CmdPromptIPPort(string prompt, string defaultvalue) - { - int port; - string portStr; - - while (true) - { - portStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); - if (int.TryParse(portStr, out port)) - { - if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort) - { - break; - } - } - - MainLog.Instance.Error("Illegal address. Please re-enter."); - } - - return port; - } - - // 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); - } - } -} +/* +* 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.Net; + +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(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 (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; + } + + public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue) + { + IPAddress address; + string addressStr; + + while (true) + { + addressStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); + if (IPAddress.TryParse(addressStr, out address)) + { + break; + } + else + { + MainLog.Instance.Error("Illegal address. Please re-enter."); + } + } + + return address; + } + + public int CmdPromptIPPort(string prompt, string defaultvalue) + { + int port; + string portStr; + + while (true) + { + portStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); + if (int.TryParse(portStr, out port)) + { + if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort) + { + break; + } + } + + MainLog.Instance.Error("Illegal address. Please re-enter."); + } + + return port; + } + + // 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 index 7d52622..e6bf9d9 100644 --- a/OpenSim/Framework/Console/MainLog.cs +++ b/OpenSim/Framework/Console/MainLog.cs @@ -1,47 +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. -* -*/ -namespace OpenSim.Framework.Console -{ - public class MainLog { - - private static LogBase instance; - - public static LogBase Instance - { - get - { - return instance; - } - set - { - instance = value; - } - } - } - -} +/* +* 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. +* +*/ +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/Data.DB4o/DB4oGridData.cs b/OpenSim/Framework/Data.DB4o/DB4oGridData.cs index 5fec367..e57a3aa 100644 --- a/OpenSim/Framework/Data.DB4o/DB4oGridData.cs +++ b/OpenSim/Framework/Data.DB4o/DB4oGridData.cs @@ -1,162 +1,162 @@ -/* -* 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; - -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() + "). Total Registered Regions: " + manager.simProfiles.Count); - } - - /// - /// 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; - } - } -} +/* +* 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; + +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() + "). Total Registered Regions: " + manager.simProfiles.Count); + } + + /// + /// 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 index 0df6350..43f9095 100644 --- a/OpenSim/Framework/Data.DB4o/DB4oManager.cs +++ b/OpenSim/Framework/Data.DB4o/DB4oManager.cs @@ -1,163 +1,163 @@ -/* -* 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 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) - { - 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) - { - return false; - } - } - - - } -} +/* +* 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 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) + { + 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) + { + return false; + } + } + + + } +} diff --git a/OpenSim/Framework/Data.DB4o/DB4oUserData.cs b/OpenSim/Framework/Data.DB4o/DB4oUserData.cs index 2e33ab0..845b764 100644 --- a/OpenSim/Framework/Data.DB4o/DB4oUserData.cs +++ b/OpenSim/Framework/Data.DB4o/DB4oUserData.cs @@ -1,202 +1,202 @@ -/* -* 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; - -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) - { - 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) - { - 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"; - } - } -} +/* +* 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; + +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) + { + 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) + { + 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/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs index 905cd9b..52d09fa 100644 --- a/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Data.DB4o/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Data.DB4o")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.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")] +using System.Reflection; +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.Data.DB4o")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.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 index ca9196a5..dc60ca4 100644 --- a/OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs +++ b/OpenSim/Framework/Data.MSSQL/MSSQLGridData.cs @@ -1,194 +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.Data; -using System.Security.Cryptography; -using System.Text; -using libsecondlife; - -namespace OpenSim.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(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); - 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(LLUUID uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid.ToStringHyphenated(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); - 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) - { - SHA512Managed HashProvider = new SHA512Managed(); - 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; - } - } - -} +/* +* 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.Data; +using System.Security.Cryptography; +using System.Text; +using libsecondlife; + +namespace OpenSim.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(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); + 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(LLUUID uuid) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToStringHyphenated(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); + 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) + { + SHA512Managed HashProvider = new SHA512Managed(); + 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 index 49bf31c..26677a5 100644 --- a/OpenSim/Framework/Data.MSSQL/MSSQLManager.cs +++ b/OpenSim/Framework/Data.MSSQL/MSSQLManager.cs @@ -1,211 +1,211 @@ -/* -* 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.Data; -using System.Data.SqlClient; -using libsecondlife; - -namespace OpenSim.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 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) - { - return false; - } - - return returnval; - } - } -} +/* +* 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.Data; +using System.Data.SqlClient; +using libsecondlife; + +namespace OpenSim.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 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) + { + return false; + } + + return returnval; + } + } +} diff --git a/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs index 066c739..eeac06c 100644 --- a/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Data.MSSQL/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Data.MSSQL")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.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")] +using System.Reflection; +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.Data.MSSQL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.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 index ef643d2..09f5e83 100644 --- a/OpenSim/Framework/Data.MySQL/MySQLGridData.cs +++ b/OpenSim/Framework/Data.MySQL/MySQLGridData.cs @@ -1,287 +1,287 @@ -/* -* 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.Data; -using System.Security.Cryptography; -using System.Text; -using libsecondlife; - -namespace OpenSim.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(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param); - 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(LLUUID uuid) - { - try - { - lock (database) - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToStringHyphenated(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = ?uuid", param); - 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) - { - SHA512Managed HashProvider = new SHA512Managed(); - 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(); - IDbCommand result = database.Query("SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", param); - 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; - } - } - } - - -} +/* +* 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.Data; +using System.Security.Cryptography; +using System.Text; +using libsecondlife; + +namespace OpenSim.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(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param); + 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(LLUUID uuid) + { + try + { + lock (database) + { + Dictionary param = new Dictionary(); + param["?uuid"] = uuid.ToStringHyphenated(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = ?uuid", param); + 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) + { + SHA512Managed HashProvider = new SHA512Managed(); + 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(); + IDbCommand result = database.Query("SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", param); + 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 index 790759a..d32db1b 100644 --- a/OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs +++ b/OpenSim/Framework/Data.MySQL/MySQLInventoryData.cs @@ -1,309 +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.Data; -using libsecondlife; - -namespace OpenSim.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(); - - IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", param); - 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); - } - } -} +/* +* 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.Data; +using libsecondlife; + +namespace OpenSim.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(); + + IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", param); + 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 index 38f9fd3..2ba9c3d 100644 --- a/OpenSim/Framework/Data.MySQL/MySQLLogData.cs +++ b/OpenSim/Framework/Data.MySQL/MySQLLogData.cs @@ -1,105 +1,105 @@ -/* -* 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.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 - { - 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"; - } - } -} +/* +* 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.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 + { + 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 index ab7f277..a5434c8 100644 --- a/OpenSim/Framework/Data.MySQL/MySQLManager.cs +++ b/OpenSim/Framework/Data.MySQL/MySQLManager.cs @@ -1,606 +1,606 @@ -/* -* 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.Data; -using libsecondlife; -using MySql.Data.MySqlClient; - -namespace OpenSim.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(); - - 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 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"]; - retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); - retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); - - // 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 LLUUID(tempRegionMap); - } - else - { - retval.regionMapTextureID = new 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 = Convert.ToInt32(reader["resXMax"].ToString()); - retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString()); - retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString()); - retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString()); - retval.reservationName = (string)reader["resName"]; - retval.status = Convert.ToInt32(reader["status"].ToString()) == 1; - retval.userUUID = new 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 LLUUID((string)reader["UUID"]); - retval.sessionID = new LLUUID((string)reader["sessionID"]); - retval.secureSessionID = new 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()); - 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 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 LLVector3( - Convert.ToSingle(reader["homeLocationX"].ToString()), - Convert.ToSingle(reader["homeLocationY"].ToString()), - Convert.ToSingle(reader["homeLocationZ"].ToString())); - retval.homeLookAt = new 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 LLUUID((string)reader["profileImage"]); - retval.profileFirstImage = new 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 LLUUID((string)reader["agentID"]); - folder.parentID = new LLUUID((string)reader["parentFolderID"]); - folder.folderID = new 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 LLUUID((string)reader["assetID"]); - item.avatarID = new LLUUID((string)reader["avatarID"]); - item.inventoryCurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"].ToString()); - item.inventoryDescription = (string)reader["inventoryDescription"]; - item.inventoryID = new LLUUID((string)reader["inventoryID"]); - item.inventoryName = (string)reader["inventoryName"]; - item.inventoryNextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"].ToString()); - item.parentFolderID = new 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, serverHttpPort, serverRemotingPort) 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, ?serverHttpPort, ?serverRemotingPort);"; - - 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(); - parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); - parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); - - 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; - } - } -} +/* +* 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.Data; +using libsecondlife; +using MySql.Data.MySqlClient; + +namespace OpenSim.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(); + + 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 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"]; + retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); + retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); + + // 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 LLUUID(tempRegionMap); + } + else + { + retval.regionMapTextureID = new 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 = Convert.ToInt32(reader["resXMax"].ToString()); + retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString()); + retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString()); + retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString()); + retval.reservationName = (string)reader["resName"]; + retval.status = Convert.ToInt32(reader["status"].ToString()) == 1; + retval.userUUID = new 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 LLUUID((string)reader["UUID"]); + retval.sessionID = new LLUUID((string)reader["sessionID"]); + retval.secureSessionID = new 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()); + 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 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 LLVector3( + Convert.ToSingle(reader["homeLocationX"].ToString()), + Convert.ToSingle(reader["homeLocationY"].ToString()), + Convert.ToSingle(reader["homeLocationZ"].ToString())); + retval.homeLookAt = new 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 LLUUID((string)reader["profileImage"]); + retval.profileFirstImage = new 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 LLUUID((string)reader["agentID"]); + folder.parentID = new LLUUID((string)reader["parentFolderID"]); + folder.folderID = new 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 LLUUID((string)reader["assetID"]); + item.avatarID = new LLUUID((string)reader["avatarID"]); + item.inventoryCurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"].ToString()); + item.inventoryDescription = (string)reader["inventoryDescription"]; + item.inventoryID = new LLUUID((string)reader["inventoryID"]); + item.inventoryName = (string)reader["inventoryName"]; + item.inventoryNextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"].ToString()); + item.parentFolderID = new 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, serverHttpPort, serverRemotingPort) 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, ?serverHttpPort, ?serverRemotingPort);"; + + 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(); + parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); + parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); + + 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 index c116536..b044bdd 100644 --- a/OpenSim/Framework/Data.MySQL/MySQLUserData.cs +++ b/OpenSim/Framework/Data.MySQL/MySQLUserData.cs @@ -1,256 +1,256 @@ -/* -* 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.Data; -using libsecondlife; - -namespace OpenSim.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; - - IDbCommand result = database.Query("SELECT * FROM users WHERE username = ?first AND lastname = ?second", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM users WHERE UUID = ?uuid", param); - 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(); - - IDbCommand result = database.Query("SELECT * FROM agents WHERE UUID = ?uuid", param); - 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"; - } - } -} +/* +* 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.Data; +using libsecondlife; + +namespace OpenSim.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; + + IDbCommand result = database.Query("SELECT * FROM users WHERE username = ?first AND lastname = ?second", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM users WHERE UUID = ?uuid", param); + 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(); + + IDbCommand result = database.Query("SELECT * FROM agents WHERE UUID = ?uuid", param); + 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/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs index 52d6a54..46c0ae0 100644 --- a/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Data.MySQL/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Data.MySQL")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.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")] +using System.Reflection; +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.Data.MySQL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.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/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs index 9de5edb..8136bc1 100644 --- a/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Data.SQLite/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Data.SQLite")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.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")] +using System.Reflection; +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.Data.SQLite")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.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 index 511c5f0..c1d74ae 100644 --- a/OpenSim/Framework/Data.SQLite/SQLiteGridData.cs +++ b/OpenSim/Framework/Data.SQLite/SQLiteGridData.cs @@ -1,197 +1,197 @@ -/* -* 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.Data; -using System.Security.Cryptography; -using System.Text; -using libsecondlife; - -namespace OpenSim.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(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); - 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(LLUUID uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid.ToStringHyphenated(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); - 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) - { - SHA512Managed HashProvider = new SHA512Managed(); - 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; - } - } - - -} +/* +* 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.Data; +using System.Security.Cryptography; +using System.Text; +using libsecondlife; + +namespace OpenSim.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(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); + 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(LLUUID uuid) + { + Dictionary param = new Dictionary(); + param["uuid"] = uuid.ToStringHyphenated(); + + IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); + 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(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(LLUUID uuid, ulong handle, string authhash, string challenge) + { + SHA512Managed HashProvider = new SHA512Managed(); + 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 index c9931ab..a69611a 100644 --- a/OpenSim/Framework/Data.SQLite/SQLiteManager.cs +++ b/OpenSim/Framework/Data.SQLite/SQLiteManager.cs @@ -1,206 +1,206 @@ -/* -* 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.Data; -using System.Data.SQLite; -using libsecondlife; - -namespace OpenSim.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 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) - { - return false; - } - - return returnval; - } - } -} +/* +* 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.Data; +using System.Data.SQLite; +using libsecondlife; + +namespace OpenSim.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 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) + { + return false; + } + + return returnval; + } + } +} diff --git a/OpenSim/Framework/Data/GridData.cs b/OpenSim/Framework/Data/GridData.cs index 5a17d20..c96353b 100644 --- a/OpenSim/Framework/Data/GridData.cs +++ b/OpenSim/Framework/Data/GridData.cs @@ -1,111 +1,111 @@ -/* -* 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 libsecondlife; - -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(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(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); - - } -} +/* +* 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 libsecondlife; + +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(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(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 index 059fef5..a827c0c 100644 --- a/OpenSim/Framework/Data/ILogData.cs +++ b/OpenSim/Framework/Data/ILogData.cs @@ -1,90 +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. -* -*/ -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(); - } - -} +/* +* 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. +* +*/ +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 index 2b52fd1..5dcb2fd 100644 --- a/OpenSim/Framework/Data/IniConfig.cs +++ b/OpenSim/Framework/Data/IniConfig.cs @@ -1,96 +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.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; - } -} +/* +* 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.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 index 7253cc7..f6aeb58 100644 --- a/OpenSim/Framework/Data/InventoryData.cs +++ b/OpenSim/Framework/Data/InventoryData.cs @@ -1,197 +1,197 @@ -/* -* 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.Collections.Generic; -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 - /// - public LLUUID parentFolderID; - /// - /// The owner of this inventory item - /// - public LLUUID avatarID; - /// - /// The creator of this item - /// - public LLUUID creatorsID; - /// - /// 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 - /// - public LLUUID parentID; - /// - /// The UUID for this folder - /// - public LLUUID folderID; - /// - /// Tyep of Items normally stored in this folder - /// - public ushort type; - /// - /// - /// - public ushort version; - } - - /// - /// 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); - } -} +/* +* 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.Collections.Generic; +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 + /// + public LLUUID parentFolderID; + /// + /// The owner of this inventory item + /// + public LLUUID avatarID; + /// + /// The creator of this item + /// + public LLUUID creatorsID; + /// + /// 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 + /// + public LLUUID parentID; + /// + /// The UUID for this folder + /// + public LLUUID folderID; + /// + /// Tyep of Items normally stored in this folder + /// + public ushort type; + /// + /// + /// + public ushort version; + } + + /// + /// 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/Properties/AssemblyInfo.cs b/OpenSim/Framework/Data/Properties/AssemblyInfo.cs index f9260a1..556d589 100644 --- a/OpenSim/Framework/Data/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/Data/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Data")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.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")] +using System.Reflection; +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.Data")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.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 index 0078df0..8344d6c 100644 --- a/OpenSim/Framework/Data/ReservationData.cs +++ b/OpenSim/Framework/Data/ReservationData.cs @@ -1,47 +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 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 = ""; - } -} +/* +* 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 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 index b920cab..c963455 100644 --- a/OpenSim/Framework/Data/SimProfileData.cs +++ b/OpenSim/Framework/Data/SimProfileData.cs @@ -1,192 +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 libsecondlife; -using Nwc.XmlRpc; - -using System; -using System.Collections; - -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 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 = ""; - - public uint httpPort; - public uint remotingPort; - public string httpServerURI = ""; - - /// - /// 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 LLUUID regionMapTextureID = new LLUUID("00000000-0000-0000-9999-000000000006"); - - /// - /// Get Sim profile data from grid server when in grid mode - /// - /// - /// - /// - /// - public SimProfileData RequestSimProfileData(LLUUID region_uuid, string gridserver_url, string gridserver_sendkey, string gridserver_recvkey) - { - Hashtable requestData = new Hashtable(); - requestData["region_uuid"] = region_uuid.UUID.ToString(); - requestData["authkey"] = gridserver_sendkey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridserver_url, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - return null; - } - - SimProfileData simData = new SimProfileData(); - simData.regionLocX = Convert.ToUInt32((string)responseData["region_locx"]); - simData.regionLocY = Convert.ToUInt32((string)responseData["region_locy"]); - simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * 256), (simData.regionLocY * 256)); - simData.serverIP = (string)responseData["sim_ip"]; - simData.serverPort = Convert.ToUInt32((string)responseData["sim_port"]); - simData.httpPort = Convert.ToUInt32((string)responseData["http_port"]); - simData.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - simData.serverURI = "http://" + simData.serverIP + ":" + simData.serverPort.ToString() + "/"; - simData.httpServerURI = "http://" + simData.serverIP + ":" + simData.httpPort.ToString() + "/"; - simData.UUID = new LLUUID((string)responseData["region_UUID"]); - simData.regionName = (string)responseData["region_name"]; - - return simData; - } - public SimProfileData RequestSimProfileData(ulong region_handle, string gridserver_url, string gridserver_sendkey, string gridserver_recvkey) - { - Hashtable requestData = new Hashtable(); - requestData["region_handle"] = region_handle.ToString(); - requestData["authkey"] = gridserver_sendkey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridserver_url, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - return null; - } - - SimProfileData simData = new SimProfileData(); - simData.regionLocX = Convert.ToUInt32((string)responseData["region_locx"]); - simData.regionLocY = Convert.ToUInt32((string)responseData["region_locy"]); - simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * 256), (simData.regionLocY * 256)); - simData.serverIP = (string)responseData["sim_ip"]; - simData.serverPort = Convert.ToUInt32((string)responseData["sim_port"]); - simData.httpPort = Convert.ToUInt32((string)responseData["http_port"]); - simData.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - simData.httpServerURI = "http://" + simData.serverIP + ":" + simData.httpPort.ToString() + "/"; - simData.serverURI = "http://" + simData.serverIP + ":" + simData.serverPort.ToString() + "/"; - simData.UUID = new LLUUID((string)responseData["region_UUID"]); - simData.regionName = (string)responseData["region_name"]; - - return simData; - } - } -} +/* +* 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 libsecondlife; +using Nwc.XmlRpc; + +using System; +using System.Collections; + +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 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 = ""; + + public uint httpPort; + public uint remotingPort; + public string httpServerURI = ""; + + /// + /// 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 LLUUID regionMapTextureID = new LLUUID("00000000-0000-0000-9999-000000000006"); + + /// + /// Get Sim profile data from grid server when in grid mode + /// + /// + /// + /// + /// + public SimProfileData RequestSimProfileData(LLUUID region_uuid, string gridserver_url, string gridserver_sendkey, string gridserver_recvkey) + { + Hashtable requestData = new Hashtable(); + requestData["region_uuid"] = region_uuid.UUID.ToString(); + requestData["authkey"] = gridserver_sendkey; + ArrayList SendParams = new ArrayList(); + SendParams.Add(requestData); + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); + XmlRpcResponse GridResp = GridReq.Send(gridserver_url, 3000); + + Hashtable responseData = (Hashtable)GridResp.Value; + + if (responseData.ContainsKey("error")) + { + return null; + } + + SimProfileData simData = new SimProfileData(); + simData.regionLocX = Convert.ToUInt32((string)responseData["region_locx"]); + simData.regionLocY = Convert.ToUInt32((string)responseData["region_locy"]); + simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * 256), (simData.regionLocY * 256)); + simData.serverIP = (string)responseData["sim_ip"]; + simData.serverPort = Convert.ToUInt32((string)responseData["sim_port"]); + simData.httpPort = Convert.ToUInt32((string)responseData["http_port"]); + simData.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); + simData.serverURI = "http://" + simData.serverIP + ":" + simData.serverPort.ToString() + "/"; + simData.httpServerURI = "http://" + simData.serverIP + ":" + simData.httpPort.ToString() + "/"; + simData.UUID = new LLUUID((string)responseData["region_UUID"]); + simData.regionName = (string)responseData["region_name"]; + + return simData; + } + public SimProfileData RequestSimProfileData(ulong region_handle, string gridserver_url, string gridserver_sendkey, string gridserver_recvkey) + { + Hashtable requestData = new Hashtable(); + requestData["region_handle"] = region_handle.ToString(); + requestData["authkey"] = gridserver_sendkey; + ArrayList SendParams = new ArrayList(); + SendParams.Add(requestData); + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); + XmlRpcResponse GridResp = GridReq.Send(gridserver_url, 3000); + + Hashtable responseData = (Hashtable)GridResp.Value; + + if (responseData.ContainsKey("error")) + { + return null; + } + + SimProfileData simData = new SimProfileData(); + simData.regionLocX = Convert.ToUInt32((string)responseData["region_locx"]); + simData.regionLocY = Convert.ToUInt32((string)responseData["region_locy"]); + simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * 256), (simData.regionLocY * 256)); + simData.serverIP = (string)responseData["sim_ip"]; + simData.serverPort = Convert.ToUInt32((string)responseData["sim_port"]); + simData.httpPort = Convert.ToUInt32((string)responseData["http_port"]); + simData.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); + simData.httpServerURI = "http://" + simData.serverIP + ":" + simData.httpPort.ToString() + "/"; + simData.serverURI = "http://" + simData.serverIP + ":" + simData.serverPort.ToString() + "/"; + simData.UUID = new LLUUID((string)responseData["region_UUID"]); + simData.regionName = (string)responseData["region_name"]; + + return simData; + } + } +} diff --git a/OpenSim/Framework/Data/UserData.cs b/OpenSim/Framework/Data/UserData.cs index c65f9fd..d849e12 100644 --- a/OpenSim/Framework/Data/UserData.cs +++ b/OpenSim/Framework/Data/UserData.cs @@ -1,128 +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 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(); - } -} +/* +* 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 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 index bb7d48c..88f956f 100644 --- a/OpenSim/Framework/Data/UserProfileData.cs +++ b/OpenSim/Framework/Data/UserProfileData.cs @@ -1,180 +1,180 @@ -/* -* 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; - -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 = String.Empty; - /// - /// 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; - } -} +/* +* 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; + +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 = String.Empty; + /// + /// 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 index e45a0cd..0aeb0b3 100644 --- a/OpenSim/Framework/General/AgentInventory.cs +++ b/OpenSim/Framework/General/AgentInventory.cs @@ -1,265 +1,265 @@ -/* -* 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.Collections.Generic; -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; - } - } -} +/* +* 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.Collections.Generic; +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 index 71616e3..2d02286 100644 --- a/OpenSim/Framework/General/AuthenticateSessionBase.cs +++ b/OpenSim/Framework/General/AuthenticateSessionBase.cs @@ -1,130 +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.Collections.Generic; -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; - } - } +/* +* 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.Collections.Generic; +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 index 0cc8124..e263d71 100644 --- a/OpenSim/Framework/General/BlockingQueue.cs +++ b/OpenSim/Framework/General/BlockingQueue.cs @@ -1,58 +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.Collections.Generic; -using System.Threading; - -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(); - } - } - } -} +/* +* 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.Collections.Generic; +using System.Threading; + +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/ClientManager.cs b/OpenSim/Framework/General/ClientManager.cs index b560ca8..0e45d03 100644 --- a/OpenSim/Framework/General/ClientManager.cs +++ b/OpenSim/Framework/General/ClientManager.cs @@ -1,36 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Framework.Interfaces; - -namespace OpenSim.Framework -{ - public delegate void ForEachClientDelegate( IClientAPI client ); - public class ClientManager - { - private Dictionary m_clients; - - public void ForEachClient(ForEachClientDelegate whatToDo) - { - foreach (IClientAPI client in m_clients.Values) - { - whatToDo(client); - } - } - - public ClientManager() - { - m_clients = new Dictionary(); - } - - public void Remove(uint id) - { - m_clients.Remove(id); - } - - public void Add(uint id, IClientAPI client ) - { - m_clients.Add( id, client ); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Framework +{ + public delegate void ForEachClientDelegate( IClientAPI client ); + public class ClientManager + { + private Dictionary m_clients; + + public void ForEachClient(ForEachClientDelegate whatToDo) + { + foreach (IClientAPI client in m_clients.Values) + { + whatToDo(client); + } + } + + public ClientManager() + { + m_clients = new Dictionary(); + } + + public void Remove(uint id) + { + m_clients.Remove(id); + } + + public void Add(uint id, IClientAPI client ) + { + m_clients.Add( id, client ); + } + } +} diff --git a/OpenSim/Framework/General/IRegionCommsListener.cs b/OpenSim/Framework/General/IRegionCommsListener.cs index 32444f9..81da5d4 100644 --- a/OpenSim/Framework/General/IRegionCommsListener.cs +++ b/OpenSim/Framework/General/IRegionCommsListener.cs @@ -1,46 +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.Collections.Generic; -using libsecondlife; -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, LLUUID agentID, LLVector3 position); - - public interface IRegionCommsListener - { - event ExpectUserDelegate OnExpectUser; - event GenericCall2 OnExpectChildAgent; - event AgentCrossing OnAvatarCrossingIntoRegion; - event UpdateNeighbours OnNeighboursUpdate; - } -} +/* +* 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.Collections.Generic; +using libsecondlife; +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, LLUUID agentID, 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 index 508485b..7c49785 100644 --- a/OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs +++ b/OpenSim/Framework/General/Interfaces/AuthenticateResponse.cs @@ -1,43 +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 OpenSim.Framework.Types; - -namespace OpenSim.Framework.Interfaces -{ - public class AuthenticateResponse - { - public bool Authorised; - public Login LoginInfo; - - public AuthenticateResponse() - { - - } - - } -} +/* +* 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 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 index 2c379dd..57aa0c0 100644 --- a/OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs +++ b/OpenSim/Framework/General/Interfaces/Config/IGenericConfig.cs @@ -1,38 +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. -* -*/ -namespace OpenSim.Framework.Interfaces -{ - public interface IGenericConfig - { - void LoadData(); - string GetAttribute(string attributeName); - bool SetAttribute(string attributeName, string attributeValue); - void Commit(); - void Close(); - } -} +/* +* 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. +* +*/ +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 index 81dc293..20cc320 100644 --- a/OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs +++ b/OpenSim/Framework/General/Interfaces/Config/IGridConfig.cs @@ -1,59 +1,59 @@ -/* -* 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 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(); - } -} +/* +* 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 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 index ae6cedb..a17804a 100644 --- a/OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs +++ b/OpenSim/Framework/General/Interfaces/Config/IUserConfig.cs @@ -1,53 +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 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(); - } -} +/* +* 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 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 index ab60dd7..cbb5c36 100644 --- a/OpenSim/Framework/General/Interfaces/IAssetServer.cs +++ b/OpenSim/Framework/General/Interfaces/IAssetServer.cs @@ -1,64 +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 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; - } -} +/* +* 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 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 index bd258a3..0606e43 100644 --- a/OpenSim/Framework/General/Interfaces/IClientAPI.cs +++ b/OpenSim/Framework/General/Interfaces/IClientAPI.cs @@ -1,195 +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.Collections.Generic; -using System.Net; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Types; -using OpenSim.Framework.Data; - -namespace OpenSim.Framework.Interfaces -{ - public delegate void ChatFromViewer(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID); - public delegate void ImprovedInstantMessage(LLUUID fromAgentID, LLUUID toAgentID, uint timestamp, string fromAgentName, string message); // Cut down from full list - 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 GenericCall7(uint localID, string message); - - public delegate void UpdateShape(uint localID, ObjectShapePacket.ObjectDataBlock shapeBlock); - public delegate void ObjectSelect(uint localID, IClientAPI remoteClient); - public delegate void ObjectDeselect(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 UpdatePrimSingleRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient); - public delegate void UpdatePrimGroupRotation(uint localID,LLVector3 pos, LLQuaternion rot, IClientAPI remoteClient); - public delegate void ObjectDuplicate(uint localID, LLVector3 offset, uint dupeFlags); - 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); - public delegate void ParcelSelectObjects(int parcel_local_id, int request_type, IClientAPI remote_client); - public delegate void ParcelObjectOwnerRequest(int local_id, IClientAPI remote_client); - public delegate void EstateOwnerMessageRequest(EstateOwnerMessagePacket packet, IClientAPI remote_client); - - public delegate void UUIDNameRequest(LLUUID id, IClientAPI remote_client); - - public delegate void AddNewPrim(LLUUID ownerID, LLVector3 pos, PrimitiveBaseShape shape); - - - - public interface IClientAPI - { - event ImprovedInstantMessage OnInstantMessage; - 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 AddNewPrim OnAddPrim; - event ObjectDuplicate OnObjectDuplicate; - event UpdateVector OnGrapObject; - event ObjectSelect OnDeGrapObject; - event MoveObject OnGrapUpdate; - - event UpdateShape OnUpdatePrimShape; - event ObjectSelect OnObjectSelect; - event ObjectDeselect OnObjectDeselect; - event GenericCall7 OnObjectDescription; - event GenericCall7 OnObjectName; - event UpdatePrimFlags OnUpdatePrimFlags; - event UpdatePrimTexture OnUpdatePrimTexture; - event UpdateVector OnUpdatePrimGroupPosition; - event UpdateVector OnUpdatePrimSinglePosition; - event UpdatePrimRotation OnUpdatePrimGroupRotation; - event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; - event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; - event UpdateVector OnUpdatePrimScale; - event StatusChange OnChildAgentStatus; - event GenericCall2 OnStopMovement; - event NewAvatar OnNewAvatar; - event GenericCall6 OnRemoveAvatar; - - event UUIDNameRequest OnNameFromUUIDRequest; - - event ParcelPropertiesRequest OnParcelPropertiesRequest; - event ParcelDivideRequest OnParcelDivideRequest; - event ParcelJoinRequest OnParcelJoinRequest; - event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; - event ParcelSelectObjects OnParcelSelectObjects; - event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; - 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 SendStartPingCheck(byte seq); - void SendKillObject(ulong regionHandle, uint avatarLocalID); - void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId); - 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 SendInstantMessage(string message, LLUUID target, string fromName); - void SendLayerData(float[] map); - void SendLayerData(int px, int py, float[] map); - void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look); - void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint ); - AgentCircuitData RequestClientInfo(); - void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint ); - void SendMapBlock(List mapBlocks); - void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags); - void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, 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 SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID); - void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID); - void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation); - - void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items); - void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item); - void SendNameReply(LLUUID profileId, string firstname, string lastname); - - - } -} +/* +* 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.Collections.Generic; +using System.Net; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Types; +using OpenSim.Framework.Data; + +namespace OpenSim.Framework.Interfaces +{ + public delegate void ChatFromViewer(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID); + public delegate void ImprovedInstantMessage(LLUUID fromAgentID, LLUUID toAgentID, uint timestamp, string fromAgentName, string message); // Cut down from full list + 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 GenericCall7(uint localID, string message); + + public delegate void UpdateShape(uint localID, ObjectShapePacket.ObjectDataBlock shapeBlock); + public delegate void ObjectSelect(uint localID, IClientAPI remoteClient); + public delegate void ObjectDeselect(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 UpdatePrimSingleRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient); + public delegate void UpdatePrimGroupRotation(uint localID,LLVector3 pos, LLQuaternion rot, IClientAPI remoteClient); + public delegate void ObjectDuplicate(uint localID, LLVector3 offset, uint dupeFlags); + 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); + public delegate void ParcelSelectObjects(int parcel_local_id, int request_type, IClientAPI remote_client); + public delegate void ParcelObjectOwnerRequest(int local_id, IClientAPI remote_client); + public delegate void EstateOwnerMessageRequest(EstateOwnerMessagePacket packet, IClientAPI remote_client); + + public delegate void UUIDNameRequest(LLUUID id, IClientAPI remote_client); + + public delegate void AddNewPrim(LLUUID ownerID, LLVector3 pos, PrimitiveBaseShape shape); + + + + public interface IClientAPI + { + event ImprovedInstantMessage OnInstantMessage; + 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 AddNewPrim OnAddPrim; + event ObjectDuplicate OnObjectDuplicate; + event UpdateVector OnGrapObject; + event ObjectSelect OnDeGrapObject; + event MoveObject OnGrapUpdate; + + event UpdateShape OnUpdatePrimShape; + event ObjectSelect OnObjectSelect; + event ObjectDeselect OnObjectDeselect; + event GenericCall7 OnObjectDescription; + event GenericCall7 OnObjectName; + event UpdatePrimFlags OnUpdatePrimFlags; + event UpdatePrimTexture OnUpdatePrimTexture; + event UpdateVector OnUpdatePrimGroupPosition; + event UpdateVector OnUpdatePrimSinglePosition; + event UpdatePrimRotation OnUpdatePrimGroupRotation; + event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; + event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; + event UpdateVector OnUpdatePrimScale; + event StatusChange OnChildAgentStatus; + event GenericCall2 OnStopMovement; + event NewAvatar OnNewAvatar; + event GenericCall6 OnRemoveAvatar; + + event UUIDNameRequest OnNameFromUUIDRequest; + + event ParcelPropertiesRequest OnParcelPropertiesRequest; + event ParcelDivideRequest OnParcelDivideRequest; + event ParcelJoinRequest OnParcelJoinRequest; + event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + event ParcelSelectObjects OnParcelSelectObjects; + event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; + 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 SendStartPingCheck(byte seq); + void SendKillObject(ulong regionHandle, uint avatarLocalID); + void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId); + 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 SendInstantMessage(string message, LLUUID target, string fromName); + void SendLayerData(float[] map); + void SendLayerData(int px, int py, float[] map); + void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look); + void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint ); + AgentCircuitData RequestClientInfo(); + void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint ); + void SendMapBlock(List mapBlocks); + void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags); + void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, 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 SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID); + void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID); + void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation); + + void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items); + void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item); + void SendNameReply(LLUUID profileId, string firstname, string lastname); + + + } +} diff --git a/OpenSim/Framework/General/Interfaces/ILocalStorage.cs b/OpenSim/Framework/General/Interfaces/ILocalStorage.cs index 7093121..c7c0b5f 100644 --- a/OpenSim/Framework/General/Interfaces/ILocalStorage.cs +++ b/OpenSim/Framework/General/Interfaces/ILocalStorage.cs @@ -1,71 +1,71 @@ -/* -* 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 libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Framework.Interfaces -{ - /// - /// ILocalStorage. Really hacked together right now needs cleaning up - /// - [System.Obsolete("Redundant, use IRegionDataStore instead")] - public interface ILocalStorage - { - void Initialise(string datastore); - - void StorePrim(PrimData prim); - void RemovePrim(LLUUID primID); - void LoadPrimitives(ILocalStorageReceiver receiver); - - [System.Obsolete("Use DataStorage instead")] - float[] LoadWorld(); - [System.Obsolete("Use DataStorage instead")] - 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(); - } -} - +/* +* 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 libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + /// + /// ILocalStorage. Really hacked together right now needs cleaning up + /// + [System.Obsolete("Redundant, use IRegionDataStore instead")] + public interface ILocalStorage + { + void Initialise(string datastore); + + void StorePrim(PrimData prim); + void RemovePrim(LLUUID primID); + void LoadPrimitives(ILocalStorageReceiver receiver); + + [System.Obsolete("Use DataStorage instead")] + float[] LoadWorld(); + [System.Obsolete("Use DataStorage instead")] + 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 index b3700d2..ca5816d 100644 --- a/OpenSim/Framework/General/Interfaces/IUserServer.cs +++ b/OpenSim/Framework/General/Interfaces/IUserServer.cs @@ -1,39 +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 libsecondlife; -using OpenSim.Framework.Inventory; - -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); - } -} +/* +* 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 libsecondlife; +using OpenSim.Framework.Inventory; + +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 index 204c01b..a474636 100644 --- a/OpenSim/Framework/General/Interfaces/IWorld.cs +++ b/OpenSim/Framework/General/Interfaces/IWorld.cs @@ -1,42 +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 libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Framework.Interfaces -{ - public interface IWorld - { - void AddNewClient(IClientAPI client, bool child); - void RemoveClient(LLUUID agentID); - - RegionInfo RegionInfo { get; } - object SyncRoot { get; } - uint NextLocalId { get; } - } -} +/* +* 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 libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Framework.Interfaces +{ + public interface IWorld + { + void AddNewClient(IClientAPI client, bool child); + void RemoveClient(LLUUID agentID); + + RegionInfo RegionInfo { get; } + object SyncRoot { get; } + uint NextLocalId { get; } + } +} diff --git a/OpenSim/Framework/General/NpcClientBase.cs b/OpenSim/Framework/General/NpcClientBase.cs index 44d6d3c..044431b 100644 --- a/OpenSim/Framework/General/NpcClientBase.cs +++ b/OpenSim/Framework/General/NpcClientBase.cs @@ -1,127 +1,127 @@ -using System.Collections.Generic; -using System.Net; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Data; -using libsecondlife; -using libsecondlife.Packets; - - -namespace OpenSim.Framework -{ - public class NpcClientBase :IClientAPI - { - public event ImprovedInstantMessage OnInstantMessage; - public event ChatFromViewer OnChatFromViewer; - public event RezObject OnRezObject; - public event ModifyTerrain OnModifyTerrain; - public event SetAppearance OnSetAppearance; - public event StartAnim OnStartAnim; - public event LinkObjects OnLinkObjects; - public event RequestMapBlocks OnRequestMapBlocks; - public event TeleportLocationRequest OnTeleportLocationRequest; - - public event GenericCall4 OnDeRezObject; - public event GenericCall OnRegionHandShakeReply; - public event GenericCall OnRequestWearables; - public event GenericCall2 OnCompleteMovementToRegion; - public event UpdateAgent OnAgentUpdate; - public event GenericCall OnRequestAvatarsData; - public event AddNewPrim OnAddPrim; - public event ObjectDuplicate OnObjectDuplicate; - public event UpdateVector OnGrapObject; - public event ObjectSelect OnDeGrapObject; - public event MoveObject OnGrapUpdate; - - public event UpdateShape OnUpdatePrimShape; - public event ObjectSelect OnObjectSelect; - public event GenericCall7 OnObjectDescription; - public event GenericCall7 OnObjectName; - public event UpdatePrimFlags OnUpdatePrimFlags; - public event UpdatePrimTexture OnUpdatePrimTexture; - public event UpdateVector OnUpdatePrimGroupPosition; - public event UpdateVector OnUpdatePrimSinglePosition; - public event UpdatePrimRotation OnUpdatePrimGroupRotation; - public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; - public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; - public event UpdateVector OnUpdatePrimScale; - public event StatusChange OnChildAgentStatus; - public event GenericCall2 OnStopMovement; - public event NewAvatar OnNewAvatar; - public event GenericCall6 OnRemoveAvatar; - - public event UUIDNameRequest OnNameFromUUIDRequest; - - public event ParcelPropertiesRequest OnParcelPropertiesRequest; - public event ParcelDivideRequest OnParcelDivideRequest; - public event ParcelJoinRequest OnParcelJoinRequest; - public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; - public event ParcelSelectObjects OnParcelSelectObjects; - public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; - public event ObjectDeselect OnObjectDeselect; - - - public event EstateOwnerMessageRequest OnEstateOwnerMessage; - - public virtual LLVector3 StartPos - { - get { return new LLVector3(); } - set { } - } - - public virtual LLUUID AgentId - { - get { return LLUUID.Random(); } - } - - public virtual string FirstName - { - get { return ""; } - } - - public virtual string LastName - { - get { return ""; } - } - - public NpcClientBase() - { - } - - public virtual void OutPacket(Packet newPack){} - public virtual void SendWearables(AvatarWearable[] wearables){} - public virtual void SendStartPingCheck(byte seq){} - public virtual void SendKillObject(ulong regionHandle, uint avatarLocalID){} - public virtual void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId){} - public virtual void SendRegionHandshake(RegionInfo regionInfo){} - public virtual void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID){} - public virtual void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID){} - public virtual void SendInstantMessage(string message, LLUUID target, string fromName){} - public virtual void SendLayerData(float[] map){} - public virtual void SendLayerData(int px, int py, float[] map){} - public virtual void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look){} - public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint){} - public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } - public virtual void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint){} - public virtual void SendMapBlock(List mapBlocks){} - public virtual void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags){} - public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags){} - public virtual void SendTeleportCancel(){} - public virtual void SendTeleportLocationStart(){} - public virtual void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance){} - - public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry){} - public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity){} - - public virtual void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint){} - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID, uint flags){} - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID, uint flags){} - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID){} - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID){} - public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation){} - - public virtual void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items){} - public virtual void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item){} - public virtual void SendNameReply(LLUUID profileId, string firstname, string lastname){} - } -} +using System.Collections.Generic; +using System.Net; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Data; +using libsecondlife; +using libsecondlife.Packets; + + +namespace OpenSim.Framework +{ + public class NpcClientBase :IClientAPI + { + public event ImprovedInstantMessage OnInstantMessage; + public event ChatFromViewer OnChatFromViewer; + public event RezObject OnRezObject; + public event ModifyTerrain OnModifyTerrain; + public event SetAppearance OnSetAppearance; + public event StartAnim OnStartAnim; + public event LinkObjects OnLinkObjects; + public event RequestMapBlocks OnRequestMapBlocks; + public event TeleportLocationRequest OnTeleportLocationRequest; + + public event GenericCall4 OnDeRezObject; + public event GenericCall OnRegionHandShakeReply; + public event GenericCall OnRequestWearables; + public event GenericCall2 OnCompleteMovementToRegion; + public event UpdateAgent OnAgentUpdate; + public event GenericCall OnRequestAvatarsData; + public event AddNewPrim OnAddPrim; + public event ObjectDuplicate OnObjectDuplicate; + public event UpdateVector OnGrapObject; + public event ObjectSelect OnDeGrapObject; + public event MoveObject OnGrapUpdate; + + public event UpdateShape OnUpdatePrimShape; + public event ObjectSelect OnObjectSelect; + public event GenericCall7 OnObjectDescription; + public event GenericCall7 OnObjectName; + public event UpdatePrimFlags OnUpdatePrimFlags; + public event UpdatePrimTexture OnUpdatePrimTexture; + public event UpdateVector OnUpdatePrimGroupPosition; + public event UpdateVector OnUpdatePrimSinglePosition; + public event UpdatePrimRotation OnUpdatePrimGroupRotation; + public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; + public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; + public event UpdateVector OnUpdatePrimScale; + public event StatusChange OnChildAgentStatus; + public event GenericCall2 OnStopMovement; + public event NewAvatar OnNewAvatar; + public event GenericCall6 OnRemoveAvatar; + + public event UUIDNameRequest OnNameFromUUIDRequest; + + public event ParcelPropertiesRequest OnParcelPropertiesRequest; + public event ParcelDivideRequest OnParcelDivideRequest; + public event ParcelJoinRequest OnParcelJoinRequest; + public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + public event ParcelSelectObjects OnParcelSelectObjects; + public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; + public event ObjectDeselect OnObjectDeselect; + + + public event EstateOwnerMessageRequest OnEstateOwnerMessage; + + public virtual LLVector3 StartPos + { + get { return new LLVector3(); } + set { } + } + + public virtual LLUUID AgentId + { + get { return LLUUID.Random(); } + } + + public virtual string FirstName + { + get { return ""; } + } + + public virtual string LastName + { + get { return ""; } + } + + public NpcClientBase() + { + } + + public virtual void OutPacket(Packet newPack){} + public virtual void SendWearables(AvatarWearable[] wearables){} + public virtual void SendStartPingCheck(byte seq){} + public virtual void SendKillObject(ulong regionHandle, uint avatarLocalID){} + public virtual void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId){} + public virtual void SendRegionHandshake(RegionInfo regionInfo){} + public virtual void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID){} + public virtual void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID){} + public virtual void SendInstantMessage(string message, LLUUID target, string fromName){} + public virtual void SendLayerData(float[] map){} + public virtual void SendLayerData(int px, int py, float[] map){} + public virtual void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look){} + public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint){} + public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } + public virtual void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint){} + public virtual void SendMapBlock(List mapBlocks){} + public virtual void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags){} + public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags){} + public virtual void SendTeleportCancel(){} + public virtual void SendTeleportLocationStart(){} + public virtual void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance){} + + public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry){} + public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity){} + + public virtual void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint){} + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID, uint flags){} + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID, uint flags){} + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID){} + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID){} + public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation){} + + public virtual void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items){} + public virtual void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item){} + public virtual void SendNameReply(LLUUID profileId, string firstname, string lastname){} + } +} diff --git a/OpenSim/Framework/General/Properties/AssemblyInfo.cs b/OpenSim/Framework/General/Properties/AssemblyInfo.cs index 004040b..655cffc 100644 --- a/OpenSim/Framework/General/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/General/Properties/AssemblyInfo.cs @@ -1,31 +1,31 @@ -using System.Reflection; -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")] +using System.Reflection; +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 index 4d6b59c..f5b8272 100644 --- a/OpenSim/Framework/General/RegionCommsListener.cs +++ b/OpenSim/Framework/General/RegionCommsListener.cs @@ -1,103 +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 libsecondlife; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -using System.Collections.Generic; - -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, LLUUID agentID, LLVector3 position) - { - if (OnAvatarCrossingIntoRegion != null) - { - OnAvatarCrossingIntoRegion(regionHandle, agentID, position); - return true; - } - return false; - } - - /// - /// - /// - /// TODO: Doesnt take any args?? - /// - public virtual bool TriggerExpectChildAgent() - { - if (OnExpectChildAgent != null) - { - OnExpectChildAgent(); - return true; - } - - return false; - } - - /// - /// - /// - /// Added to avoid a unused compiler warning on OnNeighboursUpdate, TODO: Check me - /// - /// - public virtual bool TriggerOnNeighboursUpdate(List neighbours) - { - if (OnNeighboursUpdate != null) - { - OnNeighboursUpdate(neighbours); - return true; - } - - return false; - } - } -} +/* +* 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 libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +using System.Collections.Generic; + +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, LLUUID agentID, LLVector3 position) + { + if (OnAvatarCrossingIntoRegion != null) + { + OnAvatarCrossingIntoRegion(regionHandle, agentID, position); + return true; + } + return false; + } + + /// + /// + /// + /// TODO: Doesnt take any args?? + /// + public virtual bool TriggerExpectChildAgent() + { + if (OnExpectChildAgent != null) + { + OnExpectChildAgent(); + return true; + } + + return false; + } + + /// + /// + /// + /// Added to avoid a unused compiler warning on OnNeighboursUpdate, TODO: Check me + /// + /// + public virtual bool TriggerOnNeighboursUpdate(List neighbours) + { + if (OnNeighboursUpdate != null) + { + OnNeighboursUpdate(neighbours); + return true; + } + + return false; + } + } +} diff --git a/OpenSim/Framework/General/Remoting.cs b/OpenSim/Framework/General/Remoting.cs index df32db2..0e94b90 100644 --- a/OpenSim/Framework/General/Remoting.cs +++ b/OpenSim/Framework/General/Remoting.cs @@ -1,135 +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.Security.Cryptography; -using System.Text; - -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; - } - - } -} +/* +* 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.Text; + +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/Types/AgentCiruitData.cs b/OpenSim/Framework/General/Types/AgentCiruitData.cs index ed9ee3c..36bb26d 100644 --- a/OpenSim/Framework/General/Types/AgentCiruitData.cs +++ b/OpenSim/Framework/General/Types/AgentCiruitData.cs @@ -1,49 +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 libsecondlife; -using System; - -namespace OpenSim.Framework.Types -{ - [Serializable] - 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 = ""; - } -} +/* +* 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 libsecondlife; +using System; + +namespace OpenSim.Framework.Types +{ + [Serializable] + 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 index 6152b7d..404df0d 100644 --- a/OpenSim/Framework/General/Types/AgentWearable.cs +++ b/OpenSim/Framework/General/Types/AgentWearable.cs @@ -1,57 +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 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; - } - } - } -} +/* +* 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 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 index c203f51..181e1e3 100644 --- a/OpenSim/Framework/General/Types/AssetBase.cs +++ b/OpenSim/Framework/General/Types/AssetBase.cs @@ -1,46 +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 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() - { - - } - } -} +/* +* 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 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 index 8aa872e..7cec6f6 100644 --- a/OpenSim/Framework/General/Types/AssetLandmark.cs +++ b/OpenSim/Framework/General/Types/AssetLandmark.cs @@ -1,59 +1,59 @@ -/* -* 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.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 = 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); - } - } -} +/* +* 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.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 = 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 index 3681336..d49e9e8 100644 --- a/OpenSim/Framework/General/Types/AssetStorage.cs +++ b/OpenSim/Framework/General/Types/AssetStorage.cs @@ -1,47 +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 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; - } -} +/* +* 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 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 index 436b109..25b3b18 100644 --- a/OpenSim/Framework/General/Types/EstateSettings.cs +++ b/OpenSim/Framework/General/Types/EstateSettings.cs @@ -1,93 +1,93 @@ -/* -* 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 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 Simulator.RegionFlags regionFlags = Simulator.RegionFlags.None; //Booleam values of various region settings - public Simulator.SimAccess simAccess = 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 - - } -} +/* +* 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 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 Simulator.RegionFlags regionFlags = Simulator.RegionFlags.None; //Booleam values of various region settings + public Simulator.SimAccess simAccess = 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 index d54c019..3aaf613 100644 --- a/OpenSim/Framework/General/Types/Login.cs +++ b/OpenSim/Framework/General/Types/Login.cs @@ -1,49 +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 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() - { - - } - } -} +/* +* 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 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 index fbb3b73..212ce4b 100644 --- a/OpenSim/Framework/General/Types/MapBlockData.cs +++ b/OpenSim/Framework/General/Types/MapBlockData.cs @@ -1,23 +1,23 @@ -using System; -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() - { - - } - } -} +using System; +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 index bb67981..7e83ffc 100644 --- a/OpenSim/Framework/General/Types/NeighbourInfo.cs +++ b/OpenSim/Framework/General/Types/NeighbourInfo.cs @@ -1,42 +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. -* -*/ -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; - } -} +/* +* 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. +* +*/ +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 index 900354c..6259d7b 100644 --- a/OpenSim/Framework/General/Types/NetworkServersInfo.cs +++ b/OpenSim/Framework/General/Types/NetworkServersInfo.cs @@ -1,219 +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 OpenSim.Framework.Console; -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 = 1000; - public uint DefaultHomeLocY = 1000; - - 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 = 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 = 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 = 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 = 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 = 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 = 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 = MainLog.Instance.CmdPrompt("Key to expect from grid server", "null"); - configData.SetAttribute("GridRecvKey", this.GridRecvKey); - } - else - { - this.GridRecvKey = attri; - } - - //Grid Server - attri = ""; - attri = configData.GetAttribute("UserServerURL"); - if (attri == "") - { - this.UserURL= MainLog.Instance.CmdPrompt("User server URL", "http://127.0.0.1:8002/"); - configData.SetAttribute("UserServerURL", this.UserURL); - } - else - { - this.UserURL = attri; - } - - //Grid Send Key - attri = ""; - attri = configData.GetAttribute("UserSendKey"); - if (attri == "") - { - this.UserSendKey = MainLog.Instance.CmdPrompt("Key to send to user server", "null"); - configData.SetAttribute("UserSendKey", this.UserSendKey); - } - else - { - this.UserSendKey = attri; - } - - //Grid Receive Key - attri = ""; - attri = configData.GetAttribute("UserRecvKey"); - if (attri == "") - { - this.UserRecvKey = MainLog.Instance.CmdPrompt("Key to expect from user server", "null"); - configData.SetAttribute("UserRecvKey", this.UserRecvKey); - } - else - { - this.UserRecvKey = attri; - } - - attri = ""; - attri = configData.GetAttribute("AssetServerURL"); - if (attri == "") - { - this.AssetURL = 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) - { - MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); - MainLog.Instance.Warn(e.ToString()); - } - } - } -} +/* +* 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 OpenSim.Framework.Console; +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 = 1000; + public uint DefaultHomeLocY = 1000; + + 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 = 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 = 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 = 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 = 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 = 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 = 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 = MainLog.Instance.CmdPrompt("Key to expect from grid server", "null"); + configData.SetAttribute("GridRecvKey", this.GridRecvKey); + } + else + { + this.GridRecvKey = attri; + } + + //Grid Server + attri = ""; + attri = configData.GetAttribute("UserServerURL"); + if (attri == "") + { + this.UserURL= MainLog.Instance.CmdPrompt("User server URL", "http://127.0.0.1:8002/"); + configData.SetAttribute("UserServerURL", this.UserURL); + } + else + { + this.UserURL = attri; + } + + //Grid Send Key + attri = ""; + attri = configData.GetAttribute("UserSendKey"); + if (attri == "") + { + this.UserSendKey = MainLog.Instance.CmdPrompt("Key to send to user server", "null"); + configData.SetAttribute("UserSendKey", this.UserSendKey); + } + else + { + this.UserSendKey = attri; + } + + //Grid Receive Key + attri = ""; + attri = configData.GetAttribute("UserRecvKey"); + if (attri == "") + { + this.UserRecvKey = MainLog.Instance.CmdPrompt("Key to expect from user server", "null"); + configData.SetAttribute("UserRecvKey", this.UserRecvKey); + } + else + { + this.UserRecvKey = attri; + } + + attri = ""; + attri = configData.GetAttribute("AssetServerURL"); + if (attri == "") + { + this.AssetURL = 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) + { + MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + MainLog.Instance.Warn(e.ToString()); + } + } + } +} diff --git a/OpenSim/Framework/General/Types/ParcelData.cs b/OpenSim/Framework/General/Types/ParcelData.cs index 17de655..5626299 100644 --- a/OpenSim/Framework/General/Types/ParcelData.cs +++ b/OpenSim/Framework/General/Types/ParcelData.cs @@ -1,120 +1,120 @@ -/* -* 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 libsecondlife; - -namespace OpenSim.Framework.Types -{ - - public class ParcelData - { - public byte[] parcelBitmapByteArray = new byte[512]; - public string parcelName = "Your Parcel"; - 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 Parcel.ParcelCategory category = new 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; - public int otherPrims = 0; - public int ownerPrims = 0; - public int selectedPrims = 0; - public int simwidePrims = 0; - public int simwideArea = 0; - public int salePrice = 0; //Unemeplemented. Parcels price. - public Parcel.ParcelStatus parcelStatus = Parcel.ParcelStatus.Leased; - public uint parcelFlags = (uint)Parcel.ParcelFlags.AllowFly | (uint)Parcel.ParcelFlags.AllowLandmark | (uint)Parcel.ParcelFlags.AllowAllObjectEntry | (uint)Parcel.ParcelFlags.AllowDeedToGroup | (uint)Parcel.ParcelFlags.AllowTerraform | (uint)Parcel.ParcelFlags.CreateObjects | (uint)Parcel.ParcelFlags.AllowOtherScripts; - 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.otherPrims = this.otherPrims; - parcelData.ownerPrims = this.ownerPrims; - parcelData.selectedPrims = this.selectedPrims; - 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; - - } - } - -} +/* +* 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 libsecondlife; + +namespace OpenSim.Framework.Types +{ + + public class ParcelData + { + public byte[] parcelBitmapByteArray = new byte[512]; + public string parcelName = "Your Parcel"; + 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 Parcel.ParcelCategory category = new 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; + public int otherPrims = 0; + public int ownerPrims = 0; + public int selectedPrims = 0; + public int simwidePrims = 0; + public int simwideArea = 0; + public int salePrice = 0; //Unemeplemented. Parcels price. + public Parcel.ParcelStatus parcelStatus = Parcel.ParcelStatus.Leased; + public uint parcelFlags = (uint)Parcel.ParcelFlags.AllowFly | (uint)Parcel.ParcelFlags.AllowLandmark | (uint)Parcel.ParcelFlags.AllowAllObjectEntry | (uint)Parcel.ParcelFlags.AllowDeedToGroup | (uint)Parcel.ParcelFlags.AllowTerraform | (uint)Parcel.ParcelFlags.CreateObjects | (uint)Parcel.ParcelFlags.AllowOtherScripts; + 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.otherPrims = this.otherPrims; + parcelData.ownerPrims = this.ownerPrims; + parcelData.selectedPrims = this.selectedPrims; + 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 index ff81bcd..6b8fa3a 100644 --- a/OpenSim/Framework/General/Types/PrimData.cs +++ b/OpenSim/Framework/General/Types/PrimData.cs @@ -1,228 +1,228 @@ -/* -* 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; - -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; - } - } -} +/* +* 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; + +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/PrimitiveBaseShape.cs b/OpenSim/Framework/General/Types/PrimitiveBaseShape.cs index a085a44..e058c07 100644 --- a/OpenSim/Framework/General/Types/PrimitiveBaseShape.cs +++ b/OpenSim/Framework/General/Types/PrimitiveBaseShape.cs @@ -1,109 +1,109 @@ -using libsecondlife; -using libsecondlife.Packets; - -namespace OpenSim.Framework.Types -{ - public enum ShapeType - { - Box, - Sphere, - Ring, - Tube, - Torus, - Prism, - Scuplted, - Cylinder, - Foliage, - Unknown - } - - public class PrimitiveBaseShape - { - private ShapeType type = ShapeType.Unknown; - - 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 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 ShapeType PrimType - { - get - { - return this.type; - } - } - - public LLVector3 PrimScale - { - get - { - return this.Scale; - } - } - - public PrimitiveBaseShape() - { - - } - - //void returns need to change of course - public void GetMesh() - { - - } - - public PrimitiveBaseShape Copy() - { - return (PrimitiveBaseShape) this.MemberwiseClone(); - } - - public static PrimitiveBaseShape DefaultBox() - { - PrimitiveBaseShape primShape = new PrimitiveBaseShape(); - - primShape.type = ShapeType.Box; - primShape.Scale = new LLVector3(0.5f, 0.5f, 0.5f); - primShape.PCode = 9; - primShape.PathBegin = 0; - primShape.PathEnd = 0; - primShape.PathScaleX = 0; - primShape.PathScaleY = 0; - primShape.PathShearX = 0; - primShape.PathShearY = 0; - primShape.PathSkew = 0; - primShape.ProfileBegin = 0; - primShape.ProfileEnd = 0; - primShape.PathCurve = 16; - primShape.ProfileCurve = 1; - primShape.ProfileHollow = 0; - primShape.PathRadiusOffset = 0; - primShape.PathRevolutions = 0; - primShape.PathTaperX = 0; - primShape.PathTaperY = 0; - primShape.PathTwist = 0; - primShape.PathTwistBegin = 0; - LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-9999-000000000005")); - primShape.TextureEntry = ntex.ToBytes(); - - return primShape; - } - } -} +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim.Framework.Types +{ + public enum ShapeType + { + Box, + Sphere, + Ring, + Tube, + Torus, + Prism, + Scuplted, + Cylinder, + Foliage, + Unknown + } + + public class PrimitiveBaseShape + { + private ShapeType type = ShapeType.Unknown; + + 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 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 ShapeType PrimType + { + get + { + return this.type; + } + } + + public LLVector3 PrimScale + { + get + { + return this.Scale; + } + } + + public PrimitiveBaseShape() + { + + } + + //void returns need to change of course + public void GetMesh() + { + + } + + public PrimitiveBaseShape Copy() + { + return (PrimitiveBaseShape) this.MemberwiseClone(); + } + + public static PrimitiveBaseShape DefaultBox() + { + PrimitiveBaseShape primShape = new PrimitiveBaseShape(); + + primShape.type = ShapeType.Box; + primShape.Scale = new LLVector3(0.5f, 0.5f, 0.5f); + primShape.PCode = 9; + primShape.PathBegin = 0; + primShape.PathEnd = 0; + primShape.PathScaleX = 0; + primShape.PathScaleY = 0; + primShape.PathShearX = 0; + primShape.PathShearY = 0; + primShape.PathSkew = 0; + primShape.ProfileBegin = 0; + primShape.ProfileEnd = 0; + primShape.PathCurve = 16; + primShape.ProfileCurve = 1; + primShape.ProfileHollow = 0; + primShape.PathRadiusOffset = 0; + primShape.PathRevolutions = 0; + primShape.PathTaperX = 0; + primShape.PathTaperY = 0; + primShape.PathTwist = 0; + primShape.PathTwistBegin = 0; + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-9999-000000000005")); + primShape.TextureEntry = ntex.ToBytes(); + + return primShape; + } + } +} diff --git a/OpenSim/Framework/General/Types/RegionHandle.cs b/OpenSim/Framework/General/Types/RegionHandle.cs index 4a055ad..d90acc6 100644 --- a/OpenSim/Framework/General/Types/RegionHandle.cs +++ b/OpenSim/Framework/General/Types/RegionHandle.cs @@ -1,121 +1,121 @@ -using System; -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); - - if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) - throw new Exception("Bad RegionHandle Parameter - must be an IPv4 address"); - - uint baseHandle = BitConverter.ToUInt32(addr.GetAddressBytes(), 0); - - // 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; - } - } -} +using System; +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); + + if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) + throw new Exception("Bad RegionHandle Parameter - must be an IPv4 address"); + + uint baseHandle = BitConverter.ToUInt32(addr.GetAddressBytes(), 0); + + // 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 index cfc0925..a216b52 100644 --- a/OpenSim/Framework/General/Types/RegionInfo.cs +++ b/OpenSim/Framework/General/Types/RegionInfo.cs @@ -1,342 +1,342 @@ -/* -* 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.Globalization; -using System.Net; -using System.Net.Sockets; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Framework.Types -{ - public class RegionInfo - { - public LLUUID SimUUID = new LLUUID(); - public string RegionName = ""; - - private IPEndPoint m_internalEndPoint; - public IPEndPoint InternalEndPoint - { - get - { - return m_internalEndPoint; - } - } - - public IPEndPoint ExternalEndPoint - { - get - { - // Old one defaults to IPv6 - //return new IPEndPoint( Dns.GetHostAddresses( m_externalHostName )[0], m_internalEndPoint.Port ); - - // New method favors IPv4 - IPAddress ia = null; - foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName)) - { - if (ia == null) - ia = Adr; - - if (Adr.AddressFamily == AddressFamily.InterNetwork) - { - ia = Adr; - break; - } - - } - - return new IPEndPoint(ia, m_internalEndPoint.Port); - } - } - - private string m_externalHostName; - public string ExternalHostName - { - get - { - return m_externalHostName; - } - } - - private uint? m_regionLocX; - public uint RegionLocX - { - get - { - return m_regionLocX.Value; - } - } - - private uint? m_regionLocY; - public uint RegionLocY - { - get - { - return m_regionLocY.Value; - } - } - - private ulong? m_regionHandle; - public ulong RegionHandle - { - get - { - if (!m_regionHandle.HasValue) - { - m_regionHandle = Util.UIntsToLong((RegionLocX * 256), (RegionLocY * 256)); - } - - return m_regionHandle.Value; - } - } - - // Only used for remote regions , ie ones not in the current instance - private uint m_remotingPort; - public uint RemotingPort - { - get - { - return m_remotingPort; - } - set - { - m_remotingPort = value; - } - } - public string RemotingAddress; - - public string DataStore = ""; - public bool isSandbox = false; - - public LLUUID MasterAvatarAssignedUUID = new LLUUID(); - public string MasterAvatarFirstName = ""; - public string MasterAvatarLastName = ""; - public string MasterAvatarSandboxPassword = ""; - - public EstateSettings estateSettings; - - public RegionInfo() - { - estateSettings = new EstateSettings(); - } - - public RegionInfo(uint regionLocX, uint regionLocY, IPEndPoint internalEndPoint, string externalUri) - : this() - { - m_regionLocX = regionLocX; - m_regionLocY = regionLocY; - - m_internalEndPoint = internalEndPoint; - m_externalHostName = externalUri; - } - - public void InitConfig(bool sandboxMode, IGenericConfig configData) - { - this.isSandbox = sandboxMode; - try - { - string attri = ""; - - // Sim UUID - string simId = configData.GetAttribute("SimUUID"); - if (String.IsNullOrEmpty( simId )) - { - this.SimUUID = LLUUID.Random(); - } - else - { - this.SimUUID = new LLUUID(simId); - } - configData.SetAttribute("SimUUID", this.SimUUID.ToString()); - - this.RegionName = GetString(configData, "SimName", "OpenSim test", "Region Name"); - - //m_regionLocX = (uint) GetInt(configData, "SimLocationX", 1000, "Grid Location X"); - - attri = ""; - attri = configData.GetAttribute("SimLocationX"); - if (attri == "") - { - string location = MainLog.Instance.CmdPrompt("Grid Location X", "1000"); - configData.SetAttribute("SimLocationX", location); - m_regionLocX = (uint)Convert.ToUInt32(location); - } - else - { - m_regionLocX = (uint)Convert.ToUInt32(attri); - } - // Sim/Grid location Y - attri = ""; - attri = configData.GetAttribute("SimLocationY"); - if (attri == "") - { - string location = MainLog.Instance.CmdPrompt("Grid Location Y", "1000"); - configData.SetAttribute("SimLocationY", location); - m_regionLocY = (uint)Convert.ToUInt32(location); - } - else - { - m_regionLocY = (uint)Convert.ToUInt32(attri); - } - - m_regionHandle = null; - - this.DataStore = GetString(configData, "Datastore", "localworld.yap", "Filename for local storage"); - - IPAddress internalAddress = GetIPAddress(configData, "InternalIPAddress", "0.0.0.0", "Internal IP Address for UDP client connections"); - int internalPort = GetIPPort(configData, "InternalIPPort", "9000", "Internal IP Port for UDP client connections"); - m_internalEndPoint = new IPEndPoint(internalAddress, internalPort); - - m_externalHostName = GetString(configData, "ExternalHostName", "127.0.0.1", "External Host Name"); - - estateSettings.terrainFile = - GetString(configData, "TerrainFile", "default.r32", "GENERAL SETTING: Default Terrain File"); - - attri = ""; - attri = configData.GetAttribute("TerrainMultiplier"); - if (attri == "") - { - string re = 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 = 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 = 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 = 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; - } - } - - configData.Commit(); - } - catch (Exception e) - { - MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); - MainLog.Instance.Warn(e.ToString()); - } - - MainLog.Instance.Verbose("Sim settings loaded:"); - MainLog.Instance.Verbose("UUID: " + this.SimUUID.ToStringHyphenated()); - MainLog.Instance.Verbose("Name: " + this.RegionName); - MainLog.Instance.Verbose("Region Location: [" + this.RegionLocX.ToString() + "," + this.RegionLocY + "]"); - MainLog.Instance.Verbose("Region Handle: " + this.RegionHandle.ToString()); - MainLog.Instance.Verbose("Listening on IP end point: " + m_internalEndPoint.ToString() ); - MainLog.Instance.Verbose("Sandbox Mode? " + isSandbox.ToString()); - - } - - private uint GetInt(IGenericConfig configData, string p, int p_3, string p_4) - { - throw new Exception("The method or operation is not implemented."); - } - - private string GetString(IGenericConfig configData, string attrName, string defaultvalue, string prompt) - { - string s = configData.GetAttribute(attrName); - - if (String.IsNullOrEmpty( s )) - { - s = MainLog.Instance.CmdPrompt(prompt, defaultvalue); - configData.SetAttribute(attrName, s ); - } - return s; - } - - private IPAddress GetIPAddress(IGenericConfig configData, string attrName, string defaultvalue, string prompt) - { - string addressStr = configData.GetAttribute(attrName); - - IPAddress address; - - if (!IPAddress.TryParse(addressStr, out address)) - { - address = MainLog.Instance.CmdPromptIPAddress(prompt, defaultvalue); - configData.SetAttribute(attrName, address.ToString()); - } - return address; - } - - private int GetIPPort(IGenericConfig configData, string attrName, string defaultvalue, string prompt) - { - string portStr = configData.GetAttribute(attrName); - - int port; - - if (!int.TryParse(portStr, out port)) - { - port = MainLog.Instance.CmdPromptIPPort(prompt, defaultvalue); - configData.SetAttribute(attrName, port.ToString()); - } - - return port; - } - } -} +/* +* 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.Globalization; +using System.Net; +using System.Net.Sockets; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Framework.Types +{ + public class RegionInfo + { + public LLUUID SimUUID = new LLUUID(); + public string RegionName = ""; + + private IPEndPoint m_internalEndPoint; + public IPEndPoint InternalEndPoint + { + get + { + return m_internalEndPoint; + } + } + + public IPEndPoint ExternalEndPoint + { + get + { + // Old one defaults to IPv6 + //return new IPEndPoint( Dns.GetHostAddresses( m_externalHostName )[0], m_internalEndPoint.Port ); + + // New method favors IPv4 + IPAddress ia = null; + foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName)) + { + if (ia == null) + ia = Adr; + + if (Adr.AddressFamily == AddressFamily.InterNetwork) + { + ia = Adr; + break; + } + + } + + return new IPEndPoint(ia, m_internalEndPoint.Port); + } + } + + private string m_externalHostName; + public string ExternalHostName + { + get + { + return m_externalHostName; + } + } + + private uint? m_regionLocX; + public uint RegionLocX + { + get + { + return m_regionLocX.Value; + } + } + + private uint? m_regionLocY; + public uint RegionLocY + { + get + { + return m_regionLocY.Value; + } + } + + private ulong? m_regionHandle; + public ulong RegionHandle + { + get + { + if (!m_regionHandle.HasValue) + { + m_regionHandle = Util.UIntsToLong((RegionLocX * 256), (RegionLocY * 256)); + } + + return m_regionHandle.Value; + } + } + + // Only used for remote regions , ie ones not in the current instance + private uint m_remotingPort; + public uint RemotingPort + { + get + { + return m_remotingPort; + } + set + { + m_remotingPort = value; + } + } + public string RemotingAddress; + + public string DataStore = ""; + public bool isSandbox = false; + + public LLUUID MasterAvatarAssignedUUID = new LLUUID(); + public string MasterAvatarFirstName = ""; + public string MasterAvatarLastName = ""; + public string MasterAvatarSandboxPassword = ""; + + public EstateSettings estateSettings; + + public RegionInfo() + { + estateSettings = new EstateSettings(); + } + + public RegionInfo(uint regionLocX, uint regionLocY, IPEndPoint internalEndPoint, string externalUri) + : this() + { + m_regionLocX = regionLocX; + m_regionLocY = regionLocY; + + m_internalEndPoint = internalEndPoint; + m_externalHostName = externalUri; + } + + public void InitConfig(bool sandboxMode, IGenericConfig configData) + { + this.isSandbox = sandboxMode; + try + { + string attri = ""; + + // Sim UUID + string simId = configData.GetAttribute("SimUUID"); + if (String.IsNullOrEmpty( simId )) + { + this.SimUUID = LLUUID.Random(); + } + else + { + this.SimUUID = new LLUUID(simId); + } + configData.SetAttribute("SimUUID", this.SimUUID.ToString()); + + this.RegionName = GetString(configData, "SimName", "OpenSim test", "Region Name"); + + //m_regionLocX = (uint) GetInt(configData, "SimLocationX", 1000, "Grid Location X"); + + attri = ""; + attri = configData.GetAttribute("SimLocationX"); + if (attri == "") + { + string location = MainLog.Instance.CmdPrompt("Grid Location X", "1000"); + configData.SetAttribute("SimLocationX", location); + m_regionLocX = (uint)Convert.ToUInt32(location); + } + else + { + m_regionLocX = (uint)Convert.ToUInt32(attri); + } + // Sim/Grid location Y + attri = ""; + attri = configData.GetAttribute("SimLocationY"); + if (attri == "") + { + string location = MainLog.Instance.CmdPrompt("Grid Location Y", "1000"); + configData.SetAttribute("SimLocationY", location); + m_regionLocY = (uint)Convert.ToUInt32(location); + } + else + { + m_regionLocY = (uint)Convert.ToUInt32(attri); + } + + m_regionHandle = null; + + this.DataStore = GetString(configData, "Datastore", "localworld.yap", "Filename for local storage"); + + IPAddress internalAddress = GetIPAddress(configData, "InternalIPAddress", "0.0.0.0", "Internal IP Address for UDP client connections"); + int internalPort = GetIPPort(configData, "InternalIPPort", "9000", "Internal IP Port for UDP client connections"); + m_internalEndPoint = new IPEndPoint(internalAddress, internalPort); + + m_externalHostName = GetString(configData, "ExternalHostName", "127.0.0.1", "External Host Name"); + + estateSettings.terrainFile = + GetString(configData, "TerrainFile", "default.r32", "GENERAL SETTING: Default Terrain File"); + + attri = ""; + attri = configData.GetAttribute("TerrainMultiplier"); + if (attri == "") + { + string re = 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 = 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 = 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 = 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; + } + } + + configData.Commit(); + } + catch (Exception e) + { + MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + MainLog.Instance.Warn(e.ToString()); + } + + MainLog.Instance.Verbose("Sim settings loaded:"); + MainLog.Instance.Verbose("UUID: " + this.SimUUID.ToStringHyphenated()); + MainLog.Instance.Verbose("Name: " + this.RegionName); + MainLog.Instance.Verbose("Region Location: [" + this.RegionLocX.ToString() + "," + this.RegionLocY + "]"); + MainLog.Instance.Verbose("Region Handle: " + this.RegionHandle.ToString()); + MainLog.Instance.Verbose("Listening on IP end point: " + m_internalEndPoint.ToString() ); + MainLog.Instance.Verbose("Sandbox Mode? " + isSandbox.ToString()); + + } + + private uint GetInt(IGenericConfig configData, string p, int p_3, string p_4) + { + throw new Exception("The method or operation is not implemented."); + } + + private string GetString(IGenericConfig configData, string attrName, string defaultvalue, string prompt) + { + string s = configData.GetAttribute(attrName); + + if (String.IsNullOrEmpty( s )) + { + s = MainLog.Instance.CmdPrompt(prompt, defaultvalue); + configData.SetAttribute(attrName, s ); + } + return s; + } + + private IPAddress GetIPAddress(IGenericConfig configData, string attrName, string defaultvalue, string prompt) + { + string addressStr = configData.GetAttribute(attrName); + + IPAddress address; + + if (!IPAddress.TryParse(addressStr, out address)) + { + address = MainLog.Instance.CmdPromptIPAddress(prompt, defaultvalue); + configData.SetAttribute(attrName, address.ToString()); + } + return address; + } + + private int GetIPPort(IGenericConfig configData, string attrName, string defaultvalue, string prompt) + { + string portStr = configData.GetAttribute(attrName); + + int port; + + if (!int.TryParse(portStr, out port)) + { + port = MainLog.Instance.CmdPromptIPPort(prompt, defaultvalue); + configData.SetAttribute(attrName, port.ToString()); + } + + return port; + } + } +} diff --git a/OpenSim/Framework/General/Types/UUID.cs b/OpenSim/Framework/General/Types/UUID.cs index 9cde18e..9e9654d 100644 --- a/OpenSim/Framework/General/Types/UUID.cs +++ b/OpenSim/Framework/General/Types/UUID.cs @@ -1,127 +1,127 @@ -using System; -using libsecondlife; - -namespace OpenSim.Framework.Types -{ - class UUID - { - public LLUUID llUUID; - - public UUID(string uuid) - { - llUUID = new LLUUID(uuid); - } - - public UUID(byte[] uuid) - { - llUUID = new LLUUID(uuid, 0); - } - - public UUID(byte[] uuid, int offset) - { - llUUID = new LLUUID(uuid, offset); - } - - public UUID() - { - llUUID = LLUUID.Zero; - } - - public UUID(ulong uuid) - { - llUUID = new LLUUID(uuid); - } - - public UUID(UInt32 first, UInt32 second, UInt32 third, UInt32 fourth) - { - byte[] uuid = new byte[16]; - - byte[] n = BitConverter.GetBytes(first); - n.CopyTo(uuid, 0); - n = BitConverter.GetBytes(second); - n.CopyTo(uuid, 4); - n = BitConverter.GetBytes(third); - n.CopyTo(uuid, 8); - n = BitConverter.GetBytes(fourth); - n.CopyTo(uuid, 12); - - llUUID = new LLUUID(uuid,0); - } - - public override string ToString() - { - return llUUID.ToString(); - } - - public string ToStringHyphenated() - { - return llUUID.ToStringHyphenated(); - } - - public byte[] GetBytes() - { - return llUUID.GetBytes(); - } - - public UInt32[] GetInts() - { - UInt32[] ints = new UInt32[4]; - ints[0] = BitConverter.ToUInt32(llUUID.Data, 0); - ints[1] = BitConverter.ToUInt32(llUUID.Data, 4); - ints[2] = BitConverter.ToUInt32(llUUID.Data, 8); - ints[3] = BitConverter.ToUInt32(llUUID.Data, 12); - - return ints; - } - - public LLUUID GetLLUUID() - { - return llUUID; - } - - public uint CRC() - { - return llUUID.CRC(); - } - - public override int GetHashCode() - { - return llUUID.GetHashCode(); - } - - public void Combine(UUID other) - { - llUUID.Combine(other.GetLLUUID()); - } - - public void Combine(LLUUID other) - { - llUUID.Combine(other); - } - - public override bool Equals(Object other) - { - return llUUID.Equals(other); - } - - public static bool operator ==(UUID a, UUID b) - { - return a.llUUID.Equals(b.GetLLUUID()); - } - - public static bool operator !=(UUID a, UUID b) - { - return !a.llUUID.Equals(b.GetLLUUID()); - } - - public static bool operator ==(UUID a, LLUUID b) - { - return a.Equals(b); - } - - public static bool operator !=(UUID a, LLUUID b) - { - return !a.Equals(b); - } - } -} +using System; +using libsecondlife; + +namespace OpenSim.Framework.Types +{ + class UUID + { + public LLUUID llUUID; + + public UUID(string uuid) + { + llUUID = new LLUUID(uuid); + } + + public UUID(byte[] uuid) + { + llUUID = new LLUUID(uuid, 0); + } + + public UUID(byte[] uuid, int offset) + { + llUUID = new LLUUID(uuid, offset); + } + + public UUID() + { + llUUID = LLUUID.Zero; + } + + public UUID(ulong uuid) + { + llUUID = new LLUUID(uuid); + } + + public UUID(UInt32 first, UInt32 second, UInt32 third, UInt32 fourth) + { + byte[] uuid = new byte[16]; + + byte[] n = BitConverter.GetBytes(first); + n.CopyTo(uuid, 0); + n = BitConverter.GetBytes(second); + n.CopyTo(uuid, 4); + n = BitConverter.GetBytes(third); + n.CopyTo(uuid, 8); + n = BitConverter.GetBytes(fourth); + n.CopyTo(uuid, 12); + + llUUID = new LLUUID(uuid,0); + } + + public override string ToString() + { + return llUUID.ToString(); + } + + public string ToStringHyphenated() + { + return llUUID.ToStringHyphenated(); + } + + public byte[] GetBytes() + { + return llUUID.GetBytes(); + } + + public UInt32[] GetInts() + { + UInt32[] ints = new UInt32[4]; + ints[0] = BitConverter.ToUInt32(llUUID.Data, 0); + ints[1] = BitConverter.ToUInt32(llUUID.Data, 4); + ints[2] = BitConverter.ToUInt32(llUUID.Data, 8); + ints[3] = BitConverter.ToUInt32(llUUID.Data, 12); + + return ints; + } + + public LLUUID GetLLUUID() + { + return llUUID; + } + + public uint CRC() + { + return llUUID.CRC(); + } + + public override int GetHashCode() + { + return llUUID.GetHashCode(); + } + + public void Combine(UUID other) + { + llUUID.Combine(other.GetLLUUID()); + } + + public void Combine(LLUUID other) + { + llUUID.Combine(other); + } + + public override bool Equals(Object other) + { + return llUUID.Equals(other); + } + + public static bool operator ==(UUID a, UUID b) + { + return a.llUUID.Equals(b.GetLLUUID()); + } + + public static bool operator !=(UUID a, UUID b) + { + return !a.llUUID.Equals(b.GetLLUUID()); + } + + public static bool operator ==(UUID a, LLUUID b) + { + return a.Equals(b); + } + + public static bool operator !=(UUID a, LLUUID b) + { + return !a.Equals(b); + } + } +} diff --git a/OpenSim/Framework/General/UserProfile.cs b/OpenSim/Framework/General/UserProfile.cs index 243208a..ec5a485 100644 --- a/OpenSim/Framework/General/UserProfile.cs +++ b/OpenSim/Framework/General/UserProfile.cs @@ -1,87 +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.Collections.Generic; -using System.Security.Cryptography; -using libsecondlife; -using OpenSim.Framework.Inventory; - -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((1000 * 256), (1000 * 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); - } - - } -} +/* +* 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.Collections.Generic; +using System.Security.Cryptography; +using libsecondlife; +using OpenSim.Framework.Inventory; + +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((1000 * 256), (1000 * 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 index 13e3af2..3333ced 100644 --- a/OpenSim/Framework/General/Util.cs +++ b/OpenSim/Framework/General/Util.cs @@ -1,184 +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.Security.Cryptography; -using System.Text; -using libsecondlife; - -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() - { - - } - } -} +/* +* 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.Text; +using libsecondlife; + +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/Properties/AssemblyInfo.cs b/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs index fcffd67..28779ee 100644 --- a/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs +++ b/OpenSim/Framework/GenericConfig/Xml/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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")] +using System.Reflection; +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 index 7fa085d..2ed8d28 100644 --- a/OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs +++ b/OpenSim/Framework/GenericConfig/Xml/XmlConfig.cs @@ -1,122 +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.IO; -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 (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; - } - - } -} +/* +* 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.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 (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 index f790477..4b3b3de 100644 --- a/OpenSim/Framework/Servers/BaseHttpServer.cs +++ b/OpenSim/Framework/Servers/BaseHttpServer.cs @@ -1,224 +1,224 @@ -/* -* 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.IO; -using System.Net; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using Nwc.XmlRpc; -using OpenSim.Framework.Console; - -namespace OpenSim.Framework.Servers -{ - public class BaseHttpServer - { - protected Thread m_workerThread; - protected HttpListener m_httpListener; - protected Dictionary m_rpcHandlers = new Dictionary(); - protected Dictionary m_streamHandlers = new Dictionary(); - protected int m_port; - protected bool m_firstcaps = true; - - public BaseHttpServer(int port) - { - m_port = port; - } - - public void AddStreamHandler( IStreamHandler handler) - { - string httpMethod = handler.HttpMethod; - string path = handler.Path; - - string handlerKey = GetHandlerKey(httpMethod, path); - m_streamHandlers.Add(handlerKey, handler); - } - - private static string GetHandlerKey(string httpMethod, string path) - { - return httpMethod + ":" + path; - } - - 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; - } - - - public virtual void HandleRequest(Object stateinfo) - { - HttpListenerContext context = (HttpListenerContext)stateinfo; - - HttpListenerRequest request = context.Request; - HttpListenerResponse response = context.Response; - - response.KeepAlive = false; - response.SendChunked = false; - - string path = request.RawUrl; - string handlerKey = GetHandlerKey( request.HttpMethod, path ); - - IStreamHandler streamHandler; - - if (TryGetStreamHandler( handlerKey, out streamHandler)) - { - byte[] buffer = streamHandler.Handle(path, request.InputStream); - request.InputStream.Close(); - - response.ContentType = streamHandler.ContentType; - response.ContentLength64 = buffer.LongLength; - response.OutputStream.Write(buffer, 0, buffer.Length); - response.OutputStream.Close(); - } - else - { - HandleXmlRpcRequests(request, response); - } - } - - private bool TryGetStreamHandler(string handlerKey, out IStreamHandler streamHandler) - { - string bestMatch = null; - - foreach (string pattern in m_streamHandlers.Keys) - { - if (handlerKey.StartsWith(pattern)) - { - if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length) - { - bestMatch = pattern; - } - } - } - - if (String.IsNullOrEmpty(bestMatch)) - { - streamHandler = null; - return false; - } - else - { - streamHandler = m_streamHandlers[bestMatch]; - return true; - } - } - - private void HandleXmlRpcRequests(HttpListenerRequest request, HttpListenerResponse response) - { - Stream requestStream = request.InputStream; - - Encoding encoding = Encoding.UTF8; - StreamReader reader = new StreamReader(requestStream, encoding); - - string requestBody = reader.ReadToEnd(); - reader.Close(); - requestStream.Close(); - - XmlRpcRequest xmlRprcRequest = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(requestBody); - - string methodName = xmlRprcRequest.MethodName; - - XmlRpcResponse xmlRpcResponse; - - XmlRpcMethod method; - if (this.m_rpcHandlers.TryGetValue(methodName, out method)) - { - xmlRpcResponse = method(xmlRprcRequest); - } - else - { - xmlRpcResponse = new XmlRpcResponse(); - Hashtable unknownMethodError = new Hashtable(); - unknownMethodError["reason"] = "XmlRequest"; ; - unknownMethodError["message"] = "Unknown Rpc Request ["+methodName+"]"; - unknownMethodError["login"] = "false"; - xmlRpcResponse.Value = unknownMethodError; - } - - response.AddHeader("Content-type", "text/xml"); - - string responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse); - - byte[] buffer = Encoding.UTF8.GetBytes(responseString); - - response.SendChunked = false; - response.ContentLength64 = buffer.Length; - response.ContentEncoding = Encoding.UTF8; - - response.OutputStream.Write(buffer, 0, buffer.Length); - response.OutputStream.Close(); - } - - public void Start() - { - 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 - { - 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) - { - MainLog.Instance.WriteLine(LogPriority.MEDIUM, e.Message); - } - } - - - public void RemoveStreamHandler(string httpMethod, string path) - { - m_streamHandlers.Remove(GetHandlerKey(httpMethod, path)); - } - } -} +/* +* 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.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using Nwc.XmlRpc; +using OpenSim.Framework.Console; + +namespace OpenSim.Framework.Servers +{ + public class BaseHttpServer + { + protected Thread m_workerThread; + protected HttpListener m_httpListener; + protected Dictionary m_rpcHandlers = new Dictionary(); + protected Dictionary m_streamHandlers = new Dictionary(); + protected int m_port; + protected bool m_firstcaps = true; + + public BaseHttpServer(int port) + { + m_port = port; + } + + public void AddStreamHandler( IStreamHandler handler) + { + string httpMethod = handler.HttpMethod; + string path = handler.Path; + + string handlerKey = GetHandlerKey(httpMethod, path); + m_streamHandlers.Add(handlerKey, handler); + } + + private static string GetHandlerKey(string httpMethod, string path) + { + return httpMethod + ":" + path; + } + + 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; + } + + + public virtual void HandleRequest(Object stateinfo) + { + HttpListenerContext context = (HttpListenerContext)stateinfo; + + HttpListenerRequest request = context.Request; + HttpListenerResponse response = context.Response; + + response.KeepAlive = false; + response.SendChunked = false; + + string path = request.RawUrl; + string handlerKey = GetHandlerKey( request.HttpMethod, path ); + + IStreamHandler streamHandler; + + if (TryGetStreamHandler( handlerKey, out streamHandler)) + { + byte[] buffer = streamHandler.Handle(path, request.InputStream); + request.InputStream.Close(); + + response.ContentType = streamHandler.ContentType; + response.ContentLength64 = buffer.LongLength; + response.OutputStream.Write(buffer, 0, buffer.Length); + response.OutputStream.Close(); + } + else + { + HandleXmlRpcRequests(request, response); + } + } + + private bool TryGetStreamHandler(string handlerKey, out IStreamHandler streamHandler) + { + string bestMatch = null; + + foreach (string pattern in m_streamHandlers.Keys) + { + if (handlerKey.StartsWith(pattern)) + { + if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length) + { + bestMatch = pattern; + } + } + } + + if (String.IsNullOrEmpty(bestMatch)) + { + streamHandler = null; + return false; + } + else + { + streamHandler = m_streamHandlers[bestMatch]; + return true; + } + } + + private void HandleXmlRpcRequests(HttpListenerRequest request, HttpListenerResponse response) + { + Stream requestStream = request.InputStream; + + Encoding encoding = Encoding.UTF8; + StreamReader reader = new StreamReader(requestStream, encoding); + + string requestBody = reader.ReadToEnd(); + reader.Close(); + requestStream.Close(); + + XmlRpcRequest xmlRprcRequest = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(requestBody); + + string methodName = xmlRprcRequest.MethodName; + + XmlRpcResponse xmlRpcResponse; + + XmlRpcMethod method; + if (this.m_rpcHandlers.TryGetValue(methodName, out method)) + { + xmlRpcResponse = method(xmlRprcRequest); + } + else + { + xmlRpcResponse = new XmlRpcResponse(); + Hashtable unknownMethodError = new Hashtable(); + unknownMethodError["reason"] = "XmlRequest"; ; + unknownMethodError["message"] = "Unknown Rpc Request ["+methodName+"]"; + unknownMethodError["login"] = "false"; + xmlRpcResponse.Value = unknownMethodError; + } + + response.AddHeader("Content-type", "text/xml"); + + string responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse); + + byte[] buffer = Encoding.UTF8.GetBytes(responseString); + + response.SendChunked = false; + response.ContentLength64 = buffer.Length; + response.ContentEncoding = Encoding.UTF8; + + response.OutputStream.Write(buffer, 0, buffer.Length); + response.OutputStream.Close(); + } + + public void Start() + { + 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 + { + 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) + { + MainLog.Instance.WriteLine(LogPriority.MEDIUM, e.Message); + } + } + + + public void RemoveStreamHandler(string httpMethod, string path) + { + m_streamHandlers.Remove(GetHandlerKey(httpMethod, path)); + } + } +} diff --git a/OpenSim/Framework/Servers/BaseStreamHandler.cs b/OpenSim/Framework/Servers/BaseStreamHandler.cs index 0d9c674..0c714e6 100644 --- a/OpenSim/Framework/Servers/BaseStreamHandler.cs +++ b/OpenSim/Framework/Servers/BaseStreamHandler.cs @@ -1,40 +1,40 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; - -namespace OpenSim.Framework.Servers -{ - public abstract class BaseStreamHandler : IStreamHandler - { - virtual public string ContentType - { - get { return "application/xml"; } - } - - private string m_httpMethod; - virtual public string HttpMethod - { - get { return m_httpMethod; } - } - - private string m_path; - virtual public string Path - { - get { return m_path; } - } - - protected string GetParam( string path ) - { - return path.Substring( m_path.Length ); - } - - public abstract byte[] Handle(string path, Stream request); - - protected BaseStreamHandler(string httpMethod, string path) - { - m_httpMethod = httpMethod; - m_path = path; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace OpenSim.Framework.Servers +{ + public abstract class BaseStreamHandler : IStreamHandler + { + virtual public string ContentType + { + get { return "application/xml"; } + } + + private string m_httpMethod; + virtual public string HttpMethod + { + get { return m_httpMethod; } + } + + private string m_path; + virtual public string Path + { + get { return m_path; } + } + + protected string GetParam( string path ) + { + return path.Substring( m_path.Length ); + } + + public abstract byte[] Handle(string path, Stream request); + + protected BaseStreamHandler(string httpMethod, string path) + { + m_httpMethod = httpMethod; + m_path = path; + } + } +} diff --git a/OpenSim/Framework/Servers/BinaryStreamHandler.cs b/OpenSim/Framework/Servers/BinaryStreamHandler.cs index 7d4e4ce..6e512f6 100644 --- a/OpenSim/Framework/Servers/BinaryStreamHandler.cs +++ b/OpenSim/Framework/Servers/BinaryStreamHandler.cs @@ -1,49 +1,49 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; - -namespace OpenSim.Framework.Servers -{ - public delegate string BinaryMethod(byte[] data, string path, string param); - - public class BinaryStreamHandler : BaseStreamHandler - { - BinaryMethod m_method; - - override public byte[] Handle(string path, Stream request) - { - byte[] data = ReadFully(request); - string param = GetParam(path); - string responseString = m_method(data, path, param); - - return Encoding.UTF8.GetBytes(responseString); - } - - public BinaryStreamHandler(string httpMethod, string path, BinaryMethod binaryMethod) - : base(httpMethod, path) - { - m_method = binaryMethod; - } - - private byte[] ReadFully(Stream stream) - { - byte[] buffer = new byte[32768]; - using (MemoryStream ms = new MemoryStream()) - { - while (true) - { - int read = stream.Read(buffer, 0, buffer.Length); - - if (read <= 0) - { - return ms.ToArray(); - } - - ms.Write(buffer, 0, read); - } - } - } - } - -} +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace OpenSim.Framework.Servers +{ + public delegate string BinaryMethod(byte[] data, string path, string param); + + public class BinaryStreamHandler : BaseStreamHandler + { + BinaryMethod m_method; + + override public byte[] Handle(string path, Stream request) + { + byte[] data = ReadFully(request); + string param = GetParam(path); + string responseString = m_method(data, path, param); + + return Encoding.UTF8.GetBytes(responseString); + } + + public BinaryStreamHandler(string httpMethod, string path, BinaryMethod binaryMethod) + : base(httpMethod, path) + { + m_method = binaryMethod; + } + + private byte[] ReadFully(Stream stream) + { + byte[] buffer = new byte[32768]; + using (MemoryStream ms = new MemoryStream()) + { + while (true) + { + int read = stream.Read(buffer, 0, buffer.Length); + + if (read <= 0) + { + return ms.ToArray(); + } + + ms.Write(buffer, 0, read); + } + } + } + } + +} diff --git a/OpenSim/Framework/Servers/CheckSumServer.cs b/OpenSim/Framework/Servers/CheckSumServer.cs index 89ec095..b1fa5cd 100644 --- a/OpenSim/Framework/Servers/CheckSumServer.cs +++ b/OpenSim/Framework/Servers/CheckSumServer.cs @@ -1,127 +1,127 @@ -/* -* 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. -* -*/ -namespace OpenSim.Framework.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); - } - * } - */ - +/* +* 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. +* +*/ +namespace OpenSim.Framework.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/IStreamHandler.cs b/OpenSim/Framework/Servers/IStreamHandler.cs index 6cab40d..8858c99 100644 --- a/OpenSim/Framework/Servers/IStreamHandler.cs +++ b/OpenSim/Framework/Servers/IStreamHandler.cs @@ -1,22 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; - -namespace OpenSim.Framework.Servers -{ - public interface IStreamHandler - { - // Handle request stream, return byte array - byte[] Handle(string path, Stream request ); - - // Return response content type - string ContentType { get; } - - // Return required http method - string HttpMethod { get;} - - // Return path - string Path { get; } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace OpenSim.Framework.Servers +{ + public interface IStreamHandler + { + // Handle request stream, return byte array + byte[] Handle(string path, Stream request ); + + // Return response content type + string ContentType { get; } + + // Return required http method + string HttpMethod { get;} + + // Return path + string Path { get; } + } +} diff --git a/OpenSim/Framework/Servers/RestMethod.cs b/OpenSim/Framework/Servers/RestMethod.cs index c6cb230..0c2624b 100644 --- a/OpenSim/Framework/Servers/RestMethod.cs +++ b/OpenSim/Framework/Servers/RestMethod.cs @@ -1,31 +1,31 @@ -/* -* 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. -* -*/ -namespace OpenSim.Framework.Servers -{ - public delegate string RestMethod( string request, string path, string param ); -} +/* +* 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. +* +*/ +namespace OpenSim.Framework.Servers +{ + public delegate string RestMethod( string request, string path, string param ); +} diff --git a/OpenSim/Framework/Servers/RestStreamHandler.cs b/OpenSim/Framework/Servers/RestStreamHandler.cs index 1b3b41c..6753a06 100644 --- a/OpenSim/Framework/Servers/RestStreamHandler.cs +++ b/OpenSim/Framework/Servers/RestStreamHandler.cs @@ -1,31 +1,31 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; - -namespace OpenSim.Framework.Servers -{ - public class RestStreamHandler : BaseStreamHandler - { - RestMethod m_restMethod; - - override public byte[] Handle(string path, Stream request ) - { - Encoding encoding = Encoding.UTF8; - StreamReader streamReader = new StreamReader(request, encoding); - - string requestBody = streamReader.ReadToEnd(); - streamReader.Close(); - - string param = GetParam(path); - string responseString = m_restMethod(requestBody, path, param ); - - return Encoding.UTF8.GetBytes(responseString); - } - - public RestStreamHandler(string httpMethod, string path, RestMethod restMethod) : base( httpMethod, path ) - { - m_restMethod = restMethod; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace OpenSim.Framework.Servers +{ + public class RestStreamHandler : BaseStreamHandler + { + RestMethod m_restMethod; + + override public byte[] Handle(string path, Stream request ) + { + Encoding encoding = Encoding.UTF8; + StreamReader streamReader = new StreamReader(request, encoding); + + string requestBody = streamReader.ReadToEnd(); + streamReader.Close(); + + string param = GetParam(path); + string responseString = m_restMethod(requestBody, path, param ); + + return Encoding.UTF8.GetBytes(responseString); + } + + public RestStreamHandler(string httpMethod, string path, RestMethod restMethod) : base( httpMethod, path ) + { + m_restMethod = restMethod; + } + } +} diff --git a/OpenSim/Framework/Servers/UDPServerBase.cs b/OpenSim/Framework/Servers/UDPServerBase.cs index 508eb9d..8113207 100644 --- a/OpenSim/Framework/Servers/UDPServerBase.cs +++ b/OpenSim/Framework/Servers/UDPServerBase.cs @@ -1,87 +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.Net; -using System.Net.Sockets; -using libsecondlife.Packets; - -namespace OpenSim.Framework.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.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), listenPort); - Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - Server.Bind(ServerIncoming); - - ipeSender = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 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) - { - - } - } -} - +/* +* 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 libsecondlife.Packets; + +namespace OpenSim.Framework.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.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), listenPort); + Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + Server.Bind(ServerIncoming); + + ipeSender = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 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 index b76ac51..b8abecf 100644 --- a/OpenSim/Framework/Servers/XmlRpcMethod.cs +++ b/OpenSim/Framework/Servers/XmlRpcMethod.cs @@ -1,33 +1,33 @@ -/* -* 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; - -namespace OpenSim.Framework.Servers -{ - public delegate XmlRpcResponse XmlRpcMethod( XmlRpcRequest request ); -} +/* +* 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; + +namespace OpenSim.Framework.Servers +{ + public delegate XmlRpcResponse XmlRpcMethod( XmlRpcRequest request ); +} diff --git a/OpenSim/Framework/UserManager/LoginResponse.cs b/OpenSim/Framework/UserManager/LoginResponse.cs index abcbd48..d3dfd5b 100644 --- a/OpenSim/Framework/UserManager/LoginResponse.cs +++ b/OpenSim/Framework/UserManager/LoginResponse.cs @@ -1,643 +1,643 @@ -using System; -using System.Collections; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework.Console; - -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" + (1000 * 256).ToString() + ",r" + (1000 * 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; - - MainLog.Instance.Warn("SIM IP: " + responseData["sim_ip"] + "; SIM PORT: " + responseData["sim_port"]); - - 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) - { - MainLog.Instance.WriteLine( - 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; - } - } -} - +using System; +using System.Collections; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Console; + +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" + (1000 * 256).ToString() + ",r" + (1000 * 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; + + MainLog.Instance.Warn("SIM IP: " + responseData["sim_ip"] + "; SIM PORT: " + responseData["sim_port"]); + + 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) + { + MainLog.Instance.WriteLine( + 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/UserManagerBase.cs b/OpenSim/Framework/UserManager/UserManagerBase.cs index 4e688f7..fe45d1b 100644 --- a/OpenSim/Framework/UserManager/UserManagerBase.cs +++ b/OpenSim/Framework/UserManager/UserManagerBase.cs @@ -1,631 +1,631 @@ -/* -* 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.Security.Cryptography; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework.Console; -using OpenSim.Framework.Data; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Inventory; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Framework.UserManagement -{ - public abstract class UserManagerBase - { - public 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) - { - MainLog.Instance.Verbose( "Userstorage: Attempting to load " + FileName); - Assembly pluginAssembly = Assembly.LoadFrom(FileName); - - 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); - 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) - { - 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) - { - System.Console.WriteLine("EEK!"); - 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); - - profile.currentAgent = getUserAgent(profile.UUID); - - return profile; - } - catch (Exception e) - { - 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) - { - 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) - { - 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) - { - 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(UserProfileData profile, XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - - UserAgentData agent = new UserAgentData(); - - // User connection - agent.agentOnline = true; - - // 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) - { - - } - } - } - - // 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(UserProfileData profile, string password) - { - 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 abstract void CustomiseResponse( LoginResponse response, UserProfileData theUser); - - /// - /// Main user login function - /// - /// The XMLRPC request - /// The response to send - public XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) - { - - System.Console.WriteLine("Attempting login now..."); - 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 userProfile; - LoginResponse logResponse = new LoginResponse(); - - if (GoodXML) - { - firstname = (string)requestData["first"]; - lastname = (string)requestData["last"]; - passwd = (string)requestData["passwd"]; - - userProfile = GetTheUser(firstname, lastname); - if (userProfile == null) - return logResponse.CreateLoginFailedResponse(); - - GoodLogin = AuthenticateUser(userProfile, passwd); - } - else - { - return logResponse.CreateGridErrorResponse(); - } - - if (!GoodLogin) - { - return logResponse.CreateLoginFailedResponse(); - } - else - { - // If we already have a session... - if (userProfile.currentAgent != null && userProfile.currentAgent.agentOnline) - { - // Reject the login - return logResponse.CreateAlreadyLoggedInResponse(); - } - // Otherwise... - // Create a new agent session - CreateAgent( userProfile, request); - - try - { - - LLUUID AgentID = userProfile.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 = userProfile.surname; - logResponse.Firstname = userProfile.username; - logResponse.AgentID = AgentID.ToStringHyphenated(); - logResponse.SessionID = userProfile.currentAgent.sessionID.ToStringHyphenated(); - logResponse.SecureSessionID = userProfile.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( logResponse, userProfile); - } - catch (Exception e) - { - System.Console.WriteLine(e.ToString()); - return logResponse.CreateDeadRegionResponse(); - //return logResponse.ToXmlRpcResponse(); - } - CommitAgent(ref userProfile); - 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) - { - 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 XmlRpcResponse CreateUnknownUserErrorResponse() - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - responseData["error_type"] = "unknown_user"; - responseData["error_desc"] = "The user requested is not in the database"; - - response.Value = responseData; - return response; - } - - /// - /// 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 XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - // Account information - responseData["firstname"] = profile.username; - responseData["lastname"] = profile.surname; - responseData["uuid"] = profile.UUID.ToStringHyphenated(); - // Server Information - responseData["server_inventory"] = profile.userInventoryURI; - responseData["server_asset"] = profile.userAssetURI; - // Profile Information - responseData["profile_about"] = profile.profileAboutText; - responseData["profile_firstlife_about"] = profile.profileFirstText; - responseData["profile_firstlife_image"] = profile.profileFirstImage.ToStringHyphenated(); - responseData["profile_can_do"] = profile.profileCanDoMask.ToString(); - responseData["profile_want_do"] = profile.profileWantDoMask.ToString(); - responseData["profile_image"] = profile.profileImage.ToStringHyphenated(); - responseData["profile_created"] = profile.created.ToString(); - responseData["profile_lastlogin"] = profile.lastLogin.ToString(); - // Home region information - responseData["home_coordinates_x"] = profile.homeLocation.X.ToString(); - responseData["home_coordinates_y"] = profile.homeLocation.Y.ToString(); - responseData["home_coordinates_z"] = profile.homeLocation.Z.ToString(); - - responseData["home_region"] = profile.homeRegion.ToString(); - - responseData["home_look_x"] = profile.homeLookAt.X.ToString(); - responseData["home_look_y"] = profile.homeLookAt.Y.ToString(); - responseData["home_look_z"] = profile.homeLookAt.Z.ToString(); - response.Value = responseData; - - return response; - } - - #region XMLRPC User Methods - //should most likely move out of here and into the grid's userserver sub class - public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - UserProfileData userProfile; - if (requestData.Contains("avatar_name")) - { - userProfile = getUserProfile((string)requestData["avatar_name"]); - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return ProfileToXmlRPCResponse(userProfile); - } - - public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - UserProfileData userProfile; - System.Console.WriteLine("METHOD BY UUID CALLED"); - if (requestData.Contains("avatar_uuid")) - { - userProfile = getUserProfile((LLUUID)requestData["avatar_uuid"]); - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - - return ProfileToXmlRPCResponse(userProfile); - } - #endregion - - } -} +/* +* 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.Security.Cryptography; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Console; +using OpenSim.Framework.Data; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Framework.UserManagement +{ + public abstract class UserManagerBase + { + public 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) + { + MainLog.Instance.Verbose( "Userstorage: Attempting to load " + FileName); + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + 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); + 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) + { + 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) + { + System.Console.WriteLine("EEK!"); + 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); + + profile.currentAgent = getUserAgent(profile.UUID); + + return profile; + } + catch (Exception e) + { + 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) + { + 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) + { + 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) + { + 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(UserProfileData profile, XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + UserAgentData agent = new UserAgentData(); + + // User connection + agent.agentOnline = true; + + // 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) + { + + } + } + } + + // 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(UserProfileData profile, string password) + { + 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 abstract void CustomiseResponse( LoginResponse response, UserProfileData theUser); + + /// + /// Main user login function + /// + /// The XMLRPC request + /// The response to send + public XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) + { + + System.Console.WriteLine("Attempting login now..."); + 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 userProfile; + LoginResponse logResponse = new LoginResponse(); + + if (GoodXML) + { + firstname = (string)requestData["first"]; + lastname = (string)requestData["last"]; + passwd = (string)requestData["passwd"]; + + userProfile = GetTheUser(firstname, lastname); + if (userProfile == null) + return logResponse.CreateLoginFailedResponse(); + + GoodLogin = AuthenticateUser(userProfile, passwd); + } + else + { + return logResponse.CreateGridErrorResponse(); + } + + if (!GoodLogin) + { + return logResponse.CreateLoginFailedResponse(); + } + else + { + // If we already have a session... + if (userProfile.currentAgent != null && userProfile.currentAgent.agentOnline) + { + // Reject the login + return logResponse.CreateAlreadyLoggedInResponse(); + } + // Otherwise... + // Create a new agent session + CreateAgent( userProfile, request); + + try + { + + LLUUID AgentID = userProfile.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 = userProfile.surname; + logResponse.Firstname = userProfile.username; + logResponse.AgentID = AgentID.ToStringHyphenated(); + logResponse.SessionID = userProfile.currentAgent.sessionID.ToStringHyphenated(); + logResponse.SecureSessionID = userProfile.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( logResponse, userProfile); + } + catch (Exception e) + { + System.Console.WriteLine(e.ToString()); + return logResponse.CreateDeadRegionResponse(); + //return logResponse.ToXmlRpcResponse(); + } + CommitAgent(ref userProfile); + 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) + { + 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 XmlRpcResponse CreateUnknownUserErrorResponse() + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + responseData["error_type"] = "unknown_user"; + responseData["error_desc"] = "The user requested is not in the database"; + + response.Value = responseData; + return response; + } + + /// + /// 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 XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + + // Account information + responseData["firstname"] = profile.username; + responseData["lastname"] = profile.surname; + responseData["uuid"] = profile.UUID.ToStringHyphenated(); + // Server Information + responseData["server_inventory"] = profile.userInventoryURI; + responseData["server_asset"] = profile.userAssetURI; + // Profile Information + responseData["profile_about"] = profile.profileAboutText; + responseData["profile_firstlife_about"] = profile.profileFirstText; + responseData["profile_firstlife_image"] = profile.profileFirstImage.ToStringHyphenated(); + responseData["profile_can_do"] = profile.profileCanDoMask.ToString(); + responseData["profile_want_do"] = profile.profileWantDoMask.ToString(); + responseData["profile_image"] = profile.profileImage.ToStringHyphenated(); + responseData["profile_created"] = profile.created.ToString(); + responseData["profile_lastlogin"] = profile.lastLogin.ToString(); + // Home region information + responseData["home_coordinates_x"] = profile.homeLocation.X.ToString(); + responseData["home_coordinates_y"] = profile.homeLocation.Y.ToString(); + responseData["home_coordinates_z"] = profile.homeLocation.Z.ToString(); + + responseData["home_region"] = profile.homeRegion.ToString(); + + responseData["home_look_x"] = profile.homeLookAt.X.ToString(); + responseData["home_look_y"] = profile.homeLookAt.Y.ToString(); + responseData["home_look_z"] = profile.homeLookAt.Z.ToString(); + response.Value = responseData; + + return response; + } + + #region XMLRPC User Methods + //should most likely move out of here and into the grid's userserver sub class + public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + UserProfileData userProfile; + if (requestData.Contains("avatar_name")) + { + userProfile = getUserProfile((string)requestData["avatar_name"]); + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXmlRPCResponse(userProfile); + } + + public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + UserProfileData userProfile; + System.Console.WriteLine("METHOD BY UUID CALLED"); + if (requestData.Contains("avatar_uuid")) + { + userProfile = getUserProfile((LLUUID)requestData["avatar_uuid"]); + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + + return ProfileToXmlRPCResponse(userProfile); + } + #endregion + + } +} diff --git a/OpenSim/Grid/AssetServer/Main.cs b/OpenSim/Grid/AssetServer/Main.cs index 4126ff4..5093f4d 100644 --- a/OpenSim/Grid/AssetServer/Main.cs +++ b/OpenSim/Grid/AssetServer/Main.cs @@ -1,406 +1,406 @@ -/* -* 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 Db4objects.Db4o; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Types; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.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); - 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"); - BaseHttpServer httpServer = new BaseHttpServer(8003); - - httpServer.AddStreamHandler( new GetAssetStreamHandler(this)); - httpServer.AddStreamHandler(new PostAssetStreamHandler( this )); - - //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 = File.Exists("gridassets.yap"); - try - { - db = Db4oFactory.OpenFile("gridassets.yap"); - MainLog.Instance.Verbose("Main.cs:setupDB() - creation"); - } - catch (Exception e) - { - db.Close(); - MainLog.Instance.Warn("Main.cs:setupDB() - Exception occured"); - 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(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 CreateAsset(LLUUID assetId, byte[] assetData) - { - AssetBase asset = new AssetBase(); - asset.Name = ""; - asset.FullID = assetId; - asset.Data = assetData; - - AssetStorage store = new AssetStorage(); - store.Data = asset.Data; - store.Name = asset.Name; - store.UUID = asset.FullID; - db.Set(store); - db.Commit(); - } - - 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) - { - } - } - - public class GetAssetStreamHandler : BaseStreamHandler - { - OpenAsset_Main m_assetManager; - - override public byte[] Handle(string path, Stream request) - { - string param = GetParam(path); - - byte[] assetdata = m_assetManager.GetAssetData(new LLUUID(param), false); - if (assetdata != null) - { - return assetdata; - } - else - { - return new byte[]{}; - } - } - - public GetAssetStreamHandler(OpenAsset_Main assetManager):base( "/assets/", "GET") - { - m_assetManager = assetManager; - } - } - - public class PostAssetStreamHandler : BaseStreamHandler - { - OpenAsset_Main m_assetManager; - - override public byte[] Handle(string path, Stream request) - { - string param = GetParam(path); - LLUUID assetId = new LLUUID(param); - byte[] txBuffer = new byte[4096]; - - using( BinaryReader binReader = new BinaryReader( request ) ) - { - using (MemoryStream memoryStream = new MemoryStream(4096)) - { - int count; - while ((count = binReader.Read(txBuffer, 0, 4096)) > 0) - { - memoryStream.Write(txBuffer, 0, count); - } - - byte[] assetData = memoryStream.ToArray(); - - m_assetManager.CreateAsset(assetId, assetData); - } - } - - return new byte[]{}; - } - - public PostAssetStreamHandler( OpenAsset_Main assetManager ) - : base("/assets/", "POST") - { - m_assetManager = assetManager; - } - } -} +/* +* 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 Db4objects.Db4o; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Types; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.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); + 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"); + BaseHttpServer httpServer = new BaseHttpServer(8003); + + httpServer.AddStreamHandler( new GetAssetStreamHandler(this)); + httpServer.AddStreamHandler(new PostAssetStreamHandler( this )); + + //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 = File.Exists("gridassets.yap"); + try + { + db = Db4oFactory.OpenFile("gridassets.yap"); + MainLog.Instance.Verbose("Main.cs:setupDB() - creation"); + } + catch (Exception e) + { + db.Close(); + MainLog.Instance.Warn("Main.cs:setupDB() - Exception occured"); + 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(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 CreateAsset(LLUUID assetId, byte[] assetData) + { + AssetBase asset = new AssetBase(); + asset.Name = ""; + asset.FullID = assetId; + asset.Data = assetData; + + AssetStorage store = new AssetStorage(); + store.Data = asset.Data; + store.Name = asset.Name; + store.UUID = asset.FullID; + db.Set(store); + db.Commit(); + } + + 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) + { + } + } + + public class GetAssetStreamHandler : BaseStreamHandler + { + OpenAsset_Main m_assetManager; + + override public byte[] Handle(string path, Stream request) + { + string param = GetParam(path); + + byte[] assetdata = m_assetManager.GetAssetData(new LLUUID(param), false); + if (assetdata != null) + { + return assetdata; + } + else + { + return new byte[]{}; + } + } + + public GetAssetStreamHandler(OpenAsset_Main assetManager):base( "/assets/", "GET") + { + m_assetManager = assetManager; + } + } + + public class PostAssetStreamHandler : BaseStreamHandler + { + OpenAsset_Main m_assetManager; + + override public byte[] Handle(string path, Stream request) + { + string param = GetParam(path); + LLUUID assetId = new LLUUID(param); + byte[] txBuffer = new byte[4096]; + + using( BinaryReader binReader = new BinaryReader( request ) ) + { + using (MemoryStream memoryStream = new MemoryStream(4096)) + { + int count; + while ((count = binReader.Read(txBuffer, 0, 4096)) > 0) + { + memoryStream.Write(txBuffer, 0, count); + } + + byte[] assetData = memoryStream.ToArray(); + + m_assetManager.CreateAsset(assetId, assetData); + } + } + + return new byte[]{}; + } + + public PostAssetStreamHandler( OpenAsset_Main assetManager ) + : base("/assets/", "POST") + { + m_assetManager = assetManager; + } + } +} diff --git a/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs b/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs index dc39ce2..f9b48d5 100644 --- a/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs +++ b/OpenSim/Grid/AssetServer/Properties/AssemblyInfo.cs @@ -1,58 +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.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")] +/* +* 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.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 index 6c916a2..989df26 100644 --- a/OpenSim/Grid/Framework.Manager/GridManagementAgent.cs +++ b/OpenSim/Grid/Framework.Manager/GridManagementAgent.cs @@ -1,138 +1,138 @@ -/* -* 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.Collections; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework.Servers; - -namespace OpenSim.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 OpenSim.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; - - } - - } -} +/* +* 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.Collections; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Servers; + +namespace OpenSim.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 OpenSim.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 index 67cd35d..729e42b 100644 --- a/OpenSim/Grid/Framework.Manager/GridServerManager.cs +++ b/OpenSim/Grid/Framework.Manager/GridServerManager.cs @@ -1,93 +1,93 @@ -/* -* 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.Threading; -using libsecondlife; -using Nwc.XmlRpc; - -namespace OpenSim.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"); - } - } -} - +/* +* 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.Threading; +using libsecondlife; +using Nwc.XmlRpc; + +namespace OpenSim.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/GridServer.Config/AssemblyInfo.cs b/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs index 39c9e8f..4aa58f8 100644 --- a/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs +++ b/OpenSim/Grid/GridServer.Config/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index 4acf81d..7d7690b 100644 --- a/OpenSim/Grid/GridServer.Config/DbGridConfig.cs +++ b/OpenSim/Grid/GridServer.Config/DbGridConfig.cs @@ -1,160 +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 Db4objects.Db4o; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; - -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() - { - 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() { - MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); - - // About the grid options - this.GridOwner = MainLog.Instance.CmdPrompt("Grid owner", "OGS development team"); - - // Asset Options - this.DefaultAssetServer = MainLog.Instance.CmdPrompt("Default asset server","http://127.0.0.1:8003/"); - this.AssetSendKey = MainLog.Instance.CmdPrompt("Key to send to asset server","null"); - this.AssetRecvKey = MainLog.Instance.CmdPrompt("Key to expect from asset server","null"); - - // User Server Options - this.DefaultUserServer = MainLog.Instance.CmdPrompt("Default user server","http://127.0.0.1:8002/"); - this.UserSendKey = MainLog.Instance.CmdPrompt("Key to send to user server","null"); - this.UserRecvKey = MainLog.Instance.CmdPrompt("Key to expect from user server","null"); - - // Region Server Options - this.SimSendKey = MainLog.Instance.CmdPrompt("Key to send to sims","null"); - this.SimRecvKey = 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) { - 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 { - 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... - MainLog.Instance.Verbose( "Writing out default settings to local database"); - db.Set(this); - - // Closes file locks - db.Close(); - } - } catch(Exception e) { - MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); - MainLog.Instance.Warn(e.ToString()); - } - - // Grid Settings - MainLog.Instance.Verbose("Grid settings loaded:"); - MainLog.Instance.Verbose("Grid owner: " + this.GridOwner); - - // Asset Settings - MainLog.Instance.Verbose("Default asset server: " + this.DefaultAssetServer); - MainLog.Instance.Verbose("Key to send to asset server: " + this.AssetSendKey); - MainLog.Instance.Verbose("Key to expect from asset server: " + this.AssetRecvKey); - - // User Settings - MainLog.Instance.Verbose("Default user server: " + this.DefaultUserServer); - MainLog.Instance.Verbose("Key to send to user server: " + this.UserSendKey); - MainLog.Instance.Verbose("Key to expect from user server: " + this.UserRecvKey); - - // Region Settings - MainLog.Instance.Verbose("Key to send to sims: " + this.SimSendKey); - MainLog.Instance.Verbose("Key to expect from sims: " + this.SimRecvKey); - } - - /// - /// Closes down the database and releases filesystem locks - /// - public void Shutdown() { - db.Close(); - } - } - -} +/* +* 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 Db4objects.Db4o; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; + +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() + { + 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() { + MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); + + // About the grid options + this.GridOwner = MainLog.Instance.CmdPrompt("Grid owner", "OGS development team"); + + // Asset Options + this.DefaultAssetServer = MainLog.Instance.CmdPrompt("Default asset server","http://127.0.0.1:8003/"); + this.AssetSendKey = MainLog.Instance.CmdPrompt("Key to send to asset server","null"); + this.AssetRecvKey = MainLog.Instance.CmdPrompt("Key to expect from asset server","null"); + + // User Server Options + this.DefaultUserServer = MainLog.Instance.CmdPrompt("Default user server","http://127.0.0.1:8002/"); + this.UserSendKey = MainLog.Instance.CmdPrompt("Key to send to user server","null"); + this.UserRecvKey = MainLog.Instance.CmdPrompt("Key to expect from user server","null"); + + // Region Server Options + this.SimSendKey = MainLog.Instance.CmdPrompt("Key to send to sims","null"); + this.SimRecvKey = 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) { + 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 { + 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... + MainLog.Instance.Verbose( "Writing out default settings to local database"); + db.Set(this); + + // Closes file locks + db.Close(); + } + } catch(Exception e) { + MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + MainLog.Instance.Warn(e.ToString()); + } + + // Grid Settings + MainLog.Instance.Verbose("Grid settings loaded:"); + MainLog.Instance.Verbose("Grid owner: " + this.GridOwner); + + // Asset Settings + MainLog.Instance.Verbose("Default asset server: " + this.DefaultAssetServer); + MainLog.Instance.Verbose("Key to send to asset server: " + this.AssetSendKey); + MainLog.Instance.Verbose("Key to expect from asset server: " + this.AssetRecvKey); + + // User Settings + MainLog.Instance.Verbose("Default user server: " + this.DefaultUserServer); + MainLog.Instance.Verbose("Key to send to user server: " + this.UserSendKey); + MainLog.Instance.Verbose("Key to expect from user server: " + this.UserRecvKey); + + // Region Settings + MainLog.Instance.Verbose("Key to send to sims: " + this.SimSendKey); + 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/GridManager.cs b/OpenSim/Grid/GridServer/GridManager.cs index 64b51b4..22bffa0 100644 --- a/OpenSim/Grid/GridServer/GridManager.cs +++ b/OpenSim/Grid/GridServer/GridManager.cs @@ -1,710 +1,710 @@ -/* -* 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.Xml; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework.Console; -using OpenSim.Framework.Data; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Grid.GridServer -{ - class GridManager - { - Dictionary _plugins = new Dictionary(); - Dictionary _logplugins = new Dictionary(); - - public 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) - { - MainLog.Instance.Verbose("Storage: Attempting to load " + FileName); - Assembly pluginAssembly = Assembly.LoadFrom(FileName); - - 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); - 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); - 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) - { - 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(LLUUID uuid) - { - foreach(KeyValuePair kvp in _plugins) { - try - { - return kvp.Value.GetProfileByLLUUID(uuid); - } - catch (Exception e) - { - MainLog.Instance.Warn("Message from Storage: " + e.Message); - } - } - 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 - { - 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 - { - 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 XmlRpcSimulatorLoginMethod(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(),"XmlRpcSimulatorLoginMethod","", 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"], "XmlRpcSimulatorLoginMethod", "", 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) // Shouldnt this be in the REST Simulator Set method? - { - //NEW REGION - TheSim = new SimProfileData(); - - 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; - - TheSim.serverIP = (string)requestData["sim_ip"]; - TheSim.serverPort = Convert.ToUInt32((string)requestData["sim_port"]); - TheSim.httpPort = Convert.ToUInt32((string)requestData["http_port"]); - TheSim.remotingPort = Convert.ToUInt32((string)requestData["remoting_port"]); - TheSim.regionLocX = Convert.ToUInt32((string)requestData["region_locx"]); - TheSim.regionLocY = Convert.ToUInt32((string)requestData["region_locy"]); - TheSim.regionLocZ = 0; - TheSim.regionMapTextureID = new LLUUID((string)requestData["map-image-id"]); - - TheSim.regionHandle = Helpers.UIntsToLong((TheSim.regionLocX * 256), (TheSim.regionLocY * 256)); - System.Console.WriteLine("adding region " + TheSim.regionLocX + " , " + TheSim.regionLocY + " , " + TheSim.regionHandle); - TheSim.serverURI = "http://" + TheSim.serverIP + ":" + TheSim.serverPort + "/"; - TheSim.httpServerURI = "http://" + TheSim.serverIP + ":" + TheSim.httpPort + "/"; - - Console.WriteLine("NEW SIM: " + TheSim.serverURI); - TheSim.regionName = (string)requestData["sim_name"]; - TheSim.UUID = new LLUUID((string)requestData["UUID"]); - - foreach (KeyValuePair kvp in _plugins) - { - try - { - DataResponse insertResponse = kvp.Value.AddProfile(TheSim); - switch(insertResponse) - { - case DataResponse.RESPONSE_OK: - OpenSim.Framework.Console.MainLog.Instance.Verbose("New sim creation successful: " + TheSim.regionName); - break; - case DataResponse.RESPONSE_ERROR: - OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Error): " + TheSim.regionName); - break; - case DataResponse.RESPONSE_INVALIDCREDENTIALS: - OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Invalid Credentials): " + TheSim.regionName); - break; - case DataResponse.RESPONSE_AUTHREQUIRED: - OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Authentication Required): " + TheSim.regionName); - break; - } - - } - catch (Exception e) - { - OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: Unable to add region " + TheSim.UUID.ToStringHyphenated() + " via " + kvp.Key); - OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); - } - } - - - if (getRegion(TheSim.regionHandle) == null) - { - responseData["error"] = "Unable to add new region"; - return response; - } - } - - - 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 XmlRpcSimulatorDataRequestMethod(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - SimProfileData simData = null; - if (requestData.ContainsKey("region_UUID")) - { - simData = getRegion(new LLUUID((string)requestData["region_UUID"])); - } - else if (requestData.ContainsKey("region_handle")) - { - Console.WriteLine("requesting data for region " + (string)requestData["region_handle"]); - simData = getRegion(Convert.ToUInt64((string)requestData["region_handle"])); - } - - if (simData == null) - { - //Sim does not exist - Console.WriteLine("region not found"); - responseData["error"] = "Sim does not exist"; - } - else - { - Console.WriteLine("found region"); - responseData["sim_ip"] = simData.serverIP; - responseData["sim_port"] = simData.serverPort.ToString(); - responseData["http_port"] = simData.httpPort.ToString(); - responseData["remoting_port"] = simData.remotingPort.ToString(); - responseData["region_locx"] = simData.regionLocX.ToString() ; - responseData["region_locy"] = simData.regionLocY.ToString(); - responseData["region_UUID"] = simData.UUID.UUID.ToString(); - responseData["region_name"] = simData.regionName; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = responseData; - 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 = false; // 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(); - System.Console.WriteLine("send neighbour info for " + aSim.Value.regionLocX.ToString() + " , " + 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); - } - 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+1; x++) - { - for (int y = ymin; y < ymax+1; y++) - { - ulong regHandle = Helpers.UIntsToLong((uint)(x * 256), (uint)(y * 256)); - simProfile = getRegion(regHandle); - 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.ToStringHyphenated(); - - // 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); - } - } - } - 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 via REST method"); - 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"; - } - - //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; - bool requireValid = true; - - 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."; - } - - if (requireValid && (TheSim.serverIP.StartsWith("0."))) - { - return "ERROR! 0.*.*.* Addresses are invalid, please check your server config and try again"; - } - - - try - { - 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 && authkeynode.InnerText != TheSim.regionRecvKey)) - { - kvp.Value.AddProfile(TheSim); - MainLog.Instance.Verbose("New sim added to grid (" + TheSim.regionName + ")"); - logToDB(TheSim.UUID.ToStringHyphenated(), "RestSetSimMethod", "", 5, "Region successfully updated and connected to grid."); - } - else - { - MainLog.Instance.Warn("Unable to update region (RestSetSimMethod): Incorrect reservation auth key.");// Wanted: " + reserveData.gridRecvKey + ", Got: " + TheSim.regionRecvKey + "."); - return "Unable to update region (RestSetSimMethod): Incorrect auth key."; - } - } - catch (Exception e) - { - 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() + ")"; - } - } - - } -} +/* +* 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.Xml; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Console; +using OpenSim.Framework.Data; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Grid.GridServer +{ + class GridManager + { + Dictionary _plugins = new Dictionary(); + Dictionary _logplugins = new Dictionary(); + + public 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) + { + MainLog.Instance.Verbose("Storage: Attempting to load " + FileName); + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + 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); + 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); + 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) + { + 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(LLUUID uuid) + { + foreach(KeyValuePair kvp in _plugins) { + try + { + return kvp.Value.GetProfileByLLUUID(uuid); + } + catch (Exception e) + { + MainLog.Instance.Warn("Message from Storage: " + e.Message); + } + } + 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 + { + 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 + { + 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 XmlRpcSimulatorLoginMethod(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(),"XmlRpcSimulatorLoginMethod","", 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"], "XmlRpcSimulatorLoginMethod", "", 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) // Shouldnt this be in the REST Simulator Set method? + { + //NEW REGION + TheSim = new SimProfileData(); + + 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; + + TheSim.serverIP = (string)requestData["sim_ip"]; + TheSim.serverPort = Convert.ToUInt32((string)requestData["sim_port"]); + TheSim.httpPort = Convert.ToUInt32((string)requestData["http_port"]); + TheSim.remotingPort = Convert.ToUInt32((string)requestData["remoting_port"]); + TheSim.regionLocX = Convert.ToUInt32((string)requestData["region_locx"]); + TheSim.regionLocY = Convert.ToUInt32((string)requestData["region_locy"]); + TheSim.regionLocZ = 0; + TheSim.regionMapTextureID = new LLUUID((string)requestData["map-image-id"]); + + TheSim.regionHandle = Helpers.UIntsToLong((TheSim.regionLocX * 256), (TheSim.regionLocY * 256)); + System.Console.WriteLine("adding region " + TheSim.regionLocX + " , " + TheSim.regionLocY + " , " + TheSim.regionHandle); + TheSim.serverURI = "http://" + TheSim.serverIP + ":" + TheSim.serverPort + "/"; + TheSim.httpServerURI = "http://" + TheSim.serverIP + ":" + TheSim.httpPort + "/"; + + Console.WriteLine("NEW SIM: " + TheSim.serverURI); + TheSim.regionName = (string)requestData["sim_name"]; + TheSim.UUID = new LLUUID((string)requestData["UUID"]); + + foreach (KeyValuePair kvp in _plugins) + { + try + { + DataResponse insertResponse = kvp.Value.AddProfile(TheSim); + switch(insertResponse) + { + case DataResponse.RESPONSE_OK: + OpenSim.Framework.Console.MainLog.Instance.Verbose("New sim creation successful: " + TheSim.regionName); + break; + case DataResponse.RESPONSE_ERROR: + OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Error): " + TheSim.regionName); + break; + case DataResponse.RESPONSE_INVALIDCREDENTIALS: + OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Invalid Credentials): " + TheSim.regionName); + break; + case DataResponse.RESPONSE_AUTHREQUIRED: + OpenSim.Framework.Console.MainLog.Instance.Warn("New sim creation failed (Authentication Required): " + TheSim.regionName); + break; + } + + } + catch (Exception e) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Storage: Unable to add region " + TheSim.UUID.ToStringHyphenated() + " via " + kvp.Key); + OpenSim.Framework.Console.MainLog.Instance.Warn(e.ToString()); + } + } + + + if (getRegion(TheSim.regionHandle) == null) + { + responseData["error"] = "Unable to add new region"; + return response; + } + } + + + 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 XmlRpcSimulatorDataRequestMethod(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + SimProfileData simData = null; + if (requestData.ContainsKey("region_UUID")) + { + simData = getRegion(new LLUUID((string)requestData["region_UUID"])); + } + else if (requestData.ContainsKey("region_handle")) + { + Console.WriteLine("requesting data for region " + (string)requestData["region_handle"]); + simData = getRegion(Convert.ToUInt64((string)requestData["region_handle"])); + } + + if (simData == null) + { + //Sim does not exist + Console.WriteLine("region not found"); + responseData["error"] = "Sim does not exist"; + } + else + { + Console.WriteLine("found region"); + responseData["sim_ip"] = simData.serverIP; + responseData["sim_port"] = simData.serverPort.ToString(); + responseData["http_port"] = simData.httpPort.ToString(); + responseData["remoting_port"] = simData.remotingPort.ToString(); + responseData["region_locx"] = simData.regionLocX.ToString() ; + responseData["region_locy"] = simData.regionLocY.ToString(); + responseData["region_UUID"] = simData.UUID.UUID.ToString(); + responseData["region_name"] = simData.regionName; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = responseData; + 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 = false; // 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(); + System.Console.WriteLine("send neighbour info for " + aSim.Value.regionLocX.ToString() + " , " + 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); + } + 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+1; x++) + { + for (int y = ymin; y < ymax+1; y++) + { + ulong regHandle = Helpers.UIntsToLong((uint)(x * 256), (uint)(y * 256)); + simProfile = getRegion(regHandle); + 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.ToStringHyphenated(); + + // 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); + } + } + } + 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 via REST method"); + 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"; + } + + //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; + bool requireValid = true; + + 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."; + } + + if (requireValid && (TheSim.serverIP.StartsWith("0."))) + { + return "ERROR! 0.*.*.* Addresses are invalid, please check your server config and try again"; + } + + + try + { + 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 && authkeynode.InnerText != TheSim.regionRecvKey)) + { + kvp.Value.AddProfile(TheSim); + MainLog.Instance.Verbose("New sim added to grid (" + TheSim.regionName + ")"); + logToDB(TheSim.UUID.ToStringHyphenated(), "RestSetSimMethod", "", 5, "Region successfully updated and connected to grid."); + } + else + { + MainLog.Instance.Warn("Unable to update region (RestSetSimMethod): Incorrect reservation auth key.");// Wanted: " + reserveData.gridRecvKey + ", Got: " + TheSim.regionRecvKey + "."); + return "Unable to update region (RestSetSimMethod): Incorrect auth key."; + } + } + catch (Exception e) + { + 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 index dc5e4fa..09aeab5 100644 --- a/OpenSim/Grid/GridServer/Main.cs +++ b/OpenSim/Grid/GridServer/Main.cs @@ -1,258 +1,258 @@ -/* -* 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.Reflection; -using System.Threading; -using System.Timers; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.GenericConfig; -using Timer=System.Timers.Timer; - -namespace OpenSim.Grid.GridServer -{ - /// - /// - public class OpenGrid_Main : conscmd_callback - { - private string ConfigDll = "OpenSim.Grid.GridServer.Config.dll"; - private string GridDll = "OpenSim.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() - { - m_console.Notice("Enter help for a list of commands\n"); - - while (true) - { - m_console.MainLogPrompt(); - } - } - - 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.XmlRpcSimulatorLoginMethod); - httpServer.AddXmlRPCHandler("simulator_data_request", m_gridManager.XmlRpcSimulatorDataRequestMethod); - httpServer.AddXmlRPCHandler("map_block", m_gridManager.XmlRpcMapBlockMethod); - - httpServer.AddStreamHandler(new RestStreamHandler("GET", "/sims/", m_gridManager.RestGetSimMethod )); - httpServer.AddStreamHandler(new RestStreamHandler("POST", "/sims/", m_gridManager.RestSetSimMethod )); - - httpServer.AddStreamHandler( new RestStreamHandler("GET", "/regions/", m_gridManager.RestGetRegionMethod )); - httpServer.AddStreamHandler( new RestStreamHandler("POST","/regions/", m_gridManager.RestSetRegionMethod )); - - //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); - - httpServer.Start(); - - m_console.Verbose( "Main.cs:Startup() - Starting sim status checker"); - - Timer simCheckTimer = new 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 = "OpenSim.Framework.Data.DB4o.dll"; - configData.SetAttribute("DataBaseProvider", "OpenSim.Framework.Data.DB4o.dll"); - } - else - { - GridDll = attri; - } - configData.Commit(); - } - catch - { - - } - } - } -} +/* +* 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.Reflection; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.GenericConfig; +using Timer=System.Timers.Timer; + +namespace OpenSim.Grid.GridServer +{ + /// + /// + public class OpenGrid_Main : conscmd_callback + { + private string ConfigDll = "OpenSim.Grid.GridServer.Config.dll"; + private string GridDll = "OpenSim.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() + { + m_console.Notice("Enter help for a list of commands\n"); + + while (true) + { + m_console.MainLogPrompt(); + } + } + + 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.XmlRpcSimulatorLoginMethod); + httpServer.AddXmlRPCHandler("simulator_data_request", m_gridManager.XmlRpcSimulatorDataRequestMethod); + httpServer.AddXmlRPCHandler("map_block", m_gridManager.XmlRpcMapBlockMethod); + + httpServer.AddStreamHandler(new RestStreamHandler("GET", "/sims/", m_gridManager.RestGetSimMethod )); + httpServer.AddStreamHandler(new RestStreamHandler("POST", "/sims/", m_gridManager.RestSetSimMethod )); + + httpServer.AddStreamHandler( new RestStreamHandler("GET", "/regions/", m_gridManager.RestGetRegionMethod )); + httpServer.AddStreamHandler( new RestStreamHandler("POST","/regions/", m_gridManager.RestSetRegionMethod )); + + //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); + + httpServer.Start(); + + m_console.Verbose( "Main.cs:Startup() - Starting sim status checker"); + + Timer simCheckTimer = new 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 = "OpenSim.Framework.Data.DB4o.dll"; + configData.SetAttribute("DataBaseProvider", "OpenSim.Framework.Data.DB4o.dll"); + } + else + { + GridDll = attri; + } + configData.Commit(); + } + catch + { + + } + } + } +} diff --git a/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs b/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs index 62a68a8..1eeac93 100644 --- a/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs +++ b/OpenSim/Grid/GridServer/Properties/AssemblyInfo.cs @@ -1,58 +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.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")] +/* +* 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.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 index 9ca9b5e..0685088 100644 --- a/OpenSim/Grid/InventoryServer/InventoryManager.cs +++ b/OpenSim/Grid/InventoryServer/InventoryManager.cs @@ -1,125 +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; - } - } -} +/* +* 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 index f479a79..e1276a9 100644 --- a/OpenSim/Grid/InventoryServer/Main.cs +++ b/OpenSim/Grid/InventoryServer/Main.cs @@ -1,87 +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) - { - } - } -} +/* +* 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/BlockingQueue.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs index 83685fc..be47385 100644 --- a/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/BlockingQueue.cs @@ -1,33 +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(); - } - } - } -} +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/Util.cs b/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs index 5bf7ff9..5646be4 100644 --- a/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs +++ b/OpenSim/Grid/Manager/OpenGridServices.Manager/Util.cs @@ -1,133 +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() - { - - } - } -} +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/UserServer.Config/AssemblyInfo.cs b/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs index 15298e8..885bada 100644 --- a/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs +++ b/OpenSim/Grid/UserServer.Config/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index c7f8255..170f34b 100644 --- a/OpenSim/Grid/UserServer.Config/DbUserConfig.cs +++ b/OpenSim/Grid/UserServer.Config/DbUserConfig.cs @@ -1,95 +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 Db4objects.Db4o; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; - -namespace OpenUser.Config.UserConfigDb4o -{ - public class Db4oConfigPlugin: IUserConfig - { - public UserConfig GetConfigObject() - { - MainLog.Instance.Verbose("Loading Db40Config dll"); - return ( new DbUserConfig()); - } - } - - public class DbUserConfig : UserConfig - { - private IObjectContainer db; - - public void LoadDefaults() { - MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); - - this.DefaultStartupMsg = MainLog.Instance.CmdPrompt("Default startup message", "Welcome to OGS"); - - this.GridServerURL = MainLog.Instance.CmdPrompt("Grid server URL","http://127.0.0.1:8001/"); - this.GridSendKey = MainLog.Instance.CmdPrompt("Key to send to grid server","null"); - this.GridRecvKey = 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) { - 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 { - MainLog.Instance.Verbose("Config.cs:InitConfig() - Could not find object in database, loading precompiled defaults"); - LoadDefaults(); - MainLog.Instance.Verbose("Writing out default settings to local database"); - db.Set(this); - db.Close(); - } - } catch(Exception e) { - MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); - MainLog.Instance.Warn(e.ToString()); - } - - MainLog.Instance.Verbose("User settings loaded:"); - MainLog.Instance.Verbose("Default startup message: " + this.DefaultStartupMsg); - MainLog.Instance.Verbose("Grid server URL: " + this.GridServerURL); - MainLog.Instance.Verbose("Key to send to grid: " + this.GridSendKey); - MainLog.Instance.Verbose("Key to expect from grid: " + this.GridRecvKey); - } - - - public void Shutdown() { - db.Close(); - } - } - -} +/* +* 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 Db4objects.Db4o; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; + +namespace OpenUser.Config.UserConfigDb4o +{ + public class Db4oConfigPlugin: IUserConfig + { + public UserConfig GetConfigObject() + { + MainLog.Instance.Verbose("Loading Db40Config dll"); + return ( new DbUserConfig()); + } + } + + public class DbUserConfig : UserConfig + { + private IObjectContainer db; + + public void LoadDefaults() { + MainLog.Instance.Notice("Config.cs:LoadDefaults() - Please press enter to retain default or enter new settings"); + + this.DefaultStartupMsg = MainLog.Instance.CmdPrompt("Default startup message", "Welcome to OGS"); + + this.GridServerURL = MainLog.Instance.CmdPrompt("Grid server URL","http://127.0.0.1:8001/"); + this.GridSendKey = MainLog.Instance.CmdPrompt("Key to send to grid server","null"); + this.GridRecvKey = 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) { + 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 { + MainLog.Instance.Verbose("Config.cs:InitConfig() - Could not find object in database, loading precompiled defaults"); + LoadDefaults(); + MainLog.Instance.Verbose("Writing out default settings to local database"); + db.Set(this); + db.Close(); + } + } catch(Exception e) { + MainLog.Instance.Warn("Config.cs:InitConfig() - Exception occured"); + MainLog.Instance.Warn(e.ToString()); + } + + MainLog.Instance.Verbose("User settings loaded:"); + MainLog.Instance.Verbose("Default startup message: " + this.DefaultStartupMsg); + MainLog.Instance.Verbose("Grid server URL: " + this.GridServerURL); + MainLog.Instance.Verbose("Key to send to grid: " + this.GridSendKey); + MainLog.Instance.Verbose("Key to expect from grid: " + this.GridRecvKey); + } + + + public void Shutdown() { + db.Close(); + } + } + +} diff --git a/OpenSim/Grid/UserServer/Main.cs b/OpenSim/Grid/UserServer/Main.cs index c792918..9bdf8d7 100644 --- a/OpenSim/Grid/UserServer/Main.cs +++ b/OpenSim/Grid/UserServer/Main.cs @@ -1,214 +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.Reflection; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.User; -using OpenSim.Framework.Utilities; -using OpenSim.GenericConfig; - -namespace OpenSim.Grid.UserServer -{ - /// - /// - public class OpenUser_Main : conscmd_callback - { - private string ConfigDll = "OpenSim.Grid.UserServer.Config.dll"; - private string StorageDll = "OpenSim.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); - 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(); - - MainLog.Instance.Verbose("Main.cs:Startup() - Loading configuration"); - Cfg = this.LoadConfigDll(this.ConfigDll); - Cfg.InitConfig(); - - MainLog.Instance.Verbose("Main.cs:Startup() - Establishing data connection"); - m_userManager = new UserManager(); - m_userManager._config = Cfg; - m_userManager.AddPlugin(StorageDll); - - MainLog.Instance.Verbose("Main.cs:Startup() - Starting HTTP process"); - BaseHttpServer httpServer = new BaseHttpServer(8002); - - httpServer.AddXmlRPCHandler("login_to_simulator", m_userManager.XmlRpcLoginMethod); - - httpServer.AddXmlRPCHandler("get_user_by_name", m_userManager.XmlRPCGetUserMethodName); - httpServer.AddXmlRPCHandler("get_user_by_uuid", m_userManager.XmlRPCGetUserMethodUUID); - - httpServer.AddStreamHandler( new RestStreamHandler("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 = 1000; - uint regY = 1000; - - 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 = "OpenSim.Framework.Data.DB4o.dll"; - configData.SetAttribute("DataBaseProvider", "OpenSim.Framework.Data.DB4o.dll"); - } - else - { - StorageDll = attri; - } - configData.Commit(); - } - catch - { - - } - } - - 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) - { - } - } -} +/* +* 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.Reflection; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.User; +using OpenSim.Framework.Utilities; +using OpenSim.GenericConfig; + +namespace OpenSim.Grid.UserServer +{ + /// + /// + public class OpenUser_Main : conscmd_callback + { + private string ConfigDll = "OpenSim.Grid.UserServer.Config.dll"; + private string StorageDll = "OpenSim.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); + 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(); + + MainLog.Instance.Verbose("Main.cs:Startup() - Loading configuration"); + Cfg = this.LoadConfigDll(this.ConfigDll); + Cfg.InitConfig(); + + MainLog.Instance.Verbose("Main.cs:Startup() - Establishing data connection"); + m_userManager = new UserManager(); + m_userManager._config = Cfg; + m_userManager.AddPlugin(StorageDll); + + MainLog.Instance.Verbose("Main.cs:Startup() - Starting HTTP process"); + BaseHttpServer httpServer = new BaseHttpServer(8002); + + httpServer.AddXmlRPCHandler("login_to_simulator", m_userManager.XmlRpcLoginMethod); + + httpServer.AddXmlRPCHandler("get_user_by_name", m_userManager.XmlRPCGetUserMethodName); + httpServer.AddXmlRPCHandler("get_user_by_uuid", m_userManager.XmlRPCGetUserMethodUUID); + + httpServer.AddStreamHandler( new RestStreamHandler("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 = 1000; + uint regY = 1000; + + 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 = "OpenSim.Framework.Data.DB4o.dll"; + configData.SetAttribute("DataBaseProvider", "OpenSim.Framework.Data.DB4o.dll"); + } + else + { + StorageDll = attri; + } + configData.Commit(); + } + catch + { + + } + } + + 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/Properties/AssemblyInfo.cs b/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs index a0a6f3c..877f02f 100644 --- a/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs +++ b/OpenSim/Grid/UserServer/Properties/AssemblyInfo.cs @@ -1,31 +1,31 @@ -using System.Reflection; -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")] +using System.Reflection; +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 index f5275e2..bb7d673 100644 --- a/OpenSim/Grid/UserServer/UserManager.cs +++ b/OpenSim/Grid/UserServer/UserManager.cs @@ -1,100 +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; -using Nwc.XmlRpc; -using OpenSim.Framework.Data; -using OpenSim.Framework.UserManagement; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Grid.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( LoginResponse response, UserProfileData theUser) - { - // Load information from the gridserver - SimProfileData SimInfo = new SimProfileData(); - SimInfo = SimInfo.RequestSimProfileData(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 - Console.WriteLine("CUSTOMISERESPONSE: Region X: " + SimInfo.regionLocX + "; Region Y: " + SimInfo.regionLocY); - response.SimAddress = SimInfo.serverIP; - response.SimPort = (Int32)SimInfo.serverPort; - response.RegionX = SimInfo.regionLocX; - response.RegionY = SimInfo.regionLocY; - - //Not sure if the + "/CAPS/" should in fact be +"CAPS/" depending if there is already a / as part of httpServerURI - string capsPath = Util.GetRandomCapsPath(); - response.SeedCapability = SimInfo.httpServerURI + "CAPS/" + capsPath + "0000/"; - - // Notify the target of an incoming user - Console.WriteLine("Notifying " + SimInfo.regionName + " (" + SimInfo.serverURI+ ")"); - - // 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(); - SimParams["caps_path"] = capsPath; - ArrayList SendParams = new ArrayList(); - SendParams.Add(SimParams); - - // Update agent with target sim - theUser.currentAgent.currentRegion = SimInfo.UUID; - theUser.currentAgent.currentHandle = SimInfo.regionHandle; - - System.Console.WriteLine("Informing region --> " + SimInfo.httpServerURI); - // Send - XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 3000); - } - } -} +/* +* 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 Nwc.XmlRpc; +using OpenSim.Framework.Data; +using OpenSim.Framework.UserManagement; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Grid.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( LoginResponse response, UserProfileData theUser) + { + // Load information from the gridserver + SimProfileData SimInfo = new SimProfileData(); + SimInfo = SimInfo.RequestSimProfileData(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 + Console.WriteLine("CUSTOMISERESPONSE: Region X: " + SimInfo.regionLocX + "; Region Y: " + SimInfo.regionLocY); + response.SimAddress = SimInfo.serverIP; + response.SimPort = (Int32)SimInfo.serverPort; + response.RegionX = SimInfo.regionLocX; + response.RegionY = SimInfo.regionLocY; + + //Not sure if the + "/CAPS/" should in fact be +"CAPS/" depending if there is already a / as part of httpServerURI + string capsPath = Util.GetRandomCapsPath(); + response.SeedCapability = SimInfo.httpServerURI + "CAPS/" + capsPath + "0000/"; + + // Notify the target of an incoming user + Console.WriteLine("Notifying " + SimInfo.regionName + " (" + SimInfo.serverURI+ ")"); + + // 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(); + SimParams["caps_path"] = capsPath; + ArrayList SendParams = new ArrayList(); + SendParams.Add(SimParams); + + // Update agent with target sim + theUser.currentAgent.currentRegion = SimInfo.UUID; + theUser.currentAgent.currentHandle = SimInfo.regionHandle; + + System.Console.WriteLine("Informing region --> " + SimInfo.httpServerURI); + // Send + XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 3000); + } + } +} diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs index 10beaff..666be33 100644 --- a/OpenSim/Region/Application/Application.cs +++ b/OpenSim/Region/Application/Application.cs @@ -1,125 +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 OpenSim.Framework.Console; -using OpenSim.Region.Environment.Scenes; - -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] == "-bulletX") - { - physicsEngine = "BulletXEngine"; - 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; - ScenePresence.PhysicsEngineFlying = allowFlying; - - sim.StartUp(); - - while (true) - { - MainLog.Instance.MainLogPrompt(); - } - } - } -} +/* +* 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 OpenSim.Framework.Console; +using OpenSim.Region.Environment.Scenes; + +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] == "-bulletX") + { + physicsEngine = "BulletXEngine"; + 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; + ScenePresence.PhysicsEngineFlying = allowFlying; + + sim.StartUp(); + + while (true) + { + MainLog.Instance.MainLogPrompt(); + } + } + } +} diff --git a/OpenSim/Region/Application/OpenSimMain.cs b/OpenSim/Region/Application/OpenSimMain.cs index 99164f1..08d7619 100644 --- a/OpenSim/Region/Application/OpenSimMain.cs +++ b/OpenSim/Region/Application/OpenSimMain.cs @@ -1,496 +1,496 @@ -/* -* 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 libsecondlife; -using OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Console; -using OpenSim.Framework.Data; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.GenericConfig; -using OpenSim.Physics.Manager; -using OpenSim.Region.Caches; -using OpenSim.Region.ClientStack; -using OpenSim.Region.Communications.Local; -using OpenSim.Region.Communications.OGS1; -using OpenSim.Region.Environment.Scenes; -using OpenSim.Region.Environment; -using System.Text; - -namespace OpenSim -{ - - public class OpenSimMain : RegionApplicationBase, conscmd_callback - { - protected CommunicationsManager commsManager; - // private CheckSumServer checkServer; - - 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); - 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()); - - this.SetupHttpListener(); - - if (m_sandbox) - { - this.SetupLocalGridServers(); - // this.checkServer = new CheckSumServer(12036); - // this.checkServer.ServerListener(); - } - else - { - this.SetupRemoteGridServers(); - } - - startuptime = DateTime.Now; - - this.physManager = new PhysicsManager(); - this.physManager.LoadPlugins(); - - this.SetupScene(); - - m_log.Verbose("Main.cs:Startup() - Initialising HTTP server"); - - //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.Region.GridInterfaces.Local.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); - InventoryCache = new InventoryCache(); - this.commsManager = new CommunicationsLocal(this.serversData, httpServer); - } - 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.Region.GridInterfaces.Local.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); - InventoryCache = new InventoryCache(); - this.commsManager = new CommunicationsOGS1(this.serversData, httpServer); - } - catch (Exception e) - { - m_log.Error(e.Message + "\nSorry, could not setup remote cache"); - Environment.Exit(1); - } - } - - protected override void SetupScene() - { - IGenericConfig regionConfig; - Scene scene; - UDPServer udpServer; - RegionInfo regionDat = new RegionInfo(); - AuthenticateSessionsBase authenBase; - - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Regions"); - string[] configFiles = Directory.GetFiles(path, "*.xml"); - - if (configFiles.Length == 0) - { - string path2 = Path.Combine(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.InternalEndPoint.Port, this.AssetCache, this.InventoryCache, this.m_log, authenBase); - - m_udpServer.Add(udpServer); - this.regionData.Add(regionDat); - - StorageManager tmpStoreManager = new StorageManager("OpenSim.DataStore.NullStorage.dll", regionDat.DataStore, regionDat.RegionName); - - scene = new Scene( regionDat, authenBase, commsManager, this.AssetCache, tmpStoreManager, httpServer); - this.m_localWorld.Add(scene); - - udpServer.LocalWorld = scene; - - scene.LoadStorageDLL("OpenSim.Region.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded. - scene.LoadWorldMap(); - - m_log.Verbose("Main.cs:Startup() - Starting up messaging system"); - scene.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); - scene.PhysScene.SetTerrain(scene.Terrain.getHeights1D()); - scene.LoadPrimsFromStorage(); - - //Master Avatar Setup - UserProfileData masterAvatar = commsManager.UserServer.SetupMasterUser(scene.RegionInfo.MasterAvatarFirstName, scene.RegionInfo.MasterAvatarLastName, scene.RegionInfo.MasterAvatarSandboxPassword); - if (masterAvatar != null) - { - m_log.Notice("Parcels - Found master avatar [" + masterAvatar.UUID.ToStringHyphenated() + "]"); - scene.RegionInfo.MasterAvatarAssignedUUID = masterAvatar.UUID; - scene.localStorage.LoadParcels((ILocalStorageParcelReceiver)scene.ParcelManager); - } - else - { - m_log.Notice("Parcels - No master avatar found, using null."); - scene.RegionInfo.MasterAvatarAssignedUUID = libsecondlife.LLUUID.Zero; - scene.localStorage.LoadParcels((ILocalStorageParcelReceiver)scene.ParcelManager); - } - scene.performParcelPrimCountUpdate(); - scene.StartTimer(); - } - } - - private class SimStatusHandler : IStreamHandler - { - public byte[] Handle(string path, Stream request) - { - return Encoding.UTF8.GetBytes("OK"); - } - - public string ContentType - { - get { return "text/plain"; } - } - - public string HttpMethod - { - get { return "GET"; } - } - - public string Path - { - get { return "/simstatus/"; } - } - } - - protected override void SetupHttpListener() - { - httpServer = new BaseHttpServer(this.serversData.HttpListenerPort); //regionData[0].IPListenPort); - - if (!this.m_sandbox) - { - httpServer.AddStreamHandler( new SimStatusHandler() ); - } - } - - 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"); - ScenePresence.PhysicsEngineFlying = false; - break; - - case "basicphysics": - this.m_physicsEngine = "basicphysics"; - configData.SetAttribute("PhysicsEngine", "basicphysics"); - ScenePresence.PhysicsEngineFlying = false; - break; - - case "RealPhysX": - this.m_physicsEngine = "RealPhysX"; - ScenePresence.PhysicsEngineFlying = true; - break; - - case "OpenDynamicsEngine": - this.m_physicsEngine = "OpenDynamicsEngine"; - ScenePresence.PhysicsEngineFlying = true; - break; - - case "BulletXEngine": - this.m_physicsEngine = "BulletXEngine"; - 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("quit - 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_localWorld[i].RegionInfo.RegionName)) - { - m_log.Error(result); - } - } - break; - case "script": - for (int i = 0; i < m_localWorld.Count; i++) - { - ((Scene)m_localWorld[i]).SendCommandToScripts(cmdparams); - } - break; - - case "quit": - 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": - ScenePresence TempAv; - m_log.Error(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP", "World")); - for (int i = 0; i < m_localWorld.Count; i++) - { - foreach (libsecondlife.LLUUID UUID in ((Scene)m_localWorld[i]).Entities.Keys) - { - if (((Scene)m_localWorld[i]).Entities[UUID].ToString() == "OpenSim.world.Avatar") - { - TempAv = (ScenePresence)((Scene)m_localWorld[i]).Entities[UUID]; - m_log.Error(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.AgentId, "Unknown", "Unknown"), ((Scene)m_localWorld[i]).RegionInfo.RegionName); - } - } - } - break; - } - } - #endregion - } - - -} +/* +* 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 libsecondlife; +using OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Console; +using OpenSim.Framework.Data; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.GenericConfig; +using OpenSim.Physics.Manager; +using OpenSim.Region.Caches; +using OpenSim.Region.ClientStack; +using OpenSim.Region.Communications.Local; +using OpenSim.Region.Communications.OGS1; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.Environment; +using System.Text; + +namespace OpenSim +{ + + public class OpenSimMain : RegionApplicationBase, conscmd_callback + { + protected CommunicationsManager commsManager; + // private CheckSumServer checkServer; + + 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); + 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()); + + this.SetupHttpListener(); + + if (m_sandbox) + { + this.SetupLocalGridServers(); + // this.checkServer = new CheckSumServer(12036); + // this.checkServer.ServerListener(); + } + else + { + this.SetupRemoteGridServers(); + } + + startuptime = DateTime.Now; + + this.physManager = new PhysicsManager(); + this.physManager.LoadPlugins(); + + this.SetupScene(); + + m_log.Verbose("Main.cs:Startup() - Initialising HTTP server"); + + //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.Region.GridInterfaces.Local.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); + InventoryCache = new InventoryCache(); + this.commsManager = new CommunicationsLocal(this.serversData, httpServer); + } + 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.Region.GridInterfaces.Local.dll", this.serversData.AssetURL, this.serversData.AssetSendKey); + InventoryCache = new InventoryCache(); + this.commsManager = new CommunicationsOGS1(this.serversData, httpServer); + } + catch (Exception e) + { + m_log.Error(e.Message + "\nSorry, could not setup remote cache"); + Environment.Exit(1); + } + } + + protected override void SetupScene() + { + IGenericConfig regionConfig; + Scene scene; + UDPServer udpServer; + RegionInfo regionDat = new RegionInfo(); + AuthenticateSessionsBase authenBase; + + string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Regions"); + string[] configFiles = Directory.GetFiles(path, "*.xml"); + + if (configFiles.Length == 0) + { + string path2 = Path.Combine(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.InternalEndPoint.Port, this.AssetCache, this.InventoryCache, this.m_log, authenBase); + + m_udpServer.Add(udpServer); + this.regionData.Add(regionDat); + + StorageManager tmpStoreManager = new StorageManager("OpenSim.DataStore.NullStorage.dll", regionDat.DataStore, regionDat.RegionName); + + scene = new Scene( regionDat, authenBase, commsManager, this.AssetCache, tmpStoreManager, httpServer); + this.m_localWorld.Add(scene); + + udpServer.LocalWorld = scene; + + scene.LoadStorageDLL("OpenSim.Region.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded. + scene.LoadWorldMap(); + + m_log.Verbose("Main.cs:Startup() - Starting up messaging system"); + scene.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); + scene.PhysScene.SetTerrain(scene.Terrain.getHeights1D()); + scene.LoadPrimsFromStorage(); + + //Master Avatar Setup + UserProfileData masterAvatar = commsManager.UserServer.SetupMasterUser(scene.RegionInfo.MasterAvatarFirstName, scene.RegionInfo.MasterAvatarLastName, scene.RegionInfo.MasterAvatarSandboxPassword); + if (masterAvatar != null) + { + m_log.Notice("Parcels - Found master avatar [" + masterAvatar.UUID.ToStringHyphenated() + "]"); + scene.RegionInfo.MasterAvatarAssignedUUID = masterAvatar.UUID; + scene.localStorage.LoadParcels((ILocalStorageParcelReceiver)scene.ParcelManager); + } + else + { + m_log.Notice("Parcels - No master avatar found, using null."); + scene.RegionInfo.MasterAvatarAssignedUUID = libsecondlife.LLUUID.Zero; + scene.localStorage.LoadParcels((ILocalStorageParcelReceiver)scene.ParcelManager); + } + scene.performParcelPrimCountUpdate(); + scene.StartTimer(); + } + } + + private class SimStatusHandler : IStreamHandler + { + public byte[] Handle(string path, Stream request) + { + return Encoding.UTF8.GetBytes("OK"); + } + + public string ContentType + { + get { return "text/plain"; } + } + + public string HttpMethod + { + get { return "GET"; } + } + + public string Path + { + get { return "/simstatus/"; } + } + } + + protected override void SetupHttpListener() + { + httpServer = new BaseHttpServer(this.serversData.HttpListenerPort); //regionData[0].IPListenPort); + + if (!this.m_sandbox) + { + httpServer.AddStreamHandler( new SimStatusHandler() ); + } + } + + 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"); + ScenePresence.PhysicsEngineFlying = false; + break; + + case "basicphysics": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + ScenePresence.PhysicsEngineFlying = false; + break; + + case "RealPhysX": + this.m_physicsEngine = "RealPhysX"; + ScenePresence.PhysicsEngineFlying = true; + break; + + case "OpenDynamicsEngine": + this.m_physicsEngine = "OpenDynamicsEngine"; + ScenePresence.PhysicsEngineFlying = true; + break; + + case "BulletXEngine": + this.m_physicsEngine = "BulletXEngine"; + 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("quit - 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_localWorld[i].RegionInfo.RegionName)) + { + m_log.Error(result); + } + } + break; + case "script": + for (int i = 0; i < m_localWorld.Count; i++) + { + ((Scene)m_localWorld[i]).SendCommandToScripts(cmdparams); + } + break; + + case "quit": + 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": + ScenePresence TempAv; + m_log.Error(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP", "World")); + for (int i = 0; i < m_localWorld.Count; i++) + { + foreach (libsecondlife.LLUUID UUID in ((Scene)m_localWorld[i]).Entities.Keys) + { + if (((Scene)m_localWorld[i]).Entities[UUID].ToString() == "OpenSim.world.Avatar") + { + TempAv = (ScenePresence)((Scene)m_localWorld[i]).Entities[UUID]; + m_log.Error(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.AgentId, "Unknown", "Unknown"), ((Scene)m_localWorld[i]).RegionInfo.RegionName); + } + } + } + break; + } + } + #endregion + } + + +} diff --git a/OpenSim/Region/Application/VersionInfo.cs b/OpenSim/Region/Application/VersionInfo.cs index 2c720a3..6952d24 100644 --- a/OpenSim/Region/Application/VersionInfo.cs +++ b/OpenSim/Region/Application/VersionInfo.cs @@ -1,36 +1,36 @@ -/* -* 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. -* -*/ -namespace OpenSim -{ - /// - /// - public class VersionInfo - { - public static string Version = "0.3, SVN build "; - } -} +/* +* 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. +* +*/ +namespace OpenSim +{ + /// + /// + public class VersionInfo + { + public static string Version = "0.3, SVN build "; + } +} diff --git a/OpenSim/Region/Caches/AssetCache.cs b/OpenSim/Region/Caches/AssetCache.cs index 453edbe..8deb0a1 100644 --- a/OpenSim/Region/Caches/AssetCache.cs +++ b/OpenSim/Region/Caches/AssetCache.cs @@ -1,669 +1,669 @@ -/* -* 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.Reflection; -using System.Threading; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.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(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); - } - - } - } - } -} - +/* +* 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.Reflection; +using System.Threading; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.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(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/Properties/AssemblyInfo.cs b/OpenSim/Region/Caches/Properties/AssemblyInfo.cs index 8389415..4ba42b9 100644 --- a/OpenSim/Region/Caches/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Caches/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Region.Caches")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.Region.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")] +using System.Reflection; +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.Region.Caches")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Region.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/Capabilities/Caps.cs b/OpenSim/Region/Capabilities/Caps.cs index 7acbf8e..d2ef526 100644 --- a/OpenSim/Region/Capabilities/Caps.cs +++ b/OpenSim/Region/Capabilities/Caps.cs @@ -1,313 +1,313 @@ -/* -* 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.IO; -using libsecondlife; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; -using OpenSim.Region.Caches; - -namespace OpenSim.Region.Capabilities -{ - public delegate void UpLoadedTexture(LLUUID assetID, LLUUID inventoryItem, byte[] data); - - public class Caps - { - private string m_httpListenerHostName; - private int m_httpListenPort; - private string m_capsObjectPath = "00001-"; - private string m_requestPath = "0000/"; - private string m_mapLayerPath = "0001/"; - private string m_newInventory = "0002/"; - // private string m_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, int httpPort, string capsPath, LLUUID agent) - { - assetCache = assetCach; - m_capsObjectPath = capsPath; - httpListener = httpServer; - m_httpListenerHostName = httpListen; - m_httpListenPort = httpPort; - agentID = agent; - } - - /// - /// - /// - public void RegisterHandlers() - { - Console.WriteLine("registering CAPS handlers"); - string capsBase = "/CAPS/" + m_capsObjectPath; - - httpListener.AddStreamHandler(new LLSDStreamhandler("POST", capsBase + m_mapLayerPath, this.GetMapLayer )); - httpListener.AddStreamHandler( new LLSDStreamhandler("POST", capsBase + m_newInventory, this.NewAgentInventoryRequest)); - - AddLegacyCapsHandler(httpListener, m_requestPath, CapsRequest); - // AddLegacyCapsHandler( httpListener, eventQueue, ProcessEventQueue); - // AddLegacyCapsHandler( httpListener, m_requestTexture, RequestTexture); - } - - [Obsolete("Use BaseHttpServer.AddStreamHandler(new LLSDStreamHandler( LLSDMethod delegate )) instead.")] - private void AddLegacyCapsHandler(BaseHttpServer httpListener, string path, RestMethod restMethod) - { - string capsBase = "/CAPS/" + m_capsObjectPath; - httpListener.AddStreamHandler(new RestStreamHandler("POST", capsBase + path, restMethod)); - } - - /// - /// - /// - /// - /// - /// - /// - public string CapsRequest(string request, string path, string param) - { - // Console.WriteLine("caps request " + request); - string result = LLSDHelpers.SerialiseLLSDReply(this.GetCapabilities()); - return result; - } - - /// - /// - /// - /// - protected LLSDCapsDetails GetCapabilities() - { - LLSDCapsDetails caps = new LLSDCapsDetails(); - string capsBaseUrl = "http://" + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + "/CAPS/" + m_capsObjectPath; - caps.MapLayer = capsBaseUrl + m_mapLayerPath; - caps.NewFileAgentInventory = capsBaseUrl + m_newInventory; - //caps.RequestTextureDownload = capsBaseUrl + m_requestTexture; - // caps.ChatSessionRequest = capsBaseUrl + m_requestTexture; - return caps; - } - - /// - /// - /// - /// - /// - public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) - { - LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); - mapResponse.LayerData.Array.Add(this.GetLLSDMapLayerResponse()); - return mapResponse; - } - - /// - /// - /// - /// - protected LLSDMapLayer GetLLSDMapLayerResponse() - { - LLSDMapLayer mapLayer = new LLSDMapLayer(); - mapLayer.Right = 5000; - mapLayer.Top = 5000; - mapLayer.ImageID = new LLUUID("00000000-0000-0000-9999-000000000006"); - return mapLayer; - } - - /// - /// - /// - /// - /// - /// - /// - public string RequestTexture(string request, string path, string param) - { - Console.WriteLine("texture request " + request); - // Needs implementing (added to remove compiler warning) - return ""; - } - - #region EventQueue (Currently not enabled) - /// - /// - /// - /// - /// - /// - /// - public string ProcessEventQueue(string request, string path, string param) - { - string res = ""; - - 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) - { - LLSDCapEvent eventItem = new LLSDCapEvent(); - eventItem.id = eventQueueCount; - //should be creating a EstablishAgentComms item, but there isn't a class for it yet - eventItem.events.Array.Add(new LLSDEmpty()); - string res = LLSDHelpers.SerialiseLLSDReply(eventItem); - eventQueueCount++; - - this.CapsEventQueue.Enqueue(res); - return res; - } - - /// - /// - /// - /// - public string CreateEmptyEventResponse() - { - LLSDCapEvent eventItem = new LLSDCapEvent(); - eventItem.id = eventQueueCount; - eventItem.events.Array.Add(new LLSDEmpty()); - string res = LLSDHelpers.SerialiseLLSDReply(eventItem); - eventQueueCount++; - return res; - } - #endregion - - /// - /// - /// - /// - /// - public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest) - { - string capsBase = "/CAPS/" + m_capsObjectPath; - LLUUID newAsset = LLUUID.Random(); - LLUUID newInvItem = LLUUID.Random(); - string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000"); - - AssetUploader uploader = new AssetUploader(newAsset, newInvItem, capsBase + uploaderPath, this.httpListener); - httpListener.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps)); - string uploaderURL = "http://" + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase + uploaderPath; - - LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse(); - uploadResponse.uploader = uploaderURL; - uploadResponse.state = "upload"; - uploader.OnUpLoad += this.UploadCompleteHandler; - return uploadResponse; - } - - /// - /// - /// - /// - /// - /// - public void UploadCompleteHandler(LLUUID assetID, LLUUID inventoryItem, byte[] data) - { - 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(byte[] data, string path, string param) - { - LLUUID inv = this.inventoryItemID; - string res = ""; - LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); - uploadComplete.new_asset = newAssetID.ToStringHyphenated(); - uploadComplete.new_inventory_item = inv; - uploadComplete.state = "complete"; - res = LLSDHelpers.SerialiseLLSDReply(uploadComplete); - - httpListener.RemoveStreamHandler("POST", uploaderPath); - - if (OnUpLoad != null) - { - OnUpLoad(newAssetID, inv, data); - } - return res; - } - } - } -} +/* +* 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.IO; +using libsecondlife; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using OpenSim.Region.Caches; + +namespace OpenSim.Region.Capabilities +{ + public delegate void UpLoadedTexture(LLUUID assetID, LLUUID inventoryItem, byte[] data); + + public class Caps + { + private string m_httpListenerHostName; + private int m_httpListenPort; + private string m_capsObjectPath = "00001-"; + private string m_requestPath = "0000/"; + private string m_mapLayerPath = "0001/"; + private string m_newInventory = "0002/"; + // private string m_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, int httpPort, string capsPath, LLUUID agent) + { + assetCache = assetCach; + m_capsObjectPath = capsPath; + httpListener = httpServer; + m_httpListenerHostName = httpListen; + m_httpListenPort = httpPort; + agentID = agent; + } + + /// + /// + /// + public void RegisterHandlers() + { + Console.WriteLine("registering CAPS handlers"); + string capsBase = "/CAPS/" + m_capsObjectPath; + + httpListener.AddStreamHandler(new LLSDStreamhandler("POST", capsBase + m_mapLayerPath, this.GetMapLayer )); + httpListener.AddStreamHandler( new LLSDStreamhandler("POST", capsBase + m_newInventory, this.NewAgentInventoryRequest)); + + AddLegacyCapsHandler(httpListener, m_requestPath, CapsRequest); + // AddLegacyCapsHandler( httpListener, eventQueue, ProcessEventQueue); + // AddLegacyCapsHandler( httpListener, m_requestTexture, RequestTexture); + } + + [Obsolete("Use BaseHttpServer.AddStreamHandler(new LLSDStreamHandler( LLSDMethod delegate )) instead.")] + private void AddLegacyCapsHandler(BaseHttpServer httpListener, string path, RestMethod restMethod) + { + string capsBase = "/CAPS/" + m_capsObjectPath; + httpListener.AddStreamHandler(new RestStreamHandler("POST", capsBase + path, restMethod)); + } + + /// + /// + /// + /// + /// + /// + /// + public string CapsRequest(string request, string path, string param) + { + // Console.WriteLine("caps request " + request); + string result = LLSDHelpers.SerialiseLLSDReply(this.GetCapabilities()); + return result; + } + + /// + /// + /// + /// + protected LLSDCapsDetails GetCapabilities() + { + LLSDCapsDetails caps = new LLSDCapsDetails(); + string capsBaseUrl = "http://" + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + "/CAPS/" + m_capsObjectPath; + caps.MapLayer = capsBaseUrl + m_mapLayerPath; + caps.NewFileAgentInventory = capsBaseUrl + m_newInventory; + //caps.RequestTextureDownload = capsBaseUrl + m_requestTexture; + // caps.ChatSessionRequest = capsBaseUrl + m_requestTexture; + return caps; + } + + /// + /// + /// + /// + /// + public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) + { + LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); + mapResponse.LayerData.Array.Add(this.GetLLSDMapLayerResponse()); + return mapResponse; + } + + /// + /// + /// + /// + protected LLSDMapLayer GetLLSDMapLayerResponse() + { + LLSDMapLayer mapLayer = new LLSDMapLayer(); + mapLayer.Right = 5000; + mapLayer.Top = 5000; + mapLayer.ImageID = new LLUUID("00000000-0000-0000-9999-000000000006"); + return mapLayer; + } + + /// + /// + /// + /// + /// + /// + /// + public string RequestTexture(string request, string path, string param) + { + Console.WriteLine("texture request " + request); + // Needs implementing (added to remove compiler warning) + return ""; + } + + #region EventQueue (Currently not enabled) + /// + /// + /// + /// + /// + /// + /// + public string ProcessEventQueue(string request, string path, string param) + { + string res = ""; + + 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) + { + LLSDCapEvent eventItem = new LLSDCapEvent(); + eventItem.id = eventQueueCount; + //should be creating a EstablishAgentComms item, but there isn't a class for it yet + eventItem.events.Array.Add(new LLSDEmpty()); + string res = LLSDHelpers.SerialiseLLSDReply(eventItem); + eventQueueCount++; + + this.CapsEventQueue.Enqueue(res); + return res; + } + + /// + /// + /// + /// + public string CreateEmptyEventResponse() + { + LLSDCapEvent eventItem = new LLSDCapEvent(); + eventItem.id = eventQueueCount; + eventItem.events.Array.Add(new LLSDEmpty()); + string res = LLSDHelpers.SerialiseLLSDReply(eventItem); + eventQueueCount++; + return res; + } + #endregion + + /// + /// + /// + /// + /// + public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest) + { + string capsBase = "/CAPS/" + m_capsObjectPath; + LLUUID newAsset = LLUUID.Random(); + LLUUID newInvItem = LLUUID.Random(); + string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000"); + + AssetUploader uploader = new AssetUploader(newAsset, newInvItem, capsBase + uploaderPath, this.httpListener); + httpListener.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps)); + string uploaderURL = "http://" + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase + uploaderPath; + + LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse(); + uploadResponse.uploader = uploaderURL; + uploadResponse.state = "upload"; + uploader.OnUpLoad += this.UploadCompleteHandler; + return uploadResponse; + } + + /// + /// + /// + /// + /// + /// + public void UploadCompleteHandler(LLUUID assetID, LLUUID inventoryItem, byte[] data) + { + 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(byte[] data, string path, string param) + { + LLUUID inv = this.inventoryItemID; + string res = ""; + LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); + uploadComplete.new_asset = newAssetID.ToStringHyphenated(); + uploadComplete.new_inventory_item = inv; + uploadComplete.state = "complete"; + res = LLSDHelpers.SerialiseLLSDReply(uploadComplete); + + httpListener.RemoveStreamHandler("POST", uploaderPath); + + if (OnUpLoad != null) + { + OnUpLoad(newAssetID, inv, data); + } + return res; + } + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDArray.cs b/OpenSim/Region/Capabilities/LLSDArray.cs index e04849f..d3e1979 100644 --- a/OpenSim/Region/Capabilities/LLSDArray.cs +++ b/OpenSim/Region/Capabilities/LLSDArray.cs @@ -1,42 +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.Collections; - -namespace OpenSim.Region.Capabilities -{ - [LLSDType("ARRAY")] - public class LLSDArray - { - public ArrayList Array = new ArrayList(); - - public LLSDArray() - { - - } - } -} +/* +* 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.Collections; + +namespace OpenSim.Region.Capabilities +{ + [LLSDType("ARRAY")] + public class LLSDArray + { + public ArrayList Array = new ArrayList(); + + public LLSDArray() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDAssetUploadComplete.cs b/OpenSim/Region/Capabilities/LLSDAssetUploadComplete.cs index 1b78353..5718b8f 100644 --- a/OpenSim/Region/Capabilities/LLSDAssetUploadComplete.cs +++ b/OpenSim/Region/Capabilities/LLSDAssetUploadComplete.cs @@ -1,44 +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 libsecondlife; - -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDAssetUploadComplete - { - public string new_asset = ""; - public LLUUID new_inventory_item = LLUUID.Zero; - public string state = ""; - - public LLSDAssetUploadComplete() - { - - } - } -} +/* +* 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 libsecondlife; + +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDAssetUploadComplete + { + public string new_asset = ""; + public LLUUID new_inventory_item = LLUUID.Zero; + public string state = ""; + + public LLSDAssetUploadComplete() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDAssetUploadRequest.cs b/OpenSim/Region/Capabilities/LLSDAssetUploadRequest.cs index 7ef77cb..0096fb1 100644 --- a/OpenSim/Region/Capabilities/LLSDAssetUploadRequest.cs +++ b/OpenSim/Region/Capabilities/LLSDAssetUploadRequest.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; -using libsecondlife; - -namespace OpenSim.Region.Capabilities -{ - [LLSDMap] - public class LLSDAssetUploadRequest - { - public string asset_type = ""; - public string description = ""; - public LLUUID folder_id = LLUUID.Zero; - public string inventory_type = ""; - public string name = ""; - - public LLSDAssetUploadRequest() - { - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.Region.Capabilities +{ + [LLSDMap] + public class LLSDAssetUploadRequest + { + public string asset_type = ""; + public string description = ""; + public LLUUID folder_id = LLUUID.Zero; + public string inventory_type = ""; + public string name = ""; + + public LLSDAssetUploadRequest() + { + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDAssetUploadResponse.cs b/OpenSim/Region/Capabilities/LLSDAssetUploadResponse.cs index 1a620ae..2a2a5d1 100644 --- a/OpenSim/Region/Capabilities/LLSDAssetUploadResponse.cs +++ b/OpenSim/Region/Capabilities/LLSDAssetUploadResponse.cs @@ -1,18 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Capabilities -{ - [LLSDMap] - public class LLSDAssetUploadResponse - { - public string uploader = ""; - public string state = ""; - - public LLSDAssetUploadResponse() - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Capabilities +{ + [LLSDMap] + public class LLSDAssetUploadResponse + { + public string uploader = ""; + public string state = ""; + + public LLSDAssetUploadResponse() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDCapEvent.cs b/OpenSim/Region/Capabilities/LLSDCapEvent.cs index 51b4fe0..2c2689b 100644 --- a/OpenSim/Region/Capabilities/LLSDCapEvent.cs +++ b/OpenSim/Region/Capabilities/LLSDCapEvent.cs @@ -1,41 +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. -* -*/ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDCapEvent - { - public int id = 0; - public LLSDArray events = new LLSDArray(); - - public LLSDCapEvent() - { - - } - } -} +/* +* 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. +* +*/ +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDCapEvent + { + public int id = 0; + public LLSDArray events = new LLSDArray(); + + public LLSDCapEvent() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDCapsDetails.cs b/OpenSim/Region/Capabilities/LLSDCapsDetails.cs index ecb2328..132b8f7 100644 --- a/OpenSim/Region/Capabilities/LLSDCapsDetails.cs +++ b/OpenSim/Region/Capabilities/LLSDCapsDetails.cs @@ -1,17 +1,17 @@ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDCapsDetails - { - public string MapLayer = ""; - public string NewFileAgentInventory = ""; - //public string EventQueueGet = ""; - //public string RequestTextureDownload = ""; - //public string ChatSessionRequest = ""; - - public LLSDCapsDetails() - { - - } - } -} +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDCapsDetails + { + public string MapLayer = ""; + public string NewFileAgentInventory = ""; + //public string EventQueueGet = ""; + //public string RequestTextureDownload = ""; + //public string ChatSessionRequest = ""; + + public LLSDCapsDetails() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDEmpty.cs b/OpenSim/Region/Capabilities/LLSDEmpty.cs index d79c09e..ca27c9d 100644 --- a/OpenSim/Region/Capabilities/LLSDEmpty.cs +++ b/OpenSim/Region/Capabilities/LLSDEmpty.cs @@ -1,38 +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. -* -*/ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDEmpty - { - public LLSDEmpty() - { - - } - } -} +/* +* 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. +* +*/ +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDEmpty + { + public LLSDEmpty() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDHelpers.cs b/OpenSim/Region/Capabilities/LLSDHelpers.cs index 19ef0c9..efeb9b1 100644 --- a/OpenSim/Region/Capabilities/LLSDHelpers.cs +++ b/OpenSim/Region/Capabilities/LLSDHelpers.cs @@ -1,164 +1,164 @@ -/* -* 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.IO; -using System.Reflection; -using System.Xml; -using libsecondlife; - -namespace OpenSim.Region.Capabilities -{ - 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); - 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); - 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 - { - 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); - if (a != null) - { - 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()) - { - 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; - } - } - - - - - - - - - - - - - - - - - - - -} +/* +* 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.IO; +using System.Reflection; +using System.Xml; +using libsecondlife; + +namespace OpenSim.Region.Capabilities +{ + 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); + 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); + 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 + { + 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); + if (a != null) + { + 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()) + { + 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; + } + } + + + + + + + + + + + + + + + + + + + +} diff --git a/OpenSim/Region/Capabilities/LLSDMapLayer.cs b/OpenSim/Region/Capabilities/LLSDMapLayer.cs index 566d0e9..e0c006c 100644 --- a/OpenSim/Region/Capabilities/LLSDMapLayer.cs +++ b/OpenSim/Region/Capabilities/LLSDMapLayer.cs @@ -1,46 +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 libsecondlife; - -namespace OpenSim.Region.Capabilities -{ - [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() - { - - } - } -} +/* +* 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 libsecondlife; + +namespace OpenSim.Region.Capabilities +{ + [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() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDMapLayerResponse.cs b/OpenSim/Region/Capabilities/LLSDMapLayerResponse.cs index ce746ae..8b9837b 100644 --- a/OpenSim/Region/Capabilities/LLSDMapLayerResponse.cs +++ b/OpenSim/Region/Capabilities/LLSDMapLayerResponse.cs @@ -1,41 +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. -* -*/ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDMapLayerResponse - { - public LLSDMapRequest AgentData = new LLSDMapRequest(); - public LLSDArray LayerData = new LLSDArray(); - - public LLSDMapLayerResponse() - { - - } - } -} +/* +* 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. +* +*/ +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDMapLayerResponse + { + public LLSDMapRequest AgentData = new LLSDMapRequest(); + public LLSDArray LayerData = new LLSDArray(); + + public LLSDMapLayerResponse() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDMapRequest.cs b/OpenSim/Region/Capabilities/LLSDMapRequest.cs index fb739cd..8ac7943 100644 --- a/OpenSim/Region/Capabilities/LLSDMapRequest.cs +++ b/OpenSim/Region/Capabilities/LLSDMapRequest.cs @@ -1,13 +1,13 @@ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDMapRequest - { - public int Flags = 0; - - public LLSDMapRequest() - { - - } - } -} +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDMapRequest + { + public int Flags = 0; + + public LLSDMapRequest() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDMethod.cs b/OpenSim/Region/Capabilities/LLSDMethod.cs index 5f42f44..068d539 100644 --- a/OpenSim/Region/Capabilities/LLSDMethod.cs +++ b/OpenSim/Region/Capabilities/LLSDMethod.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Capabilities -{ - public delegate TResponse LLSDMethod(TRequest request); -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Capabilities +{ + public delegate TResponse LLSDMethod(TRequest request); +} diff --git a/OpenSim/Region/Capabilities/LLSDStreamHandler.cs b/OpenSim/Region/Capabilities/LLSDStreamHandler.cs index 7d99b6e..d98e23f 100644 --- a/OpenSim/Region/Capabilities/LLSDStreamHandler.cs +++ b/OpenSim/Region/Capabilities/LLSDStreamHandler.cs @@ -1,42 +1,42 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Framework.Servers; -using System.IO; -using System.Collections; -using libsecondlife; - -namespace OpenSim.Region.Capabilities -{ - public class LLSDStreamhandler : BaseStreamHandler - where TRequest : new() - { - private LLSDMethod m_method; - - public LLSDStreamhandler(string httpMethod, string path, LLSDMethod method) - : base(httpMethod, path ) - { - m_method = method; - } - - public override byte[] Handle(string path, Stream request) - { - //Encoding encoding = Encoding.UTF8; - //StreamReader streamReader = new StreamReader(request, false); - - //string requestBody = streamReader.ReadToEnd(); - //streamReader.Close(); - - Hashtable hash = (Hashtable)LLSD.LLSDDeserialize( request ); - TRequest llsdRequest = new TRequest(); - LLSDHelpers.DeserialiseLLSDMap(hash, llsdRequest); - - TResponse response = m_method(llsdRequest); - - Encoding encoding = new UTF8Encoding(false); - - return encoding.GetBytes( LLSDHelpers.SerialiseLLSDReply(response) ); - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Servers; +using System.IO; +using System.Collections; +using libsecondlife; + +namespace OpenSim.Region.Capabilities +{ + public class LLSDStreamhandler : BaseStreamHandler + where TRequest : new() + { + private LLSDMethod m_method; + + public LLSDStreamhandler(string httpMethod, string path, LLSDMethod method) + : base(httpMethod, path ) + { + m_method = method; + } + + public override byte[] Handle(string path, Stream request) + { + //Encoding encoding = Encoding.UTF8; + //StreamReader streamReader = new StreamReader(request, false); + + //string requestBody = streamReader.ReadToEnd(); + //streamReader.Close(); + + Hashtable hash = (Hashtable)LLSD.LLSDDeserialize( request ); + TRequest llsdRequest = new TRequest(); + LLSDHelpers.DeserialiseLLSDMap(hash, llsdRequest); + + TResponse response = m_method(llsdRequest); + + Encoding encoding = new UTF8Encoding(false); + + return encoding.GetBytes( LLSDHelpers.SerialiseLLSDReply(response) ); + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDTest.cs b/OpenSim/Region/Capabilities/LLSDTest.cs index f23e327..78ccf67 100644 --- a/OpenSim/Region/Capabilities/LLSDTest.cs +++ b/OpenSim/Region/Capabilities/LLSDTest.cs @@ -1,41 +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. -* -*/ -namespace OpenSim.Region.Capabilities -{ - [LLSDType("MAP")] - public class LLSDTest - { - public int Test1 = 20; - public int Test2 = 10; - - public LLSDTest() - { - - } - } -} +/* +* 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. +* +*/ +namespace OpenSim.Region.Capabilities +{ + [LLSDType("MAP")] + public class LLSDTest + { + public int Test1 = 20; + public int Test2 = 10; + + public LLSDTest() + { + + } + } +} diff --git a/OpenSim/Region/Capabilities/LLSDType.cs b/OpenSim/Region/Capabilities/LLSDType.cs index c58a937..04f4d9a 100644 --- a/OpenSim/Region/Capabilities/LLSDType.cs +++ b/OpenSim/Region/Capabilities/LLSDType.cs @@ -1,59 +1,59 @@ -/* -* 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.Region.Capabilities -{ - [AttributeUsage(AttributeTargets.Class)] - public class LLSDType : Attribute - { - protected string myType; - - public LLSDType(string type) - { - myType = type; - - } - - public string ObjectType - { - get - { - return myType; - } - } - } - - [AttributeUsage(AttributeTargets.Class)] - public class LLSDMap : LLSDType - { - public LLSDMap() : base( "MAP" ) - { - } - } -} +/* +* 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.Region.Capabilities +{ + [AttributeUsage(AttributeTargets.Class)] + public class LLSDType : Attribute + { + protected string myType; + + public LLSDType(string type) + { + myType = type; + + } + + public string ObjectType + { + get + { + return myType; + } + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class LLSDMap : LLSDType + { + public LLSDMap() : base( "MAP" ) + { + } + } +} diff --git a/OpenSim/Region/ClientStack/Assets/InventoryCache.cs b/OpenSim/Region/ClientStack/Assets/InventoryCache.cs index e2cfa46..1bb6c07 100644 --- a/OpenSim/Region/ClientStack/Assets/InventoryCache.cs +++ b/OpenSim/Region/ClientStack/Assets/InventoryCache.cs @@ -1,338 +1,338 @@ -/* -* 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.Inventory; -using OpenSim.Framework.Types; -using OpenSim.Region.ClientStack; - -namespace OpenSim.Assets -{ - /// - /// Description of InventoryManager. - /// - public class InventoryCache - { - private Dictionary _agentsInventory; - private List _serverRequests; //list of requests made to user server. - private Encoding _enc = 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, 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, 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 = 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 = 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 = 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() - { - - } - } -} +/* +* 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.Inventory; +using OpenSim.Framework.Types; +using OpenSim.Region.ClientStack; + +namespace OpenSim.Assets +{ + /// + /// Description of InventoryManager. + /// + public class InventoryCache + { + private Dictionary _agentsInventory; + private List _serverRequests; //list of requests made to user server. + private Encoding _enc = 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, 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, 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 = 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 = 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 = 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 index f4e537c..e3ad9d0 100644 --- a/OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs +++ b/OpenSim/Region/ClientStack/ClientStackNetworkHandler.cs @@ -1,40 +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.Net.Sockets; - -namespace OpenSim.Region.ClientStack -{ - - public interface ClientStackNetworkHandler - { - void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode);// EndPoint packetSender); - void RemoveClientCircuit(uint circuitcode); - void RegisterPacketServer(PacketServer server); - } - -} +/* +* 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.Net.Sockets; + +namespace OpenSim.Region.ClientStack +{ + + 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 index 33e34c1..2ac1000 100644 --- a/OpenSim/Region/ClientStack/ClientView.API.cs +++ b/OpenSim/Region/ClientStack/ClientView.API.cs @@ -1,1180 +1,1180 @@ -/* -* 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 Axiom.Math; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Data; - -namespace OpenSim.Region.ClientStack -{ - partial class ClientView - { - public event ImprovedInstantMessage OnInstantMessage; - 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 ObjectDuplicate OnObjectDuplicate; - public event MoveObject OnGrapUpdate; - public event AddNewPrim OnAddPrim; - public event UpdateShape OnUpdatePrimShape; - public event ObjectSelect OnObjectSelect; - public event ObjectDeselect OnObjectDeselect; - public event GenericCall7 OnObjectDescription; - public event GenericCall7 OnObjectName; - public event UpdatePrimFlags OnUpdatePrimFlags; - public event UpdatePrimTexture OnUpdatePrimTexture; - public event UpdateVector OnUpdatePrimGroupPosition; - public event UpdateVector OnUpdatePrimSinglePosition; - public event UpdatePrimRotation OnUpdatePrimGroupRotation; - public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; - public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; - 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 UUIDNameRequest OnNameFromUUIDRequest; - - public event ParcelPropertiesRequest OnParcelPropertiesRequest; - public event ParcelDivideRequest OnParcelDivideRequest; - public event ParcelJoinRequest OnParcelJoinRequest; - public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; - public event ParcelSelectObjects OnParcelSelectObjects; - public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; - 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) - { - Encoding _enc = 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) - { - Encoding enc = Encoding.ASCII; - 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); - } - - /// - /// - /// - /// TODO - /// - /// - public void SendInstantMessage(string message, LLUUID target, string fromName) - { - if (message != "typing") - { - Encoding enc = Encoding.ASCII; - ImprovedInstantMessagePacket msg = new ImprovedInstantMessagePacket(); - msg.AgentData.AgentID = this.AgentID; - msg.AgentData.SessionID = this.SessionID; - msg.MessageBlock.FromAgentName = enc.GetBytes(fromName + " \0"); - msg.MessageBlock.Dialog = 0; - msg.MessageBlock.FromGroup = false; - msg.MessageBlock.ID = target.Combine(this.SecureSessionID); - msg.MessageBlock.Offline = 0; - msg.MessageBlock.ParentEstateID = 0; - msg.MessageBlock.Position = new LLVector3(); - msg.MessageBlock.RegionID = new LLUUID(); - msg.MessageBlock.Timestamp = 0; - msg.MessageBlock.ToAgentID = target; - msg.MessageBlock.Message = enc.GetBytes(message + "\0"); - msg.MessageBlock.BinaryBucket = new byte[0]; - - this.OutPacket(msg); - } - } - - /// - /// 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) - { - 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) - { - MainLog.Instance.Warn("ClientView API .cs: SendLayerData() - Failed with exception " + e.ToString()); - } - } - - /// - /// - /// - /// - /// - /// - public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourEndPoint) - { - IPAddress neighbourIP = neighbourEndPoint.Address; - ushort neighbourPort = (ushort)neighbourEndPoint.Port; - - 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, IPEndPoint externalIPEndPoint) - { - 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 CrossedRegionPacket.RegionDataBlock(); - newSimPack.RegionData.RegionHandle = newRegionHandle; - byte[] byteIP = externalIPEndPoint.Address.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 = (ushort)externalIPEndPoint.Port; - newSimPack.RegionData.SeedCapability = new byte[0]; - - this.OutPacket(newSimPack); - //this.DowngradeClient(); - } - - public void SendMapBlock(List mapBlocks) - { - 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 = Helpers.StringToField(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, IPEndPoint newRegionEndPoint, 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]; - - IPAddress oIP = newRegionEndPoint.Address; - 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 = (ushort)newRegionEndPoint.Port; - 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); - } - - public void SendStartPingCheck(byte seq) - { - StartPingCheckPacket pc = new StartPingCheckPacket(); - pc.PingID.PingID = seq; - OutPacket(pc); - } - - public void SendKillObject(ulong regionHandle, uint avatarLocalID) - { - KillObjectPacket kill = new KillObjectPacket(); - kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; - kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); - kill.ObjectData[0].ID = avatarLocalID; - OutPacket(kill); - } - - public void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items) - { - Encoding enc = Encoding.ASCII; - uint FULL_MASK_PERMISSIONS = 2147483647; - InventoryDescendentsPacket descend = new InventoryDescendentsPacket(); - descend.AgentData.AgentID = this.AgentId; - descend.AgentData.OwnerID = ownerID; - descend.AgentData.FolderID = folderID; - descend.AgentData.Descendents = items.Count; - descend.AgentData.Version = 0; - descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[items.Count]; - int i = 0; - foreach (InventoryItemBase item in items) - { - descend.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock(); - descend.ItemData[i].ItemID = item.inventoryID; - descend.ItemData[i].AssetID = item.assetID; - descend.ItemData[i].CreatorID = item.creatorsID; - descend.ItemData[i].BaseMask = FULL_MASK_PERMISSIONS; - descend.ItemData[i].CreationDate = 1000; - descend.ItemData[i].Description = enc.GetBytes(item.inventoryDescription+ "\0"); - descend.ItemData[i].EveryoneMask = FULL_MASK_PERMISSIONS; - descend.ItemData[i].Flags = 1; - descend.ItemData[i].FolderID = item.parentFolderID; - descend.ItemData[i].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); - descend.ItemData[i].GroupMask = FULL_MASK_PERMISSIONS; - descend.ItemData[i].InvType = (sbyte)item.type; - descend.ItemData[i].Name = enc.GetBytes(item.inventoryName+ "\0"); - descend.ItemData[i].NextOwnerMask = FULL_MASK_PERMISSIONS; - descend.ItemData[i].OwnerID = item.avatarID; - descend.ItemData[i].OwnerMask = FULL_MASK_PERMISSIONS; - descend.ItemData[i].SalePrice = 0; - descend.ItemData[i].SaleType = 0; - descend.ItemData[i].Type = (sbyte)item.type; - descend.ItemData[i].CRC = 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); - - i++; - } - - this.OutPacket(descend); - - } - - public void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item) - { - Encoding enc = Encoding.ASCII; - uint FULL_MASK_PERMISSIONS = 2147483647; - FetchInventoryReplyPacket inventoryReply = new FetchInventoryReplyPacket(); - inventoryReply.AgentData.AgentID = this.AgentId; - inventoryReply.InventoryData = new FetchInventoryReplyPacket.InventoryDataBlock[1]; - inventoryReply.InventoryData[0] = new FetchInventoryReplyPacket.InventoryDataBlock(); - inventoryReply.InventoryData[0].ItemID = item.inventoryID; - inventoryReply.InventoryData[0].AssetID = item.assetID; - inventoryReply.InventoryData[0].CreatorID = item.creatorsID; - 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.inventoryDescription + "\0"); - inventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; - inventoryReply.InventoryData[0].Flags = 0; - inventoryReply.InventoryData[0].FolderID = item.parentFolderID; - inventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); - inventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; - inventoryReply.InventoryData[0].InvType = (sbyte)item.type; - inventoryReply.InventoryData[0].Name = enc.GetBytes(item.inventoryName + "\0"); - inventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; - inventoryReply.InventoryData[0].OwnerID = item.avatarID; - inventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; - inventoryReply.InventoryData[0].SalePrice = 0; - inventoryReply.InventoryData[0].SaleType = 0; - inventoryReply.InventoryData[0].Type = (sbyte)item.type; - inventoryReply.InventoryData[0].CRC = 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); - - this.OutPacket(inventoryReply); - } - - #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); - } - - public void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId) - { - AvatarAnimationPacket ani = new AvatarAnimationPacket(); - ani.AnimationSourceList = new AvatarAnimationPacket.AnimationSourceListBlock[1]; - ani.AnimationSourceList[0] = new AvatarAnimationPacket.AnimationSourceListBlock(); - ani.AnimationSourceList[0].ObjectID = sourceAgentId; - ani.Sender = new AvatarAnimationPacket.SenderBlock(); - ani.Sender.ID = sourceAgentId; - ani.AnimationList = new AvatarAnimationPacket.AnimationListBlock[1]; - ani.AnimationList[0] = new AvatarAnimationPacket.AnimationListBlock(); - ani.AnimationList[0].AnimID = animID; - ani.AnimationList[0].AnimSequenceID = seq; - this.OutPacket(ani); - } - - #endregion - - #region Avatar Packet/data sending Methods - - /// - /// send a objectupdate packet with information about the clients avatar - /// - /// - /// - /// - /// - /// - /// - public void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry) - { - ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); - objupdate.RegionData.RegionHandle = regionHandle; - objupdate.RegionData.TimeDilation = 64096; - objupdate.ObjectData = new 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 = Helpers.StringToField("FirstName STRING RW SV " + firstName + "\nLastName STRING RW SV " + lastName ); - 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 SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) - { - ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); - outPacket.RegionData.RegionHandle = regionHandle; - outPacket.RegionData.TimeDilation = timeDilation; - outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; - outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primShape, flags); - outPacket.ObjectData[0].ID = localID; - outPacket.ObjectData[0].FullID = objectID; - outPacket.ObjectData[0].OwnerID = ownerID; - outPacket.ObjectData[0].Text = enc.GetBytes(text); - outPacket.ObjectData[0].ParentID = parentID; - 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, 36, rot.Length); - OutPacket(outPacket); - } - - public void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) - { - ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); - outPacket.RegionData.RegionHandle = regionHandle; - outPacket.RegionData.TimeDilation = timeDilation; - outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; - outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primShape, flags); - outPacket.ObjectData[0].ID = localID; - outPacket.ObjectData[0].FullID = objectID; - outPacket.ObjectData[0].OwnerID = ownerID; - outPacket.ObjectData[0].Text = enc.GetBytes(text); - outPacket.ObjectData[0].ParentID = parentID; - 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; - Vector3 internDirec = new Vector3(0, 0, 0); - - internDirec = new 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; - } - - /// - /// Create the ObjectDataBlock for a ObjectUpdatePacket (for a Primitive) - /// - /// - /// - protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(PrimitiveBaseShape primShape, uint flags) - { - ObjectUpdatePacket.ObjectDataBlock objupdate = new ObjectUpdatePacket.ObjectDataBlock(); - this.SetDefaultPrimPacketValues(objupdate); - objupdate.UpdateFlags = flags; - this.SetPrimPacketShapeData(objupdate, primShape); - - 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.ParentID = primData.ParentID; - 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.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; - } - - protected void SetPrimPacketShapeData(ObjectUpdatePacket.ObjectDataBlock objectData, PrimitiveBaseShape primData) - { - - objectData.TextureEntry = primData.TextureEntry; - 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.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) - { - 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; - } - Encoding enc = Encoding.ASCII; - 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"); - 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; - } - - #endregion - - public void SendNameReply(LLUUID profileId, string firstname, string lastname) - { - UUIDNameReplyPacket packet = new UUIDNameReplyPacket(); - - packet.UUIDNameBlock = new UUIDNameReplyPacket.UUIDNameBlockBlock[1]; - packet.UUIDNameBlock[0] = new UUIDNameReplyPacket.UUIDNameBlockBlock(); - packet.UUIDNameBlock[0].ID = profileId; - packet.UUIDNameBlock[0].FirstName = Helpers.StringToField( firstname ); - packet.UUIDNameBlock[0].LastName = Helpers.StringToField( lastname ); - - OutPacket( packet ); - } - } -} +/* +* 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 Axiom.Math; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Data; + +namespace OpenSim.Region.ClientStack +{ + partial class ClientView + { + public event ImprovedInstantMessage OnInstantMessage; + 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 ObjectDuplicate OnObjectDuplicate; + public event MoveObject OnGrapUpdate; + public event AddNewPrim OnAddPrim; + public event UpdateShape OnUpdatePrimShape; + public event ObjectSelect OnObjectSelect; + public event ObjectDeselect OnObjectDeselect; + public event GenericCall7 OnObjectDescription; + public event GenericCall7 OnObjectName; + public event UpdatePrimFlags OnUpdatePrimFlags; + public event UpdatePrimTexture OnUpdatePrimTexture; + public event UpdateVector OnUpdatePrimGroupPosition; + public event UpdateVector OnUpdatePrimSinglePosition; + public event UpdatePrimRotation OnUpdatePrimGroupRotation; + public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; + public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; + 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 UUIDNameRequest OnNameFromUUIDRequest; + + public event ParcelPropertiesRequest OnParcelPropertiesRequest; + public event ParcelDivideRequest OnParcelDivideRequest; + public event ParcelJoinRequest OnParcelJoinRequest; + public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + public event ParcelSelectObjects OnParcelSelectObjects; + public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; + 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) + { + Encoding _enc = 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) + { + Encoding enc = Encoding.ASCII; + 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); + } + + /// + /// + /// + /// TODO + /// + /// + public void SendInstantMessage(string message, LLUUID target, string fromName) + { + if (message != "typing") + { + Encoding enc = Encoding.ASCII; + ImprovedInstantMessagePacket msg = new ImprovedInstantMessagePacket(); + msg.AgentData.AgentID = this.AgentID; + msg.AgentData.SessionID = this.SessionID; + msg.MessageBlock.FromAgentName = enc.GetBytes(fromName + " \0"); + msg.MessageBlock.Dialog = 0; + msg.MessageBlock.FromGroup = false; + msg.MessageBlock.ID = target.Combine(this.SecureSessionID); + msg.MessageBlock.Offline = 0; + msg.MessageBlock.ParentEstateID = 0; + msg.MessageBlock.Position = new LLVector3(); + msg.MessageBlock.RegionID = new LLUUID(); + msg.MessageBlock.Timestamp = 0; + msg.MessageBlock.ToAgentID = target; + msg.MessageBlock.Message = enc.GetBytes(message + "\0"); + msg.MessageBlock.BinaryBucket = new byte[0]; + + this.OutPacket(msg); + } + } + + /// + /// 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) + { + 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) + { + MainLog.Instance.Warn("ClientView API .cs: SendLayerData() - Failed with exception " + e.ToString()); + } + } + + /// + /// + /// + /// + /// + /// + public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourEndPoint) + { + IPAddress neighbourIP = neighbourEndPoint.Address; + ushort neighbourPort = (ushort)neighbourEndPoint.Port; + + 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, IPEndPoint externalIPEndPoint) + { + 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 CrossedRegionPacket.RegionDataBlock(); + newSimPack.RegionData.RegionHandle = newRegionHandle; + byte[] byteIP = externalIPEndPoint.Address.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 = (ushort)externalIPEndPoint.Port; + newSimPack.RegionData.SeedCapability = new byte[0]; + + this.OutPacket(newSimPack); + //this.DowngradeClient(); + } + + public void SendMapBlock(List mapBlocks) + { + 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 = Helpers.StringToField(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, IPEndPoint newRegionEndPoint, 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]; + + IPAddress oIP = newRegionEndPoint.Address; + 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 = (ushort)newRegionEndPoint.Port; + 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); + } + + public void SendStartPingCheck(byte seq) + { + StartPingCheckPacket pc = new StartPingCheckPacket(); + pc.PingID.PingID = seq; + OutPacket(pc); + } + + public void SendKillObject(ulong regionHandle, uint avatarLocalID) + { + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + kill.ObjectData[0].ID = avatarLocalID; + OutPacket(kill); + } + + public void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items) + { + Encoding enc = Encoding.ASCII; + uint FULL_MASK_PERMISSIONS = 2147483647; + InventoryDescendentsPacket descend = new InventoryDescendentsPacket(); + descend.AgentData.AgentID = this.AgentId; + descend.AgentData.OwnerID = ownerID; + descend.AgentData.FolderID = folderID; + descend.AgentData.Descendents = items.Count; + descend.AgentData.Version = 0; + descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[items.Count]; + int i = 0; + foreach (InventoryItemBase item in items) + { + descend.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock(); + descend.ItemData[i].ItemID = item.inventoryID; + descend.ItemData[i].AssetID = item.assetID; + descend.ItemData[i].CreatorID = item.creatorsID; + descend.ItemData[i].BaseMask = FULL_MASK_PERMISSIONS; + descend.ItemData[i].CreationDate = 1000; + descend.ItemData[i].Description = enc.GetBytes(item.inventoryDescription+ "\0"); + descend.ItemData[i].EveryoneMask = FULL_MASK_PERMISSIONS; + descend.ItemData[i].Flags = 1; + descend.ItemData[i].FolderID = item.parentFolderID; + descend.ItemData[i].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + descend.ItemData[i].GroupMask = FULL_MASK_PERMISSIONS; + descend.ItemData[i].InvType = (sbyte)item.type; + descend.ItemData[i].Name = enc.GetBytes(item.inventoryName+ "\0"); + descend.ItemData[i].NextOwnerMask = FULL_MASK_PERMISSIONS; + descend.ItemData[i].OwnerID = item.avatarID; + descend.ItemData[i].OwnerMask = FULL_MASK_PERMISSIONS; + descend.ItemData[i].SalePrice = 0; + descend.ItemData[i].SaleType = 0; + descend.ItemData[i].Type = (sbyte)item.type; + descend.ItemData[i].CRC = 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); + + i++; + } + + this.OutPacket(descend); + + } + + public void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item) + { + Encoding enc = Encoding.ASCII; + uint FULL_MASK_PERMISSIONS = 2147483647; + FetchInventoryReplyPacket inventoryReply = new FetchInventoryReplyPacket(); + inventoryReply.AgentData.AgentID = this.AgentId; + inventoryReply.InventoryData = new FetchInventoryReplyPacket.InventoryDataBlock[1]; + inventoryReply.InventoryData[0] = new FetchInventoryReplyPacket.InventoryDataBlock(); + inventoryReply.InventoryData[0].ItemID = item.inventoryID; + inventoryReply.InventoryData[0].AssetID = item.assetID; + inventoryReply.InventoryData[0].CreatorID = item.creatorsID; + 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.inventoryDescription + "\0"); + inventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; + inventoryReply.InventoryData[0].Flags = 0; + inventoryReply.InventoryData[0].FolderID = item.parentFolderID; + inventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + inventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; + inventoryReply.InventoryData[0].InvType = (sbyte)item.type; + inventoryReply.InventoryData[0].Name = enc.GetBytes(item.inventoryName + "\0"); + inventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; + inventoryReply.InventoryData[0].OwnerID = item.avatarID; + inventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; + inventoryReply.InventoryData[0].SalePrice = 0; + inventoryReply.InventoryData[0].SaleType = 0; + inventoryReply.InventoryData[0].Type = (sbyte)item.type; + inventoryReply.InventoryData[0].CRC = 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); + + this.OutPacket(inventoryReply); + } + + #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); + } + + public void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId) + { + AvatarAnimationPacket ani = new AvatarAnimationPacket(); + ani.AnimationSourceList = new AvatarAnimationPacket.AnimationSourceListBlock[1]; + ani.AnimationSourceList[0] = new AvatarAnimationPacket.AnimationSourceListBlock(); + ani.AnimationSourceList[0].ObjectID = sourceAgentId; + ani.Sender = new AvatarAnimationPacket.SenderBlock(); + ani.Sender.ID = sourceAgentId; + ani.AnimationList = new AvatarAnimationPacket.AnimationListBlock[1]; + ani.AnimationList[0] = new AvatarAnimationPacket.AnimationListBlock(); + ani.AnimationList[0].AnimID = animID; + ani.AnimationList[0].AnimSequenceID = seq; + this.OutPacket(ani); + } + + #endregion + + #region Avatar Packet/data sending Methods + + /// + /// send a objectupdate packet with information about the clients avatar + /// + /// + /// + /// + /// + /// + /// + public void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry) + { + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = regionHandle; + objupdate.RegionData.TimeDilation = 64096; + objupdate.ObjectData = new 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 = Helpers.StringToField("FirstName STRING RW SV " + firstName + "\nLastName STRING RW SV " + lastName ); + 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 SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) + { + ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); + outPacket.RegionData.RegionHandle = regionHandle; + outPacket.RegionData.TimeDilation = timeDilation; + outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; + outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primShape, flags); + outPacket.ObjectData[0].ID = localID; + outPacket.ObjectData[0].FullID = objectID; + outPacket.ObjectData[0].OwnerID = ownerID; + outPacket.ObjectData[0].Text = enc.GetBytes(text); + outPacket.ObjectData[0].ParentID = parentID; + 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, 36, rot.Length); + OutPacket(outPacket); + } + + public void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) + { + ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); + outPacket.RegionData.RegionHandle = regionHandle; + outPacket.RegionData.TimeDilation = timeDilation; + outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; + outPacket.ObjectData[0] = this.CreatePrimUpdateBlock(primShape, flags); + outPacket.ObjectData[0].ID = localID; + outPacket.ObjectData[0].FullID = objectID; + outPacket.ObjectData[0].OwnerID = ownerID; + outPacket.ObjectData[0].Text = enc.GetBytes(text); + outPacket.ObjectData[0].ParentID = parentID; + 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; + Vector3 internDirec = new Vector3(0, 0, 0); + + internDirec = new 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; + } + + /// + /// Create the ObjectDataBlock for a ObjectUpdatePacket (for a Primitive) + /// + /// + /// + protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(PrimitiveBaseShape primShape, uint flags) + { + ObjectUpdatePacket.ObjectDataBlock objupdate = new ObjectUpdatePacket.ObjectDataBlock(); + this.SetDefaultPrimPacketValues(objupdate); + objupdate.UpdateFlags = flags; + this.SetPrimPacketShapeData(objupdate, primShape); + + 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.ParentID = primData.ParentID; + 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.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; + } + + protected void SetPrimPacketShapeData(ObjectUpdatePacket.ObjectDataBlock objectData, PrimitiveBaseShape primData) + { + + objectData.TextureEntry = primData.TextureEntry; + 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.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) + { + 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; + } + Encoding enc = Encoding.ASCII; + 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"); + 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; + } + + #endregion + + public void SendNameReply(LLUUID profileId, string firstname, string lastname) + { + UUIDNameReplyPacket packet = new UUIDNameReplyPacket(); + + packet.UUIDNameBlock = new UUIDNameReplyPacket.UUIDNameBlockBlock[1]; + packet.UUIDNameBlock[0] = new UUIDNameReplyPacket.UUIDNameBlockBlock(); + packet.UUIDNameBlock[0].ID = profileId; + packet.UUIDNameBlock[0].FirstName = Helpers.StringToField( firstname ); + packet.UUIDNameBlock[0].LastName = Helpers.StringToField( lastname ); + + OutPacket( packet ); + } + } +} diff --git a/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs b/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs index 60cd33a..109f7e6 100644 --- a/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs +++ b/OpenSim/Region/ClientStack/ClientView.AgentAssetUpload.cs @@ -1,357 +1,357 @@ -/* -* 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 libsecondlife.Packets; -using OpenSim.Assets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; -using OpenSim.Region.Caches; - -namespace OpenSim.Region.ClientStack -{ - 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(); - } - } - } - } - } - } -} +/* +* 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 libsecondlife.Packets; +using OpenSim.Assets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using OpenSim.Region.Caches; + +namespace OpenSim.Region.ClientStack +{ + 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 index e67807e..27265cf 100644 --- a/OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs +++ b/OpenSim/Region/ClientStack/ClientView.PacketHandlers.cs @@ -1,236 +1,236 @@ -/* -* 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 libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Console; - -namespace OpenSim.Region.ClientStack -{ - 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) - { - 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); - // - this.KillClient(); - 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; - //System.Console.WriteLine("new multi update packet " + multipleupdate.ToString()); - for (int i = 0; i < multipleupdate.ObjectData.Length; i++) - { - #region position - if (multipleupdate.ObjectData[i].Type == 9) //change position - { - if (OnUpdatePrimGroupPosition != null) - { - LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); - OnUpdatePrimGroupPosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); - } - - } - else if (multipleupdate.ObjectData[i].Type == 1) //single item of group change position - { - if (OnUpdatePrimSinglePosition != null) - { - libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); - // System.Console.WriteLine("new movement position is " + pos.X + " , " + pos.Y + " , " + pos.Z); - OnUpdatePrimSinglePosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); - } - } - #endregion position - #region rotation - else if (multipleupdate.ObjectData[i].Type == 2)// single item of group rotation from tab - { - if (OnUpdatePrimSingleRotation != null) - { - LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); - // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); - OnUpdatePrimSingleRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 3)// single item of group rotation from mouse - { - if (OnUpdatePrimSingleRotation != null) - { - libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 12, true); - // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); - OnUpdatePrimSingleRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 10)//group rotation from object tab - { - if (OnUpdatePrimGroupRotation != null) - { - libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); - // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); - OnUpdatePrimGroupRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 11)//group rotation from mouse - { - if (OnUpdatePrimGroupMouseRotation != null) - { - libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); - libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 12, true); - //Console.WriteLine("new rotation position is " + pos.X + " , " + pos.Y + " , " + pos.Z); - // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); - OnUpdatePrimGroupMouseRotation(multipleupdate.ObjectData[i].ObjectLocalID, pos, rot, this); - } - } - #endregion - #region scale - else if (multipleupdate.ObjectData[i].Type == 13)//group scale from object tab - { - if (OnUpdatePrimScale != null) - { - LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); - //Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); - OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 29)//group scale from mouse - { - if (OnUpdatePrimScale != null) - { - libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 0); - // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z ); - // OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 5)//single prim scale from object tab - { - if (OnUpdatePrimScale != null) - { - libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); - // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); - OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); - } - } - else if (multipleupdate.ObjectData[i].Type == 21)//single prim scale from mouse - { - if (OnUpdatePrimScale != null) - { - libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); - // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); - OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); - } - } - #endregion - } - 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); - */ - } - } -} +/* +* 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 libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Console; + +namespace OpenSim.Region.ClientStack +{ + 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) + { + 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); + // + this.KillClient(); + 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; + //System.Console.WriteLine("new multi update packet " + multipleupdate.ToString()); + for (int i = 0; i < multipleupdate.ObjectData.Length; i++) + { + #region position + if (multipleupdate.ObjectData[i].Type == 9) //change position + { + if (OnUpdatePrimGroupPosition != null) + { + LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + OnUpdatePrimGroupPosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); + } + + } + else if (multipleupdate.ObjectData[i].Type == 1) //single item of group change position + { + if (OnUpdatePrimSinglePosition != null) + { + libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + // System.Console.WriteLine("new movement position is " + pos.X + " , " + pos.Y + " , " + pos.Z); + OnUpdatePrimSinglePosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); + } + } + #endregion position + #region rotation + else if (multipleupdate.ObjectData[i].Type == 2)// single item of group rotation from tab + { + if (OnUpdatePrimSingleRotation != null) + { + LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); + // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); + OnUpdatePrimSingleRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 3)// single item of group rotation from mouse + { + if (OnUpdatePrimSingleRotation != null) + { + libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 12, true); + // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); + OnUpdatePrimSingleRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 10)//group rotation from object tab + { + if (OnUpdatePrimGroupRotation != null) + { + libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); + // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); + OnUpdatePrimGroupRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 11)//group rotation from mouse + { + if (OnUpdatePrimGroupMouseRotation != null) + { + libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 12, true); + //Console.WriteLine("new rotation position is " + pos.X + " , " + pos.Y + " , " + pos.Z); + // Console.WriteLine("new rotation is " + rot.X + " , " + rot.Y + " , " + rot.Z + " , " + rot.W); + OnUpdatePrimGroupMouseRotation(multipleupdate.ObjectData[i].ObjectLocalID, pos, rot, this); + } + } + #endregion + #region scale + else if (multipleupdate.ObjectData[i].Type == 13)//group scale from object tab + { + if (OnUpdatePrimScale != null) + { + LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); + //Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); + OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 29)//group scale from mouse + { + if (OnUpdatePrimScale != null) + { + libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z ); + // OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 5)//single prim scale from object tab + { + if (OnUpdatePrimScale != null) + { + libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); + // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); + OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + else if (multipleupdate.ObjectData[i].Type == 21)//single prim scale from mouse + { + if (OnUpdatePrimScale != null) + { + libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); + // Console.WriteLine("new scale is " + scale.X + " , " + scale.Y + " , " + scale.Z); + OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + #endregion + } + 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 index a8512a7..1f9110c 100644 --- a/OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs +++ b/OpenSim/Region/ClientStack/ClientView.ProcessPackets.cs @@ -1,647 +1,647 @@ -/* -* 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.Inventory; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Region.ClientStack -{ - public partial class ClientView - { - protected override void ProcessInPacket(Packet Pack) - { - ack_pack(Pack); - if (debug) - { - if (Pack.Type != PacketType.AgentUpdate) - { - Console.WriteLine(CircuitCode + ":IN: " + Pack.Type.ToString()); - } - } - - if (this.ProcessPacketMethod(Pack)) - { - //there is a handler registered that handled this packet type - return; - } - else - { - Encoding _enc = 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.ImprovedInstantMessage: - ImprovedInstantMessagePacket msgpack = (ImprovedInstantMessagePacket)Pack; - - string IMfromName = Util.FieldToString(msgpack.MessageBlock.FromAgentName); - string IMmessage = Util.FieldToString(msgpack.MessageBlock.Message); - - if (OnInstantMessage != null) - { - this.OnInstantMessage(msgpack.AgentData.AgentID, msgpack.MessageBlock.ToAgentID, - msgpack.MessageBlock.Timestamp, IMfromName, IMmessage); - } - 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: - if (OnAddPrim != null) - { - ObjectAddPacket addPacket = (ObjectAddPacket) Pack ; - - PrimitiveBaseShape shape = new PrimitiveBaseShape(); - - shape.PCode = addPacket.ObjectData.PCode; - shape.PathBegin = addPacket.ObjectData.PathBegin; - shape.PathEnd = addPacket.ObjectData.PathEnd; - shape.PathScaleX = addPacket.ObjectData.PathScaleX; - shape.PathScaleY = addPacket.ObjectData.PathScaleY; - shape.PathShearX = addPacket.ObjectData.PathShearX; - shape.PathShearY = addPacket.ObjectData.PathShearY; - shape.PathSkew = addPacket.ObjectData.PathSkew; - shape.ProfileBegin = addPacket.ObjectData.ProfileBegin; - shape.ProfileEnd = addPacket.ObjectData.ProfileEnd; - shape.Scale = addPacket.ObjectData.Scale; - shape.PathCurve = addPacket.ObjectData.PathCurve; - shape.ProfileCurve = addPacket.ObjectData.ProfileCurve; - shape.ProfileHollow = addPacket.ObjectData.ProfileHollow; - shape.PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; - shape.PathRevolutions = addPacket.ObjectData.PathRevolutions; - shape.PathTaperX = addPacket.ObjectData.PathTaperX; - shape.PathTaperY = addPacket.ObjectData.PathTaperY; - shape.PathTwist = addPacket.ObjectData.PathTwist; - shape.PathTwistBegin = addPacket.ObjectData.PathTwistBegin; - LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-9999-000000000005")); - shape.TextureEntry = ntex.ToBytes(); - - OnAddPrim(this.AgentId, addPacket.ObjectData.RayEnd, shape); - } - break; - case PacketType.ObjectShape: - ObjectShapePacket shapePacket = (ObjectShapePacket)Pack; - for (int i = 0; i < shapePacket.ObjectData.Length; i++) - { - if (OnUpdatePrimShape != null) - { - OnUpdatePrimShape(shapePacket.ObjectData[i].ObjectLocalID, shapePacket.ObjectData[i]); - } - } - break; - case PacketType.ObjectDuplicate: - ObjectDuplicatePacket dupe = (ObjectDuplicatePacket)Pack; - for (int i = 0; i < dupe.ObjectData.Length; i++) - { - if (OnObjectDuplicate != null) - { - OnObjectDuplicate(dupe.ObjectData[i].ObjectLocalID, dupe.SharedData.Offset, dupe.SharedData.DuplicateFlags); - } - } - - 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.ObjectDeselect: - ObjectDeselectPacket incomingdeselect = (ObjectDeselectPacket)Pack; - for (int i = 0; i < incomingdeselect.ObjectData.Length; i++) - { - if (OnObjectDeselect != null) - { - OnObjectDeselect(incomingdeselect.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; - case PacketType.ObjectDescription: - ObjectDescriptionPacket objDes = (ObjectDescriptionPacket)Pack; - for (int i = 0; i < objDes.ObjectData.Length; i++) - { - if (OnObjectDescription != null) - { - OnObjectDescription(objDes.ObjectData[i].LocalID, enc.GetString(objDes.ObjectData[i].Description)); - } - } - break; - case PacketType.ObjectName: - ObjectNamePacket objName = (ObjectNamePacket)Pack; - for (int i = 0; i < objName.ObjectData.Length; i++) - { - if (OnObjectName != null) - { - OnObjectName(objName.ObjectData[i].LocalID, enc.GetString(objName.ObjectData[i].Name)); - } - } - break; - case PacketType.ObjectPermissions: - //Console.WriteLine("permissions set " + Pack.ToString()); - 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 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_world.RegionInfo.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; - case PacketType.UUIDNameRequest: - UUIDNameRequestPacket incoming = (UUIDNameRequestPacket)Pack; - foreach (UUIDNameRequestPacket.UUIDNameBlockBlock UUIDBlock in incoming.UUIDNameBlock) - { - OnNameFromUUIDRequest(UUIDBlock.ID, this); - } - 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; - case PacketType.ParcelSelectObjects: - ParcelSelectObjectsPacket selectPacket = (ParcelSelectObjectsPacket)Pack; - if (OnParcelSelectObjects != null) - { - OnParcelSelectObjects(selectPacket.ParcelData.LocalID, Convert.ToInt32(selectPacket.ParcelData.ReturnType), this); - } - break; - - case PacketType.ParcelObjectOwnersRequest: - ParcelObjectOwnersRequestPacket reqPacket = (ParcelObjectOwnersRequestPacket)Pack; - if (OnParcelObjectOwnerRequest != null) - { - OnParcelObjectOwnerRequest(reqPacket.ParcelData.LocalID, 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 - } - } - } - } -} +/* +* 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.Inventory; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Region.ClientStack +{ + public partial class ClientView + { + protected override void ProcessInPacket(Packet Pack) + { + ack_pack(Pack); + if (debug) + { + if (Pack.Type != PacketType.AgentUpdate) + { + Console.WriteLine(CircuitCode + ":IN: " + Pack.Type.ToString()); + } + } + + if (this.ProcessPacketMethod(Pack)) + { + //there is a handler registered that handled this packet type + return; + } + else + { + Encoding _enc = 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.ImprovedInstantMessage: + ImprovedInstantMessagePacket msgpack = (ImprovedInstantMessagePacket)Pack; + + string IMfromName = Util.FieldToString(msgpack.MessageBlock.FromAgentName); + string IMmessage = Util.FieldToString(msgpack.MessageBlock.Message); + + if (OnInstantMessage != null) + { + this.OnInstantMessage(msgpack.AgentData.AgentID, msgpack.MessageBlock.ToAgentID, + msgpack.MessageBlock.Timestamp, IMfromName, IMmessage); + } + 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: + if (OnAddPrim != null) + { + ObjectAddPacket addPacket = (ObjectAddPacket) Pack ; + + PrimitiveBaseShape shape = new PrimitiveBaseShape(); + + shape.PCode = addPacket.ObjectData.PCode; + shape.PathBegin = addPacket.ObjectData.PathBegin; + shape.PathEnd = addPacket.ObjectData.PathEnd; + shape.PathScaleX = addPacket.ObjectData.PathScaleX; + shape.PathScaleY = addPacket.ObjectData.PathScaleY; + shape.PathShearX = addPacket.ObjectData.PathShearX; + shape.PathShearY = addPacket.ObjectData.PathShearY; + shape.PathSkew = addPacket.ObjectData.PathSkew; + shape.ProfileBegin = addPacket.ObjectData.ProfileBegin; + shape.ProfileEnd = addPacket.ObjectData.ProfileEnd; + shape.Scale = addPacket.ObjectData.Scale; + shape.PathCurve = addPacket.ObjectData.PathCurve; + shape.ProfileCurve = addPacket.ObjectData.ProfileCurve; + shape.ProfileHollow = addPacket.ObjectData.ProfileHollow; + shape.PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; + shape.PathRevolutions = addPacket.ObjectData.PathRevolutions; + shape.PathTaperX = addPacket.ObjectData.PathTaperX; + shape.PathTaperY = addPacket.ObjectData.PathTaperY; + shape.PathTwist = addPacket.ObjectData.PathTwist; + shape.PathTwistBegin = addPacket.ObjectData.PathTwistBegin; + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-9999-000000000005")); + shape.TextureEntry = ntex.ToBytes(); + + OnAddPrim(this.AgentId, addPacket.ObjectData.RayEnd, shape); + } + break; + case PacketType.ObjectShape: + ObjectShapePacket shapePacket = (ObjectShapePacket)Pack; + for (int i = 0; i < shapePacket.ObjectData.Length; i++) + { + if (OnUpdatePrimShape != null) + { + OnUpdatePrimShape(shapePacket.ObjectData[i].ObjectLocalID, shapePacket.ObjectData[i]); + } + } + break; + case PacketType.ObjectDuplicate: + ObjectDuplicatePacket dupe = (ObjectDuplicatePacket)Pack; + for (int i = 0; i < dupe.ObjectData.Length; i++) + { + if (OnObjectDuplicate != null) + { + OnObjectDuplicate(dupe.ObjectData[i].ObjectLocalID, dupe.SharedData.Offset, dupe.SharedData.DuplicateFlags); + } + } + + 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.ObjectDeselect: + ObjectDeselectPacket incomingdeselect = (ObjectDeselectPacket)Pack; + for (int i = 0; i < incomingdeselect.ObjectData.Length; i++) + { + if (OnObjectDeselect != null) + { + OnObjectDeselect(incomingdeselect.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; + case PacketType.ObjectDescription: + ObjectDescriptionPacket objDes = (ObjectDescriptionPacket)Pack; + for (int i = 0; i < objDes.ObjectData.Length; i++) + { + if (OnObjectDescription != null) + { + OnObjectDescription(objDes.ObjectData[i].LocalID, enc.GetString(objDes.ObjectData[i].Description)); + } + } + break; + case PacketType.ObjectName: + ObjectNamePacket objName = (ObjectNamePacket)Pack; + for (int i = 0; i < objName.ObjectData.Length; i++) + { + if (OnObjectName != null) + { + OnObjectName(objName.ObjectData[i].LocalID, enc.GetString(objName.ObjectData[i].Name)); + } + } + break; + case PacketType.ObjectPermissions: + //Console.WriteLine("permissions set " + Pack.ToString()); + 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 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_world.RegionInfo.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; + case PacketType.UUIDNameRequest: + UUIDNameRequestPacket incoming = (UUIDNameRequestPacket)Pack; + foreach (UUIDNameRequestPacket.UUIDNameBlockBlock UUIDBlock in incoming.UUIDNameBlock) + { + OnNameFromUUIDRequest(UUIDBlock.ID, this); + } + 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; + case PacketType.ParcelSelectObjects: + ParcelSelectObjectsPacket selectPacket = (ParcelSelectObjectsPacket)Pack; + if (OnParcelSelectObjects != null) + { + OnParcelSelectObjects(selectPacket.ParcelData.LocalID, Convert.ToInt32(selectPacket.ParcelData.ReturnType), this); + } + break; + + case PacketType.ParcelObjectOwnersRequest: + ParcelObjectOwnersRequestPacket reqPacket = (ParcelObjectOwnersRequestPacket)Pack; + if (OnParcelObjectOwnerRequest != null) + { + OnParcelObjectOwnerRequest(reqPacket.ParcelData.LocalID, 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 index 0fe3884..9fddc7b 100644 --- a/OpenSim/Region/ClientStack/ClientView.cs +++ b/OpenSim/Region/ClientStack/ClientView.cs @@ -1,293 +1,293 @@ -/* -* 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.Threading; -using System.Timers; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Inventory; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; -using OpenSim.Region.Caches; -using Timer=System.Timers.Timer; - -namespace OpenSim.Region.ClientStack -{ - 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; - protected AuthenticateSessionsBase m_authenticateSessionsHandler; - private Encoding enc = Encoding.ASCII; - // Dead client detection vars - private Timer clientPingTimer; - private int packetsReceived = 0; - private int probesWithNoIngressPackets = 0; - private int lastPacketsReceived = 0; - - 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; - - 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 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() - { - clientPingTimer.Stop(); - 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() - { - MainLog.Instance.Verbose( "OpenSimClient.cs:ClientLoop() - Entered loop"); - while (true) - { - QueItem nextPacket = PacketQueue.Dequeue(); - if (nextPacket.Incoming) - { - //is a incoming packet - if (nextPacket.Packet.Type != PacketType.AgentUpdate) { - packetsReceived++; - } - ProcessInPacket(nextPacket.Packet); - } - else - { - //is a out going packet - ProcessOutPacket(nextPacket.Packet); - } - } - } - # endregion - - protected void CheckClientConnectivity(object sender, ElapsedEventArgs e) - { - if (packetsReceived == lastPacketsReceived) { - probesWithNoIngressPackets++; - if (probesWithNoIngressPackets > 30) { - this.KillClient(); - } else { - // this will normally trigger at least one packet (ping response) - SendStartPingCheck(0); - } - } else { - // Something received in the meantime - we can reset the counters - probesWithNoIngressPackets = 0; - lastPacketsReceived = packetsReceived; - } - } - - # region Setup - - protected virtual void InitNewClient() - { - clientPingTimer = new Timer(1000); - clientPingTimer.Elapsed += new ElapsedEventHandler(CheckClientConnectivity); - clientPingTimer.Enabled = true; - - MainLog.Instance.Verbose( "OpenSimClient.cs:InitNewClient() - Adding viewer agent to world"); - this.m_world.AddNewClient(this, 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 - MainLog.Instance.Notice("OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString()); - ClientThread.Abort(); - } - else - { - 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 - - } -} +/* +* 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.Threading; +using System.Timers; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using OpenSim.Region.Caches; +using Timer=System.Timers.Timer; + +namespace OpenSim.Region.ClientStack +{ + 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; + protected AuthenticateSessionsBase m_authenticateSessionsHandler; + private Encoding enc = Encoding.ASCII; + // Dead client detection vars + private Timer clientPingTimer; + private int packetsReceived = 0; + private int probesWithNoIngressPackets = 0; + private int lastPacketsReceived = 0; + + 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; + + 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 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() + { + clientPingTimer.Stop(); + 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() + { + MainLog.Instance.Verbose( "OpenSimClient.cs:ClientLoop() - Entered loop"); + while (true) + { + QueItem nextPacket = PacketQueue.Dequeue(); + if (nextPacket.Incoming) + { + //is a incoming packet + if (nextPacket.Packet.Type != PacketType.AgentUpdate) { + packetsReceived++; + } + ProcessInPacket(nextPacket.Packet); + } + else + { + //is a out going packet + ProcessOutPacket(nextPacket.Packet); + } + } + } + # endregion + + protected void CheckClientConnectivity(object sender, ElapsedEventArgs e) + { + if (packetsReceived == lastPacketsReceived) { + probesWithNoIngressPackets++; + if (probesWithNoIngressPackets > 30) { + this.KillClient(); + } else { + // this will normally trigger at least one packet (ping response) + SendStartPingCheck(0); + } + } else { + // Something received in the meantime - we can reset the counters + probesWithNoIngressPackets = 0; + lastPacketsReceived = packetsReceived; + } + } + + # region Setup + + protected virtual void InitNewClient() + { + clientPingTimer = new Timer(1000); + clientPingTimer.Elapsed += new ElapsedEventHandler(CheckClientConnectivity); + clientPingTimer.Enabled = true; + + MainLog.Instance.Verbose( "OpenSimClient.cs:InitNewClient() - Adding viewer agent to world"); + this.m_world.AddNewClient(this, 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 + MainLog.Instance.Notice("OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString()); + ClientThread.Abort(); + } + else + { + 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 index cc04bda..597cd7d 100644 --- a/OpenSim/Region/ClientStack/ClientViewBase.cs +++ b/OpenSim/Region/ClientStack/ClientViewBase.cs @@ -1,326 +1,326 @@ -/* -* 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.Net.Sockets; -using System.Timers; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Console; -using OpenSim.Framework.Utilities; -using OpenSim.Region.Environment; - -namespace OpenSim.Region.ClientStack -{ - public class ClientViewBase - { - protected BlockingQueue PacketQueue; - protected Dictionary PendingAcks = new Dictionary(); - protected Dictionary NeedAck = new Dictionary(); - - protected 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 = System.Environment.TickCount; - - // Console.WriteLine(CircuitCode + ":OUT: " + Pack.Type.ToString()); - - 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) - { - 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 - StartPingCheckPacket startPing = (StartPingCheckPacket)NewPack; - 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) - { - 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 = System.Environment.TickCount; - - lock (NeedAck) - { - foreach (Packet packet in NeedAck.Values) - { - if ((now - packet.TickCount > RESEND_TIMEOUT) && (!packet.Header.Resent)) - { - 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 - 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 - } -} +/* +* 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.Net.Sockets; +using System.Timers; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Console; +using OpenSim.Framework.Utilities; +using OpenSim.Region.Environment; + +namespace OpenSim.Region.ClientStack +{ + public class ClientViewBase + { + protected BlockingQueue PacketQueue; + protected Dictionary PendingAcks = new Dictionary(); + protected Dictionary NeedAck = new Dictionary(); + + protected 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 = System.Environment.TickCount; + + // Console.WriteLine(CircuitCode + ":OUT: " + Pack.Type.ToString()); + + 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) + { + 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 + StartPingCheckPacket startPing = (StartPingCheckPacket)NewPack; + 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) + { + 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 = System.Environment.TickCount; + + lock (NeedAck) + { + foreach (Packet packet in NeedAck.Values) + { + if ((now - packet.TickCount > RESEND_TIMEOUT) && (!packet.Header.Resent)) + { + 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 + 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/PacketServer.cs b/OpenSim/Region/ClientStack/PacketServer.cs index a88c682..466fdde 100644 --- a/OpenSim/Region/ClientStack/PacketServer.cs +++ b/OpenSim/Region/ClientStack/PacketServer.cs @@ -1,184 +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.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using libsecondlife.Packets; -using OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Interfaces; -using OpenSim.Region.Caches; - -namespace OpenSim.Region.ClientStack -{ - public class PacketServer - { - private ClientStackNetworkHandler _networkHandler; - private IWorld _localWorld; - public Dictionary ClientThreads = new Dictionary(); - private ClientManager m_clientManager = new ClientManager(); - public ClientManager ClientManager - { - get { return m_clientManager; } - } - - public PacketServer(ClientStackNetworkHandler networkHandler) - { - _networkHandler = networkHandler; - _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.m_clientManager.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); - this.m_clientManager.Remove(circuitcode); - } - } -} +/* +* 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.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using libsecondlife.Packets; +using OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Region.Caches; + +namespace OpenSim.Region.ClientStack +{ + public class PacketServer + { + private ClientStackNetworkHandler _networkHandler; + private IWorld _localWorld; + public Dictionary ClientThreads = new Dictionary(); + private ClientManager m_clientManager = new ClientManager(); + public ClientManager ClientManager + { + get { return m_clientManager; } + } + + public PacketServer(ClientStackNetworkHandler networkHandler) + { + _networkHandler = networkHandler; + _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.m_clientManager.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); + this.m_clientManager.Remove(circuitcode); + } + } +} diff --git a/OpenSim/Region/ClientStack/RegionApplicationBase.cs b/OpenSim/Region/ClientStack/RegionApplicationBase.cs index 7ae74f8..ed7df17 100644 --- a/OpenSim/Region/ClientStack/RegionApplicationBase.cs +++ b/OpenSim/Region/ClientStack/RegionApplicationBase.cs @@ -1,118 +1,118 @@ -/* -* 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 OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.Physics.Manager; -using OpenSim.Region.Caches; -using OpenSim.Region.Environment; - -namespace OpenSim.Region.ClientStack -{ - 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 SetupScene() - { - } - - protected virtual void SetupHttpListener() - { - } - - protected virtual void ConnectToRemoteGridServer() - { - - } - } -} +/* +* 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 OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.Physics.Manager; +using OpenSim.Region.Caches; +using OpenSim.Region.Environment; + +namespace OpenSim.Region.ClientStack +{ + 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 SetupScene() + { + } + + protected virtual void SetupHttpListener() + { + } + + protected virtual void ConnectToRemoteGridServer() + { + + } + } +} diff --git a/OpenSim/Region/ClientStack/UDPServer.cs b/OpenSim/Region/ClientStack/UDPServer.cs index 6eea524..781f96a 100644 --- a/OpenSim/Region/ClientStack/UDPServer.cs +++ b/OpenSim/Region/ClientStack/UDPServer.cs @@ -1,196 +1,196 @@ -/* -* 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.Net.Sockets; -using libsecondlife.Packets; -using OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Region.Caches; - -namespace OpenSim.Region.ClientStack -{ - - 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); - } - - protected virtual void OnReceivedData(IAsyncResult result) - { - ipeSender = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), 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; - } - } - } - - - } +/* +* 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.Net.Sockets; +using libsecondlife.Packets; +using OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Region.Caches; + +namespace OpenSim.Region.ClientStack +{ + + 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); + } + + protected virtual void OnReceivedData(IAsyncResult result) + { + ipeSender = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), 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.Parse("0.0.0.0"), 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/Communications/Local/CommunicationsLocal.cs b/OpenSim/Region/Communications/Local/CommunicationsLocal.cs index c47904d..3ce0cc5 100644 --- a/OpenSim/Region/Communications/Local/CommunicationsLocal.cs +++ b/OpenSim/Region/Communications/Local/CommunicationsLocal.cs @@ -1,55 +1,55 @@ -/* -* 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 OpenSim.Framework.Communications; -using OpenSim.Framework.Types; -using OpenSim.Framework.Servers; - -namespace OpenSim.Region.Communications.Local -{ - public class CommunicationsLocal : CommunicationsManager - { - public LocalBackEndServices SandBoxServices = new LocalBackEndServices(); - public LocalUserServices UserServices; - - public CommunicationsLocal(NetworkServersInfo serversInfo, BaseHttpServer httpServer ) - : base(serversInfo, httpServer) - { - UserServices = new LocalUserServices(this, serversInfo); - UserServices.AddPlugin("OpenSim.Framework.Data.DB4o.dll"); - UserServer = UserServices; - GridServer = SandBoxServices; - InterRegion = SandBoxServices; - httpServer.AddXmlRPCHandler("login_to_simulator", UserServices.XmlRpcLoginMethod); - } - - internal void InformRegionOfLogin(ulong regionHandle, Login login) - { - this.SandBoxServices.AddNewSession(regionHandle, login); - } - } -} +/* +* 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 OpenSim.Framework.Communications; +using OpenSim.Framework.Types; +using OpenSim.Framework.Servers; + +namespace OpenSim.Region.Communications.Local +{ + public class CommunicationsLocal : CommunicationsManager + { + public LocalBackEndServices SandBoxServices = new LocalBackEndServices(); + public LocalUserServices UserServices; + + public CommunicationsLocal(NetworkServersInfo serversInfo, BaseHttpServer httpServer ) + : base(serversInfo, httpServer) + { + UserServices = new LocalUserServices(this, serversInfo); + UserServices.AddPlugin("OpenSim.Framework.Data.DB4o.dll"); + UserServer = UserServices; + GridServer = SandBoxServices; + InterRegion = SandBoxServices; + httpServer.AddXmlRPCHandler("login_to_simulator", UserServices.XmlRpcLoginMethod); + } + + internal void InformRegionOfLogin(ulong regionHandle, Login login) + { + this.SandBoxServices.AddNewSession(regionHandle, login); + } + } +} diff --git a/OpenSim/Region/Communications/Local/LocalBackEndServices.cs b/OpenSim/Region/Communications/Local/LocalBackEndServices.cs index d0cd991..9322f3b 100644 --- a/OpenSim/Region/Communications/Local/LocalBackEndServices.cs +++ b/OpenSim/Region/Communications/Local/LocalBackEndServices.cs @@ -1,206 +1,206 @@ -/* -* 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.Collections.Generic; -using libsecondlife; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Communications.Local -{ - - 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) - { - //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, LLUUID agentID, 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) - { - 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; - } - } -} - +/* +* 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.Collections.Generic; +using libsecondlife; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Communications.Local +{ + + 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) + { + //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, LLUUID agentID, 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) + { + 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/Communications/Local/LocalUserServices.cs b/OpenSim/Region/Communications/Local/LocalUserServices.cs index 592b36c..a4cefc4 100644 --- a/OpenSim/Region/Communications/Local/LocalUserServices.cs +++ b/OpenSim/Region/Communications/Local/LocalUserServices.cs @@ -1,142 +1,142 @@ -using System; -using libsecondlife; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Data; -using OpenSim.Framework.Types; -using OpenSim.Framework.UserManagement; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Region.Communications.Local -{ - public class LocalUserServices : UserManagerBase, IUserServices - { - private CommunicationsLocal m_Parent; - - private NetworkServersInfo serversInfo; - private uint defaultHomeX ; - private uint defaultHomeY; - public LocalUserServices(CommunicationsLocal parent, NetworkServersInfo serversData) - { - m_Parent = parent; - this.serversInfo = serversData; - defaultHomeX = this.serversInfo.DefaultHomeLocX; - defaultHomeY = this.serversInfo.DefaultHomeLocY; - } - - 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(UserProfileData profile, string password) - { - //for now we will accept any password in sandbox mode - Console.WriteLine("authorising user"); - return true; - } - - public override void CustomiseResponse(LoginResponse response, 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.ExternalEndPoint.Address.ToString(); - response.SimPort = (Int32)reg.ExternalEndPoint.Port; - response.RegionX = reg.RegionLocX ; - response.RegionY = reg.RegionLocY ; - - //following port needs changing as we don't want a http listener for every region (or do we?) - response.SeedCapability = "http://" + reg.ExternalHostName + ":" + this.serversInfo.HttpListenerPort.ToString() + "/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); - } - - } - - public UserProfileData SetupMasterUser(string firstName, string lastName) - { - return SetupMasterUser(firstName, lastName, ""); - } - - public UserProfileData SetupMasterUser(string firstName, string lastName, string password) - { - UserProfileData profile = getUserProfile(firstName, lastName); - if (profile != null) - { - - return profile; - } - - Console.WriteLine("Unknown Master User. Sandbox Mode: Creating Account"); - this.AddUserProfile(firstName, lastName, password, defaultHomeX, defaultHomeY); - - profile = getUserProfile(firstName, lastName); - - if (profile == null) - { - Console.WriteLine("Unknown Master User after creation attempt. No clue what to do here."); - } - - return profile; - } - } -} +using System; +using libsecondlife; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Data; +using OpenSim.Framework.Types; +using OpenSim.Framework.UserManagement; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Region.Communications.Local +{ + public class LocalUserServices : UserManagerBase, IUserServices + { + private CommunicationsLocal m_Parent; + + private NetworkServersInfo serversInfo; + private uint defaultHomeX ; + private uint defaultHomeY; + public LocalUserServices(CommunicationsLocal parent, NetworkServersInfo serversData) + { + m_Parent = parent; + this.serversInfo = serversData; + defaultHomeX = this.serversInfo.DefaultHomeLocX; + defaultHomeY = this.serversInfo.DefaultHomeLocY; + } + + 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(UserProfileData profile, string password) + { + //for now we will accept any password in sandbox mode + Console.WriteLine("authorising user"); + return true; + } + + public override void CustomiseResponse(LoginResponse response, 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.ExternalEndPoint.Address.ToString(); + response.SimPort = (Int32)reg.ExternalEndPoint.Port; + response.RegionX = reg.RegionLocX ; + response.RegionY = reg.RegionLocY ; + + //following port needs changing as we don't want a http listener for every region (or do we?) + response.SeedCapability = "http://" + reg.ExternalHostName + ":" + this.serversInfo.HttpListenerPort.ToString() + "/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); + } + + } + + public UserProfileData SetupMasterUser(string firstName, string lastName) + { + return SetupMasterUser(firstName, lastName, ""); + } + + public UserProfileData SetupMasterUser(string firstName, string lastName, string password) + { + UserProfileData profile = getUserProfile(firstName, lastName); + if (profile != null) + { + + return profile; + } + + Console.WriteLine("Unknown Master User. Sandbox Mode: Creating Account"); + this.AddUserProfile(firstName, lastName, password, defaultHomeX, defaultHomeY); + + profile = getUserProfile(firstName, lastName); + + if (profile == null) + { + Console.WriteLine("Unknown Master User after creation attempt. No clue what to do here."); + } + + return profile; + } + } +} diff --git a/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs b/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs index 9afb75e..ca64319 100644 --- a/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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.Region.Communications.Local")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.Region.Communications.Local")] -[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")] +using System.Reflection; +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.Region.Communications.Local")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Region.Communications.Local")] +[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/Communications/OGS1/CommunicationsOGS1.cs b/OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs index cc05845..9df0901 100644 --- a/OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs +++ b/OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs @@ -1,18 +1,18 @@ -using OpenSim.Framework.Communications; -using OpenSim.Framework.Types; -using OpenSim.Framework.Servers; - -namespace OpenSim.Region.Communications.OGS1 -{ - public class CommunicationsOGS1 : CommunicationsManager - { - - public CommunicationsOGS1(NetworkServersInfo serversInfo, BaseHttpServer httpServer ) :base(serversInfo, httpServer) - { - OGS1GridServices gridInterComms = new OGS1GridServices(serversInfo, httpServer); - GridServer = gridInterComms; - InterRegion = gridInterComms; - UserServer = new OGS1UserServices(this); - } - } -} +using OpenSim.Framework.Communications; +using OpenSim.Framework.Types; +using OpenSim.Framework.Servers; + +namespace OpenSim.Region.Communications.OGS1 +{ + public class CommunicationsOGS1 : CommunicationsManager + { + + public CommunicationsOGS1(NetworkServersInfo serversInfo, BaseHttpServer httpServer ) :base(serversInfo, httpServer) + { + OGS1GridServices gridInterComms = new OGS1GridServices(serversInfo, httpServer); + GridServer = gridInterComms; + InterRegion = gridInterComms; + UserServer = new OGS1UserServices(this); + } + } +} diff --git a/OpenSim/Region/Communications/OGS1/OGS1GridServices.cs b/OpenSim/Region/Communications/OGS1/OGS1GridServices.cs index e5a73fd..3cb2889 100644 --- a/OpenSim/Region/Communications/OGS1/OGS1GridServices.cs +++ b/OpenSim/Region/Communications/OGS1/OGS1GridServices.cs @@ -1,431 +1,431 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Runtime.Remoting; -using System.Runtime.Remoting.Channels; -using System.Runtime.Remoting.Channels.Tcp; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Console; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Communications.OGS1 -{ - public class OGS1GridServices : IGridServices, IInterRegionCommunications - { - public Dictionary listeners = new Dictionary(); - protected Dictionary regions = new Dictionary(); - - public BaseHttpServer httpListener; - public NetworkServersInfo serversInfo; - public BaseHttpServer httpServer; - - /// - /// - /// - /// - /// - public OGS1GridServices(NetworkServersInfo servers_info, BaseHttpServer httpServe) - { - serversInfo = servers_info; - httpServer = httpServe; - httpServer.AddXmlRPCHandler("expect_user", this.ExpectUser); - this.StartRemoting(); - } - - /// - /// - /// - /// - /// - public RegionCommsListener RegisterRegion(RegionInfo regionInfo) - { - if (!this.regions.ContainsKey((uint)regionInfo.RegionHandle)) - { - this.regions.Add(regionInfo.RegionHandle, regionInfo); - } - - Hashtable GridParams = new Hashtable(); - // Login / Authentication - - GridParams["authkey"] = serversInfo.GridSendKey; - GridParams["UUID"] = regionInfo.SimUUID.ToStringHyphenated(); - GridParams["sim_ip"] = regionInfo.ExternalHostName; - GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString(); - GridParams["region_locx"] = regionInfo.RegionLocX.ToString(); - GridParams["region_locy"] = regionInfo.RegionLocY.ToString(); - GridParams["sim_name"] = regionInfo.RegionName; - GridParams["http_port"] = serversInfo.HttpListenerPort.ToString(); - GridParams["remoting_port"] = serversInfo.RemotingListenerPort.ToString(); - GridParams["map-image-id"] = regionInfo.estateSettings.terrainImageID.ToStringHyphenated(); - - // 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(serversInfo.GridURL, 3000); - Hashtable GridRespData = (Hashtable)GridResp.Value; - - Hashtable griddatahash = GridRespData; - - // Process Response - if (GridRespData.ContainsKey("error")) - { - string errorstring = (string)GridRespData["error"]; - MainLog.Instance.Error("Unable to connect to grid: " + errorstring); - return null; - } - - // Initialise the background listeners - RegionCommsListener regListener = new RegionCommsListener(); - if (!this.listeners.ContainsKey(regionInfo.RegionHandle)) - { - this.listeners.Add(regionInfo.RegionHandle, regListener); - } - else - { - listeners[regionInfo.RegionHandle] = regListener; - } - - return regListener; - } - - /// - /// - /// - /// - /// - 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 (ArrayList a in respData.Values) - { - foreach (Hashtable n in a) - { - uint regX = Convert.ToUInt32(n["x"]); - uint regY = Convert.ToUInt32(n["y"]); - if ((regionInfo.RegionLocX != regX) || (regionInfo.RegionLocY != regY)) - { - string externalIpStr = (string)n["sim_ip"]; - uint port = Convert.ToUInt32(n["sim_port"]); - string externalUri = (string)n["sim_uri"]; - - IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(externalIpStr), (int)port); - string neighbourExternalUri = externalUri; - RegionInfo neighbour = new RegionInfo(regX, regY, neighbourInternalEndPoint, externalIpStr); - - //OGS1 - //neighbour.RegionHandle = (ulong)n["regionhandle"]; is now calculated locally - - neighbour.RegionName = (string)n["name"]; - - //OGS1+ - neighbour.SimUUID = (string)n["uuid"]; - - neighbours.Add(neighbour); - } - } - } - - return neighbours; - } - - /// - /// - /// - /// - /// - public RegionInfo RequestNeighbourInfo(ulong regionHandle) - { - if (this.regions.ContainsKey(regionHandle)) - { - return this.regions[regionHandle]; - } - //TODO not a region in this instance so ask remote grid server - - Hashtable requestData = new Hashtable(); - requestData["region_handle"] = regionHandle.ToString(); - requestData["authkey"] = this.serversInfo.GridSendKey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(this.serversInfo.GridURL, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - Console.WriteLine("error received from grid server" + responseData["error"]); - return null; - } - - uint regX = Convert.ToUInt32((string)responseData["region_locx"]); - uint regY = Convert.ToUInt32((string)responseData["region_locy"]); - string internalIpStr = (string)responseData["sim_ip"]; - uint port = Convert.ToUInt32(responseData["sim_port"]); - string externalUri = (string)responseData["sim_uri"]; - - IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int)port); - string neighbourExternalUri = externalUri; - RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr); - - regionInfo.RemotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - regionInfo.RemotingAddress = internalIpStr; - - regionInfo.SimUUID = new LLUUID((string)responseData["region_UUID"]); - regionInfo.RegionName = (string)responseData["region_name"]; - - return regionInfo; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) - { - Hashtable respData = MapBlockQuery(minX, minY, maxX, maxY); - - List neighbours = new List(); - - foreach (ArrayList a in respData.Values) - { - foreach (Hashtable n in a) - { - MapBlockData neighbour = new MapBlockData(); - - neighbour.X = Convert.ToUInt16(n["x"]); - neighbour.Y = Convert.ToUInt16(n["y"]); - - neighbour.Name = (string)n["name"]; - neighbour.Access = Convert.ToByte(n["access"]); - neighbour.RegionFlags = Convert.ToUInt32(n["region-flags"]); - neighbour.WaterHeight = Convert.ToByte(n["water-height"]); - neighbour.MapImageId = new LLUUID((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(serversInfo.GridURL, 3000); - Hashtable respData = (Hashtable)resp.Value; - return respData; - } - - // Grid Request Processing - /// - /// - /// - /// - /// - public XmlRpcResponse ExpectUser(XmlRpcRequest request) - { - Console.WriteLine("Expecting User..."); - 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"]); - agentData.CapsPath = (string)requestData["caps_path"]; - - 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(Convert.ToUInt64((string)requestData["regionhandle"]))) - { - this.listeners[Convert.ToUInt64((string)requestData["regionhandle"])].TriggerExpectUser(Convert.ToUInt64((string)requestData["regionhandle"]), agentData); - } - else - { - MainLog.Instance.Error("ExpectUser() - Unknown region " + ((ulong)requestData["regionhandle"]).ToString()); - } - - MainLog.Instance.Verbose("ExpectUser() - Welcoming new user..."); - - return new XmlRpcResponse(); - } - - #region InterRegion Comms - /// - /// - /// - private void StartRemoting() - { - TcpChannel ch = new TcpChannel(this.serversInfo.RemotingListenerPort); - ChannelServices.RegisterChannel(ch, true); - - WellKnownServiceTypeEntry wellType = new WellKnownServiceTypeEntry(typeof(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; - } - RegionInfo regInfo = this.RequestNeighbourInfo(regionHandle); - if (regInfo != null) - { - //don't want to be creating a new link to the remote instance every time like we are here - bool retValue = false; - - - OGS1InterRegionRemoting remObject = (OGS1InterRegionRemoting)Activator.GetObject( - typeof(OGS1InterRegionRemoting), - "tcp://"+ regInfo.RemotingAddress+":"+regInfo.RemotingPort+"/InterRegions"); - if (remObject != null) - { - - retValue = remObject.InformRegionOfChildAgent(regionHandle, agentData); - } - else - { - Console.WriteLine("remoting object not found"); - } - remObject = null; - - - return retValue; - } - - return false; - } - - /// - /// - /// - /// - /// - /// - /// - public bool ExpectAvatarCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position) - { - if (this.listeners.ContainsKey(regionHandle)) - { - this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); - return true; - } - RegionInfo regInfo = this.RequestNeighbourInfo(regionHandle); - if (regInfo != null) - { - bool retValue = false; - - - OGS1InterRegionRemoting remObject = (OGS1InterRegionRemoting)Activator.GetObject( - typeof(OGS1InterRegionRemoting), - "tcp://" + regInfo.RemotingAddress + ":" + regInfo.RemotingPort + "/InterRegions"); - if (remObject != null) - { - - retValue = remObject.ExpectAvatarCrossing(regionHandle, agentID, position); - } - else - { - Console.WriteLine("remoting object not found"); - } - remObject = null; - - - return retValue; - } - //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, LLUUID agentID, LLVector3 position) - { - if (this.listeners.ContainsKey(regionHandle)) - { - this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); - return true; - } - return false; - } - #endregion - #endregion - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Runtime.Remoting; +using System.Runtime.Remoting.Channels; +using System.Runtime.Remoting.Channels.Tcp; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Console; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Communications.OGS1 +{ + public class OGS1GridServices : IGridServices, IInterRegionCommunications + { + public Dictionary listeners = new Dictionary(); + protected Dictionary regions = new Dictionary(); + + public BaseHttpServer httpListener; + public NetworkServersInfo serversInfo; + public BaseHttpServer httpServer; + + /// + /// + /// + /// + /// + public OGS1GridServices(NetworkServersInfo servers_info, BaseHttpServer httpServe) + { + serversInfo = servers_info; + httpServer = httpServe; + httpServer.AddXmlRPCHandler("expect_user", this.ExpectUser); + this.StartRemoting(); + } + + /// + /// + /// + /// + /// + public RegionCommsListener RegisterRegion(RegionInfo regionInfo) + { + if (!this.regions.ContainsKey((uint)regionInfo.RegionHandle)) + { + this.regions.Add(regionInfo.RegionHandle, regionInfo); + } + + Hashtable GridParams = new Hashtable(); + // Login / Authentication + + GridParams["authkey"] = serversInfo.GridSendKey; + GridParams["UUID"] = regionInfo.SimUUID.ToStringHyphenated(); + GridParams["sim_ip"] = regionInfo.ExternalHostName; + GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString(); + GridParams["region_locx"] = regionInfo.RegionLocX.ToString(); + GridParams["region_locy"] = regionInfo.RegionLocY.ToString(); + GridParams["sim_name"] = regionInfo.RegionName; + GridParams["http_port"] = serversInfo.HttpListenerPort.ToString(); + GridParams["remoting_port"] = serversInfo.RemotingListenerPort.ToString(); + GridParams["map-image-id"] = regionInfo.estateSettings.terrainImageID.ToStringHyphenated(); + + // 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(serversInfo.GridURL, 3000); + Hashtable GridRespData = (Hashtable)GridResp.Value; + + Hashtable griddatahash = GridRespData; + + // Process Response + if (GridRespData.ContainsKey("error")) + { + string errorstring = (string)GridRespData["error"]; + MainLog.Instance.Error("Unable to connect to grid: " + errorstring); + return null; + } + + // Initialise the background listeners + RegionCommsListener regListener = new RegionCommsListener(); + if (!this.listeners.ContainsKey(regionInfo.RegionHandle)) + { + this.listeners.Add(regionInfo.RegionHandle, regListener); + } + else + { + listeners[regionInfo.RegionHandle] = regListener; + } + + return regListener; + } + + /// + /// + /// + /// + /// + 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 (ArrayList a in respData.Values) + { + foreach (Hashtable n in a) + { + uint regX = Convert.ToUInt32(n["x"]); + uint regY = Convert.ToUInt32(n["y"]); + if ((regionInfo.RegionLocX != regX) || (regionInfo.RegionLocY != regY)) + { + string externalIpStr = (string)n["sim_ip"]; + uint port = Convert.ToUInt32(n["sim_port"]); + string externalUri = (string)n["sim_uri"]; + + IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(externalIpStr), (int)port); + string neighbourExternalUri = externalUri; + RegionInfo neighbour = new RegionInfo(regX, regY, neighbourInternalEndPoint, externalIpStr); + + //OGS1 + //neighbour.RegionHandle = (ulong)n["regionhandle"]; is now calculated locally + + neighbour.RegionName = (string)n["name"]; + + //OGS1+ + neighbour.SimUUID = (string)n["uuid"]; + + neighbours.Add(neighbour); + } + } + } + + return neighbours; + } + + /// + /// + /// + /// + /// + public RegionInfo RequestNeighbourInfo(ulong regionHandle) + { + if (this.regions.ContainsKey(regionHandle)) + { + return this.regions[regionHandle]; + } + //TODO not a region in this instance so ask remote grid server + + Hashtable requestData = new Hashtable(); + requestData["region_handle"] = regionHandle.ToString(); + requestData["authkey"] = this.serversInfo.GridSendKey; + ArrayList SendParams = new ArrayList(); + SendParams.Add(requestData); + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); + XmlRpcResponse GridResp = GridReq.Send(this.serversInfo.GridURL, 3000); + + Hashtable responseData = (Hashtable)GridResp.Value; + + if (responseData.ContainsKey("error")) + { + Console.WriteLine("error received from grid server" + responseData["error"]); + return null; + } + + uint regX = Convert.ToUInt32((string)responseData["region_locx"]); + uint regY = Convert.ToUInt32((string)responseData["region_locy"]); + string internalIpStr = (string)responseData["sim_ip"]; + uint port = Convert.ToUInt32(responseData["sim_port"]); + string externalUri = (string)responseData["sim_uri"]; + + IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int)port); + string neighbourExternalUri = externalUri; + RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr); + + regionInfo.RemotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); + regionInfo.RemotingAddress = internalIpStr; + + regionInfo.SimUUID = new LLUUID((string)responseData["region_UUID"]); + regionInfo.RegionName = (string)responseData["region_name"]; + + return regionInfo; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) + { + Hashtable respData = MapBlockQuery(minX, minY, maxX, maxY); + + List neighbours = new List(); + + foreach (ArrayList a in respData.Values) + { + foreach (Hashtable n in a) + { + MapBlockData neighbour = new MapBlockData(); + + neighbour.X = Convert.ToUInt16(n["x"]); + neighbour.Y = Convert.ToUInt16(n["y"]); + + neighbour.Name = (string)n["name"]; + neighbour.Access = Convert.ToByte(n["access"]); + neighbour.RegionFlags = Convert.ToUInt32(n["region-flags"]); + neighbour.WaterHeight = Convert.ToByte(n["water-height"]); + neighbour.MapImageId = new LLUUID((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(serversInfo.GridURL, 3000); + Hashtable respData = (Hashtable)resp.Value; + return respData; + } + + // Grid Request Processing + /// + /// + /// + /// + /// + public XmlRpcResponse ExpectUser(XmlRpcRequest request) + { + Console.WriteLine("Expecting User..."); + 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"]); + agentData.CapsPath = (string)requestData["caps_path"]; + + 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(Convert.ToUInt64((string)requestData["regionhandle"]))) + { + this.listeners[Convert.ToUInt64((string)requestData["regionhandle"])].TriggerExpectUser(Convert.ToUInt64((string)requestData["regionhandle"]), agentData); + } + else + { + MainLog.Instance.Error("ExpectUser() - Unknown region " + ((ulong)requestData["regionhandle"]).ToString()); + } + + MainLog.Instance.Verbose("ExpectUser() - Welcoming new user..."); + + return new XmlRpcResponse(); + } + + #region InterRegion Comms + /// + /// + /// + private void StartRemoting() + { + TcpChannel ch = new TcpChannel(this.serversInfo.RemotingListenerPort); + ChannelServices.RegisterChannel(ch, true); + + WellKnownServiceTypeEntry wellType = new WellKnownServiceTypeEntry(typeof(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; + } + RegionInfo regInfo = this.RequestNeighbourInfo(regionHandle); + if (regInfo != null) + { + //don't want to be creating a new link to the remote instance every time like we are here + bool retValue = false; + + + OGS1InterRegionRemoting remObject = (OGS1InterRegionRemoting)Activator.GetObject( + typeof(OGS1InterRegionRemoting), + "tcp://"+ regInfo.RemotingAddress+":"+regInfo.RemotingPort+"/InterRegions"); + if (remObject != null) + { + + retValue = remObject.InformRegionOfChildAgent(regionHandle, agentData); + } + else + { + Console.WriteLine("remoting object not found"); + } + remObject = null; + + + return retValue; + } + + return false; + } + + /// + /// + /// + /// + /// + /// + /// + public bool ExpectAvatarCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); + return true; + } + RegionInfo regInfo = this.RequestNeighbourInfo(regionHandle); + if (regInfo != null) + { + bool retValue = false; + + + OGS1InterRegionRemoting remObject = (OGS1InterRegionRemoting)Activator.GetObject( + typeof(OGS1InterRegionRemoting), + "tcp://" + regInfo.RemotingAddress + ":" + regInfo.RemotingPort + "/InterRegions"); + if (remObject != null) + { + + retValue = remObject.ExpectAvatarCrossing(regionHandle, agentID, position); + } + else + { + Console.WriteLine("remoting object not found"); + } + remObject = null; + + + return retValue; + } + //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, LLUUID agentID, LLVector3 position) + { + if (this.listeners.ContainsKey(regionHandle)) + { + this.listeners[regionHandle].TriggerExpectAvatarCrossing(regionHandle, agentID, position); + return true; + } + return false; + } + #endregion + #endregion + } +} diff --git a/OpenSim/Region/Communications/OGS1/OGS1InterSimComms.cs b/OpenSim/Region/Communications/OGS1/OGS1InterSimComms.cs index f514a29..520c593 100644 --- a/OpenSim/Region/Communications/OGS1/OGS1InterSimComms.cs +++ b/OpenSim/Region/Communications/OGS1/OGS1InterSimComms.cs @@ -1,69 +1,69 @@ -using System; -using libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Communications.OGS1 -{ - public delegate bool InformRegionChild(ulong regionHandle, AgentCircuitData agentData); - public delegate bool ExpectArrival(ulong regionHandle, LLUUID agentID, 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, LLUUID agentID, 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, LLUUID agentID, LLVector3 position) - { - return InterRegionSingleton.Instance.ExpectAvatarCrossing(regionHandle, agentID, position); - } - } -} +using System; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Communications.OGS1 +{ + public delegate bool InformRegionChild(ulong regionHandle, AgentCircuitData agentData); + public delegate bool ExpectArrival(ulong regionHandle, LLUUID agentID, 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, LLUUID agentID, 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, LLUUID agentID, LLVector3 position) + { + return InterRegionSingleton.Instance.ExpectAvatarCrossing(regionHandle, agentID, position); + } + } +} diff --git a/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs b/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs index 46d71c4..0847148 100644 --- a/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs +++ b/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs @@ -1,101 +1,101 @@ -using System; -using System.Collections; -using libsecondlife; -using Nwc.XmlRpc; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Data; - -namespace OpenSim.Region.Communications.OGS1 -{ - public class OGS1UserServices :IUserServices - { - CommunicationsOGS1 m_parent; - public OGS1UserServices(CommunicationsOGS1 parent) - { - m_parent = parent; - } - - public UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data) - { - if (data.Contains("error_type")) - { - Console.WriteLine("Error sent by user server when trying to get user profile: (" + data["error_type"] + "): " + data["error_desc"]); - return null; - } - - UserProfileData userData = new UserProfileData(); - userData.username = (string)data["firstname"]; - userData.surname = (string)data["lastname"]; - userData.UUID = new LLUUID((string)data["uuid"]); - userData.userInventoryURI = (string)data["server_inventory"]; - userData.userAssetURI = (string)data["server_asset"]; - userData.profileFirstText = (string)data["profile_firstlife_about"]; - userData.profileFirstImage = new LLUUID((string)data["profile_firstlife_image"]); - userData.profileCanDoMask = Convert.ToUInt32((string)data["profile_can_do"]); - userData.profileWantDoMask = Convert.ToUInt32(data["profile_want_do"]); - userData.profileImage = new LLUUID((string)data["profile_image"]); - userData.lastLogin = Convert.ToInt32((string)data["profile_lastlogin"]); - userData.homeRegion = Convert.ToUInt64((string)data["home_region"]); - userData.homeLocation = new LLVector3((float)Convert.ToDecimal((string)data["home_coordinates_x"]), (float)Convert.ToDecimal((string)data["home_coordinates_y"]), (float)Convert.ToDecimal((string)data["home_coordinates_z"])); - userData.homeLookAt = new LLVector3((float)Convert.ToDecimal((string)data["home_look_x"]), (float)Convert.ToDecimal((string)data["home_look_y"]), (float)Convert.ToDecimal((string)data["home_look_z"])); - - return userData; - } - public UserProfileData GetUserProfile(string firstName, string lastName) - { - return GetUserProfile(firstName + " " + lastName); - } - public UserProfileData GetUserProfile(string name) - { - //try - //{ - Hashtable param = new Hashtable(); - param["avatar_name"] = name; - IList parameters = new ArrayList(); - parameters.Add(param); - XmlRpcRequest req = new XmlRpcRequest("get_user_by_name", parameters); - XmlRpcResponse resp = req.Send(m_parent.ServersInfo.UserURL, 3000); - Hashtable respData = (Hashtable)resp.Value; - - return ConvertXMLRPCDataToUserProfile(respData); - //} - //catch (Exception e) - //{ - // Console.WriteLine("Error when trying to fetch profile data by name from remote user server: " + e.Message); - //} - //return null; - } - public UserProfileData GetUserProfile(LLUUID avatarID) - { - try - { - - Hashtable param = new Hashtable(); - param["avatar_uuid"] = avatarID.ToString(); - IList parameters = new ArrayList(); - parameters.Add(param); - XmlRpcRequest req = new XmlRpcRequest("get_user_by_uuid", parameters); - XmlRpcResponse resp = req.Send(m_parent.ServersInfo.UserURL, 3000); - Hashtable respData = (Hashtable)resp.Value; - - return ConvertXMLRPCDataToUserProfile(respData); - } - catch (Exception e) - { - Console.WriteLine("Error when trying to fetch profile data by uuid from remote user server: " + e.Message); - } - return null; - } - - public UserProfileData SetupMasterUser(string firstName, string lastName) - { - return SetupMasterUser(firstName, lastName, ""); - } - - public UserProfileData SetupMasterUser(string firstName, string lastName, string password) - { - UserProfileData profile = GetUserProfile(firstName, lastName); - return profile; - } - } -} +using System; +using System.Collections; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Data; + +namespace OpenSim.Region.Communications.OGS1 +{ + public class OGS1UserServices :IUserServices + { + CommunicationsOGS1 m_parent; + public OGS1UserServices(CommunicationsOGS1 parent) + { + m_parent = parent; + } + + public UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data) + { + if (data.Contains("error_type")) + { + Console.WriteLine("Error sent by user server when trying to get user profile: (" + data["error_type"] + "): " + data["error_desc"]); + return null; + } + + UserProfileData userData = new UserProfileData(); + userData.username = (string)data["firstname"]; + userData.surname = (string)data["lastname"]; + userData.UUID = new LLUUID((string)data["uuid"]); + userData.userInventoryURI = (string)data["server_inventory"]; + userData.userAssetURI = (string)data["server_asset"]; + userData.profileFirstText = (string)data["profile_firstlife_about"]; + userData.profileFirstImage = new LLUUID((string)data["profile_firstlife_image"]); + userData.profileCanDoMask = Convert.ToUInt32((string)data["profile_can_do"]); + userData.profileWantDoMask = Convert.ToUInt32(data["profile_want_do"]); + userData.profileImage = new LLUUID((string)data["profile_image"]); + userData.lastLogin = Convert.ToInt32((string)data["profile_lastlogin"]); + userData.homeRegion = Convert.ToUInt64((string)data["home_region"]); + userData.homeLocation = new LLVector3((float)Convert.ToDecimal((string)data["home_coordinates_x"]), (float)Convert.ToDecimal((string)data["home_coordinates_y"]), (float)Convert.ToDecimal((string)data["home_coordinates_z"])); + userData.homeLookAt = new LLVector3((float)Convert.ToDecimal((string)data["home_look_x"]), (float)Convert.ToDecimal((string)data["home_look_y"]), (float)Convert.ToDecimal((string)data["home_look_z"])); + + return userData; + } + public UserProfileData GetUserProfile(string firstName, string lastName) + { + return GetUserProfile(firstName + " " + lastName); + } + public UserProfileData GetUserProfile(string name) + { + //try + //{ + Hashtable param = new Hashtable(); + param["avatar_name"] = name; + IList parameters = new ArrayList(); + parameters.Add(param); + XmlRpcRequest req = new XmlRpcRequest("get_user_by_name", parameters); + XmlRpcResponse resp = req.Send(m_parent.ServersInfo.UserURL, 3000); + Hashtable respData = (Hashtable)resp.Value; + + return ConvertXMLRPCDataToUserProfile(respData); + //} + //catch (Exception e) + //{ + // Console.WriteLine("Error when trying to fetch profile data by name from remote user server: " + e.Message); + //} + //return null; + } + public UserProfileData GetUserProfile(LLUUID avatarID) + { + try + { + + Hashtable param = new Hashtable(); + param["avatar_uuid"] = avatarID.ToString(); + IList parameters = new ArrayList(); + parameters.Add(param); + XmlRpcRequest req = new XmlRpcRequest("get_user_by_uuid", parameters); + XmlRpcResponse resp = req.Send(m_parent.ServersInfo.UserURL, 3000); + Hashtable respData = (Hashtable)resp.Value; + + return ConvertXMLRPCDataToUserProfile(respData); + } + catch (Exception e) + { + Console.WriteLine("Error when trying to fetch profile data by uuid from remote user server: " + e.Message); + } + return null; + } + + public UserProfileData SetupMasterUser(string firstName, string lastName) + { + return SetupMasterUser(firstName, lastName, ""); + } + + public UserProfileData SetupMasterUser(string firstName, string lastName, string password) + { + UserProfileData profile = GetUserProfile(firstName, lastName); + return profile; + } + } +} diff --git a/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs b/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs index 41f811a..2bebf9f 100644 --- a/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs @@ -1,33 +1,33 @@ -using System.Reflection; -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")] +using System.Reflection; +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/Region/Environment/EstateManager.cs b/OpenSim/Region/Environment/EstateManager.cs index de0b040..3742486 100644 --- a/OpenSim/Region/Environment/EstateManager.cs +++ b/OpenSim/Region/Environment/EstateManager.cs @@ -1,299 +1,299 @@ -/* -* 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.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Region.Environment.Scenes; -using Avatar = OpenSim.Region.Environment.Scenes.ScenePresence; - - -namespace OpenSim.Region.Environment -{ - - /// - /// 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": - this.sendRegionInfoPacketToAll(); - - break; - case "setregioninfo": - if (packet.ParamList.Length != 9) - { - MainLog.Instance.Error("EstateOwnerMessage: SetRegionInfo method has a ParamList of invalid length"); - } - else - { - m_regInfo.estateSettings.regionFlags = Simulator.RegionFlags.None; - - if (convertParamStringToBool(packet.ParamList[0].Parameter)) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.BlockTerraform; - } - - if (convertParamStringToBool(packet.ParamList[1].Parameter)) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.NoFly; - } - - if (convertParamStringToBool(packet.ParamList[2].Parameter)) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.AllowDamage; - } - - if (convertParamStringToBool(packet.ParamList[3].Parameter) == false) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | 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 = (Simulator.SimAccess)tempMatureLevel; - - - if (convertParamStringToBool(packet.ParamList[7].Parameter)) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.RestrictPushObject; - } - - if (convertParamStringToBool(packet.ParamList[8].Parameter)) - { - m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | 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) - { - 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: - 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 = 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); - } - - } -} +/* +* 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.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Region.Environment.Scenes; +using Avatar = OpenSim.Region.Environment.Scenes.ScenePresence; + + +namespace OpenSim.Region.Environment +{ + + /// + /// 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": + this.sendRegionInfoPacketToAll(); + + break; + case "setregioninfo": + if (packet.ParamList.Length != 9) + { + MainLog.Instance.Error("EstateOwnerMessage: SetRegionInfo method has a ParamList of invalid length"); + } + else + { + m_regInfo.estateSettings.regionFlags = Simulator.RegionFlags.None; + + if (convertParamStringToBool(packet.ParamList[0].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.BlockTerraform; + } + + if (convertParamStringToBool(packet.ParamList[1].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.NoFly; + } + + if (convertParamStringToBool(packet.ParamList[2].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.AllowDamage; + } + + if (convertParamStringToBool(packet.ParamList[3].Parameter) == false) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | 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 = (Simulator.SimAccess)tempMatureLevel; + + + if (convertParamStringToBool(packet.ParamList[7].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | Simulator.RegionFlags.RestrictPushObject; + } + + if (convertParamStringToBool(packet.ParamList[8].Parameter)) + { + m_regInfo.estateSettings.regionFlags = m_regInfo.estateSettings.regionFlags | 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) + { + 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: + 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 = 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/Environment/Interfaces/IRegionDataStore.cs b/OpenSim/Region/Environment/Interfaces/IRegionDataStore.cs index c068866..6ee57a5 100644 --- a/OpenSim/Region/Environment/Interfaces/IRegionDataStore.cs +++ b/OpenSim/Region/Environment/Interfaces/IRegionDataStore.cs @@ -1,63 +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 libsecondlife; - -using OpenSim.Framework.Types; -using OpenSim.Region; -using OpenSim.Region.Environment; -using OpenSim.Region.Environment.Scenes; - -using System.Collections.Generic; - -namespace OpenSim.Region.Interfaces -{ - public interface IRegionDataStore - { - /// - /// Initialises the data storage engine - /// - /// The file to save the database to (may not be applicable) - /// The name of the database to store to (may not be applicable) - void Initialise(string filename, string dbname); - - void StoreObject(SceneObject obj); - void RemoveObject(LLUUID uuid); - - List LoadObjects(); - - void StoreTerrain(double[,] terrain); - double[,] LoadTerrain(); - - void StoreParcel(OpenSim.Region.Environment.Parcel Parcel); - void RemoveParcel(uint ID); - List LoadParcels(); - - void Shutdown(); - } +/* +* 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 libsecondlife; + +using OpenSim.Framework.Types; +using OpenSim.Region; +using OpenSim.Region.Environment; +using OpenSim.Region.Environment.Scenes; + +using System.Collections.Generic; + +namespace OpenSim.Region.Interfaces +{ + public interface IRegionDataStore + { + /// + /// Initialises the data storage engine + /// + /// The file to save the database to (may not be applicable) + /// The name of the database to store to (may not be applicable) + void Initialise(string filename, string dbname); + + void StoreObject(SceneObject obj); + void RemoveObject(LLUUID uuid); + + List LoadObjects(); + + void StoreTerrain(double[,] terrain); + double[,] LoadTerrain(); + + void StoreParcel(OpenSim.Region.Environment.Parcel Parcel); + void RemoveParcel(uint ID); + List LoadParcels(); + + void Shutdown(); + } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/ParcelManager.cs b/OpenSim/Region/Environment/ParcelManager.cs index 31b9b1d..fbff556 100644 --- a/OpenSim/Region/Environment/ParcelManager.cs +++ b/OpenSim/Region/Environment/ParcelManager.cs @@ -1,1206 +1,1206 @@ -/* -* 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 libsecondlife.Packets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Region.Environment.Scenes; -using Avatar = OpenSim.Region.Environment.Scenes.ScenePresence; -using System.IO; - -namespace OpenSim.Region.Environment -{ - - - #region ParcelManager Class - /// - /// Handles Parcel objects and operations requiring information from other Parcel objects (divide, join, etc) - /// - public class ParcelManager : 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 - - //ParcelSelectObjects - public const int PARCEL_SELECT_OBJECTS_OWNER = 2; - public const int PARCEL_SELECT_OBJECTS_GROUP = 4; - public const int PARCEL_SELECT_OBJECTS_OTHER = 8; - - - //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]; - - /// - /// Set to true when a prim is moved, created, added. Performs a prim count update - /// - public bool parcelPrimCountTainted = false; - - 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 Parcel 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(); - - return new_parcel; - - } - /// - /// 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(float x_float, float y_float) - { - int x = Convert.ToInt32(Math.Floor(Convert.ToDecimal(x_float) / Convert.ToDecimal(4.0))); - int y = Convert.ToInt32(Math.Floor(Convert.ToDecimal(y_float) / Convert.ToDecimal(4.0))); - - if (x > 63 || y > 63 || x < 0 || y < 0) - { - throw new Exception("Error: Parcel not found at point " + x + ", " + y); - } - else - { - // Console.WriteLine("Point (" + x + ", " + y + ") determined from point (" + x_float + ", " + y_float + ")"); - return parcelList[parcelIDList[x, y]]; - } - } - - 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(); - - - this.setPrimsTainted(); - - //Now add the new parcel - Parcel result = addParcel(newParcel); - result.sendParcelUpdateToAvatarsOverMe(); - - - - - 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; - - List selectedParcels = new List(); - int stepXSelected = 0; - int stepYSelected = 0; - for (stepYSelected = start_y; stepYSelected <= end_y; stepYSelected += 4) - { - for (stepXSelected = start_x; stepXSelected <= end_x; stepXSelected += 4) - { - Parcel p = getParcel(stepXSelected,stepYSelected); - if (!selectedParcels.Contains(p)) - { - selectedParcels.Add(p); - } - } - } - Parcel masterParcel = selectedParcels[0]; - selectedParcels.RemoveAt(0); - - - if (selectedParcels.Count < 1) - { - return false; //Only one parcel selected - } - if (masterParcel.parcelData.ownerID != attempting_user_id) - { - return false; //Not the same owner - } - foreach (Parcel p in selectedParcels) - { - if (p.parcelData.ownerID != masterParcel.parcelData.ownerID) - { - return false; //Over multiple users. TODO: make this just ignore this parcel? - } - } - foreach (Parcel slaveParcel in selectedParcels) - { - parcelList[masterParcel.parcelData.localID].setParcelBitmap(Parcel.mergeParcelBitmaps(masterParcel.getParcelBitmap(), slaveParcel.getParcelBitmap())); - performFinalParcelJoin(masterParcel, slaveParcel); - } - - - this.setPrimsTainted(); - - masterParcel.sendParcelUpdateToAvatarsOverMe(); - - 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]; - } - } - } - - - } - - 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++) - { - Parcel currentParcel = getParcel(start_x + x, start_y + y); - if (!temp.Contains(currentParcel)) - { - currentParcel.forceUpdateParcelInfo(); - temp.Add(currentParcel); - } - } - } - - int requestResult = PARCEL_RESULT_ONE_PARCEL; - if (temp.Count > 1) - { - requestResult = 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); - - } - - public void handleParcelSelectObjectsRequest(int local_id, int request_type, IClientAPI remote_client) - { - parcelList[local_id].sendForceObjectSelect(local_id, request_type, remote_client); - } - - public void handleParcelObjectOwnersRequest(int local_id, IClientAPI remote_client) - { - parcelList[local_id].sendParcelObjectOwners(remote_client); - } - #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.ownerID = m_regInfo.MasterAvatarAssignedUUID; - - addParcel(fullSimParcel); - - } - - - public void handleSignificantClientMovement(IClientAPI remote_client) - { - Avatar clientAvatar = m_world.RequestAvatar(remote_client.AgentId); - if (clientAvatar != null) - { - Parcel over = getParcel(clientAvatar.Pos.X,clientAvatar.Pos.Y); - if (over != null) - { - over.sendParcelProperties(0, false, 0, remote_client); - } - } - } - - public void resetAllParcelPrimCounts() - { - foreach (Parcel p in parcelList.Values) - { - p.resetParcelPrimCounts(); - } - } - public void setPrimsTainted() - { - this.parcelPrimCountTainted = true; - } - - public void addPrimToParcelCounts(SceneObject obj) - { - LLVector3 position = obj.Pos; - Parcel parcelUnderPrim = getParcel(position.X, position.Y); - if (parcelUnderPrim != null) - { - parcelUnderPrim.addPrimToCount(obj); - } - } - - public void removePrimFromParcelCounts(SceneObject obj) - { - foreach (Parcel p in parcelList.Values) - { - p.removePrimFromCount(obj); - } - } - - public void finalizeParcelPrimCountUpdate() - { - //Get Simwide prim count for owner - Dictionary> parcelOwnersAndParcels = new Dictionary>(); - foreach (Parcel p in parcelList.Values) - { - if(!parcelOwnersAndParcels.ContainsKey(p.parcelData.ownerID)) - { - List tempList = new List(); - tempList.Add(p); - parcelOwnersAndParcels.Add(p.parcelData.ownerID,tempList); - } - else - { - parcelOwnersAndParcels[p.parcelData.ownerID].Add(p); - } - } - - foreach (LLUUID owner in parcelOwnersAndParcels.Keys) - { - int simArea = 0; - int simPrims = 0; - foreach (Parcel p in parcelOwnersAndParcels[owner]) - { - simArea += p.parcelData.area; - simPrims += p.parcelData.ownerPrims + p.parcelData.otherPrims + p.parcelData.groupPrims + p.parcelData.selectedPrims; - } - - foreach (Parcel p in parcelOwnersAndParcels[owner]) - { - p.parcelData.simwideArea = simArea; - p.parcelData.simwidePrims = simPrims; - } - } - - } - #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 List primsOverMe = new List(); - - 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 = 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; - if (parcelData.area > 0) - { - updatePacket.ParcelData.MaxPrims = Convert.ToInt32(Math.Round((Convert.ToDecimal(parcelData.area) / Convert.ToDecimal(65536)) * 15000 * Convert.ToDecimal(m_world.RegionInfo.estateSettings.objectBonusFactor))); - } - else - { - updatePacket.ParcelData.MaxPrims = 0; - } - 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 = parcelData.otherPrims; - updatePacket.ParcelData.OwnerID = parcelData.ownerID; - updatePacket.ParcelData.OwnerPrims = parcelData.ownerPrims; - updatePacket.ParcelData.ParcelFlags = parcelData.parcelFlags; - updatePacket.ParcelData.ParcelPrimBonus = m_world.RegionInfo.estateSettings.objectBonusFactor; - updatePacket.ParcelData.PassHours = parcelData.passHours; - updatePacket.ParcelData.PassPrice = parcelData.passPrice; - updatePacket.ParcelData.PublicCount = 0; //unemplemented - updatePacket.ParcelData.RegionDenyAnonymous = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyAnonymous) > 0); - updatePacket.ParcelData.RegionDenyIdentified = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyIdentified) > 0); - updatePacket.ParcelData.RegionDenyTransacted = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyTransacted) > 0); - updatePacket.ParcelData.RegionPushOverride = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.RestrictPushObject) > 0); - updatePacket.ParcelData.RentPrice = 0; - updatePacket.ParcelData.RequestResult = request_result; - updatePacket.ParcelData.SalePrice = parcelData.salePrice; - updatePacket.ParcelData.SelectedPrims = parcelData.selectedPrims; - updatePacket.ParcelData.SelfCount = 0;//unemplemented - updatePacket.ParcelData.SequenceID = sequence_id; - if (parcelData.simwideArea > 0) - { - updatePacket.ParcelData.SimWideMaxPrims = Convert.ToInt32(Math.Round((Convert.ToDecimal(parcelData.simwideArea) / Convert.ToDecimal(65536)) * 15000 * Convert.ToDecimal(m_world.RegionInfo.estateSettings.objectBonusFactor))); - } - else - { - updatePacket.ParcelData.SimWideMaxPrims = 0; - } - updatePacket.ParcelData.SimWideTotalPrims = parcelData.simwidePrims; - updatePacket.ParcelData.SnapSelection = snap_selection; - updatePacket.ParcelData.SnapshotID = parcelData.snapshotID; - updatePacket.ParcelData.Status = (byte)parcelData.parcelStatus; - updatePacket.ParcelData.TotalPrims = parcelData.ownerPrims + parcelData.groupPrims + parcelData.otherPrims + parcelData.selectedPrims; - 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 = Helpers.FieldToUTF8String(packet.ParcelData.Name); - parcelData.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; - sendParcelUpdateToAvatarsOverMe(); - - - } - } - - public void sendParcelUpdateToAvatarsOverMe() - { - 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.parcelData.localID == this.parcelData.localID) - { - 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), (float)m_world.Terrain.get((min_x * 4), (min_y * 4))); - parcelData.AABBMax = new LLVector3((float)(max_x * 4), (float)(max_y * 4), (float)m_world.Terrain.get((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 - - #region Object Select and Object Owner Listing - public void sendForceObjectSelect(int local_id, int request_type, IClientAPI remote_client) - { - List resultLocalIDs = new List(); - foreach (SceneObject obj in primsOverMe) - { - if (obj.rootLocalID > 0) - { - if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_OWNER && obj.rootPrimitive.OwnerID == this.parcelData.ownerID) - { - resultLocalIDs.Add(obj.rootLocalID); - } - else if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_GROUP && false) //TODO: change false to group support! - { - - } - else if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_OTHER && obj.rootPrimitive.OwnerID != remote_client.AgentId) - { - resultLocalIDs.Add(obj.rootLocalID); - } - } - } - - - bool firstCall = true; - int MAX_OBJECTS_PER_PACKET = 251; - ForceObjectSelectPacket pack = new ForceObjectSelectPacket(); - ForceObjectSelectPacket.DataBlock[] data; - while (resultLocalIDs.Count > 0) - { - if (firstCall) - { - pack._Header.ResetList = true; - firstCall = false; - } - else - { - pack._Header.ResetList = false; - } - - if (resultLocalIDs.Count > MAX_OBJECTS_PER_PACKET) - { - data = new ForceObjectSelectPacket.DataBlock[MAX_OBJECTS_PER_PACKET]; - } - else - { - data = new ForceObjectSelectPacket.DataBlock[resultLocalIDs.Count]; - } - - int i; - for (i = 0; i < MAX_OBJECTS_PER_PACKET && resultLocalIDs.Count > 0; i++) - { - data[i] = new ForceObjectSelectPacket.DataBlock(); - data[i].LocalID = Convert.ToUInt32(resultLocalIDs[0]); - resultLocalIDs.RemoveAt(0); - } - pack.Data = data; - remote_client.OutPacket((Packet)pack); - } - - } - public void sendParcelObjectOwners(IClientAPI remote_client) - { - Dictionary ownersAndCount = new Dictionary(); - foreach(SceneObject obj in primsOverMe) - { - if(!ownersAndCount.ContainsKey(obj.rootPrimitive.OwnerID)) - { - ownersAndCount.Add(obj.rootPrimitive.OwnerID,0); - } - ownersAndCount[obj.rootPrimitive.OwnerID] += obj.primCount; - } - if (ownersAndCount.Count > 0) - { - - ParcelObjectOwnersReplyPacket.DataBlock[] dataBlock = new ParcelObjectOwnersReplyPacket.DataBlock[32]; - - if(ownersAndCount.Count < 32) - { - dataBlock = new ParcelObjectOwnersReplyPacket.DataBlock[ownersAndCount.Count]; - } - - - int num = 0; - foreach (LLUUID owner in ownersAndCount.Keys) - { - dataBlock[num] = new ParcelObjectOwnersReplyPacket.DataBlock(); - dataBlock[num].Count = ownersAndCount[owner]; - dataBlock[num].IsGroupOwned = false; //TODO: fix me when group support is added - dataBlock[num].OnlineStatus = true; //TODO: fix me later - dataBlock[num].OwnerID = owner; - - num++; - } - - ParcelObjectOwnersReplyPacket pack = new ParcelObjectOwnersReplyPacket(); - pack.Data = dataBlock; - remote_client.OutPacket(pack); - } - } - #endregion - - #region Object Returning - public void returnObject(SceneObject obj) - { - } - public void returnParcelObjects(int type, LLUUID owner) - { - - } - #endregion - - #region Object Adding/Removing from Parcel - public void resetParcelPrimCounts() - { - parcelData.groupPrims = 0; - parcelData.ownerPrims = 0; - parcelData.otherPrims = 0; - parcelData.selectedPrims = 0; - primsOverMe.Clear(); - } - - public void addPrimToCount(SceneObject obj) - { - LLUUID prim_owner = obj.rootPrimitive.OwnerID; - int prim_count = obj.primCount; - - if (obj.isSelected) - { - parcelData.selectedPrims += prim_count; - } - else - { - if (prim_owner == parcelData.ownerID) - { - parcelData.ownerPrims += prim_count; - } - else - { - parcelData.otherPrims += prim_count; - } - } - - primsOverMe.Add(obj); - - } - - public void removePrimFromCount(SceneObject obj) - { - if (primsOverMe.Contains(obj)) - { - LLUUID prim_owner = obj.rootPrimitive.OwnerID; - int prim_count = obj.primCount; - - if (prim_owner == parcelData.ownerID) - { - parcelData.ownerPrims -= prim_count; - } - else if (prim_owner == parcelData.groupID) - { - parcelData.groupPrims -= prim_count; - } - else - { - parcelData.otherPrims -= prim_count; - } - - primsOverMe.Remove(obj); - } - } - #endregion - - #endregion - - - } - #endregion - - -} +/* +* 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 libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Region.Environment.Scenes; +using Avatar = OpenSim.Region.Environment.Scenes.ScenePresence; +using System.IO; + +namespace OpenSim.Region.Environment +{ + + + #region ParcelManager Class + /// + /// Handles Parcel objects and operations requiring information from other Parcel objects (divide, join, etc) + /// + public class ParcelManager : 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 + + //ParcelSelectObjects + public const int PARCEL_SELECT_OBJECTS_OWNER = 2; + public const int PARCEL_SELECT_OBJECTS_GROUP = 4; + public const int PARCEL_SELECT_OBJECTS_OTHER = 8; + + + //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]; + + /// + /// Set to true when a prim is moved, created, added. Performs a prim count update + /// + public bool parcelPrimCountTainted = false; + + 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 Parcel 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(); + + return new_parcel; + + } + /// + /// 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(float x_float, float y_float) + { + int x = Convert.ToInt32(Math.Floor(Convert.ToDecimal(x_float) / Convert.ToDecimal(4.0))); + int y = Convert.ToInt32(Math.Floor(Convert.ToDecimal(y_float) / Convert.ToDecimal(4.0))); + + if (x > 63 || y > 63 || x < 0 || y < 0) + { + throw new Exception("Error: Parcel not found at point " + x + ", " + y); + } + else + { + // Console.WriteLine("Point (" + x + ", " + y + ") determined from point (" + x_float + ", " + y_float + ")"); + return parcelList[parcelIDList[x, y]]; + } + } + + 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(); + + + this.setPrimsTainted(); + + //Now add the new parcel + Parcel result = addParcel(newParcel); + result.sendParcelUpdateToAvatarsOverMe(); + + + + + 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; + + List selectedParcels = new List(); + int stepXSelected = 0; + int stepYSelected = 0; + for (stepYSelected = start_y; stepYSelected <= end_y; stepYSelected += 4) + { + for (stepXSelected = start_x; stepXSelected <= end_x; stepXSelected += 4) + { + Parcel p = getParcel(stepXSelected,stepYSelected); + if (!selectedParcels.Contains(p)) + { + selectedParcels.Add(p); + } + } + } + Parcel masterParcel = selectedParcels[0]; + selectedParcels.RemoveAt(0); + + + if (selectedParcels.Count < 1) + { + return false; //Only one parcel selected + } + if (masterParcel.parcelData.ownerID != attempting_user_id) + { + return false; //Not the same owner + } + foreach (Parcel p in selectedParcels) + { + if (p.parcelData.ownerID != masterParcel.parcelData.ownerID) + { + return false; //Over multiple users. TODO: make this just ignore this parcel? + } + } + foreach (Parcel slaveParcel in selectedParcels) + { + parcelList[masterParcel.parcelData.localID].setParcelBitmap(Parcel.mergeParcelBitmaps(masterParcel.getParcelBitmap(), slaveParcel.getParcelBitmap())); + performFinalParcelJoin(masterParcel, slaveParcel); + } + + + this.setPrimsTainted(); + + masterParcel.sendParcelUpdateToAvatarsOverMe(); + + 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]; + } + } + } + + + } + + 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++) + { + Parcel currentParcel = getParcel(start_x + x, start_y + y); + if (!temp.Contains(currentParcel)) + { + currentParcel.forceUpdateParcelInfo(); + temp.Add(currentParcel); + } + } + } + + int requestResult = PARCEL_RESULT_ONE_PARCEL; + if (temp.Count > 1) + { + requestResult = 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); + + } + + public void handleParcelSelectObjectsRequest(int local_id, int request_type, IClientAPI remote_client) + { + parcelList[local_id].sendForceObjectSelect(local_id, request_type, remote_client); + } + + public void handleParcelObjectOwnersRequest(int local_id, IClientAPI remote_client) + { + parcelList[local_id].sendParcelObjectOwners(remote_client); + } + #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.ownerID = m_regInfo.MasterAvatarAssignedUUID; + + addParcel(fullSimParcel); + + } + + + public void handleSignificantClientMovement(IClientAPI remote_client) + { + Avatar clientAvatar = m_world.RequestAvatar(remote_client.AgentId); + if (clientAvatar != null) + { + Parcel over = getParcel(clientAvatar.Pos.X,clientAvatar.Pos.Y); + if (over != null) + { + over.sendParcelProperties(0, false, 0, remote_client); + } + } + } + + public void resetAllParcelPrimCounts() + { + foreach (Parcel p in parcelList.Values) + { + p.resetParcelPrimCounts(); + } + } + public void setPrimsTainted() + { + this.parcelPrimCountTainted = true; + } + + public void addPrimToParcelCounts(SceneObject obj) + { + LLVector3 position = obj.Pos; + Parcel parcelUnderPrim = getParcel(position.X, position.Y); + if (parcelUnderPrim != null) + { + parcelUnderPrim.addPrimToCount(obj); + } + } + + public void removePrimFromParcelCounts(SceneObject obj) + { + foreach (Parcel p in parcelList.Values) + { + p.removePrimFromCount(obj); + } + } + + public void finalizeParcelPrimCountUpdate() + { + //Get Simwide prim count for owner + Dictionary> parcelOwnersAndParcels = new Dictionary>(); + foreach (Parcel p in parcelList.Values) + { + if(!parcelOwnersAndParcels.ContainsKey(p.parcelData.ownerID)) + { + List tempList = new List(); + tempList.Add(p); + parcelOwnersAndParcels.Add(p.parcelData.ownerID,tempList); + } + else + { + parcelOwnersAndParcels[p.parcelData.ownerID].Add(p); + } + } + + foreach (LLUUID owner in parcelOwnersAndParcels.Keys) + { + int simArea = 0; + int simPrims = 0; + foreach (Parcel p in parcelOwnersAndParcels[owner]) + { + simArea += p.parcelData.area; + simPrims += p.parcelData.ownerPrims + p.parcelData.otherPrims + p.parcelData.groupPrims + p.parcelData.selectedPrims; + } + + foreach (Parcel p in parcelOwnersAndParcels[owner]) + { + p.parcelData.simwideArea = simArea; + p.parcelData.simwidePrims = simPrims; + } + } + + } + #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 List primsOverMe = new List(); + + 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 = 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; + if (parcelData.area > 0) + { + updatePacket.ParcelData.MaxPrims = Convert.ToInt32(Math.Round((Convert.ToDecimal(parcelData.area) / Convert.ToDecimal(65536)) * 15000 * Convert.ToDecimal(m_world.RegionInfo.estateSettings.objectBonusFactor))); + } + else + { + updatePacket.ParcelData.MaxPrims = 0; + } + 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 = parcelData.otherPrims; + updatePacket.ParcelData.OwnerID = parcelData.ownerID; + updatePacket.ParcelData.OwnerPrims = parcelData.ownerPrims; + updatePacket.ParcelData.ParcelFlags = parcelData.parcelFlags; + updatePacket.ParcelData.ParcelPrimBonus = m_world.RegionInfo.estateSettings.objectBonusFactor; + updatePacket.ParcelData.PassHours = parcelData.passHours; + updatePacket.ParcelData.PassPrice = parcelData.passPrice; + updatePacket.ParcelData.PublicCount = 0; //unemplemented + updatePacket.ParcelData.RegionDenyAnonymous = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyAnonymous) > 0); + updatePacket.ParcelData.RegionDenyIdentified = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyIdentified) > 0); + updatePacket.ParcelData.RegionDenyTransacted = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.DenyTransacted) > 0); + updatePacket.ParcelData.RegionPushOverride = (((uint)m_world.RegionInfo.estateSettings.regionFlags & (uint)Simulator.RegionFlags.RestrictPushObject) > 0); + updatePacket.ParcelData.RentPrice = 0; + updatePacket.ParcelData.RequestResult = request_result; + updatePacket.ParcelData.SalePrice = parcelData.salePrice; + updatePacket.ParcelData.SelectedPrims = parcelData.selectedPrims; + updatePacket.ParcelData.SelfCount = 0;//unemplemented + updatePacket.ParcelData.SequenceID = sequence_id; + if (parcelData.simwideArea > 0) + { + updatePacket.ParcelData.SimWideMaxPrims = Convert.ToInt32(Math.Round((Convert.ToDecimal(parcelData.simwideArea) / Convert.ToDecimal(65536)) * 15000 * Convert.ToDecimal(m_world.RegionInfo.estateSettings.objectBonusFactor))); + } + else + { + updatePacket.ParcelData.SimWideMaxPrims = 0; + } + updatePacket.ParcelData.SimWideTotalPrims = parcelData.simwidePrims; + updatePacket.ParcelData.SnapSelection = snap_selection; + updatePacket.ParcelData.SnapshotID = parcelData.snapshotID; + updatePacket.ParcelData.Status = (byte)parcelData.parcelStatus; + updatePacket.ParcelData.TotalPrims = parcelData.ownerPrims + parcelData.groupPrims + parcelData.otherPrims + parcelData.selectedPrims; + 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 = Helpers.FieldToUTF8String(packet.ParcelData.Name); + parcelData.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; + sendParcelUpdateToAvatarsOverMe(); + + + } + } + + public void sendParcelUpdateToAvatarsOverMe() + { + 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.parcelData.localID == this.parcelData.localID) + { + 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), (float)m_world.Terrain.get((min_x * 4), (min_y * 4))); + parcelData.AABBMax = new LLVector3((float)(max_x * 4), (float)(max_y * 4), (float)m_world.Terrain.get((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 + + #region Object Select and Object Owner Listing + public void sendForceObjectSelect(int local_id, int request_type, IClientAPI remote_client) + { + List resultLocalIDs = new List(); + foreach (SceneObject obj in primsOverMe) + { + if (obj.rootLocalID > 0) + { + if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_OWNER && obj.rootPrimitive.OwnerID == this.parcelData.ownerID) + { + resultLocalIDs.Add(obj.rootLocalID); + } + else if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_GROUP && false) //TODO: change false to group support! + { + + } + else if (request_type == ParcelManager.PARCEL_SELECT_OBJECTS_OTHER && obj.rootPrimitive.OwnerID != remote_client.AgentId) + { + resultLocalIDs.Add(obj.rootLocalID); + } + } + } + + + bool firstCall = true; + int MAX_OBJECTS_PER_PACKET = 251; + ForceObjectSelectPacket pack = new ForceObjectSelectPacket(); + ForceObjectSelectPacket.DataBlock[] data; + while (resultLocalIDs.Count > 0) + { + if (firstCall) + { + pack._Header.ResetList = true; + firstCall = false; + } + else + { + pack._Header.ResetList = false; + } + + if (resultLocalIDs.Count > MAX_OBJECTS_PER_PACKET) + { + data = new ForceObjectSelectPacket.DataBlock[MAX_OBJECTS_PER_PACKET]; + } + else + { + data = new ForceObjectSelectPacket.DataBlock[resultLocalIDs.Count]; + } + + int i; + for (i = 0; i < MAX_OBJECTS_PER_PACKET && resultLocalIDs.Count > 0; i++) + { + data[i] = new ForceObjectSelectPacket.DataBlock(); + data[i].LocalID = Convert.ToUInt32(resultLocalIDs[0]); + resultLocalIDs.RemoveAt(0); + } + pack.Data = data; + remote_client.OutPacket((Packet)pack); + } + + } + public void sendParcelObjectOwners(IClientAPI remote_client) + { + Dictionary ownersAndCount = new Dictionary(); + foreach(SceneObject obj in primsOverMe) + { + if(!ownersAndCount.ContainsKey(obj.rootPrimitive.OwnerID)) + { + ownersAndCount.Add(obj.rootPrimitive.OwnerID,0); + } + ownersAndCount[obj.rootPrimitive.OwnerID] += obj.primCount; + } + if (ownersAndCount.Count > 0) + { + + ParcelObjectOwnersReplyPacket.DataBlock[] dataBlock = new ParcelObjectOwnersReplyPacket.DataBlock[32]; + + if(ownersAndCount.Count < 32) + { + dataBlock = new ParcelObjectOwnersReplyPacket.DataBlock[ownersAndCount.Count]; + } + + + int num = 0; + foreach (LLUUID owner in ownersAndCount.Keys) + { + dataBlock[num] = new ParcelObjectOwnersReplyPacket.DataBlock(); + dataBlock[num].Count = ownersAndCount[owner]; + dataBlock[num].IsGroupOwned = false; //TODO: fix me when group support is added + dataBlock[num].OnlineStatus = true; //TODO: fix me later + dataBlock[num].OwnerID = owner; + + num++; + } + + ParcelObjectOwnersReplyPacket pack = new ParcelObjectOwnersReplyPacket(); + pack.Data = dataBlock; + remote_client.OutPacket(pack); + } + } + #endregion + + #region Object Returning + public void returnObject(SceneObject obj) + { + } + public void returnParcelObjects(int type, LLUUID owner) + { + + } + #endregion + + #region Object Adding/Removing from Parcel + public void resetParcelPrimCounts() + { + parcelData.groupPrims = 0; + parcelData.ownerPrims = 0; + parcelData.otherPrims = 0; + parcelData.selectedPrims = 0; + primsOverMe.Clear(); + } + + public void addPrimToCount(SceneObject obj) + { + LLUUID prim_owner = obj.rootPrimitive.OwnerID; + int prim_count = obj.primCount; + + if (obj.isSelected) + { + parcelData.selectedPrims += prim_count; + } + else + { + if (prim_owner == parcelData.ownerID) + { + parcelData.ownerPrims += prim_count; + } + else + { + parcelData.otherPrims += prim_count; + } + } + + primsOverMe.Add(obj); + + } + + public void removePrimFromCount(SceneObject obj) + { + if (primsOverMe.Contains(obj)) + { + LLUUID prim_owner = obj.rootPrimitive.OwnerID; + int prim_count = obj.primCount; + + if (prim_owner == parcelData.ownerID) + { + parcelData.ownerPrims -= prim_count; + } + else if (prim_owner == parcelData.groupID) + { + parcelData.groupPrims -= prim_count; + } + else + { + parcelData.otherPrims -= prim_count; + } + + primsOverMe.Remove(obj); + } + } + #endregion + + #endregion + + + } + #endregion + + +} diff --git a/OpenSim/Region/Environment/RegionManager.cs b/OpenSim/Region/Environment/RegionManager.cs index cd67e97..35fbf45 100644 --- a/OpenSim/Region/Environment/RegionManager.cs +++ b/OpenSim/Region/Environment/RegionManager.cs @@ -1,29 +1,29 @@ -using System.Collections.Generic; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; -using OpenSim.Region.Capabilities; -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Environment -{ - 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 Scene m_Scene; - - public ParcelManager parcelManager; - public EstateManager estateManager; - - public RegionManager() - { - - } - - } -} +using System.Collections.Generic; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; +using OpenSim.Region.Capabilities; +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Environment +{ + 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 Scene m_Scene; + + public ParcelManager parcelManager; + public EstateManager estateManager; + + public RegionManager() + { + + } + + } +} diff --git a/OpenSim/Region/Environment/Scenes/Entity.cs b/OpenSim/Region/Environment/Scenes/Entity.cs index 084c9ab..2456a4e 100644 --- a/OpenSim/Region/Environment/Scenes/Entity.cs +++ b/OpenSim/Region/Environment/Scenes/Entity.cs @@ -1,115 +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 libsecondlife; -using OpenSim.Physics.Manager; - -namespace OpenSim.Region.Environment.Scenes -{ - public abstract class Entity :EntityBase //this class (Entity) will be phased out - { - protected PhysicsActor _physActor; - - /// - /// - /// - public override 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 override LLVector3 Velocity - { - get - { - if (this._physActor != null) - { - m_velocity.X = _physActor.Velocity.X; - m_velocity.Y = _physActor.Velocity.Y; - m_velocity.Z = _physActor.Velocity.Z; - } - - return m_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); - } - } - - m_velocity = value; - } - } - } -} +/* +* 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.Physics.Manager; + +namespace OpenSim.Region.Environment.Scenes +{ + public abstract class Entity :EntityBase //this class (Entity) will be phased out + { + protected PhysicsActor _physActor; + + /// + /// + /// + public override 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 override LLVector3 Velocity + { + get + { + if (this._physActor != null) + { + m_velocity.X = _physActor.Velocity.X; + m_velocity.Y = _physActor.Velocity.Y; + m_velocity.Z = _physActor.Velocity.Z; + } + + return m_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); + } + } + + m_velocity = value; + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/EntityBase.cs b/OpenSim/Region/Environment/Scenes/EntityBase.cs index 65a0395..04cf595 100644 --- a/OpenSim/Region/Environment/Scenes/EntityBase.cs +++ b/OpenSim/Region/Environment/Scenes/EntityBase.cs @@ -1,142 +1,142 @@ -using System.Collections.Generic; -using Axiom.Math; -using libsecondlife; - -namespace OpenSim.Region.Environment.Scenes -{ - public abstract class EntityBase - { - public LLUUID uuid; - - protected List children; - - protected Scene m_world; - protected string m_name; - - /// - /// - /// - public virtual string Name - { - get { return m_name; } - set { m_name = value; } - } - - protected LLVector3 m_pos; - /// - /// - /// - public virtual LLVector3 Pos - { - get - { - return m_pos; - } - set - { - m_pos = value; - } - } - - public LLVector3 m_velocity; - - /// - /// - /// - public virtual LLVector3 Velocity - { - get - { - return m_velocity; - } - set - { - m_velocity = value; - } - } - - protected Quaternion m_rotation = new Quaternion(0,0,1,0); - - public virtual Quaternion Rotation - { - get - { - return m_rotation; - } - set - { - m_rotation = value; - } - } - - protected uint m_localId; - - public uint LocalId - { - get { return m_localId; } - set { m_localId = value; } - } - - /// - /// Creates a new Entity (should not occur on it's own) - /// - public EntityBase() - { - uuid = new LLUUID(); - - m_pos = new LLVector3(); - m_velocity = new LLVector3(); - Rotation = new Quaternion(); - m_name = "(basic entity)"; - children = new List(); - } - - /// - /// - /// - public virtual void updateMovement() - { - foreach (EntityBase 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 (EntityBase 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() - { - - } - - /// - /// Copies the entity - /// - /// - public virtual EntityBase Copy() - { - return (EntityBase)this.MemberwiseClone(); - } - - /// - /// Infoms the entity that the land (heightmap) has changed - /// - public virtual void LandRenegerated() - { - - } - } -} +using System.Collections.Generic; +using Axiom.Math; +using libsecondlife; + +namespace OpenSim.Region.Environment.Scenes +{ + public abstract class EntityBase + { + public LLUUID uuid; + + protected List children; + + protected Scene m_world; + protected string m_name; + + /// + /// + /// + public virtual string Name + { + get { return m_name; } + set { m_name = value; } + } + + protected LLVector3 m_pos; + /// + /// + /// + public virtual LLVector3 Pos + { + get + { + return m_pos; + } + set + { + m_pos = value; + } + } + + public LLVector3 m_velocity; + + /// + /// + /// + public virtual LLVector3 Velocity + { + get + { + return m_velocity; + } + set + { + m_velocity = value; + } + } + + protected Quaternion m_rotation = new Quaternion(0,0,1,0); + + public virtual Quaternion Rotation + { + get + { + return m_rotation; + } + set + { + m_rotation = value; + } + } + + protected uint m_localId; + + public uint LocalId + { + get { return m_localId; } + set { m_localId = value; } + } + + /// + /// Creates a new Entity (should not occur on it's own) + /// + public EntityBase() + { + uuid = new LLUUID(); + + m_pos = new LLVector3(); + m_velocity = new LLVector3(); + Rotation = new Quaternion(); + m_name = "(basic entity)"; + children = new List(); + } + + /// + /// + /// + public virtual void updateMovement() + { + foreach (EntityBase 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 (EntityBase 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() + { + + } + + /// + /// Copies the entity + /// + /// + public virtual EntityBase Copy() + { + return (EntityBase)this.MemberwiseClone(); + } + + /// + /// Infoms the entity that the land (heightmap) has changed + /// + public virtual void LandRenegerated() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs b/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs index 7c3a033..8551b70 100644 --- a/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs +++ b/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs @@ -1,14 +1,14 @@ -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Interfaces; - -namespace OpenSim.Region.Environment.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); - } -} +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Region.Environment.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/Environment/Scenes/Primitive.cs b/OpenSim/Region/Environment/Scenes/Primitive.cs index 0e5b083..b413758 100644 --- a/OpenSim/Region/Environment/Scenes/Primitive.cs +++ b/OpenSim/Region/Environment/Scenes/Primitive.cs @@ -1,648 +1,648 @@ -using System; -using System.Collections.Generic; -using Axiom.Math; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Inventory; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Environment.Scenes -{ - public delegate void PrimCountTaintedDelegate(); - - public class Primitive : EntityBase - { - private const uint FULL_MASK_PERMISSIONS = 2147483647; - - private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); - private ulong m_regionHandle; - private byte updateFlag = 0; - private uint m_flags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456 + 128; - - private Dictionary inventoryItems; - - private string m_description = ""; - - public string SitName = ""; - public string TouchName = ""; - public string Text = ""; - - public LLUUID CreatorID; - public LLUUID OwnerID; - public LLUUID LastOwnerID; - public Int32 CreationDate; - - public uint ParentID = 0; - - 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; - - private PrimitiveBaseShape m_Shape; - - public SceneObject m_RootParent; - public bool m_isRootPrim; - public EntityBase m_Parent; - - private EventManager m_eventManager; - - public event PrimCountTaintedDelegate OnPrimCountTainted; - - #region Properties - /// - /// If rootprim, will return world position - /// otherwise will return local offset from rootprim - /// - public override LLVector3 Pos - { - get - { - if (m_isRootPrim) - { - //if we are rootprim then our offset should be zero - return this.m_pos + m_Parent.Pos; - } - else - { - return this.m_pos; - } - } - set - { - if (m_isRootPrim) - { - m_Parent.Pos = value; - } - this.m_pos = value - m_Parent.Pos; - } - - } - - public PrimitiveBaseShape Shape - { - get - { - return this.m_Shape; - } - } - - public LLVector3 WorldPos - { - get - { - if (!this.m_isRootPrim) - { - Primitive parentPrim = (Primitive)this.m_Parent; - Axiom.Math.Vector3 offsetPos = new Vector3(this.m_pos.X, this.m_pos.Y, this.m_pos.Z); - offsetPos = parentPrim.Rotation * offsetPos; - return parentPrim.WorldPos + new LLVector3(offsetPos.x, offsetPos.y, offsetPos.z); - } - else - { - return this.Pos; - } - } - } - - public string Description - { - get - { - return this.m_description; - } - set - { - this.m_description = value; - } - } - - public LLVector3 Scale - { - set - { - this.m_Shape.Scale = value; - } - get - { - return this.m_Shape.Scale; - } - } - #endregion - - #region Constructors - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public Primitive(ulong regionHandle, Scene world, LLUUID ownerID, uint localID, bool isRoot, EntityBase parent, SceneObject rootObject, PrimitiveBaseShape shape, LLVector3 pos) - { - - m_regionHandle = regionHandle; - m_world = world; - inventoryItems = new Dictionary(); - this.m_Parent = parent; - this.m_isRootPrim = isRoot; - this.m_RootParent = rootObject; - this.CreateFromShape(ownerID, localID, pos, shape); - this.Rotation = Axiom.Math.Quaternion.Identity; - - m_world.AcknowledgeNewPrim(this); - - this.OnPrimCountTainted(); - } - - /// - /// - /// - /// Empty constructor for duplication - public Primitive() - { - - } - - #endregion - - #region Destructors - - ~Primitive() - { - this.OnPrimCountTainted(); - } - #endregion - - #region Duplication - - public Primitive Copy(EntityBase parent, SceneObject rootParent) - { - Primitive dupe = (Primitive)this.MemberwiseClone(); - - dupe.m_Parent = parent; - dupe.m_RootParent = rootParent; - - // TODO: Copy this properly. - dupe.inventoryItems = this.inventoryItems; - dupe.children = new List(); - dupe.m_Shape = this.m_Shape.Copy(); - dupe.m_regionHandle = this.m_regionHandle; - dupe.m_world = this.m_world; - - uint newLocalID = this.m_world.PrimIDAllocate(); - dupe.uuid = LLUUID.Random(); - dupe.LocalId = newLocalID; - - if (parent is SceneObject) - { - dupe.m_isRootPrim = true; - dupe.ParentID = 0; - } - else - { - dupe.m_isRootPrim = false; - dupe.ParentID = ((Primitive)parent).LocalId; - } - - dupe.Scale = new LLVector3(this.Scale.X, this.Scale.Y, this.Scale.Z); - dupe.Rotation = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); - dupe.m_pos = new LLVector3(this.m_pos.X, this.m_pos.Y, this.m_pos.Z); - - rootParent.AddChildToList(dupe); - this.m_world.AcknowledgeNewPrim(dupe); - dupe.TriggerOnPrimCountTainted(); - - foreach (Primitive prim in this.children) - { - Primitive primClone = prim.Copy(dupe, rootParent); - dupe.children.Add(primClone); - } - - return dupe; - } - - #endregion - - #region Override from EntityBase - /// - /// - /// - public override void update() - { - if (this.updateFlag == 1) // is a new prim just been created/reloaded or has major changes - { - this.SendFullUpdateToAllClients(); - this.updateFlag = 0; - } - if (this.updateFlag == 2) //some change has been made so update the clients - { - this.SendTerseUpdateToALLClients(); - this.updateFlag = 0; - } - - foreach (EntityBase child in children) - { - child.update(); - } - } - #endregion - - #region Setup - /// - /// - /// - /// - /// - /// - public void CreateFromShape(LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) - { - this.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; - this.OwnerID = ownerID; - this.CreatorID = this.OwnerID; - this.LastOwnerID = LLUUID.Zero; - this.Pos = pos; - this.uuid = LLUUID.Random(); - this.m_localId = (uint)(localID); - - this.m_Shape = shape; - this.updateFlag = 1; - } - - #endregion - - #region Linking / unlinking - /// - /// - /// - /// - public void AddNewChildren(SceneObject linkObject) - { - // Console.WriteLine("linking new prims " + linkObject.rootLocalID + " to me (" + this.LocalId + ")"); - //TODO check permissions - this.children.Add(linkObject.rootPrimitive); - linkObject.rootPrimitive.SetNewParent(this, this.m_RootParent); - - this.m_world.DeleteEntity(linkObject.rootUUID); - linkObject.DeleteAllChildren(); - - this.OnPrimCountTainted(); - } - - /// - /// - /// - /// - /// - public void SetNewParent(Primitive newParent, SceneObject rootParent) - { - LLVector3 oldPos = new LLVector3(this.Pos.X, this.Pos.Y, this.Pos.Z); - this.m_isRootPrim = false; - this.m_Parent = newParent; - this.ParentID = newParent.LocalId; - this.m_RootParent = rootParent; - this.m_RootParent.AddChildToList(this); - this.Pos = oldPos; - Axiom.Math.Vector3 axPos = new Axiom.Math.Vector3(this.m_pos.X, m_pos.Y, m_pos.Z); - axPos = this.m_Parent.Rotation.Inverse() * axPos; - this.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); - Axiom.Math.Quaternion oldRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); - this.Rotation = this.m_Parent.Rotation.Inverse() * this.Rotation; - this.updateFlag = 1; - - foreach (Primitive child in children) - { - child.SetRootParent(rootParent, newParent, oldPos, oldRot); - } - children.Clear(); - - - } - - /// - /// - /// - /// - public void SetRootParent(SceneObject newRoot , Primitive newParent, LLVector3 oldParentPosition, Axiom.Math.Quaternion oldParentRotation) - { - LLVector3 oldPos = new LLVector3(this.Pos.X, this.Pos.Y, this.Pos.Z); - Axiom.Math.Vector3 axOldPos = new Vector3(oldPos.X, oldPos.Y, oldPos.Z); - axOldPos = oldParentRotation * axOldPos; - oldPos = new LLVector3(axOldPos.x, axOldPos.y, axOldPos.z); - oldPos += oldParentPosition; - Axiom.Math.Quaternion oldRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); - this.m_isRootPrim = false; - this.m_Parent = newParent; - this.ParentID = newParent.LocalId; - newParent.AddToChildrenList(this); - this.m_RootParent = newRoot; - this.m_RootParent.AddChildToList(this); - this.Pos = oldPos; - Axiom.Math.Vector3 axPos = new Axiom.Math.Vector3(this.m_pos.X, m_pos.Y, m_pos.Z); - axPos = this.m_Parent.Rotation.Inverse() * axPos; - this.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); - this.Rotation = oldParentRotation * this.Rotation; - this.Rotation = this.m_Parent.Rotation.Inverse()* this.Rotation ; - this.updateFlag = 1; - foreach (Primitive child in children) - { - child.SetRootParent(newRoot, newParent, oldPos, oldRot); - } - children.Clear(); - } - - /// - /// - /// - /// - public void AddOffsetToChildren(LLVector3 offset) - { - foreach (Primitive prim in this.children) - { - prim.m_pos += offset; - prim.updateFlag = 2; - } - this.OnPrimCountTainted(); - } - - /// - /// - /// - /// - public void AddToChildrenList(Primitive prim) - { - this.children.Add(prim); - } - #endregion - - #region Resizing/Scale - /// - /// - /// - /// - public void ResizeGoup(LLVector3 scale) - { - LLVector3 offset = (scale - this.m_Shape.Scale); - offset.X /= 2; - offset.Y /= 2; - offset.Z /= 2; - if (this.m_isRootPrim) - { - this.m_Parent.Pos += offset; - } - else - { - this.m_pos += offset; - } - - this.AddOffsetToChildren(new LLVector3(-offset.X, -offset.Y, -offset.Z)); - this.m_Shape.Scale = scale; - - this.updateFlag = 1; - } - #endregion - - #region Position - /// - /// - /// - /// - public void UpdateGroupPosition(LLVector3 pos) - { - LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); - - this.Pos = newPos; - this.updateFlag = 2; - - this.OnPrimCountTainted(); - } - - /// - /// - /// - /// - public void UpdateSinglePosition(LLVector3 pos) - { - // Console.WriteLine("updating single prim position"); - if (this.m_isRootPrim) - { - LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); - LLVector3 oldPos = new LLVector3(Pos.X, Pos.Y, Pos.Z); - LLVector3 diff = oldPos - newPos; - Axiom.Math.Vector3 axDiff = new Vector3(diff.X, diff.Y, diff.Z); - axDiff = this.Rotation.Inverse() * axDiff; - diff.X = axDiff.x; - diff.Y = axDiff.y; - diff.Z = axDiff.z; - this.Pos = newPos; - - foreach (Primitive prim in this.children) - { - prim.m_pos += diff; - prim.updateFlag = 2; - } - this.updateFlag = 2; - } - else - { - LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); - this.m_pos = newPos; - this.updateFlag = 2; - } - - - } - - #endregion - - #region Rotation - /// - /// - /// - /// - public void UpdateGroupRotation(LLQuaternion rot) - { - this.Rotation = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); - this.updateFlag = 2; - - } - - /// - /// - /// - /// - /// - public void UpdateGroupMouseRotation(LLVector3 pos, LLQuaternion rot) - { - this.Rotation = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); - this.Pos = pos; - this.updateFlag = 2; - } - - /// - /// - /// - /// - public void UpdateSingleRotation(LLQuaternion rot) - { - //Console.WriteLine("updating single prim rotation"); - Axiom.Math.Quaternion axRot = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); - Axiom.Math.Quaternion oldParentRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); - this.Rotation = axRot; - foreach (Primitive prim in this.children) - { - Axiom.Math.Vector3 axPos = new Vector3(prim.m_pos.X, prim.m_pos.Y, prim.m_pos.Z); - axPos = oldParentRot * axPos; - axPos = axRot.Inverse() * axPos; - prim.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); - prim.Rotation = oldParentRot * prim.Rotation ; - prim.Rotation = axRot.Inverse()* prim.Rotation; - prim.updateFlag = 2; - } - this.updateFlag = 2; - } - #endregion - - #region Shape - /// - /// - /// - /// - public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock) - { - this.m_Shape.PathBegin = shapeBlock.PathBegin; - this.m_Shape.PathEnd = shapeBlock.PathEnd; - this.m_Shape.PathScaleX = shapeBlock.PathScaleX; - this.m_Shape.PathScaleY = shapeBlock.PathScaleY; - this.m_Shape.PathShearX = shapeBlock.PathShearX; - this.m_Shape.PathShearY = shapeBlock.PathShearY; - this.m_Shape.PathSkew = shapeBlock.PathSkew; - this.m_Shape.ProfileBegin = shapeBlock.ProfileBegin; - this.m_Shape.ProfileEnd = shapeBlock.ProfileEnd; - this.m_Shape.PathCurve = shapeBlock.PathCurve; - this.m_Shape.ProfileCurve = shapeBlock.ProfileCurve; - this.m_Shape.ProfileHollow = shapeBlock.ProfileHollow; - this.m_Shape.PathRadiusOffset = shapeBlock.PathRadiusOffset; - this.m_Shape.PathRevolutions = shapeBlock.PathRevolutions; - this.m_Shape.PathTaperX = shapeBlock.PathTaperX; - this.m_Shape.PathTaperY = shapeBlock.PathTaperY; - this.m_Shape.PathTwist = shapeBlock.PathTwist; - this.m_Shape.PathTwistBegin = shapeBlock.PathTwistBegin; - this.updateFlag = 1; - } - #endregion - - #region Texture - /// - /// - /// - /// - public void UpdateTextureEntry(byte[] textureEntry) - { - this.m_Shape.TextureEntry = textureEntry; - this.updateFlag = 1; - } - #endregion - - #region Client Update 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; - lPos = this.Pos; - LLQuaternion lRot; - lRot = new LLQuaternion(this.Rotation.x, this.Rotation.y, this.Rotation.z, this.Rotation.w); - - remoteClient.SendPrimitiveToClient(this.m_regionHandle, 64096, this.LocalId, this.m_Shape, lPos, lRot, this.m_flags, this.uuid, this.OwnerID, this.Text, this.ParentID); - } - - /// - /// - /// - public void SendFullUpdateToAllClients() - { - List avatars = this.m_world.RequestAvatarList(); - for (int i = 0; i < avatars.Count; i++) - { - this.SendFullUpdateToClient(avatars[i].ControllingClient); - } - } - - /// - /// - /// - /// - public void SendTerseUpdateForAllChildren(IClientAPI remoteClient) - { - this.SendTerseUpdateToClient(remoteClient); - for (int i = 0; i < this.children.Count; i++) - { - if (this.children[i] is Primitive) - { - ((Primitive)this.children[i]).SendTerseUpdateForAllChildren(remoteClient); - } - } - } - - /// - /// - /// - /// - public void SendTerseUpdateToClient(IClientAPI RemoteClient) - { - LLVector3 lPos; - Quaternion lRot; - - 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 - - public void TriggerOnPrimCountTainted() - { - this.OnPrimCountTainted(); - } - } -} +using System; +using System.Collections.Generic; +using Axiom.Math; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Environment.Scenes +{ + public delegate void PrimCountTaintedDelegate(); + + public class Primitive : EntityBase + { + private const uint FULL_MASK_PERMISSIONS = 2147483647; + + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + private ulong m_regionHandle; + private byte updateFlag = 0; + private uint m_flags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456 + 128; + + private Dictionary inventoryItems; + + private string m_description = ""; + + public string SitName = ""; + public string TouchName = ""; + public string Text = ""; + + public LLUUID CreatorID; + public LLUUID OwnerID; + public LLUUID LastOwnerID; + public Int32 CreationDate; + + public uint ParentID = 0; + + 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; + + private PrimitiveBaseShape m_Shape; + + public SceneObject m_RootParent; + public bool m_isRootPrim; + public EntityBase m_Parent; + + private EventManager m_eventManager; + + public event PrimCountTaintedDelegate OnPrimCountTainted; + + #region Properties + /// + /// If rootprim, will return world position + /// otherwise will return local offset from rootprim + /// + public override LLVector3 Pos + { + get + { + if (m_isRootPrim) + { + //if we are rootprim then our offset should be zero + return this.m_pos + m_Parent.Pos; + } + else + { + return this.m_pos; + } + } + set + { + if (m_isRootPrim) + { + m_Parent.Pos = value; + } + this.m_pos = value - m_Parent.Pos; + } + + } + + public PrimitiveBaseShape Shape + { + get + { + return this.m_Shape; + } + } + + public LLVector3 WorldPos + { + get + { + if (!this.m_isRootPrim) + { + Primitive parentPrim = (Primitive)this.m_Parent; + Axiom.Math.Vector3 offsetPos = new Vector3(this.m_pos.X, this.m_pos.Y, this.m_pos.Z); + offsetPos = parentPrim.Rotation * offsetPos; + return parentPrim.WorldPos + new LLVector3(offsetPos.x, offsetPos.y, offsetPos.z); + } + else + { + return this.Pos; + } + } + } + + public string Description + { + get + { + return this.m_description; + } + set + { + this.m_description = value; + } + } + + public LLVector3 Scale + { + set + { + this.m_Shape.Scale = value; + } + get + { + return this.m_Shape.Scale; + } + } + #endregion + + #region Constructors + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public Primitive(ulong regionHandle, Scene world, LLUUID ownerID, uint localID, bool isRoot, EntityBase parent, SceneObject rootObject, PrimitiveBaseShape shape, LLVector3 pos) + { + + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + this.m_Parent = parent; + this.m_isRootPrim = isRoot; + this.m_RootParent = rootObject; + this.CreateFromShape(ownerID, localID, pos, shape); + this.Rotation = Axiom.Math.Quaternion.Identity; + + m_world.AcknowledgeNewPrim(this); + + this.OnPrimCountTainted(); + } + + /// + /// + /// + /// Empty constructor for duplication + public Primitive() + { + + } + + #endregion + + #region Destructors + + ~Primitive() + { + this.OnPrimCountTainted(); + } + #endregion + + #region Duplication + + public Primitive Copy(EntityBase parent, SceneObject rootParent) + { + Primitive dupe = (Primitive)this.MemberwiseClone(); + + dupe.m_Parent = parent; + dupe.m_RootParent = rootParent; + + // TODO: Copy this properly. + dupe.inventoryItems = this.inventoryItems; + dupe.children = new List(); + dupe.m_Shape = this.m_Shape.Copy(); + dupe.m_regionHandle = this.m_regionHandle; + dupe.m_world = this.m_world; + + uint newLocalID = this.m_world.PrimIDAllocate(); + dupe.uuid = LLUUID.Random(); + dupe.LocalId = newLocalID; + + if (parent is SceneObject) + { + dupe.m_isRootPrim = true; + dupe.ParentID = 0; + } + else + { + dupe.m_isRootPrim = false; + dupe.ParentID = ((Primitive)parent).LocalId; + } + + dupe.Scale = new LLVector3(this.Scale.X, this.Scale.Y, this.Scale.Z); + dupe.Rotation = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); + dupe.m_pos = new LLVector3(this.m_pos.X, this.m_pos.Y, this.m_pos.Z); + + rootParent.AddChildToList(dupe); + this.m_world.AcknowledgeNewPrim(dupe); + dupe.TriggerOnPrimCountTainted(); + + foreach (Primitive prim in this.children) + { + Primitive primClone = prim.Copy(dupe, rootParent); + dupe.children.Add(primClone); + } + + return dupe; + } + + #endregion + + #region Override from EntityBase + /// + /// + /// + public override void update() + { + if (this.updateFlag == 1) // is a new prim just been created/reloaded or has major changes + { + this.SendFullUpdateToAllClients(); + this.updateFlag = 0; + } + if (this.updateFlag == 2) //some change has been made so update the clients + { + this.SendTerseUpdateToALLClients(); + this.updateFlag = 0; + } + + foreach (EntityBase child in children) + { + child.update(); + } + } + #endregion + + #region Setup + /// + /// + /// + /// + /// + /// + public void CreateFromShape(LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) + { + this.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + this.OwnerID = ownerID; + this.CreatorID = this.OwnerID; + this.LastOwnerID = LLUUID.Zero; + this.Pos = pos; + this.uuid = LLUUID.Random(); + this.m_localId = (uint)(localID); + + this.m_Shape = shape; + this.updateFlag = 1; + } + + #endregion + + #region Linking / unlinking + /// + /// + /// + /// + public void AddNewChildren(SceneObject linkObject) + { + // Console.WriteLine("linking new prims " + linkObject.rootLocalID + " to me (" + this.LocalId + ")"); + //TODO check permissions + this.children.Add(linkObject.rootPrimitive); + linkObject.rootPrimitive.SetNewParent(this, this.m_RootParent); + + this.m_world.DeleteEntity(linkObject.rootUUID); + linkObject.DeleteAllChildren(); + + this.OnPrimCountTainted(); + } + + /// + /// + /// + /// + /// + public void SetNewParent(Primitive newParent, SceneObject rootParent) + { + LLVector3 oldPos = new LLVector3(this.Pos.X, this.Pos.Y, this.Pos.Z); + this.m_isRootPrim = false; + this.m_Parent = newParent; + this.ParentID = newParent.LocalId; + this.m_RootParent = rootParent; + this.m_RootParent.AddChildToList(this); + this.Pos = oldPos; + Axiom.Math.Vector3 axPos = new Axiom.Math.Vector3(this.m_pos.X, m_pos.Y, m_pos.Z); + axPos = this.m_Parent.Rotation.Inverse() * axPos; + this.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); + Axiom.Math.Quaternion oldRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); + this.Rotation = this.m_Parent.Rotation.Inverse() * this.Rotation; + this.updateFlag = 1; + + foreach (Primitive child in children) + { + child.SetRootParent(rootParent, newParent, oldPos, oldRot); + } + children.Clear(); + + + } + + /// + /// + /// + /// + public void SetRootParent(SceneObject newRoot , Primitive newParent, LLVector3 oldParentPosition, Axiom.Math.Quaternion oldParentRotation) + { + LLVector3 oldPos = new LLVector3(this.Pos.X, this.Pos.Y, this.Pos.Z); + Axiom.Math.Vector3 axOldPos = new Vector3(oldPos.X, oldPos.Y, oldPos.Z); + axOldPos = oldParentRotation * axOldPos; + oldPos = new LLVector3(axOldPos.x, axOldPos.y, axOldPos.z); + oldPos += oldParentPosition; + Axiom.Math.Quaternion oldRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); + this.m_isRootPrim = false; + this.m_Parent = newParent; + this.ParentID = newParent.LocalId; + newParent.AddToChildrenList(this); + this.m_RootParent = newRoot; + this.m_RootParent.AddChildToList(this); + this.Pos = oldPos; + Axiom.Math.Vector3 axPos = new Axiom.Math.Vector3(this.m_pos.X, m_pos.Y, m_pos.Z); + axPos = this.m_Parent.Rotation.Inverse() * axPos; + this.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); + this.Rotation = oldParentRotation * this.Rotation; + this.Rotation = this.m_Parent.Rotation.Inverse()* this.Rotation ; + this.updateFlag = 1; + foreach (Primitive child in children) + { + child.SetRootParent(newRoot, newParent, oldPos, oldRot); + } + children.Clear(); + } + + /// + /// + /// + /// + public void AddOffsetToChildren(LLVector3 offset) + { + foreach (Primitive prim in this.children) + { + prim.m_pos += offset; + prim.updateFlag = 2; + } + this.OnPrimCountTainted(); + } + + /// + /// + /// + /// + public void AddToChildrenList(Primitive prim) + { + this.children.Add(prim); + } + #endregion + + #region Resizing/Scale + /// + /// + /// + /// + public void ResizeGoup(LLVector3 scale) + { + LLVector3 offset = (scale - this.m_Shape.Scale); + offset.X /= 2; + offset.Y /= 2; + offset.Z /= 2; + if (this.m_isRootPrim) + { + this.m_Parent.Pos += offset; + } + else + { + this.m_pos += offset; + } + + this.AddOffsetToChildren(new LLVector3(-offset.X, -offset.Y, -offset.Z)); + this.m_Shape.Scale = scale; + + this.updateFlag = 1; + } + #endregion + + #region Position + /// + /// + /// + /// + public void UpdateGroupPosition(LLVector3 pos) + { + LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); + + this.Pos = newPos; + this.updateFlag = 2; + + this.OnPrimCountTainted(); + } + + /// + /// + /// + /// + public void UpdateSinglePosition(LLVector3 pos) + { + // Console.WriteLine("updating single prim position"); + if (this.m_isRootPrim) + { + LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); + LLVector3 oldPos = new LLVector3(Pos.X, Pos.Y, Pos.Z); + LLVector3 diff = oldPos - newPos; + Axiom.Math.Vector3 axDiff = new Vector3(diff.X, diff.Y, diff.Z); + axDiff = this.Rotation.Inverse() * axDiff; + diff.X = axDiff.x; + diff.Y = axDiff.y; + diff.Z = axDiff.z; + this.Pos = newPos; + + foreach (Primitive prim in this.children) + { + prim.m_pos += diff; + prim.updateFlag = 2; + } + this.updateFlag = 2; + } + else + { + LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); + this.m_pos = newPos; + this.updateFlag = 2; + } + + + } + + #endregion + + #region Rotation + /// + /// + /// + /// + public void UpdateGroupRotation(LLQuaternion rot) + { + this.Rotation = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); + this.updateFlag = 2; + + } + + /// + /// + /// + /// + /// + public void UpdateGroupMouseRotation(LLVector3 pos, LLQuaternion rot) + { + this.Rotation = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); + this.Pos = pos; + this.updateFlag = 2; + } + + /// + /// + /// + /// + public void UpdateSingleRotation(LLQuaternion rot) + { + //Console.WriteLine("updating single prim rotation"); + Axiom.Math.Quaternion axRot = new Axiom.Math.Quaternion(rot.W, rot.X, rot.Y, rot.Z); + Axiom.Math.Quaternion oldParentRot = new Quaternion(this.Rotation.w, this.Rotation.x, this.Rotation.y, this.Rotation.z); + this.Rotation = axRot; + foreach (Primitive prim in this.children) + { + Axiom.Math.Vector3 axPos = new Vector3(prim.m_pos.X, prim.m_pos.Y, prim.m_pos.Z); + axPos = oldParentRot * axPos; + axPos = axRot.Inverse() * axPos; + prim.m_pos = new LLVector3(axPos.x, axPos.y, axPos.z); + prim.Rotation = oldParentRot * prim.Rotation ; + prim.Rotation = axRot.Inverse()* prim.Rotation; + prim.updateFlag = 2; + } + this.updateFlag = 2; + } + #endregion + + #region Shape + /// + /// + /// + /// + public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock) + { + this.m_Shape.PathBegin = shapeBlock.PathBegin; + this.m_Shape.PathEnd = shapeBlock.PathEnd; + this.m_Shape.PathScaleX = shapeBlock.PathScaleX; + this.m_Shape.PathScaleY = shapeBlock.PathScaleY; + this.m_Shape.PathShearX = shapeBlock.PathShearX; + this.m_Shape.PathShearY = shapeBlock.PathShearY; + this.m_Shape.PathSkew = shapeBlock.PathSkew; + this.m_Shape.ProfileBegin = shapeBlock.ProfileBegin; + this.m_Shape.ProfileEnd = shapeBlock.ProfileEnd; + this.m_Shape.PathCurve = shapeBlock.PathCurve; + this.m_Shape.ProfileCurve = shapeBlock.ProfileCurve; + this.m_Shape.ProfileHollow = shapeBlock.ProfileHollow; + this.m_Shape.PathRadiusOffset = shapeBlock.PathRadiusOffset; + this.m_Shape.PathRevolutions = shapeBlock.PathRevolutions; + this.m_Shape.PathTaperX = shapeBlock.PathTaperX; + this.m_Shape.PathTaperY = shapeBlock.PathTaperY; + this.m_Shape.PathTwist = shapeBlock.PathTwist; + this.m_Shape.PathTwistBegin = shapeBlock.PathTwistBegin; + this.updateFlag = 1; + } + #endregion + + #region Texture + /// + /// + /// + /// + public void UpdateTextureEntry(byte[] textureEntry) + { + this.m_Shape.TextureEntry = textureEntry; + this.updateFlag = 1; + } + #endregion + + #region Client Update 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; + lPos = this.Pos; + LLQuaternion lRot; + lRot = new LLQuaternion(this.Rotation.x, this.Rotation.y, this.Rotation.z, this.Rotation.w); + + remoteClient.SendPrimitiveToClient(this.m_regionHandle, 64096, this.LocalId, this.m_Shape, lPos, lRot, this.m_flags, this.uuid, this.OwnerID, this.Text, this.ParentID); + } + + /// + /// + /// + public void SendFullUpdateToAllClients() + { + List avatars = this.m_world.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + this.SendFullUpdateToClient(avatars[i].ControllingClient); + } + } + + /// + /// + /// + /// + public void SendTerseUpdateForAllChildren(IClientAPI remoteClient) + { + this.SendTerseUpdateToClient(remoteClient); + for (int i = 0; i < this.children.Count; i++) + { + if (this.children[i] is Primitive) + { + ((Primitive)this.children[i]).SendTerseUpdateForAllChildren(remoteClient); + } + } + } + + /// + /// + /// + /// + public void SendTerseUpdateToClient(IClientAPI RemoteClient) + { + LLVector3 lPos; + Quaternion lRot; + + 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 + + public void TriggerOnPrimCountTainted() + { + this.OnPrimCountTainted(); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs index 347625a..e37d105 100644 --- a/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs +++ b/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs @@ -1,618 +1,618 @@ -/* -* 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 libsecondlife.Packets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Environment.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; - } - - /// - /// - /// - /// Inefficient. TODO: Fixme - /// - /// - /// - /// - /// - public void InstantMessage(LLUUID fromAgentID, LLUUID toAgentID, uint timestamp, string fromAgentName, string message) - { - if (this.Avatars.ContainsKey(toAgentID)) - { - if (this.Avatars.ContainsKey(fromAgentID)) - { - // Local sim message - ScenePresence fromAvatar = this.Avatars[fromAgentID]; - ScenePresence toAvatar = this.Avatars[toAgentID]; - string fromName = fromAvatar.firstname + " " + fromAvatar.lastname; - toAvatar.ControllingClient.SendInstantMessage(message, toAgentID, fromName); - } - else - { - // Message came from a user outside the sim, ignore? - } - } - else - { - // Grid message - } - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void SimChat(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) - { - ScenePresence avatar = null; - if (this.Avatars.ContainsKey(fromAgentID)) - { - avatar = this.Avatars[fromAgentID]; - fromPos = avatar.Pos; - fromName = avatar.firstname + " " + avatar.lastname; - avatar = null; - } - - this.ForEachScenePresence(delegate(ScenePresence presence) - { - int dis = -1000; - if (this.Avatars.ContainsKey(presence.ControllingClient.AgentId)) - { - avatar = this.Avatars[presence.ControllingClient.AgentId]; - dis = (int)avatar.Pos.GetDistanceTo(fromPos); - } - - 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 - presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, - fromAgentID); - } - break; - case 1: // Say - if ((dis < 30) && (dis > -30)) - { - //Console.WriteLine("sending chat"); - presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, - fromAgentID); - } - break; - case 2: // Shout - if ((dis < 100) && (dis > -100)) - { - presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, - fromAgentID); - } - break; - - case 0xff: // Broadcast - presence.ControllingClient.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 DuplicateObject(uint originalPrim, LLVector3 offset, uint flags) - { - SceneObject originPrim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - if (((SceneObject)ent).rootLocalID == originalPrim) - { - originPrim = (SceneObject)ent; - break; - } - } - } - - if (originPrim != null) - { - SceneObject copy = originPrim.Copy(); - copy.Pos = copy.Pos + offset; - this.Entities.Add(copy.rootUUID, copy); - - List avatars = this.RequestAvatarList(); - for (int i = 0; i < avatars.Count; i++) - { - copy.SendAllChildPrimsToClient(avatars[i].ControllingClient); - } - - } - else - { - OpenSim.Framework.Console.MainLog.Instance.Warn("Attempted to duplicate nonexistant prim"); - } - - } - - /// - /// - /// - /// - /// - public void LinkObjects(uint parentPrim, List childPrims) - { - SceneObject parenPrim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - if (((SceneObject)ent).rootLocalID == parentPrim) - { - parenPrim = (SceneObject)ent; - break; - } - } - } - - List children = new List(); - if (parenPrim != null) - { - for (int i = 0; i < childPrims.Count; i++) - { - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - if (((SceneObject)ent).rootLocalID == childPrims[i]) - { - children.Add((SceneObject)ent); - } - } - } - } - } - - foreach (SceneObject sceneObj in children) - { - parenPrim.AddNewChildPrims(sceneObj); - } - } - - /// - /// - /// - /// - /// - public void UpdatePrimShape(uint primLocalID, ObjectShapePacket.ObjectDataBlock shapeBlock) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(primLocalID); - if (prim != null) - { - prim.UpdateShape(shapeBlock); - break; - } - } - } - } - - /// - /// - /// - /// - /// - public void SelectPrim(uint primLocalID, IClientAPI remoteClient) - { - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - if (((SceneObject)ent).rootLocalID == primLocalID) - { - ((SceneObject)ent).GetProperites(remoteClient); - ((SceneObject)ent).isSelected = true; - this.ParcelManager.setPrimsTainted(); - break; - } - } - } - } - - /// - /// - /// - /// - /// - public void DeselectPrim(uint primLocalID, IClientAPI remoteClient) - { - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - if (((SceneObject)ent).rootLocalID == primLocalID) - { - ((SceneObject)ent).isSelected = false; - this.ParcelManager.setPrimsTainted(); - break; - } - } - } - } - - /// - /// - /// - /// - /// - public void PrimDescription(uint primLocalID, string description) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(primLocalID); - if (prim != null) - { - prim.Description = description; - break; - } - } - } - } - - /// - /// - /// - /// - /// - public void PrimName(uint primLocalID, string name) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(primLocalID); - if (prim != null) - { - prim.Name = name; - break; - } - } - } - } - - public void MoveObject(LLUUID objectID, LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(objectID); - if (prim != null) - { - ((SceneObject)ent).GrapMovement(offset, pos, remoteClient); - break; - } - } - } - /* - if (this.Entities.ContainsKey(objectID)) - { - if (this.Entities[objectID] is SceneObject) - { - ((SceneObject)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) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateTextureEntry(texture); - } - } - } - } - - /// - /// - /// - /// - /// - /// - public void UpdatePrimPosition(uint localID, LLVector3 pos, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateGroupPosition(pos); - break; - } - } - } - } - - public void UpdatePrimSinglePosition(uint localID, LLVector3 pos, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateSinglePosition(pos); - break; - } - } - } - } - - /// - /// - /// - /// - /// - /// - /// - public void UpdatePrimRotation(uint localID, LLVector3 pos, LLQuaternion rot, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateGroupMouseRotation(pos, rot); - break; - } - } - } - } - - /// - /// - /// - /// - /// - /// - public void UpdatePrimRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateGroupRotation(rot); - break; - } - } - } - } - - /// - /// - /// - /// - /// - /// - public void UpdatePrimSingleRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient) - { - //Console.WriteLine("trying to update single prim rotation"); - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.UpdateSingleRotation(rot); - break; - } - } - } - } - - /// - /// - /// - /// - /// - /// - public void UpdatePrimScale(uint localID, LLVector3 scale, IClientAPI remoteClient) - { - Primitive prim = null; - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - prim = ((SceneObject)ent).HasChildPrim(localID); - if (prim != null) - { - prim.ResizeGoup(scale); - break; - } - } - } - } - - /// - /// Sends prims to a client - /// - /// Client to send to - public void GetInitialPrims(IClientAPI RemoteClient) - { - - } - } -} +/* +* 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 libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Environment.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; + } + + /// + /// + /// + /// Inefficient. TODO: Fixme + /// + /// + /// + /// + /// + public void InstantMessage(LLUUID fromAgentID, LLUUID toAgentID, uint timestamp, string fromAgentName, string message) + { + if (this.Avatars.ContainsKey(toAgentID)) + { + if (this.Avatars.ContainsKey(fromAgentID)) + { + // Local sim message + ScenePresence fromAvatar = this.Avatars[fromAgentID]; + ScenePresence toAvatar = this.Avatars[toAgentID]; + string fromName = fromAvatar.firstname + " " + fromAvatar.lastname; + toAvatar.ControllingClient.SendInstantMessage(message, toAgentID, fromName); + } + else + { + // Message came from a user outside the sim, ignore? + } + } + else + { + // Grid message + } + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void SimChat(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + ScenePresence avatar = null; + if (this.Avatars.ContainsKey(fromAgentID)) + { + avatar = this.Avatars[fromAgentID]; + fromPos = avatar.Pos; + fromName = avatar.firstname + " " + avatar.lastname; + avatar = null; + } + + this.ForEachScenePresence(delegate(ScenePresence presence) + { + int dis = -1000; + if (this.Avatars.ContainsKey(presence.ControllingClient.AgentId)) + { + avatar = this.Avatars[presence.ControllingClient.AgentId]; + dis = (int)avatar.Pos.GetDistanceTo(fromPos); + } + + 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 + presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, + fromAgentID); + } + break; + case 1: // Say + if ((dis < 30) && (dis > -30)) + { + //Console.WriteLine("sending chat"); + presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, + fromAgentID); + } + break; + case 2: // Shout + if ((dis < 100) && (dis > -100)) + { + presence.ControllingClient.SendChatMessage(message, type, fromPos, fromName, + fromAgentID); + } + break; + + case 0xff: // Broadcast + presence.ControllingClient.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 DuplicateObject(uint originalPrim, LLVector3 offset, uint flags) + { + SceneObject originPrim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + if (((SceneObject)ent).rootLocalID == originalPrim) + { + originPrim = (SceneObject)ent; + break; + } + } + } + + if (originPrim != null) + { + SceneObject copy = originPrim.Copy(); + copy.Pos = copy.Pos + offset; + this.Entities.Add(copy.rootUUID, copy); + + List avatars = this.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + copy.SendAllChildPrimsToClient(avatars[i].ControllingClient); + } + + } + else + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Attempted to duplicate nonexistant prim"); + } + + } + + /// + /// + /// + /// + /// + public void LinkObjects(uint parentPrim, List childPrims) + { + SceneObject parenPrim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + if (((SceneObject)ent).rootLocalID == parentPrim) + { + parenPrim = (SceneObject)ent; + break; + } + } + } + + List children = new List(); + if (parenPrim != null) + { + for (int i = 0; i < childPrims.Count; i++) + { + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + if (((SceneObject)ent).rootLocalID == childPrims[i]) + { + children.Add((SceneObject)ent); + } + } + } + } + } + + foreach (SceneObject sceneObj in children) + { + parenPrim.AddNewChildPrims(sceneObj); + } + } + + /// + /// + /// + /// + /// + public void UpdatePrimShape(uint primLocalID, ObjectShapePacket.ObjectDataBlock shapeBlock) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(primLocalID); + if (prim != null) + { + prim.UpdateShape(shapeBlock); + break; + } + } + } + } + + /// + /// + /// + /// + /// + public void SelectPrim(uint primLocalID, IClientAPI remoteClient) + { + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + if (((SceneObject)ent).rootLocalID == primLocalID) + { + ((SceneObject)ent).GetProperites(remoteClient); + ((SceneObject)ent).isSelected = true; + this.ParcelManager.setPrimsTainted(); + break; + } + } + } + } + + /// + /// + /// + /// + /// + public void DeselectPrim(uint primLocalID, IClientAPI remoteClient) + { + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + if (((SceneObject)ent).rootLocalID == primLocalID) + { + ((SceneObject)ent).isSelected = false; + this.ParcelManager.setPrimsTainted(); + break; + } + } + } + } + + /// + /// + /// + /// + /// + public void PrimDescription(uint primLocalID, string description) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(primLocalID); + if (prim != null) + { + prim.Description = description; + break; + } + } + } + } + + /// + /// + /// + /// + /// + public void PrimName(uint primLocalID, string name) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(primLocalID); + if (prim != null) + { + prim.Name = name; + break; + } + } + } + } + + public void MoveObject(LLUUID objectID, LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(objectID); + if (prim != null) + { + ((SceneObject)ent).GrapMovement(offset, pos, remoteClient); + break; + } + } + } + /* + if (this.Entities.ContainsKey(objectID)) + { + if (this.Entities[objectID] is SceneObject) + { + ((SceneObject)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) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateTextureEntry(texture); + } + } + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimPosition(uint localID, LLVector3 pos, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateGroupPosition(pos); + break; + } + } + } + } + + public void UpdatePrimSinglePosition(uint localID, LLVector3 pos, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateSinglePosition(pos); + break; + } + } + } + } + + /// + /// + /// + /// + /// + /// + /// + public void UpdatePrimRotation(uint localID, LLVector3 pos, LLQuaternion rot, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateGroupMouseRotation(pos, rot); + break; + } + } + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateGroupRotation(rot); + break; + } + } + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimSingleRotation(uint localID, LLQuaternion rot, IClientAPI remoteClient) + { + //Console.WriteLine("trying to update single prim rotation"); + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.UpdateSingleRotation(rot); + break; + } + } + } + } + + /// + /// + /// + /// + /// + /// + public void UpdatePrimScale(uint localID, LLVector3 scale, IClientAPI remoteClient) + { + Primitive prim = null; + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + prim = ((SceneObject)ent).HasChildPrim(localID); + if (prim != null) + { + prim.ResizeGoup(scale); + break; + } + } + } + } + + /// + /// Sends prims to a client + /// + /// Client to send to + public void GetInitialPrims(IClientAPI RemoteClient) + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/Scene.cs b/OpenSim/Region/Environment/Scenes/Scene.cs index 1e69c9e..a06d74d 100644 --- a/OpenSim/Region/Environment/Scenes/Scene.cs +++ b/OpenSim/Region/Environment/Scenes/Scene.cs @@ -1,919 +1,919 @@ -/* -* 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.Timers; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.Physics.Manager; -using OpenSim.Region.Caches; -using OpenSim.Region.Interfaces; -using OpenSim.Region.Scripting; -using OpenSim.Region.Terrain; -using Caps = OpenSim.Region.Capabilities.Caps; -using Timer = System.Timers.Timer; - -namespace OpenSim.Region.Environment.Scenes -{ - public delegate bool FilterAvatarList(ScenePresence avatar); - public delegate void ForEachScenePresenceDelegate(ScenePresence presence); - - public partial class Scene : SceneBase, ILocalStorageReceiver - { - protected Timer m_heartbeatTimer = new Timer(); - protected Dictionary Avatars; - protected Dictionary Prims; - protected PhysicsScene phyScene; - protected float timeStep = 0.1f; - private Random Rand = new Random(); - private uint _primCount = 702000; - private System.Threading.Mutex _primAllocateMutex = new Mutex(false); - private int storageCount; - private int parcelPrimCheckCount; - private Mutex updateLock; - - protected AuthenticateSessionsBase authenticateHandler; - protected RegionCommsListener regionCommsHost; - protected CommunicationsManager commsManager; - protected StorageManager storageManager; - - protected Dictionary capsHandlers = new Dictionary(); - protected BaseHttpServer httpListener; - - #region Properties - /// - /// - /// - public PhysicsScene PhysScene - { - set - { - this.phyScene = value; - } - get - { - return (this.phyScene); - } - } - - private ParcelManager m_parcelManager; - public ParcelManager ParcelManager - { - get { return m_parcelManager; } - } - - private EstateManager m_estateManager; - public EstateManager EstateManager - { - get { return m_estateManager; } - } - - private EventManager m_eventManager; - public EventManager EventManager - { - get { return m_eventManager; } - } - - private ScriptManager m_scriptManager; - public ScriptManager ScriptManager - { - get { return m_scriptManager; } - } - - public Dictionary Objects - { - get { return Prims; } - } - - #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(RegionInfo regInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer) - { - updateLock = new Mutex(false); - this.authenticateHandler = authen; - this.commsManager = commsMan; - this.storageManager = storeManager; - this.assetCache = assetCach; - m_regInfo = regInfo; - m_regionHandle = m_regInfo.RegionHandle; - m_regionName = m_regInfo.RegionName; - this.m_datastore = m_regInfo.DataStore; - this.RegisterRegionWithComms(); - - m_parcelManager = new ParcelManager(this, this.m_regInfo); - m_estateManager = new EstateManager(this, this.m_regInfo); - m_scriptManager = new ScriptManager(this); - m_eventManager = new EventManager(); - - m_eventManager.OnParcelPrimCountAdd += new EventManager.OnParcelPrimCountAddDelegate(m_parcelManager.addPrimToParcelCounts); - - MainLog.Instance.Verbose("World.cs - creating new entitities instance"); - Entities = new Dictionary(); - Avatars = new Dictionary(); - Prims = new Dictionary(); - - MainLog.Instance.Verbose("World.cs - loading objects from datastore"); - List PrimsFromDB = storageManager.DataStore.LoadObjects(); - foreach (SceneObject prim in PrimsFromDB) - { - AddEntity(prim); - } - MainLog.Instance.Verbose("World.cs - loaded " + PrimsFromDB.Count.ToString() + " object(s)"); - - - MainLog.Instance.Verbose("World.cs - creating LandMap"); - Terrain = new TerrainEngine(); - - ScenePresence.LoadAnims(); - - this.httpListener = httpServer; - } - #endregion - - #region Script Handling Methods - - public void SendCommandToScripts(string[] args) - { - m_eventManager.TriggerOnScriptConsole(args); - } - - #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, 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 (LLUUID UUID in Entities.Keys) - { - Entities[UUID].updateMovement(); - } - - lock (this.m_syncRoot) - { - this.phyScene.Simulate(timeStep); - } - - foreach (LLUUID UUID in Entities.Keys) - { - Entities[UUID].update(); - } - - // General purpose event manager - m_eventManager.TriggerOnFrame(); - - //backup world data - this.storageCount++; - if (storageCount > 1200) //set to how often you want to backup - { - this.Backup(); - storageCount = 0; - } - - this.parcelPrimCheckCount++; - if (this.parcelPrimCheckCount > 50) //check every 5 seconds for tainted prims - { - if (m_parcelManager.parcelPrimCountTainted) - { - //Perform parcel update of prim count - performParcelPrimCountUpdate(); - this.parcelPrimCheckCount = 0; - } - } - - } - catch (Exception e) - { - MainLog.Instance.Warn("World.cs: Update() - Failed with exception " + e.ToString()); - } - updateLock.ReleaseMutex(); - - } - - /// - /// - /// - /// - public bool Backup() - { - EventManager.TriggerOnBackup(this.storageManager.DataStore); - 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.storageManager.DataStore.StoreTerrain(Terrain.getHeights2DD()); - - this.ForEachScenePresence(delegate(ScenePresence presence) - { - this.SendLayerData(presence.ControllingClient); - }); - - foreach (LLUUID UUID in Entities.Keys) - { - Entities[UUID].LandRenegerated(); - } - } - catch (Exception e) - { - 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.storageManager.DataStore.StoreTerrain(Terrain.getHeights2DD()); - - this.ForEachScenePresence(delegate(ScenePresence presence) - { - this.SendLayerData(presence.ControllingClient); - }); - - foreach (LLUUID UUID in Entities.Keys) - { - Entities[UUID].LandRenegerated(); - } - } - catch (Exception e) - { - 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 */ - - this.ForEachScenePresence(delegate(ScenePresence presence) - { - this.SendLayerData(pointx, pointy, presence.ControllingClient); - }); - } - } - catch (Exception e) - { - MainLog.Instance.Warn("World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); - } - } - - #endregion - - #region Load Terrain - /// - /// Loads the World heightmap - /// - /// - public override void LoadWorldMap() - { - try - { - double[,] map = this.storageManager.DataStore.LoadTerrain(); - if (map == null) - { - if (string.IsNullOrEmpty(this.m_regInfo.estateSettings.terrainFile)) - { - Console.WriteLine("No default terrain, procedurally generating..."); - this.Terrain.hills(); - - this.storageManager.DataStore.StoreTerrain(this.Terrain.getHeights2DD()); - } - 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.storageManager.DataStore.StoreTerrain(this.Terrain.getHeights2DD()); - } - } - else - { - this.Terrain.setHeights2D(map); - } - - CreateTerrainTexture(); - - } - catch (Exception e) - { - MainLog.Instance.Warn("World.cs: LoadWorldMap() - Failed with exception " + e.ToString()); - } - } - - /// - /// - /// - public 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 - { - MainLog.Instance.Verbose("World.cs: LoadPrimsFromStorage() - Loading primitives"); - this.localStorage.LoadPrimitives(this); - } - catch (Exception e) - { - 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) - { - } - - /// - /// Returns a new unallocated primitive ID - /// - /// A brand new primitive ID - public uint PrimIDAllocate() - { - uint myID; - - _primAllocateMutex.WaitOne(); - ++_primCount; - myID = _primCount; - _primAllocateMutex.ReleaseMutex(); - - return myID; - } - - /// - /// - /// - /// - /// - public void AddNewPrim(LLUUID ownerID, LLVector3 pos, PrimitiveBaseShape shape) - { - - SceneObject sceneOb = new SceneObject(this, m_eventManager, ownerID, this.PrimIDAllocate(), pos, shape); - AddEntity(sceneOb); - } - - public void RemovePrim(uint localID, LLUUID avatar_deleter) - { - foreach (EntityBase obj in Entities.Values) - { - if (obj is SceneObject) - { - if (((SceneObject)obj).LocalId == localID) - { - RemoveEntity((SceneObject)obj); - return; - } - } - } - - } - - public void AddEntity(SceneObject sceneObject) - { - this.Entities.Add(sceneObject.rootUUID, sceneObject); - } - - public void RemoveEntity(SceneObject sceneObject) - { - if (this.Entities.ContainsKey(sceneObject.rootUUID)) - { - m_parcelManager.removePrimFromParcelCounts(sceneObject); - this.Entities.Remove(sceneObject.rootUUID); - m_parcelManager.setPrimsTainted(); - } - } - - /// - /// Called by a prim when it has been created/cloned, so that its events can be subscribed to - /// - /// - public void AcknowledgeNewPrim(Primitive prim) - { - prim.OnPrimCountTainted += m_parcelManager.setPrimsTainted; - } - #endregion - - #region Add/Remove Avatar Methods - - /// - /// - /// - /// - /// - public override void AddNewClient(IClientAPI client, bool child) - { - SubscribeToClientEvents(client); - this.m_estateManager.sendRegionHandshake(client); - CreateAndAddScenePresence(client); - this.m_parcelManager.sendParcelOverlay(client); - - } - - protected virtual void SubscribeToClientEvents(IClientAPI client) - { - client.OnRegionHandShakeReply += this.SendLayerData; - //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims); - client.OnChatFromViewer += this.SimChat; - client.OnInstantMessage += this.InstantMessage; - client.OnRequestWearables += this.InformClientOfNeighbours; - client.OnAddPrim += this.AddNewPrim; - client.OnUpdatePrimGroupPosition += this.UpdatePrimPosition; - client.OnUpdatePrimSinglePosition += this.UpdatePrimSinglePosition; - client.OnUpdatePrimGroupRotation += this.UpdatePrimRotation; - client.OnUpdatePrimGroupMouseRotation += this.UpdatePrimRotation; - client.OnUpdatePrimSingleRotation += this.UpdatePrimSingleRotation; - client.OnUpdatePrimScale += this.UpdatePrimScale; - client.OnUpdatePrimShape += this.UpdatePrimShape; - client.OnRequestMapBlocks += this.RequestMapBlocks; - client.OnUpdatePrimTexture += this.UpdatePrimTexture; - client.OnTeleportLocationRequest += this.RequestTeleportLocation; - client.OnObjectSelect += this.SelectPrim; - client.OnObjectDeselect += this.DeselectPrim; - client.OnGrapUpdate += this.MoveObject; - client.OnNameFromUUIDRequest += this.commsManager.HandleUUIDNameRequest; - client.OnObjectDescription += this.PrimDescription; - client.OnObjectName += this.PrimName; - client.OnLinkObjects += this.LinkObjects; - client.OnObjectDuplicate += this.DuplicateObject; - - client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(m_parcelManager.handleParcelPropertiesRequest); - client.OnParcelDivideRequest += new ParcelDivideRequest(m_parcelManager.handleParcelDivideRequest); - client.OnParcelJoinRequest += new ParcelJoinRequest(m_parcelManager.handleParcelJoinRequest); - client.OnParcelPropertiesUpdateRequest += new ParcelPropertiesUpdateRequest(m_parcelManager.handleParcelPropertiesUpdateRequest); - client.OnParcelSelectObjects += new ParcelSelectObjects(m_parcelManager.handleParcelSelectObjectsRequest); - client.OnParcelObjectOwnerRequest += new ParcelObjectOwnerRequest(m_parcelManager.handleParcelObjectOwnersRequest); - - client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage); - - } - - protected ScenePresence CreateAndAddScenePresence(IClientAPI client) - { - ScenePresence newAvatar = null; - - MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Creating new avatar for remote viewer agent"); - newAvatar = new ScenePresence(client, this, this.m_regInfo); - MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Adding new avatar to world"); - MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Starting RegionHandshake "); - - 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(client.AgentId)) - { - this.Entities.Add(client.AgentId, newAvatar); - } - else - { - Entities[client.AgentId] = newAvatar; - } - } - lock (Avatars) - { - if (Avatars.ContainsKey(client.AgentId)) - { - Avatars[client.AgentId] = newAvatar; - } - else - { - this.Avatars.Add(client.AgentId, newAvatar); - } - } - newAvatar.OnSignificantClientMovement += m_parcelManager.handleSignificantClientMovement; - return newAvatar; - } - - - /// - /// - /// - /// - public override void RemoveClient(LLUUID agentID) - { - m_eventManager.TriggerOnRemovePresence(agentID); - - ScenePresence avatar = this.RequestAvatar(agentID); - - this.ForEachScenePresence( - delegate(ScenePresence presence) - { - presence.ControllingClient.SendKillObject(avatar.RegionHandle, avatar.LocalId); - }); - - lock (Avatars) - { - if (Avatars.ContainsKey(agentID)) - { - Avatars.Remove(agentID); - } - } - lock (Entities) - { - if (Entities.ContainsKey(agentID)) - { - Entities.Remove(agentID); - } - } - // TODO: Add the removal from physics ? - - - - 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; - } - - public void ForEachScenePresence(ForEachScenePresenceDelegate whatToDo) - { - foreach (ScenePresence presence in this.Avatars.Values) - { - whatToDo(presence); - } - } - #endregion - - - /// - /// - /// - /// - /// - public bool DeleteEntity(LLUUID entID) - { - if (this.Entities.ContainsKey(entID)) - { - this.Entities.Remove(entID); - return true; - } - return false; - } - - public void SendAllSceneObjectsToClient(IClientAPI client) - { - foreach (EntityBase ent in Entities.Values) - { - if (ent is SceneObject) - { - ((SceneObject)ent).SendAllChildPrimsToClient(client); - } - } - } - - #region RegionCommsHost - - /// - /// - /// - public void RegisterRegionWithComms() - { - - this.regionCommsHost = this.commsManager.GridServer.RegisterRegion(this.m_regInfo); - if (this.regionCommsHost != null) - { - this.regionCommsHost.OnExpectUser += this.NewUserConnection; - this.regionCommsHost.OnAvatarCrossingIntoRegion += 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.ExternalHostName, this.m_regInfo.ExternalEndPoint.Port, agent.CapsPath, agent.AgentID); - cap.RegisterHandlers(); - if (capsHandlers.ContainsKey(agent.AgentID)) - { - OpenSim.Framework.Console.MainLog.Instance.Warn("Adding duplicate CAPS entry for user " + agent.AgentID.ToStringHyphenated()); - this.capsHandlers[agent.AgentID] = cap; - } - else - { - this.capsHandlers.Add(agent.AgentID, cap); - } - - } - this.authenticateHandler.AddNewCircuit(agent.circuitcode, agent); - } - } - - public void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position) - { - if (regionHandle == this.m_regInfo.RegionHandle) - { - if (this.Avatars.ContainsKey(agentID)) - { - this.Avatars[agentID].MakeAvatar(position); - } - } - } - - /// - /// - /// - public void InformClientOfNeighbours(IClientAPI remoteClient) - { - List neighbours = this.commsManager.GridServer.RequestNeighbours(this.m_regInfo); - - if (neighbours != null) - { - for (int i = 0; i < neighbours.Count; i++) - { - 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, neighbours[i].ExternalEndPoint); - //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.ExternalEndPoint, 4, (1 << 4)); - - } - } - } - - /// - /// - /// - /// - /// - /// - public bool InformNeighbourOfCrossing(ulong regionhandle, LLUUID agentID, LLVector3 position) - { - return this.commsManager.InterRegion.ExpectAvatarCrossing(regionhandle, agentID, position); - } - - public void performParcelPrimCountUpdate() - { - m_parcelManager.resetAllParcelPrimCounts(); - m_eventManager.TriggerParcelPrimCountUpdate(); - m_parcelManager.finalizeParcelPrimCountUpdate(); - m_parcelManager.parcelPrimCountTainted = false; - } - #endregion - - } -} +/* +* 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.Timers; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.Physics.Manager; +using OpenSim.Region.Caches; +using OpenSim.Region.Interfaces; +using OpenSim.Region.Scripting; +using OpenSim.Region.Terrain; +using Caps = OpenSim.Region.Capabilities.Caps; +using Timer = System.Timers.Timer; + +namespace OpenSim.Region.Environment.Scenes +{ + public delegate bool FilterAvatarList(ScenePresence avatar); + public delegate void ForEachScenePresenceDelegate(ScenePresence presence); + + public partial class Scene : SceneBase, ILocalStorageReceiver + { + protected Timer m_heartbeatTimer = new Timer(); + protected Dictionary Avatars; + protected Dictionary Prims; + protected PhysicsScene phyScene; + protected float timeStep = 0.1f; + private Random Rand = new Random(); + private uint _primCount = 702000; + private System.Threading.Mutex _primAllocateMutex = new Mutex(false); + private int storageCount; + private int parcelPrimCheckCount; + private Mutex updateLock; + + protected AuthenticateSessionsBase authenticateHandler; + protected RegionCommsListener regionCommsHost; + protected CommunicationsManager commsManager; + protected StorageManager storageManager; + + protected Dictionary capsHandlers = new Dictionary(); + protected BaseHttpServer httpListener; + + #region Properties + /// + /// + /// + public PhysicsScene PhysScene + { + set + { + this.phyScene = value; + } + get + { + return (this.phyScene); + } + } + + private ParcelManager m_parcelManager; + public ParcelManager ParcelManager + { + get { return m_parcelManager; } + } + + private EstateManager m_estateManager; + public EstateManager EstateManager + { + get { return m_estateManager; } + } + + private EventManager m_eventManager; + public EventManager EventManager + { + get { return m_eventManager; } + } + + private ScriptManager m_scriptManager; + public ScriptManager ScriptManager + { + get { return m_scriptManager; } + } + + public Dictionary Objects + { + get { return Prims; } + } + + #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(RegionInfo regInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer) + { + updateLock = new Mutex(false); + this.authenticateHandler = authen; + this.commsManager = commsMan; + this.storageManager = storeManager; + this.assetCache = assetCach; + m_regInfo = regInfo; + m_regionHandle = m_regInfo.RegionHandle; + m_regionName = m_regInfo.RegionName; + this.m_datastore = m_regInfo.DataStore; + this.RegisterRegionWithComms(); + + m_parcelManager = new ParcelManager(this, this.m_regInfo); + m_estateManager = new EstateManager(this, this.m_regInfo); + m_scriptManager = new ScriptManager(this); + m_eventManager = new EventManager(); + + m_eventManager.OnParcelPrimCountAdd += new EventManager.OnParcelPrimCountAddDelegate(m_parcelManager.addPrimToParcelCounts); + + MainLog.Instance.Verbose("World.cs - creating new entitities instance"); + Entities = new Dictionary(); + Avatars = new Dictionary(); + Prims = new Dictionary(); + + MainLog.Instance.Verbose("World.cs - loading objects from datastore"); + List PrimsFromDB = storageManager.DataStore.LoadObjects(); + foreach (SceneObject prim in PrimsFromDB) + { + AddEntity(prim); + } + MainLog.Instance.Verbose("World.cs - loaded " + PrimsFromDB.Count.ToString() + " object(s)"); + + + MainLog.Instance.Verbose("World.cs - creating LandMap"); + Terrain = new TerrainEngine(); + + ScenePresence.LoadAnims(); + + this.httpListener = httpServer; + } + #endregion + + #region Script Handling Methods + + public void SendCommandToScripts(string[] args) + { + m_eventManager.TriggerOnScriptConsole(args); + } + + #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, 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 (LLUUID UUID in Entities.Keys) + { + Entities[UUID].updateMovement(); + } + + lock (this.m_syncRoot) + { + this.phyScene.Simulate(timeStep); + } + + foreach (LLUUID UUID in Entities.Keys) + { + Entities[UUID].update(); + } + + // General purpose event manager + m_eventManager.TriggerOnFrame(); + + //backup world data + this.storageCount++; + if (storageCount > 1200) //set to how often you want to backup + { + this.Backup(); + storageCount = 0; + } + + this.parcelPrimCheckCount++; + if (this.parcelPrimCheckCount > 50) //check every 5 seconds for tainted prims + { + if (m_parcelManager.parcelPrimCountTainted) + { + //Perform parcel update of prim count + performParcelPrimCountUpdate(); + this.parcelPrimCheckCount = 0; + } + } + + } + catch (Exception e) + { + MainLog.Instance.Warn("World.cs: Update() - Failed with exception " + e.ToString()); + } + updateLock.ReleaseMutex(); + + } + + /// + /// + /// + /// + public bool Backup() + { + EventManager.TriggerOnBackup(this.storageManager.DataStore); + 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.storageManager.DataStore.StoreTerrain(Terrain.getHeights2DD()); + + this.ForEachScenePresence(delegate(ScenePresence presence) + { + this.SendLayerData(presence.ControllingClient); + }); + + foreach (LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + 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.storageManager.DataStore.StoreTerrain(Terrain.getHeights2DD()); + + this.ForEachScenePresence(delegate(ScenePresence presence) + { + this.SendLayerData(presence.ControllingClient); + }); + + foreach (LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + 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 */ + + this.ForEachScenePresence(delegate(ScenePresence presence) + { + this.SendLayerData(pointx, pointy, presence.ControllingClient); + }); + } + } + catch (Exception e) + { + MainLog.Instance.Warn("World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Load Terrain + /// + /// Loads the World heightmap + /// + /// + public override void LoadWorldMap() + { + try + { + double[,] map = this.storageManager.DataStore.LoadTerrain(); + if (map == null) + { + if (string.IsNullOrEmpty(this.m_regInfo.estateSettings.terrainFile)) + { + Console.WriteLine("No default terrain, procedurally generating..."); + this.Terrain.hills(); + + this.storageManager.DataStore.StoreTerrain(this.Terrain.getHeights2DD()); + } + 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.storageManager.DataStore.StoreTerrain(this.Terrain.getHeights2DD()); + } + } + else + { + this.Terrain.setHeights2D(map); + } + + CreateTerrainTexture(); + + } + catch (Exception e) + { + MainLog.Instance.Warn("World.cs: LoadWorldMap() - Failed with exception " + e.ToString()); + } + } + + /// + /// + /// + public 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 + { + MainLog.Instance.Verbose("World.cs: LoadPrimsFromStorage() - Loading primitives"); + this.localStorage.LoadPrimitives(this); + } + catch (Exception e) + { + 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) + { + } + + /// + /// Returns a new unallocated primitive ID + /// + /// A brand new primitive ID + public uint PrimIDAllocate() + { + uint myID; + + _primAllocateMutex.WaitOne(); + ++_primCount; + myID = _primCount; + _primAllocateMutex.ReleaseMutex(); + + return myID; + } + + /// + /// + /// + /// + /// + public void AddNewPrim(LLUUID ownerID, LLVector3 pos, PrimitiveBaseShape shape) + { + + SceneObject sceneOb = new SceneObject(this, m_eventManager, ownerID, this.PrimIDAllocate(), pos, shape); + AddEntity(sceneOb); + } + + public void RemovePrim(uint localID, LLUUID avatar_deleter) + { + foreach (EntityBase obj in Entities.Values) + { + if (obj is SceneObject) + { + if (((SceneObject)obj).LocalId == localID) + { + RemoveEntity((SceneObject)obj); + return; + } + } + } + + } + + public void AddEntity(SceneObject sceneObject) + { + this.Entities.Add(sceneObject.rootUUID, sceneObject); + } + + public void RemoveEntity(SceneObject sceneObject) + { + if (this.Entities.ContainsKey(sceneObject.rootUUID)) + { + m_parcelManager.removePrimFromParcelCounts(sceneObject); + this.Entities.Remove(sceneObject.rootUUID); + m_parcelManager.setPrimsTainted(); + } + } + + /// + /// Called by a prim when it has been created/cloned, so that its events can be subscribed to + /// + /// + public void AcknowledgeNewPrim(Primitive prim) + { + prim.OnPrimCountTainted += m_parcelManager.setPrimsTainted; + } + #endregion + + #region Add/Remove Avatar Methods + + /// + /// + /// + /// + /// + public override void AddNewClient(IClientAPI client, bool child) + { + SubscribeToClientEvents(client); + this.m_estateManager.sendRegionHandshake(client); + CreateAndAddScenePresence(client); + this.m_parcelManager.sendParcelOverlay(client); + + } + + protected virtual void SubscribeToClientEvents(IClientAPI client) + { + client.OnRegionHandShakeReply += this.SendLayerData; + //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims); + client.OnChatFromViewer += this.SimChat; + client.OnInstantMessage += this.InstantMessage; + client.OnRequestWearables += this.InformClientOfNeighbours; + client.OnAddPrim += this.AddNewPrim; + client.OnUpdatePrimGroupPosition += this.UpdatePrimPosition; + client.OnUpdatePrimSinglePosition += this.UpdatePrimSinglePosition; + client.OnUpdatePrimGroupRotation += this.UpdatePrimRotation; + client.OnUpdatePrimGroupMouseRotation += this.UpdatePrimRotation; + client.OnUpdatePrimSingleRotation += this.UpdatePrimSingleRotation; + client.OnUpdatePrimScale += this.UpdatePrimScale; + client.OnUpdatePrimShape += this.UpdatePrimShape; + client.OnRequestMapBlocks += this.RequestMapBlocks; + client.OnUpdatePrimTexture += this.UpdatePrimTexture; + client.OnTeleportLocationRequest += this.RequestTeleportLocation; + client.OnObjectSelect += this.SelectPrim; + client.OnObjectDeselect += this.DeselectPrim; + client.OnGrapUpdate += this.MoveObject; + client.OnNameFromUUIDRequest += this.commsManager.HandleUUIDNameRequest; + client.OnObjectDescription += this.PrimDescription; + client.OnObjectName += this.PrimName; + client.OnLinkObjects += this.LinkObjects; + client.OnObjectDuplicate += this.DuplicateObject; + + client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(m_parcelManager.handleParcelPropertiesRequest); + client.OnParcelDivideRequest += new ParcelDivideRequest(m_parcelManager.handleParcelDivideRequest); + client.OnParcelJoinRequest += new ParcelJoinRequest(m_parcelManager.handleParcelJoinRequest); + client.OnParcelPropertiesUpdateRequest += new ParcelPropertiesUpdateRequest(m_parcelManager.handleParcelPropertiesUpdateRequest); + client.OnParcelSelectObjects += new ParcelSelectObjects(m_parcelManager.handleParcelSelectObjectsRequest); + client.OnParcelObjectOwnerRequest += new ParcelObjectOwnerRequest(m_parcelManager.handleParcelObjectOwnersRequest); + + client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage); + + } + + protected ScenePresence CreateAndAddScenePresence(IClientAPI client) + { + ScenePresence newAvatar = null; + + MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Creating new avatar for remote viewer agent"); + newAvatar = new ScenePresence(client, this, this.m_regInfo); + MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Adding new avatar to world"); + MainLog.Instance.Verbose("World.cs:AddViewerAgent() - Starting RegionHandshake "); + + 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(client.AgentId)) + { + this.Entities.Add(client.AgentId, newAvatar); + } + else + { + Entities[client.AgentId] = newAvatar; + } + } + lock (Avatars) + { + if (Avatars.ContainsKey(client.AgentId)) + { + Avatars[client.AgentId] = newAvatar; + } + else + { + this.Avatars.Add(client.AgentId, newAvatar); + } + } + newAvatar.OnSignificantClientMovement += m_parcelManager.handleSignificantClientMovement; + return newAvatar; + } + + + /// + /// + /// + /// + public override void RemoveClient(LLUUID agentID) + { + m_eventManager.TriggerOnRemovePresence(agentID); + + ScenePresence avatar = this.RequestAvatar(agentID); + + this.ForEachScenePresence( + delegate(ScenePresence presence) + { + presence.ControllingClient.SendKillObject(avatar.RegionHandle, avatar.LocalId); + }); + + lock (Avatars) + { + if (Avatars.ContainsKey(agentID)) + { + Avatars.Remove(agentID); + } + } + lock (Entities) + { + if (Entities.ContainsKey(agentID)) + { + Entities.Remove(agentID); + } + } + // TODO: Add the removal from physics ? + + + + 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; + } + + public void ForEachScenePresence(ForEachScenePresenceDelegate whatToDo) + { + foreach (ScenePresence presence in this.Avatars.Values) + { + whatToDo(presence); + } + } + #endregion + + + /// + /// + /// + /// + /// + public bool DeleteEntity(LLUUID entID) + { + if (this.Entities.ContainsKey(entID)) + { + this.Entities.Remove(entID); + return true; + } + return false; + } + + public void SendAllSceneObjectsToClient(IClientAPI client) + { + foreach (EntityBase ent in Entities.Values) + { + if (ent is SceneObject) + { + ((SceneObject)ent).SendAllChildPrimsToClient(client); + } + } + } + + #region RegionCommsHost + + /// + /// + /// + public void RegisterRegionWithComms() + { + + this.regionCommsHost = this.commsManager.GridServer.RegisterRegion(this.m_regInfo); + if (this.regionCommsHost != null) + { + this.regionCommsHost.OnExpectUser += this.NewUserConnection; + this.regionCommsHost.OnAvatarCrossingIntoRegion += 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.ExternalHostName, this.m_regInfo.ExternalEndPoint.Port, agent.CapsPath, agent.AgentID); + cap.RegisterHandlers(); + if (capsHandlers.ContainsKey(agent.AgentID)) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Adding duplicate CAPS entry for user " + agent.AgentID.ToStringHyphenated()); + this.capsHandlers[agent.AgentID] = cap; + } + else + { + this.capsHandlers.Add(agent.AgentID, cap); + } + + } + this.authenticateHandler.AddNewCircuit(agent.circuitcode, agent); + } + } + + public void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position) + { + if (regionHandle == this.m_regInfo.RegionHandle) + { + if (this.Avatars.ContainsKey(agentID)) + { + this.Avatars[agentID].MakeAvatar(position); + } + } + } + + /// + /// + /// + public void InformClientOfNeighbours(IClientAPI remoteClient) + { + List neighbours = this.commsManager.GridServer.RequestNeighbours(this.m_regInfo); + + if (neighbours != null) + { + for (int i = 0; i < neighbours.Count; i++) + { + 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, neighbours[i].ExternalEndPoint); + //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.ExternalEndPoint, 4, (1 << 4)); + + } + } + } + + /// + /// + /// + /// + /// + /// + public bool InformNeighbourOfCrossing(ulong regionhandle, LLUUID agentID, LLVector3 position) + { + return this.commsManager.InterRegion.ExpectAvatarCrossing(regionhandle, agentID, position); + } + + public void performParcelPrimCountUpdate() + { + m_parcelManager.resetAllParcelPrimCounts(); + m_eventManager.TriggerParcelPrimCountUpdate(); + m_parcelManager.finalizeParcelPrimCountUpdate(); + m_parcelManager.parcelPrimCountTainted = false; + } + #endregion + + } +} diff --git a/OpenSim/Region/Environment/Scenes/SceneBase.cs b/OpenSim/Region/Environment/Scenes/SceneBase.cs index 161a5cf..cbf69ac 100644 --- a/OpenSim/Region/Environment/Scenes/SceneBase.cs +++ b/OpenSim/Region/Environment/Scenes/SceneBase.cs @@ -1,195 +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.Reflection; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Region.Caches; -using OpenSim.Region.Terrain; -using OpenSim.Framework; - -namespace OpenSim.Region.Environment.Scenes -{ - public abstract class SceneBase : IWorld - { - public Dictionary Entities; - 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) - { - 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 client, 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) - { - MainLog.Instance.WriteLine(LogPriority.HIGH, "World.cs: Close() - Failed with exception " + e.ToString()); - } - } - - #endregion - - - } -} +/* +* 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.Reflection; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Region.Caches; +using OpenSim.Region.Terrain; +using OpenSim.Framework; + +namespace OpenSim.Region.Environment.Scenes +{ + public abstract class SceneBase : IWorld + { + public Dictionary Entities; + 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) + { + 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 client, 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) + { + MainLog.Instance.WriteLine(LogPriority.HIGH, "World.cs: Close() - Failed with exception " + e.ToString()); + } + } + + #endregion + + + } +} diff --git a/OpenSim/Region/Environment/Scenes/SceneEvents.cs b/OpenSim/Region/Environment/Scenes/SceneEvents.cs index 1e4b163..255cbf2 100644 --- a/OpenSim/Region/Environment/Scenes/SceneEvents.cs +++ b/OpenSim/Region/Environment/Scenes/SceneEvents.cs @@ -1,82 +1,82 @@ -using libsecondlife; - -namespace OpenSim.Region.Environment.Scenes -{ - /// - /// A class for triggering remote scene events. - /// - public class EventManager - { - public delegate void OnFrameDelegate(); - public event OnFrameDelegate OnFrame; - - public delegate void OnBackupDelegate(Interfaces.IRegionDataStore datastore); - public event OnBackupDelegate OnBackup; - - public delegate void OnNewPresenceDelegate(ScenePresence presence); - public event OnNewPresenceDelegate OnNewPresence; - - public delegate void OnRemovePresenceDelegate(LLUUID uuid); - public event OnRemovePresenceDelegate OnRemovePresence; - - public delegate void OnParcelPrimCountUpdateDelegate(); - public event OnParcelPrimCountUpdateDelegate OnParcelPrimCountUpdate; - - public delegate void OnParcelPrimCountAddDelegate(SceneObject obj); - public event OnParcelPrimCountAddDelegate OnParcelPrimCountAdd; - - public delegate void OnScriptConsoleDelegate(string[] args); - public event OnScriptConsoleDelegate OnScriptConsole; - - public void TriggerOnScriptConsole(string[] args) - { - if (OnScriptConsole != null) - OnScriptConsole(args); - } - - public void TriggerOnFrame() - { - if (OnFrame != null) - { - OnFrame(); - } - } - - public void TriggerOnNewPresence(ScenePresence presence) - { - if (OnNewPresence != null) - OnNewPresence(presence); - } - - public void TriggerOnRemovePresence(LLUUID uuid) - { - if (OnRemovePresence != null) - { - OnRemovePresence(uuid); - } - } - - public void TriggerOnBackup(Interfaces.IRegionDataStore dstore) - { - if (OnBackup != null) - { - OnBackup(dstore); - } - } - - public void TriggerParcelPrimCountUpdate() - { - if (OnParcelPrimCountUpdate != null) - { - OnParcelPrimCountUpdate(); - } - } - public void TriggerParcelPrimCountAdd(SceneObject obj) - { - if (OnParcelPrimCountAdd != null) - { - OnParcelPrimCountAdd(obj); - } - } - } -} +using libsecondlife; + +namespace OpenSim.Region.Environment.Scenes +{ + /// + /// A class for triggering remote scene events. + /// + public class EventManager + { + public delegate void OnFrameDelegate(); + public event OnFrameDelegate OnFrame; + + public delegate void OnBackupDelegate(Interfaces.IRegionDataStore datastore); + public event OnBackupDelegate OnBackup; + + public delegate void OnNewPresenceDelegate(ScenePresence presence); + public event OnNewPresenceDelegate OnNewPresence; + + public delegate void OnRemovePresenceDelegate(LLUUID uuid); + public event OnRemovePresenceDelegate OnRemovePresence; + + public delegate void OnParcelPrimCountUpdateDelegate(); + public event OnParcelPrimCountUpdateDelegate OnParcelPrimCountUpdate; + + public delegate void OnParcelPrimCountAddDelegate(SceneObject obj); + public event OnParcelPrimCountAddDelegate OnParcelPrimCountAdd; + + public delegate void OnScriptConsoleDelegate(string[] args); + public event OnScriptConsoleDelegate OnScriptConsole; + + public void TriggerOnScriptConsole(string[] args) + { + if (OnScriptConsole != null) + OnScriptConsole(args); + } + + public void TriggerOnFrame() + { + if (OnFrame != null) + { + OnFrame(); + } + } + + public void TriggerOnNewPresence(ScenePresence presence) + { + if (OnNewPresence != null) + OnNewPresence(presence); + } + + public void TriggerOnRemovePresence(LLUUID uuid) + { + if (OnRemovePresence != null) + { + OnRemovePresence(uuid); + } + } + + public void TriggerOnBackup(Interfaces.IRegionDataStore dstore) + { + if (OnBackup != null) + { + OnBackup(dstore); + } + } + + public void TriggerParcelPrimCountUpdate() + { + if (OnParcelPrimCountUpdate != null) + { + OnParcelPrimCountUpdate(); + } + } + public void TriggerParcelPrimCountAdd(SceneObject obj) + { + if (OnParcelPrimCountAdd != null) + { + OnParcelPrimCountAdd(obj); + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/SceneObject.cs b/OpenSim/Region/Environment/Scenes/SceneObject.cs index e615599..43d41e6 100644 --- a/OpenSim/Region/Environment/Scenes/SceneObject.cs +++ b/OpenSim/Region/Environment/Scenes/SceneObject.cs @@ -1,309 +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.Collections.Generic; -using System.Text; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Physics.Manager; - -namespace OpenSim.Region.Environment.Scenes -{ - public class SceneObject : EntityBase - { - private Encoding enc = Encoding.ASCII; - private Dictionary ChildPrimitives = new Dictionary(); //list of all primitive id's that are part of this group - public Primitive rootPrimitive; - private new Scene m_world; - protected ulong m_regionHandle; - - private bool physicsEnabled = false; - private PhysicsScene m_PhysScene; - private PhysicsActor m_PhysActor; - - private EventManager m_eventManager; - - public bool isSelected = false; - - public LLUUID rootUUID - { - get - { - this.uuid = this.rootPrimitive.uuid; - return this.uuid; - } - } - - public uint rootLocalID - { - get - { - this.m_localId = this.rootPrimitive.LocalId; - return this.LocalId; - } - } - - public int primCount - { - get - { - return this.ChildPrimitives.Count; - } - } - - public Dictionary Children - { - get - { - return this.ChildPrimitives; - } - } - - /// - /// - /// - public SceneObject(Scene world, EventManager eventManager, LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) - { - m_regionHandle = world.RegionInfo.RegionHandle; - m_world = world; - m_eventManager = eventManager; - - this.Pos = pos; - this.CreateRootFromShape(ownerID, localID, shape, pos); - - registerEvents(); - - } - - /// - /// - /// - /// Need a null constructor for duplication - public SceneObject() - { - - } - - public void registerEvents() - { - m_eventManager.OnBackup += new EventManager.OnBackupDelegate(ProcessBackup); - m_eventManager.OnParcelPrimCountUpdate += new EventManager.OnParcelPrimCountUpdateDelegate(ProcessParcelPrimCountUpdate); - } - - public void unregisterEvents() - { - m_eventManager.OnBackup -= new EventManager.OnBackupDelegate(ProcessBackup); - m_eventManager.OnParcelPrimCountUpdate -= new EventManager.OnParcelPrimCountUpdateDelegate(ProcessParcelPrimCountUpdate); - } - - /// - /// Processes backup - /// - /// - public void ProcessBackup(OpenSim.Region.Interfaces.IRegionDataStore datastore) - { - datastore.StoreObject(this); - } - - /// - /// Sends my primitive info to the parcel manager for it to keep tally of all of the prims! - /// - private void ProcessParcelPrimCountUpdate() - { - - m_eventManager.TriggerParcelPrimCountAdd(this); - } - - /// - /// - /// - /// - /// - /// - public void CreateRootFromShape(LLUUID agentID, uint localID, PrimitiveBaseShape shape, LLVector3 pos) - { - - this.rootPrimitive = new Primitive(this.m_regionHandle, this.m_world, agentID, localID, true, this, this, shape, pos); - - this.children.Add(rootPrimitive); - this.ChildPrimitives.Add(this.rootUUID, this.rootPrimitive); - } - - /// - /// - /// - /// - public void CreateFromBytes(byte[] data) - { - - } - - /// - /// Makes a copy of this SceneObject (and child primitives) - /// - /// A complete copy of the object - public new SceneObject Copy() - { - SceneObject dupe = new SceneObject(); - - dupe.m_world = this.m_world; - dupe.m_eventManager = this.m_eventManager; - dupe.m_regionHandle = this.m_regionHandle; - Primitive newRoot = this.rootPrimitive.Copy(dupe, dupe); - dupe.rootPrimitive = newRoot; - dupe.children.Add(dupe.rootPrimitive); - dupe.rootPrimitive.Pos = this.Pos; - dupe.Rotation = this.Rotation; - dupe.LocalId = m_world.PrimIDAllocate(); - - dupe.registerEvents(); - return dupe; - } - - /// - /// - /// - public void DeleteAllChildren() - { - this.children.Clear(); - this.ChildPrimitives.Clear(); - this.rootPrimitive = null; - unregisterEvents(); - } - - /// - /// - /// - /// - public void AddNewChildPrims(SceneObject primObject) - { - this.rootPrimitive.AddNewChildren(primObject); - } - - public void AddChildToList(Primitive prim) - { - if (!this.ChildPrimitives.ContainsKey(prim.uuid)) - { - this.ChildPrimitives.Add(prim.uuid, prim); - } - } - /// - /// - /// - /// - /// - public Primitive HasChildPrim(LLUUID primID) - { - if (this.ChildPrimitives.ContainsKey(primID)) - { - return this.ChildPrimitives[primID]; - } - - return null; - } - - /// - /// - /// - /// - /// - public Primitive HasChildPrim(uint localID) - { - Primitive returnPrim = null; - foreach (Primitive prim in this.ChildPrimitives.Values) - { - if (prim.LocalId == localID) - { - returnPrim = prim; - break; - } - } - return returnPrim; - } - - public void SendAllChildPrimsToClient(IClientAPI client) - { - this.rootPrimitive.SendFullUpdateForAllChildren(client); - } - - /// - /// - /// - public override void BackUp() - { - - } - - /// - /// - /// - /// - /// - /// - public void GrapMovement(LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) - { - this.rootPrimitive.Pos = pos; - this.rootPrimitive.SendTerseUpdateForAllChildren(remoteClient); - } - - /// - /// - /// - /// - public void GetProperites(IClientAPI client) - { - 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.CreationDate; - proper.ObjectData[0].CreatorID = this.rootPrimitive.CreatorID; - 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 = this.rootPrimitive.LastOwnerID; - proper.ObjectData[0].ObjectID = this.rootUUID; - proper.ObjectData[0].OwnerID = this.rootPrimitive.OwnerID; - proper.ObjectData[0].TouchName = enc.GetBytes(this.rootPrimitive.TouchName + "\0"); - proper.ObjectData[0].TextureID = new byte[0]; - proper.ObjectData[0].SitName = enc.GetBytes(this.rootPrimitive.SitName + "\0"); - proper.ObjectData[0].Name = enc.GetBytes(this.rootPrimitive.Name + "\0"); - proper.ObjectData[0].Description = enc.GetBytes(this.rootPrimitive.Description + "\0"); - proper.ObjectData[0].OwnerMask = this.rootPrimitive.OwnerMask; - proper.ObjectData[0].NextOwnerMask = this.rootPrimitive.NextOwnerMask; - proper.ObjectData[0].GroupMask = this.rootPrimitive.GroupMask; - proper.ObjectData[0].EveryoneMask = this.rootPrimitive.EveryoneMask; - proper.ObjectData[0].BaseMask = this.rootPrimitive.BaseMask; - - client.OutPacket(proper); - } - - } -} +/* +* 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.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Physics.Manager; + +namespace OpenSim.Region.Environment.Scenes +{ + public class SceneObject : EntityBase + { + private Encoding enc = Encoding.ASCII; + private Dictionary ChildPrimitives = new Dictionary(); //list of all primitive id's that are part of this group + public Primitive rootPrimitive; + private new Scene m_world; + protected ulong m_regionHandle; + + private bool physicsEnabled = false; + private PhysicsScene m_PhysScene; + private PhysicsActor m_PhysActor; + + private EventManager m_eventManager; + + public bool isSelected = false; + + public LLUUID rootUUID + { + get + { + this.uuid = this.rootPrimitive.uuid; + return this.uuid; + } + } + + public uint rootLocalID + { + get + { + this.m_localId = this.rootPrimitive.LocalId; + return this.LocalId; + } + } + + public int primCount + { + get + { + return this.ChildPrimitives.Count; + } + } + + public Dictionary Children + { + get + { + return this.ChildPrimitives; + } + } + + /// + /// + /// + public SceneObject(Scene world, EventManager eventManager, LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) + { + m_regionHandle = world.RegionInfo.RegionHandle; + m_world = world; + m_eventManager = eventManager; + + this.Pos = pos; + this.CreateRootFromShape(ownerID, localID, shape, pos); + + registerEvents(); + + } + + /// + /// + /// + /// Need a null constructor for duplication + public SceneObject() + { + + } + + public void registerEvents() + { + m_eventManager.OnBackup += new EventManager.OnBackupDelegate(ProcessBackup); + m_eventManager.OnParcelPrimCountUpdate += new EventManager.OnParcelPrimCountUpdateDelegate(ProcessParcelPrimCountUpdate); + } + + public void unregisterEvents() + { + m_eventManager.OnBackup -= new EventManager.OnBackupDelegate(ProcessBackup); + m_eventManager.OnParcelPrimCountUpdate -= new EventManager.OnParcelPrimCountUpdateDelegate(ProcessParcelPrimCountUpdate); + } + + /// + /// Processes backup + /// + /// + public void ProcessBackup(OpenSim.Region.Interfaces.IRegionDataStore datastore) + { + datastore.StoreObject(this); + } + + /// + /// Sends my primitive info to the parcel manager for it to keep tally of all of the prims! + /// + private void ProcessParcelPrimCountUpdate() + { + + m_eventManager.TriggerParcelPrimCountAdd(this); + } + + /// + /// + /// + /// + /// + /// + public void CreateRootFromShape(LLUUID agentID, uint localID, PrimitiveBaseShape shape, LLVector3 pos) + { + + this.rootPrimitive = new Primitive(this.m_regionHandle, this.m_world, agentID, localID, true, this, this, shape, pos); + + this.children.Add(rootPrimitive); + this.ChildPrimitives.Add(this.rootUUID, this.rootPrimitive); + } + + /// + /// + /// + /// + public void CreateFromBytes(byte[] data) + { + + } + + /// + /// Makes a copy of this SceneObject (and child primitives) + /// + /// A complete copy of the object + public new SceneObject Copy() + { + SceneObject dupe = new SceneObject(); + + dupe.m_world = this.m_world; + dupe.m_eventManager = this.m_eventManager; + dupe.m_regionHandle = this.m_regionHandle; + Primitive newRoot = this.rootPrimitive.Copy(dupe, dupe); + dupe.rootPrimitive = newRoot; + dupe.children.Add(dupe.rootPrimitive); + dupe.rootPrimitive.Pos = this.Pos; + dupe.Rotation = this.Rotation; + dupe.LocalId = m_world.PrimIDAllocate(); + + dupe.registerEvents(); + return dupe; + } + + /// + /// + /// + public void DeleteAllChildren() + { + this.children.Clear(); + this.ChildPrimitives.Clear(); + this.rootPrimitive = null; + unregisterEvents(); + } + + /// + /// + /// + /// + public void AddNewChildPrims(SceneObject primObject) + { + this.rootPrimitive.AddNewChildren(primObject); + } + + public void AddChildToList(Primitive prim) + { + if (!this.ChildPrimitives.ContainsKey(prim.uuid)) + { + this.ChildPrimitives.Add(prim.uuid, prim); + } + } + /// + /// + /// + /// + /// + public Primitive HasChildPrim(LLUUID primID) + { + if (this.ChildPrimitives.ContainsKey(primID)) + { + return this.ChildPrimitives[primID]; + } + + return null; + } + + /// + /// + /// + /// + /// + public Primitive HasChildPrim(uint localID) + { + Primitive returnPrim = null; + foreach (Primitive prim in this.ChildPrimitives.Values) + { + if (prim.LocalId == localID) + { + returnPrim = prim; + break; + } + } + return returnPrim; + } + + public void SendAllChildPrimsToClient(IClientAPI client) + { + this.rootPrimitive.SendFullUpdateForAllChildren(client); + } + + /// + /// + /// + public override void BackUp() + { + + } + + /// + /// + /// + /// + /// + /// + public void GrapMovement(LLVector3 offset, LLVector3 pos, IClientAPI remoteClient) + { + this.rootPrimitive.Pos = pos; + this.rootPrimitive.SendTerseUpdateForAllChildren(remoteClient); + } + + /// + /// + /// + /// + public void GetProperites(IClientAPI client) + { + 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.CreationDate; + proper.ObjectData[0].CreatorID = this.rootPrimitive.CreatorID; + 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 = this.rootPrimitive.LastOwnerID; + proper.ObjectData[0].ObjectID = this.rootUUID; + proper.ObjectData[0].OwnerID = this.rootPrimitive.OwnerID; + proper.ObjectData[0].TouchName = enc.GetBytes(this.rootPrimitive.TouchName + "\0"); + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = enc.GetBytes(this.rootPrimitive.SitName + "\0"); + proper.ObjectData[0].Name = enc.GetBytes(this.rootPrimitive.Name + "\0"); + proper.ObjectData[0].Description = enc.GetBytes(this.rootPrimitive.Description + "\0"); + proper.ObjectData[0].OwnerMask = this.rootPrimitive.OwnerMask; + proper.ObjectData[0].NextOwnerMask = this.rootPrimitive.NextOwnerMask; + proper.ObjectData[0].GroupMask = this.rootPrimitive.GroupMask; + proper.ObjectData[0].EveryoneMask = this.rootPrimitive.EveryoneMask; + proper.ObjectData[0].BaseMask = this.rootPrimitive.BaseMask; + + client.OutPacket(proper); + } + + } +} diff --git a/OpenSim/Region/Environment/Scenes/ScenePresence.Animations.cs b/OpenSim/Region/Environment/Scenes/ScenePresence.Animations.cs index d1f75ed..e88ee71 100644 --- a/OpenSim/Region/Environment/Scenes/ScenePresence.Animations.cs +++ b/OpenSim/Region/Environment/Scenes/ScenePresence.Animations.cs @@ -1,74 +1,74 @@ -/* -* 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.Collections.Generic; -using System.Xml; -using libsecondlife; - -namespace OpenSim.Region.Environment.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 Animations.AnimsLLUUID) - { - AnimsNames.Add(kp.Value, kp.Key); - } - } - } - } -} +/* +* 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.Collections.Generic; +using System.Xml; +using libsecondlife; + +namespace OpenSim.Region.Environment.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 Animations.AnimsLLUUID) + { + AnimsNames.Add(kp.Value, kp.Key); + } + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/ScenePresence.Body.cs b/OpenSim/Region/Environment/Scenes/ScenePresence.Body.cs index dbb5d3f..c2599a1 100644 --- a/OpenSim/Region/Environment/Scenes/ScenePresence.Body.cs +++ b/OpenSim/Region/Environment/Scenes/ScenePresence.Body.cs @@ -1,85 +1,85 @@ -/* -* 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 libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Interfaces; - -namespace OpenSim.Region.Environment.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) - { - } - } - } - -} +/* +* 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 libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Region.Environment.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/Environment/Scenes/ScenePresence.cs b/OpenSim/Region/Environment/Scenes/ScenePresence.cs index b619b59..ae49d9f 100644 --- a/OpenSim/Region/Environment/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Environment/Scenes/ScenePresence.cs @@ -1,623 +1,623 @@ -/* -* 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 Axiom.Math; -using libsecondlife; -using libsecondlife.Packets; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Physics.Manager; - -namespace OpenSim.Region.Environment.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 Quaternion bodyRot; - private LLObject.TextureEntry avatarAppearanceTexture = null; - private byte[] visualParams; - private AvatarWearable[] Wearables; - private ulong m_regionHandle; - - public bool childAgent = false; - public bool IsRestrictedToRegion = false; - - private bool newForce = false; - private bool newAvatar = false; - private IScenePresenceBody m_body; - - protected RegionInfo m_regionInfo; - - private Vector3[] Dir_Vectors = new Vector3[6]; - private enum Dir_ControlFlags - { - DIR_CONTROL_FLAG_FOWARD = MainAvatar.ControlFlags.AGENT_CONTROL_AT_POS, - DIR_CONTROL_FLAG_BACK = MainAvatar.ControlFlags.AGENT_CONTROL_AT_NEG, - DIR_CONTROL_FLAG_LEFT = MainAvatar.ControlFlags.AGENT_CONTROL_LEFT_POS, - DIR_CONTROL_FLAG_RIGHT = MainAvatar.ControlFlags.AGENT_CONTROL_LEFT_NEG, - DIR_CONTROL_FLAG_UP = MainAvatar.ControlFlags.AGENT_CONTROL_UP_POS, - DIR_CONTROL_FLAG_DOWN = MainAvatar.ControlFlags.AGENT_CONTROL_UP_NEG - } - /// - /// Position at which a significant movement was made - /// - private LLVector3 posLastSignificantMove = new LLVector3(); - - public delegate void SignificantClientMovement(IClientAPI remote_client); - public event SignificantClientMovement OnSignificantClientMovement; - - #region Properties - /// - /// - /// - public PhysicsActor PhysActor - { - set - { - this._physActor = value; - } - get - { - return _physActor; - } - } - - public ulong RegionHandle - { - get { return m_regionHandle; } - } - - #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; - 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; - Animations = new ScenePresence.AvatarAnimations(); - Animations.LoadAnims(); - - 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); - - Dir_Vectors[0] = new Vector3(1, 0, 0); //FOWARD - Dir_Vectors[1] = new Vector3(-1, 0, 0); //BACK - Dir_Vectors[2] = new Vector3(0, 1, 0); //LEFT - Dir_Vectors[3] = new Vector3(0, -1, 0); //RIGHT - Dir_Vectors[4] = new Vector3(0, 0, 1); //UP - Dir_Vectors[5] = new Vector3(0, 0, -1); //DOWN - - } - #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) - { - int i = 0; - bool update_movementflag = false; - bool update_rotation = false; - bool DCFlagKeyPressed = false; - Vector3 agent_control_v3 = new Vector3(0, 0, 0); - Quaternion q = new Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); - - this.PhysActor.Flying = ((flags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY) != 0); - - if (q != this.bodyRot) - { - this.bodyRot = q; - update_rotation = true; - } - foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof(Dir_ControlFlags))) - { - if ((flags & (uint)DCF) != 0) - { - DCFlagKeyPressed = true; - agent_control_v3 += Dir_Vectors[i]; - if ((movementflag & (uint)DCF) == 0) - { - movementflag += (byte)(uint)DCF; - update_movementflag = true; - } - } - else - { - if ((movementflag & (uint)DCF) != 0) - { - movementflag -= (byte)(uint)DCF; - update_movementflag = true; - - } - } - i++; - } - if ((update_movementflag) || (update_rotation && DCFlagKeyPressed)) - { - this.AddNewMovement(agent_control_v3, q); - } - UpdateMovementAnimations(update_movementflag); - } - - protected void UpdateMovementAnimations(bool update_movementflag) - { - if (update_movementflag) - { - if (movementflag != 0) - { - if (this._physActor.Flying) - { - this.SendAnimPack(Animations.AnimsLLUUID["FLY"], 1); - } - else - { - this.SendAnimPack(Animations.AnimsLLUUID["WALK"], 1); - } - } - else - { - this.SendAnimPack(Animations.AnimsLLUUID["STAND"], 1); - } - } - - } - - - protected void AddNewMovement(Vector3 vec, Quaternion rotation) - { - NewForce newVelocity = new NewForce(); - 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.CheckForSignificantMovement(); - 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 SendFullUpdateToALLClients() - { - List avatars = this.m_world.RequestAvatarList(); - foreach (ScenePresence avatar in this.m_world.RequestAvatarList()) - { - this.SendFullUpdateToOtherClient(avatar); - avatar.SendFullUpdateToOtherClient(this); - } - } - - /// - /// - /// - 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); - this.SendFullUpdateToALLClients(); - this.m_world.SendAllSceneObjectsToClient(this.ControllingClient); - } - - /// - /// - /// - /// - public void SendAppearanceToOtherAgent(ScenePresence avatarInfo) - { - - } - - /// - /// - /// - /// - /// - public void SendAnimPack(LLUUID animID, int seq) - { - this.current_anim = animID; - this.anim_seq = seq; - List avatars = this.m_world.RequestAvatarList(); - for (int i = 0; i < avatars.Count; i++) - { - avatars[i].ControllingClient.SendAnimation(animID, seq, this.ControllingClient.AgentId); - } - } - - /// - /// - /// - public void SendAnimPack() - { - this.SendAnimPack(this.current_anim, this.anim_seq); - } - #endregion - - #region Significant Movement Method - - protected void CheckForSignificantMovement() - { - if (libsecondlife.Helpers.VecDist(this.Pos, this.posLastSignificantMove) > 2.0) - { - this.posLastSignificantMove = this.Pos; - if (OnSignificantClientMovement != null) - { - OnSignificantClientMovement(this.ControllingClient); - } - } - } - #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.m_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, neighbourRegion.InternalEndPoint); - } - } - } - #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() - { - - } - } - } - -} +/* +* 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 Axiom.Math; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Physics.Manager; + +namespace OpenSim.Region.Environment.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 Quaternion bodyRot; + private LLObject.TextureEntry avatarAppearanceTexture = null; + private byte[] visualParams; + private AvatarWearable[] Wearables; + private ulong m_regionHandle; + + public bool childAgent = false; + public bool IsRestrictedToRegion = false; + + private bool newForce = false; + private bool newAvatar = false; + private IScenePresenceBody m_body; + + protected RegionInfo m_regionInfo; + + private Vector3[] Dir_Vectors = new Vector3[6]; + private enum Dir_ControlFlags + { + DIR_CONTROL_FLAG_FOWARD = MainAvatar.ControlFlags.AGENT_CONTROL_AT_POS, + DIR_CONTROL_FLAG_BACK = MainAvatar.ControlFlags.AGENT_CONTROL_AT_NEG, + DIR_CONTROL_FLAG_LEFT = MainAvatar.ControlFlags.AGENT_CONTROL_LEFT_POS, + DIR_CONTROL_FLAG_RIGHT = MainAvatar.ControlFlags.AGENT_CONTROL_LEFT_NEG, + DIR_CONTROL_FLAG_UP = MainAvatar.ControlFlags.AGENT_CONTROL_UP_POS, + DIR_CONTROL_FLAG_DOWN = MainAvatar.ControlFlags.AGENT_CONTROL_UP_NEG + } + /// + /// Position at which a significant movement was made + /// + private LLVector3 posLastSignificantMove = new LLVector3(); + + public delegate void SignificantClientMovement(IClientAPI remote_client); + public event SignificantClientMovement OnSignificantClientMovement; + + #region Properties + /// + /// + /// + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + get + { + return _physActor; + } + } + + public ulong RegionHandle + { + get { return m_regionHandle; } + } + + #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; + 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; + Animations = new ScenePresence.AvatarAnimations(); + Animations.LoadAnims(); + + 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); + + Dir_Vectors[0] = new Vector3(1, 0, 0); //FOWARD + Dir_Vectors[1] = new Vector3(-1, 0, 0); //BACK + Dir_Vectors[2] = new Vector3(0, 1, 0); //LEFT + Dir_Vectors[3] = new Vector3(0, -1, 0); //RIGHT + Dir_Vectors[4] = new Vector3(0, 0, 1); //UP + Dir_Vectors[5] = new Vector3(0, 0, -1); //DOWN + + } + #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) + { + int i = 0; + bool update_movementflag = false; + bool update_rotation = false; + bool DCFlagKeyPressed = false; + Vector3 agent_control_v3 = new Vector3(0, 0, 0); + Quaternion q = new Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); + + this.PhysActor.Flying = ((flags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY) != 0); + + if (q != this.bodyRot) + { + this.bodyRot = q; + update_rotation = true; + } + foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof(Dir_ControlFlags))) + { + if ((flags & (uint)DCF) != 0) + { + DCFlagKeyPressed = true; + agent_control_v3 += Dir_Vectors[i]; + if ((movementflag & (uint)DCF) == 0) + { + movementflag += (byte)(uint)DCF; + update_movementflag = true; + } + } + else + { + if ((movementflag & (uint)DCF) != 0) + { + movementflag -= (byte)(uint)DCF; + update_movementflag = true; + + } + } + i++; + } + if ((update_movementflag) || (update_rotation && DCFlagKeyPressed)) + { + this.AddNewMovement(agent_control_v3, q); + } + UpdateMovementAnimations(update_movementflag); + } + + protected void UpdateMovementAnimations(bool update_movementflag) + { + if (update_movementflag) + { + if (movementflag != 0) + { + if (this._physActor.Flying) + { + this.SendAnimPack(Animations.AnimsLLUUID["FLY"], 1); + } + else + { + this.SendAnimPack(Animations.AnimsLLUUID["WALK"], 1); + } + } + else + { + this.SendAnimPack(Animations.AnimsLLUUID["STAND"], 1); + } + } + + } + + + protected void AddNewMovement(Vector3 vec, Quaternion rotation) + { + NewForce newVelocity = new NewForce(); + 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.CheckForSignificantMovement(); + 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 SendFullUpdateToALLClients() + { + List avatars = this.m_world.RequestAvatarList(); + foreach (ScenePresence avatar in this.m_world.RequestAvatarList()) + { + this.SendFullUpdateToOtherClient(avatar); + avatar.SendFullUpdateToOtherClient(this); + } + } + + /// + /// + /// + 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); + this.SendFullUpdateToALLClients(); + this.m_world.SendAllSceneObjectsToClient(this.ControllingClient); + } + + /// + /// + /// + /// + public void SendAppearanceToOtherAgent(ScenePresence avatarInfo) + { + + } + + /// + /// + /// + /// + /// + public void SendAnimPack(LLUUID animID, int seq) + { + this.current_anim = animID; + this.anim_seq = seq; + List avatars = this.m_world.RequestAvatarList(); + for (int i = 0; i < avatars.Count; i++) + { + avatars[i].ControllingClient.SendAnimation(animID, seq, this.ControllingClient.AgentId); + } + } + + /// + /// + /// + public void SendAnimPack() + { + this.SendAnimPack(this.current_anim, this.anim_seq); + } + #endregion + + #region Significant Movement Method + + protected void CheckForSignificantMovement() + { + if (libsecondlife.Helpers.VecDist(this.Pos, this.posLastSignificantMove) > 2.0) + { + this.posLastSignificantMove = this.Pos; + if (OnSignificantClientMovement != null) + { + OnSignificantClientMovement(this.ControllingClient); + } + } + } + #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.m_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, neighbourRegion.InternalEndPoint); + } + } + } + #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/Environment/Scenes/scripting/Engines/CSharpEngine/CSharpScriptEngine.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/CSharpScriptEngine.cs index 1fc576e..b0ccd22 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/CSharpScriptEngine.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/CSharpScriptEngine.cs @@ -1,102 +1,102 @@ -/* -* 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.CodeDom.Compiler; -using System.Collections.Generic; -using Microsoft.CSharp; -using OpenSim.Framework.Console; - -namespace OpenSim.Region.Scripting -{ - public class CSharpScriptEngine : IScriptCompiler - { - public string FileExt() - { - return ".cs"; - } - - private Dictionary LoadDotNetScript(CodeDomProvider compiler, string filename) - { - CompilerParameters compilerParams = new CompilerParameters(); - CompilerResults compilerResults; - compilerParams.GenerateExecutable = false; - compilerParams.GenerateInMemory = true; - compilerParams.IncludeDebugInformation = false; - compilerParams.ReferencedAssemblies.Add("OpenSim.Region.dll"); - compilerParams.ReferencedAssemblies.Add("OpenSim.Region.Environment.dll"); - compilerParams.ReferencedAssemblies.Add("OpenSim.Framework.dll"); - compilerParams.ReferencedAssemblies.Add("libsecondlife.dll"); - compilerParams.ReferencedAssemblies.Add("System.dll"); - - compilerResults = compiler.CompileAssemblyFromFile(compilerParams, filename); - - if (compilerResults.Errors.Count > 0) - { - MainLog.Instance.Error("Compile errors"); - foreach (CompilerError error in compilerResults.Errors) - { - MainLog.Instance.Error(error.Line.ToString() + ": " + error.ErrorText.ToString()); - } - } - else - { - Dictionary scripts = new Dictionary(); - - foreach (Type pluginType in compilerResults.CompiledAssembly.GetExportedTypes()) - { - Type testInterface = pluginType.GetInterface("IScript", true); - - if (testInterface != null) - { - IScript script = (IScript)compilerResults.CompiledAssembly.CreateInstance(pluginType.ToString()); - - string scriptName = "C#/" + script.getName(); - Console.WriteLine("Script: " + scriptName + " loaded."); - - if (!scripts.ContainsKey(scriptName)) - { - scripts.Add(scriptName, script); - } - else - { - scripts[scriptName] = script; - } - } - } - return scripts; - } - return null; - } - - public Dictionary compile(string filename) - { - CSharpCodeProvider csharpProvider = new CSharpCodeProvider(); - return LoadDotNetScript(csharpProvider, filename); - } - } -} +/* +* 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.CodeDom.Compiler; +using System.Collections.Generic; +using Microsoft.CSharp; +using OpenSim.Framework.Console; + +namespace OpenSim.Region.Scripting +{ + public class CSharpScriptEngine : IScriptCompiler + { + public string FileExt() + { + return ".cs"; + } + + private Dictionary LoadDotNetScript(CodeDomProvider compiler, string filename) + { + CompilerParameters compilerParams = new CompilerParameters(); + CompilerResults compilerResults; + compilerParams.GenerateExecutable = false; + compilerParams.GenerateInMemory = true; + compilerParams.IncludeDebugInformation = false; + compilerParams.ReferencedAssemblies.Add("OpenSim.Region.dll"); + compilerParams.ReferencedAssemblies.Add("OpenSim.Region.Environment.dll"); + compilerParams.ReferencedAssemblies.Add("OpenSim.Framework.dll"); + compilerParams.ReferencedAssemblies.Add("libsecondlife.dll"); + compilerParams.ReferencedAssemblies.Add("System.dll"); + + compilerResults = compiler.CompileAssemblyFromFile(compilerParams, filename); + + if (compilerResults.Errors.Count > 0) + { + MainLog.Instance.Error("Compile errors"); + foreach (CompilerError error in compilerResults.Errors) + { + MainLog.Instance.Error(error.Line.ToString() + ": " + error.ErrorText.ToString()); + } + } + else + { + Dictionary scripts = new Dictionary(); + + foreach (Type pluginType in compilerResults.CompiledAssembly.GetExportedTypes()) + { + Type testInterface = pluginType.GetInterface("IScript", true); + + if (testInterface != null) + { + IScript script = (IScript)compilerResults.CompiledAssembly.CreateInstance(pluginType.ToString()); + + string scriptName = "C#/" + script.getName(); + Console.WriteLine("Script: " + scriptName + " loaded."); + + if (!scripts.ContainsKey(scriptName)) + { + scripts.Add(scriptName, script); + } + else + { + scripts[scriptName] = script; + } + } + } + return scripts; + } + return null; + } + + public Dictionary compile(string filename) + { + CSharpCodeProvider csharpProvider = new CSharpCodeProvider(); + return LoadDotNetScript(csharpProvider, filename); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/Examples/ExportRegionToLSL.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/Examples/ExportRegionToLSL.cs index d9f1f0a..79d88b1 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/Examples/ExportRegionToLSL.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/CSharpEngine/Examples/ExportRegionToLSL.cs @@ -1,70 +1,70 @@ -using OpenSim.Framework.Console; -using OpenSim.Framework; -using OpenSim.Region.Environment; -using OpenSim.Region.Environment.Scenes; - -using System.Collections.Generic; -using libsecondlife; - -namespace OpenSim.Region.Scripting.Examples -{ - public class LSLExportScript : IScript - { - ScriptInfo script; - - public string getName() - { - return "LSL Export Script 0.1"; - } - - public void Initialise(ScriptInfo scriptInfo) - { - script = scriptInfo; - - script.events.OnScriptConsole += new EventManager.OnScriptConsoleDelegate(ProcessConsoleMsg); - } - - void ProcessConsoleMsg(string[] args) - { - if (args[0].ToLower() == "lslexport") - { - string sequence = ""; - - foreach (KeyValuePair obj in script.world.Objects) - { - SceneObject root = obj.Value; - - sequence += "NEWOBJ::" + obj.Key.ToStringHyphenated() + "\n"; - - string rootPrim = processPrimitiveToString(root.rootPrimitive); - - sequence += "ROOT:" + rootPrim; - - foreach (KeyValuePair prim in root.Children) - { - string child = processPrimitiveToString(prim.Value); - sequence += "CHILD:" + child; - } - } - - System.Console.WriteLine(sequence); - } - } - - string processPrimitiveToString(OpenSim.Region.Environment.Scenes.Primitive prim) - { - string desc = prim.Description; - string name = prim.Name; - LLVector3 pos = prim.Pos; - LLVector3 rot = new LLVector3(); - LLVector3 scale = prim.Scale; - LLVector3 rootPos = prim.WorldPos; - - string setPrimParams = ""; - - setPrimParams += "[PRIM_SCALE, " + scale.ToString() + ", PRIM_POS, " + rootPos.ToString() + ", PRIM_ROTATION, " + rot.ToString() + "]\n"; - - return setPrimParams; - } - } +using OpenSim.Framework.Console; +using OpenSim.Framework; +using OpenSim.Region.Environment; +using OpenSim.Region.Environment.Scenes; + +using System.Collections.Generic; +using libsecondlife; + +namespace OpenSim.Region.Scripting.Examples +{ + public class LSLExportScript : IScript + { + ScriptInfo script; + + public string getName() + { + return "LSL Export Script 0.1"; + } + + public void Initialise(ScriptInfo scriptInfo) + { + script = scriptInfo; + + script.events.OnScriptConsole += new EventManager.OnScriptConsoleDelegate(ProcessConsoleMsg); + } + + void ProcessConsoleMsg(string[] args) + { + if (args[0].ToLower() == "lslexport") + { + string sequence = ""; + + foreach (KeyValuePair obj in script.world.Objects) + { + SceneObject root = obj.Value; + + sequence += "NEWOBJ::" + obj.Key.ToStringHyphenated() + "\n"; + + string rootPrim = processPrimitiveToString(root.rootPrimitive); + + sequence += "ROOT:" + rootPrim; + + foreach (KeyValuePair prim in root.Children) + { + string child = processPrimitiveToString(prim.Value); + sequence += "CHILD:" + child; + } + } + + System.Console.WriteLine(sequence); + } + } + + string processPrimitiveToString(OpenSim.Region.Environment.Scenes.Primitive prim) + { + string desc = prim.Description; + string name = prim.Name; + LLVector3 pos = prim.Pos; + LLVector3 rot = new LLVector3(); + LLVector3 scale = prim.Scale; + LLVector3 rootPos = prim.WorldPos; + + string setPrimParams = ""; + + setPrimParams += "[PRIM_SCALE, " + scale.ToString() + ", PRIM_POS, " + rootPos.ToString() + ", PRIM_ROTATION, " + rot.ToString() + "]\n"; + + return setPrimParams; + } + } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JScriptEngine/JScriptEngine.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JScriptEngine/JScriptEngine.cs index 0833e7a..af4f8b4 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JScriptEngine/JScriptEngine.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JScriptEngine/JScriptEngine.cs @@ -1,102 +1,102 @@ -/* -* 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.CodeDom.Compiler; -using System.Collections.Generic; -using Microsoft.JScript; -using OpenSim.Framework.Console; - -namespace OpenSim.Region.Scripting -{ - public class JScriptEngine : IScriptCompiler - { - public string FileExt() - { - return ".js"; - } - - private Dictionary LoadDotNetScript(CodeDomProvider compiler, string filename) - { - CompilerParameters compilerParams = new CompilerParameters(); - CompilerResults compilerResults; - compilerParams.GenerateExecutable = false; - compilerParams.GenerateInMemory = true; - compilerParams.IncludeDebugInformation = false; - compilerParams.ReferencedAssemblies.Add("OpenSim.Region.dll"); - compilerParams.ReferencedAssemblies.Add("OpenSim.Region.Environment.dll"); - compilerParams.ReferencedAssemblies.Add("OpenSim.Framework.dll"); - compilerParams.ReferencedAssemblies.Add("libsecondlife.dll"); - compilerParams.ReferencedAssemblies.Add("System.dll"); - - compilerResults = compiler.CompileAssemblyFromFile(compilerParams, filename); - - if (compilerResults.Errors.Count > 0) - { - MainLog.Instance.Error("Compile errors"); - foreach (CompilerError error in compilerResults.Errors) - { - MainLog.Instance.Error(error.Line.ToString() + ": " + error.ErrorText.ToString()); - } - } - else - { - Dictionary scripts = new Dictionary(); - - foreach (Type pluginType in compilerResults.CompiledAssembly.GetExportedTypes()) - { - Type testInterface = pluginType.GetInterface("IScript", true); - - if (testInterface != null) - { - IScript script = (IScript)compilerResults.CompiledAssembly.CreateInstance(pluginType.ToString()); - - string scriptName = "JS.NET/" + script.getName(); - Console.WriteLine("Script: " + scriptName + " loaded."); - - if (!scripts.ContainsKey(scriptName)) - { - scripts.Add(scriptName, script); - } - else - { - scripts[scriptName] = script; - } - } - } - return scripts; - } - return null; - } - - public Dictionary compile(string filename) - { - JScriptCodeProvider jscriptProvider = new JScriptCodeProvider(); - return LoadDotNetScript(jscriptProvider, filename); - } - } -} +/* +* 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.CodeDom.Compiler; +using System.Collections.Generic; +using Microsoft.JScript; +using OpenSim.Framework.Console; + +namespace OpenSim.Region.Scripting +{ + public class JScriptEngine : IScriptCompiler + { + public string FileExt() + { + return ".js"; + } + + private Dictionary LoadDotNetScript(CodeDomProvider compiler, string filename) + { + CompilerParameters compilerParams = new CompilerParameters(); + CompilerResults compilerResults; + compilerParams.GenerateExecutable = false; + compilerParams.GenerateInMemory = true; + compilerParams.IncludeDebugInformation = false; + compilerParams.ReferencedAssemblies.Add("OpenSim.Region.dll"); + compilerParams.ReferencedAssemblies.Add("OpenSim.Region.Environment.dll"); + compilerParams.ReferencedAssemblies.Add("OpenSim.Framework.dll"); + compilerParams.ReferencedAssemblies.Add("libsecondlife.dll"); + compilerParams.ReferencedAssemblies.Add("System.dll"); + + compilerResults = compiler.CompileAssemblyFromFile(compilerParams, filename); + + if (compilerResults.Errors.Count > 0) + { + MainLog.Instance.Error("Compile errors"); + foreach (CompilerError error in compilerResults.Errors) + { + MainLog.Instance.Error(error.Line.ToString() + ": " + error.ErrorText.ToString()); + } + } + else + { + Dictionary scripts = new Dictionary(); + + foreach (Type pluginType in compilerResults.CompiledAssembly.GetExportedTypes()) + { + Type testInterface = pluginType.GetInterface("IScript", true); + + if (testInterface != null) + { + IScript script = (IScript)compilerResults.CompiledAssembly.CreateInstance(pluginType.ToString()); + + string scriptName = "JS.NET/" + script.getName(); + Console.WriteLine("Script: " + scriptName + " loaded."); + + if (!scripts.ContainsKey(scriptName)) + { + scripts.Add(scriptName, script); + } + else + { + scripts[scriptName] = script; + } + } + } + return scripts; + } + return null; + } + + public Dictionary compile(string filename) + { + JScriptCodeProvider jscriptProvider = new JScriptCodeProvider(); + return LoadDotNetScript(jscriptProvider, filename); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassInstance.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassInstance.cs index 0b1cf41..ca729b4 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassInstance.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassInstance.cs @@ -1,45 +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 OpenSim.Region.Scripting.EmbeddedJVM.Types; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class ClassInstance : Object - { - public int size; - public Dictionary Fields = new Dictionary(); - - public ClassInstance() - { - - } - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + public class ClassInstance : Object + { + public int size; + public Dictionary Fields = new Dictionary(); + + public ClassInstance() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassRecord.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassRecord.cs index f821f52..f151b7e 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassRecord.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/ClassRecord.cs @@ -1,503 +1,503 @@ -/* -* 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.Collections.Generic; -using System.Text; -using OpenSim.Region.Scripting.EmbeddedJVM.Types; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class ClassRecord - { - private ushort _majorVersion; - private ushort _minorVersion; - private ushort _constantPoolCount; - private ushort _accessFlags; - private ushort _thisClass; - private ushort _supperClass; - private ushort _interfaceCount; - private ushort _fieldCount; - private ushort _methodCount; - //private ushort _attributeCount; - //private string _name; - public Dictionary StaticFields = new Dictionary(); - public PoolClass mClass; - - public List _constantsPool = new List(); - private List _methodsList = new List(); - private List _fieldList = new List(); - - public ClassRecord() - { - - } - - public ClassInstance CreateNewInstance() - { - return new ClassInstance(); - } - - public void LoadClassFromFile(string fileName) - { - Console.WriteLine("loading script " + fileName); - FileStream fs = File.OpenRead(fileName); - this.LoadClassFromBytes(ReadFully(fs)); - fs.Close(); - } - - public void LoadClassFromBytes(byte[] data) - { - int i = 0; - i += 4; - _minorVersion = (ushort)((data[i++] << 8) + data[i++] ); - _majorVersion = (ushort)((data[i++] << 8) + data[i++] ); - _constantPoolCount = (ushort)((data[i++] << 8) + data[i++] ); - // Console.WriteLine("there should be " + _constantPoolCount + " items in the pool"); - for (int count = 0; count < _constantPoolCount -1 ; count++) - { - //read in the constant pool - byte pooltype = data[i++]; - //Console.WriteLine("#" +count +": new constant type = " +pooltype); - //Console.WriteLine("start position is: " + i); - switch (pooltype) - { - case 1: //Utf8 - ushort uLength = (ushort)((data[i++] << 8) + data[i++] ); - - // Console.WriteLine("new utf8 type, length is " + uLength); - PoolUtf8 utf8 = new PoolUtf8(); - utf8.readValue(data, ref i, uLength); - this._constantsPool.Add(utf8); - break; - case 3: //Int - break; - case 7: //Class - PoolClass pClass = new PoolClass(this); - pClass.readValue(data, ref i); - this._constantsPool.Add(pClass); - break; - case 10: //Method - PoolMethodRef pMeth = new PoolMethodRef(this); - pMeth.readValue(data, ref i); - this._constantsPool.Add(pMeth); - break; - case 12: //NamedType - PoolNamedType pNamed = new PoolNamedType(this); - pNamed.readValue(data, ref i); - this._constantsPool.Add(pNamed); - break; - } - } - - _accessFlags = (ushort)((data[i++] << 8) + data[i++] ); - _thisClass = (ushort)((data[i++] << 8) + data[i++] ); - _supperClass = (ushort)((data[i++] << 8) + data[i++] ); - - if (this._constantsPool[this._thisClass - 1] is PoolClass) - { - this.mClass = ((PoolClass)this._constantsPool[this._thisClass - 1]); - } - - _interfaceCount = (ushort)((data[i++] << 8) + data[i++]); - //should now read in the info for each interface - _fieldCount = (ushort)((data[i++] << 8) + data[i++]); - //should now read in the info for each field - _methodCount = (ushort)((data[i++] << 8) + data[i++]); - for (int count = 0; count < _methodCount; count++) - { - MethodInfo methInf = new MethodInfo(this); - methInf.ReadData(data, ref i); - this._methodsList.Add(methInf); - } - } - - public void AddMethodsToMemory(MethodMemory memory) - { - for (int count = 0; count < _methodCount; count++) - { - this._methodsList[count].AddMethodCode(memory); - } - } - - public bool StartMethod(Thread thread, string methodName) - { - for (int count = 0; count < _methodCount; count++) - { - if (this._constantsPool[this._methodsList[count].NameIndex-1] is PoolUtf8) - { - if (((PoolUtf8)this._constantsPool[this._methodsList[count].NameIndex-1]).Value == methodName) - { - //Console.WriteLine("found method: " + ((PoolUtf8)this._constantsPool[this._methodsList[count].NameIndex - 1]).Value); - thread.SetPC(this._methodsList[count].CodePointer); - return true; - } - } - } - return false; - } - - public void PrintToConsole() - { - Console.WriteLine("Class File:"); - Console.WriteLine("Major version: " + _majorVersion); - Console.WriteLine("Minor version: " + _minorVersion); - Console.WriteLine("Pool size: " + _constantPoolCount); - - for (int i = 0; i < _constantsPool.Count; i++) - { - this._constantsPool[i].Print(); - } - - Console.WriteLine("Access flags: " + _accessFlags); - Console.WriteLine("This class: " + _thisClass ); - Console.WriteLine("Super class: " + _supperClass); - - for (int count = 0; count < _methodCount; count++) - { - Console.WriteLine(); - this._methodsList[count].Print(); - } - - Console.WriteLine("class name is " + this.mClass.Name.Value); - } - - public static byte[] ReadFully(Stream stream) - { - byte[] buffer = new byte[1024]; - using (MemoryStream ms = new MemoryStream()) - { - while (true) - { - int read = stream.Read(buffer, 0, buffer.Length); - if (read <= 0) - return ms.ToArray(); - ms.Write(buffer, 0, read); - } - } - } - - #region nested classes - public class PoolItem - { - public virtual void Print() - { - - } - } - - public class PoolUtf8 : PoolItem - { - public string Value = ""; - - public void readValue(byte[] data,ref int pointer , int length) - { - for (int i = 0; i < length; i++) - { - int a =(int) data[pointer++]; - if ((a & 0x80) == 0) - { - Value = Value + (char)a; - } - else if ((a & 0x20) == 0) - { - int b = (int) data[pointer++]; - Value = Value + (char)(((a & 0x1f) << 6) + (b & 0x3f)); - } - else - { - int b = (int)data[pointer++]; - int c = (int)data[pointer++]; - Value = Value + (char)(((a & 0xf) << 12) + ((b & 0x3f) << 6) + (c & 0x3f)); - } - } - } - - public override void Print() - { - Console.WriteLine("Utf8 type: " + Value); - } - } - - private class PoolInt : PoolItem - { - - } - - public class PoolClass : PoolItem - { - //public string name = ""; - public ushort namePointer = 0; - private ClassRecord parent; - public PoolUtf8 Name; - - public PoolClass(ClassRecord paren) - { - parent = paren; - } - - public void readValue(byte[] data, ref int pointer) - { - namePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); - } - - public override void Print() - { - this.Name = ((PoolUtf8)this.parent._constantsPool[namePointer - 1]); - Console.Write("Class type: " + namePointer); - Console.WriteLine(" // " + ((PoolUtf8)this.parent._constantsPool[namePointer - 1]).Value); - - } - } - - public class PoolMethodRef : PoolItem - { - public ushort classPointer = 0; - public ushort nameTypePointer = 0; - public PoolNamedType mNameType; - public PoolClass mClass; - private ClassRecord parent; - - public PoolMethodRef(ClassRecord paren) - { - parent = paren; - } - - public void readValue(byte[] data, ref int pointer) - { - classPointer = (ushort)((data[pointer++] << 8) + data[pointer++]); - nameTypePointer = (ushort)((data[pointer++] << 8) + data[pointer++]); - } - - public override void Print() - { - this.mNameType = ((PoolNamedType)this.parent._constantsPool[nameTypePointer - 1]); - this.mClass = ((PoolClass)this.parent._constantsPool[classPointer - 1]); - Console.WriteLine("MethodRef type: " + classPointer + " , " + nameTypePointer); - } - } - - public class PoolNamedType : PoolItem - { - public ushort namePointer = 0; - public ushort typePointer = 0; - private ClassRecord parent; - public PoolUtf8 Name; - public PoolUtf8 Type; - - public PoolNamedType(ClassRecord paren) - { - parent = paren; - } - - public void readValue(byte[] data, ref int pointer) - { - namePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); - typePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); - } - - public override void Print() - { - Name = ((PoolUtf8)this.parent._constantsPool[namePointer-1]); - Type = ((PoolUtf8)this.parent._constantsPool[typePointer-1]); - Console.Write("Named type: " + namePointer + " , " + typePointer ); - Console.WriteLine(" // "+ ((PoolUtf8)this.parent._constantsPool[namePointer-1]).Value); - } - } - - //*********************** - public class MethodInfo - { - public ushort AccessFlags = 0; - public ushort NameIndex = 0; - public string Name = ""; - public ushort DescriptorIndex = 0; - public ushort AttributeCount = 0; - public List Attributes = new List(); - private ClassRecord parent; - public int CodePointer = 0; - - public MethodInfo(ClassRecord paren) - { - parent = paren; - } - - public void AddMethodCode(MethodMemory memory) - { - Array.Copy(this.Attributes[0].Code, 0, memory.MethodBuffer, memory.NextMethodPC, this.Attributes[0].Code.Length); - memory.Methodcount++; - this.CodePointer = memory.NextMethodPC; - memory.NextMethodPC += this.Attributes[0].Code.Length; - } - - public void ReadData(byte[] data, ref int pointer) - { - AccessFlags = (ushort)((data[pointer++] << 8) + data[pointer++]); - NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); - DescriptorIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); - AttributeCount = (ushort)((data[pointer++] << 8) + data[pointer++]); - for(int i =0; i< AttributeCount; i++) - { - MethodAttribute attri = new MethodAttribute(this.parent); - attri.ReadData(data, ref pointer); - this.Attributes.Add(attri); - } - } - - public void Print() - { - Console.WriteLine("Method Info Struct: "); - Console.WriteLine("AccessFlags: " + AccessFlags); - Console.WriteLine("NameIndex: " + NameIndex +" // "+ ((PoolUtf8)this.parent._constantsPool[NameIndex-1]).Value); - Console.WriteLine("DescriptorIndex: " + DescriptorIndex + " // "+ ((PoolUtf8)this.parent._constantsPool[DescriptorIndex-1]).Value); - Console.WriteLine("Attribute Count:" + AttributeCount); - for (int i = 0; i < AttributeCount; i++) - { - this.Attributes[i].Print(); - } - } - - public class MethodAttribute - { - public ushort NameIndex = 0; - public string Name = ""; - public Int32 Length = 0; - //for now only support code attribute - public ushort MaxStack = 0; - public ushort MaxLocals = 0; - public Int32 CodeLength = 0; - public byte[] Code; - public ushort ExceptionTableLength = 0; - public ushort SubAttributeCount = 0; - public List SubAttributes = new List(); - private ClassRecord parent; - - public MethodAttribute(ClassRecord paren) - { - parent = paren; - } - - public void ReadData(byte[] data, ref int pointer) - { - NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); - Length = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); - MaxStack = (ushort)((data[pointer++] << 8) + data[pointer++]); - MaxLocals = (ushort)((data[pointer++] << 8) + data[pointer++]); - CodeLength = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); - Code = new byte[CodeLength]; - for (int i = 0; i < CodeLength; i++) - { - Code[i] = data[pointer++]; - } - ExceptionTableLength = (ushort)((data[pointer++] << 8) + data[pointer++]); - SubAttributeCount = (ushort)((data[pointer++] << 8) + data[pointer++]); - for (int i = 0; i < SubAttributeCount; i++) - { - SubAttribute subAttri = new SubAttribute(this.parent); - subAttri.ReadData(data, ref pointer); - this.SubAttributes.Add(subAttri); - } - } - - public void Print() - { - Console.WriteLine("Method Attribute: "); - Console.WriteLine("Name Index: " + NameIndex + " // "+ ((PoolUtf8)this.parent._constantsPool[NameIndex-1]).Value); - Console.WriteLine("Length: " + Length); - Console.WriteLine("MaxStack: " + MaxStack); - Console.WriteLine("MaxLocals: " + MaxLocals); - Console.WriteLine("CodeLength: " + CodeLength); - for (int i = 0; i < Code.Length; i++) - { - Console.WriteLine("OpCode #" + i + " is: " + Code[i]); - } - Console.WriteLine("SubAttributes: " + SubAttributeCount); - for (int i = 0; i < SubAttributeCount; i++) - { - this.SubAttributes[i].Print(); - } - } - - public class SubAttribute - { - public ushort NameIndex = 0; - public string Name = ""; - public Int32 Length = 0; - public byte[] Data; - private ClassRecord parent; - - public SubAttribute(ClassRecord paren) - { - parent = paren; - } - - public void ReadData(byte[] data, ref int pointer) - { - NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); - Length = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); - Data = new byte[Length]; - for (int i = 0; i < Length; i++) - { - Data[i] = data[pointer++]; - } - } - - public void Print() - { - Console.WriteLine("SubAttribute: NameIndex: " + NameIndex + " // " + ((PoolUtf8)this.parent._constantsPool[NameIndex - 1]).Value); - } - - } - } - - } - private class InterfaceInfo - { - public void ReadData(byte[] data, ref int i) - { - - } - } - private class FieldInfo - { - public void ReadData(byte[] data, ref int i) - { - - } - } - private class AttributeInfo - { - public void ReadData(byte[] data, ref int i) - { - - } - } - #endregion - - } -} +/* +* 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.Collections.Generic; +using System.Text; +using OpenSim.Region.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + public class ClassRecord + { + private ushort _majorVersion; + private ushort _minorVersion; + private ushort _constantPoolCount; + private ushort _accessFlags; + private ushort _thisClass; + private ushort _supperClass; + private ushort _interfaceCount; + private ushort _fieldCount; + private ushort _methodCount; + //private ushort _attributeCount; + //private string _name; + public Dictionary StaticFields = new Dictionary(); + public PoolClass mClass; + + public List _constantsPool = new List(); + private List _methodsList = new List(); + private List _fieldList = new List(); + + public ClassRecord() + { + + } + + public ClassInstance CreateNewInstance() + { + return new ClassInstance(); + } + + public void LoadClassFromFile(string fileName) + { + Console.WriteLine("loading script " + fileName); + FileStream fs = File.OpenRead(fileName); + this.LoadClassFromBytes(ReadFully(fs)); + fs.Close(); + } + + public void LoadClassFromBytes(byte[] data) + { + int i = 0; + i += 4; + _minorVersion = (ushort)((data[i++] << 8) + data[i++] ); + _majorVersion = (ushort)((data[i++] << 8) + data[i++] ); + _constantPoolCount = (ushort)((data[i++] << 8) + data[i++] ); + // Console.WriteLine("there should be " + _constantPoolCount + " items in the pool"); + for (int count = 0; count < _constantPoolCount -1 ; count++) + { + //read in the constant pool + byte pooltype = data[i++]; + //Console.WriteLine("#" +count +": new constant type = " +pooltype); + //Console.WriteLine("start position is: " + i); + switch (pooltype) + { + case 1: //Utf8 + ushort uLength = (ushort)((data[i++] << 8) + data[i++] ); + + // Console.WriteLine("new utf8 type, length is " + uLength); + PoolUtf8 utf8 = new PoolUtf8(); + utf8.readValue(data, ref i, uLength); + this._constantsPool.Add(utf8); + break; + case 3: //Int + break; + case 7: //Class + PoolClass pClass = new PoolClass(this); + pClass.readValue(data, ref i); + this._constantsPool.Add(pClass); + break; + case 10: //Method + PoolMethodRef pMeth = new PoolMethodRef(this); + pMeth.readValue(data, ref i); + this._constantsPool.Add(pMeth); + break; + case 12: //NamedType + PoolNamedType pNamed = new PoolNamedType(this); + pNamed.readValue(data, ref i); + this._constantsPool.Add(pNamed); + break; + } + } + + _accessFlags = (ushort)((data[i++] << 8) + data[i++] ); + _thisClass = (ushort)((data[i++] << 8) + data[i++] ); + _supperClass = (ushort)((data[i++] << 8) + data[i++] ); + + if (this._constantsPool[this._thisClass - 1] is PoolClass) + { + this.mClass = ((PoolClass)this._constantsPool[this._thisClass - 1]); + } + + _interfaceCount = (ushort)((data[i++] << 8) + data[i++]); + //should now read in the info for each interface + _fieldCount = (ushort)((data[i++] << 8) + data[i++]); + //should now read in the info for each field + _methodCount = (ushort)((data[i++] << 8) + data[i++]); + for (int count = 0; count < _methodCount; count++) + { + MethodInfo methInf = new MethodInfo(this); + methInf.ReadData(data, ref i); + this._methodsList.Add(methInf); + } + } + + public void AddMethodsToMemory(MethodMemory memory) + { + for (int count = 0; count < _methodCount; count++) + { + this._methodsList[count].AddMethodCode(memory); + } + } + + public bool StartMethod(Thread thread, string methodName) + { + for (int count = 0; count < _methodCount; count++) + { + if (this._constantsPool[this._methodsList[count].NameIndex-1] is PoolUtf8) + { + if (((PoolUtf8)this._constantsPool[this._methodsList[count].NameIndex-1]).Value == methodName) + { + //Console.WriteLine("found method: " + ((PoolUtf8)this._constantsPool[this._methodsList[count].NameIndex - 1]).Value); + thread.SetPC(this._methodsList[count].CodePointer); + return true; + } + } + } + return false; + } + + public void PrintToConsole() + { + Console.WriteLine("Class File:"); + Console.WriteLine("Major version: " + _majorVersion); + Console.WriteLine("Minor version: " + _minorVersion); + Console.WriteLine("Pool size: " + _constantPoolCount); + + for (int i = 0; i < _constantsPool.Count; i++) + { + this._constantsPool[i].Print(); + } + + Console.WriteLine("Access flags: " + _accessFlags); + Console.WriteLine("This class: " + _thisClass ); + Console.WriteLine("Super class: " + _supperClass); + + for (int count = 0; count < _methodCount; count++) + { + Console.WriteLine(); + this._methodsList[count].Print(); + } + + Console.WriteLine("class name is " + this.mClass.Name.Value); + } + + public static byte[] ReadFully(Stream stream) + { + byte[] buffer = new byte[1024]; + using (MemoryStream ms = new MemoryStream()) + { + while (true) + { + int read = stream.Read(buffer, 0, buffer.Length); + if (read <= 0) + return ms.ToArray(); + ms.Write(buffer, 0, read); + } + } + } + + #region nested classes + public class PoolItem + { + public virtual void Print() + { + + } + } + + public class PoolUtf8 : PoolItem + { + public string Value = ""; + + public void readValue(byte[] data,ref int pointer , int length) + { + for (int i = 0; i < length; i++) + { + int a =(int) data[pointer++]; + if ((a & 0x80) == 0) + { + Value = Value + (char)a; + } + else if ((a & 0x20) == 0) + { + int b = (int) data[pointer++]; + Value = Value + (char)(((a & 0x1f) << 6) + (b & 0x3f)); + } + else + { + int b = (int)data[pointer++]; + int c = (int)data[pointer++]; + Value = Value + (char)(((a & 0xf) << 12) + ((b & 0x3f) << 6) + (c & 0x3f)); + } + } + } + + public override void Print() + { + Console.WriteLine("Utf8 type: " + Value); + } + } + + private class PoolInt : PoolItem + { + + } + + public class PoolClass : PoolItem + { + //public string name = ""; + public ushort namePointer = 0; + private ClassRecord parent; + public PoolUtf8 Name; + + public PoolClass(ClassRecord paren) + { + parent = paren; + } + + public void readValue(byte[] data, ref int pointer) + { + namePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); + } + + public override void Print() + { + this.Name = ((PoolUtf8)this.parent._constantsPool[namePointer - 1]); + Console.Write("Class type: " + namePointer); + Console.WriteLine(" // " + ((PoolUtf8)this.parent._constantsPool[namePointer - 1]).Value); + + } + } + + public class PoolMethodRef : PoolItem + { + public ushort classPointer = 0; + public ushort nameTypePointer = 0; + public PoolNamedType mNameType; + public PoolClass mClass; + private ClassRecord parent; + + public PoolMethodRef(ClassRecord paren) + { + parent = paren; + } + + public void readValue(byte[] data, ref int pointer) + { + classPointer = (ushort)((data[pointer++] << 8) + data[pointer++]); + nameTypePointer = (ushort)((data[pointer++] << 8) + data[pointer++]); + } + + public override void Print() + { + this.mNameType = ((PoolNamedType)this.parent._constantsPool[nameTypePointer - 1]); + this.mClass = ((PoolClass)this.parent._constantsPool[classPointer - 1]); + Console.WriteLine("MethodRef type: " + classPointer + " , " + nameTypePointer); + } + } + + public class PoolNamedType : PoolItem + { + public ushort namePointer = 0; + public ushort typePointer = 0; + private ClassRecord parent; + public PoolUtf8 Name; + public PoolUtf8 Type; + + public PoolNamedType(ClassRecord paren) + { + parent = paren; + } + + public void readValue(byte[] data, ref int pointer) + { + namePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); + typePointer = (ushort)((data[pointer++] << 8) + data[pointer++] ); + } + + public override void Print() + { + Name = ((PoolUtf8)this.parent._constantsPool[namePointer-1]); + Type = ((PoolUtf8)this.parent._constantsPool[typePointer-1]); + Console.Write("Named type: " + namePointer + " , " + typePointer ); + Console.WriteLine(" // "+ ((PoolUtf8)this.parent._constantsPool[namePointer-1]).Value); + } + } + + //*********************** + public class MethodInfo + { + public ushort AccessFlags = 0; + public ushort NameIndex = 0; + public string Name = ""; + public ushort DescriptorIndex = 0; + public ushort AttributeCount = 0; + public List Attributes = new List(); + private ClassRecord parent; + public int CodePointer = 0; + + public MethodInfo(ClassRecord paren) + { + parent = paren; + } + + public void AddMethodCode(MethodMemory memory) + { + Array.Copy(this.Attributes[0].Code, 0, memory.MethodBuffer, memory.NextMethodPC, this.Attributes[0].Code.Length); + memory.Methodcount++; + this.CodePointer = memory.NextMethodPC; + memory.NextMethodPC += this.Attributes[0].Code.Length; + } + + public void ReadData(byte[] data, ref int pointer) + { + AccessFlags = (ushort)((data[pointer++] << 8) + data[pointer++]); + NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); + DescriptorIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); + AttributeCount = (ushort)((data[pointer++] << 8) + data[pointer++]); + for(int i =0; i< AttributeCount; i++) + { + MethodAttribute attri = new MethodAttribute(this.parent); + attri.ReadData(data, ref pointer); + this.Attributes.Add(attri); + } + } + + public void Print() + { + Console.WriteLine("Method Info Struct: "); + Console.WriteLine("AccessFlags: " + AccessFlags); + Console.WriteLine("NameIndex: " + NameIndex +" // "+ ((PoolUtf8)this.parent._constantsPool[NameIndex-1]).Value); + Console.WriteLine("DescriptorIndex: " + DescriptorIndex + " // "+ ((PoolUtf8)this.parent._constantsPool[DescriptorIndex-1]).Value); + Console.WriteLine("Attribute Count:" + AttributeCount); + for (int i = 0; i < AttributeCount; i++) + { + this.Attributes[i].Print(); + } + } + + public class MethodAttribute + { + public ushort NameIndex = 0; + public string Name = ""; + public Int32 Length = 0; + //for now only support code attribute + public ushort MaxStack = 0; + public ushort MaxLocals = 0; + public Int32 CodeLength = 0; + public byte[] Code; + public ushort ExceptionTableLength = 0; + public ushort SubAttributeCount = 0; + public List SubAttributes = new List(); + private ClassRecord parent; + + public MethodAttribute(ClassRecord paren) + { + parent = paren; + } + + public void ReadData(byte[] data, ref int pointer) + { + NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); + Length = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); + MaxStack = (ushort)((data[pointer++] << 8) + data[pointer++]); + MaxLocals = (ushort)((data[pointer++] << 8) + data[pointer++]); + CodeLength = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); + Code = new byte[CodeLength]; + for (int i = 0; i < CodeLength; i++) + { + Code[i] = data[pointer++]; + } + ExceptionTableLength = (ushort)((data[pointer++] << 8) + data[pointer++]); + SubAttributeCount = (ushort)((data[pointer++] << 8) + data[pointer++]); + for (int i = 0; i < SubAttributeCount; i++) + { + SubAttribute subAttri = new SubAttribute(this.parent); + subAttri.ReadData(data, ref pointer); + this.SubAttributes.Add(subAttri); + } + } + + public void Print() + { + Console.WriteLine("Method Attribute: "); + Console.WriteLine("Name Index: " + NameIndex + " // "+ ((PoolUtf8)this.parent._constantsPool[NameIndex-1]).Value); + Console.WriteLine("Length: " + Length); + Console.WriteLine("MaxStack: " + MaxStack); + Console.WriteLine("MaxLocals: " + MaxLocals); + Console.WriteLine("CodeLength: " + CodeLength); + for (int i = 0; i < Code.Length; i++) + { + Console.WriteLine("OpCode #" + i + " is: " + Code[i]); + } + Console.WriteLine("SubAttributes: " + SubAttributeCount); + for (int i = 0; i < SubAttributeCount; i++) + { + this.SubAttributes[i].Print(); + } + } + + public class SubAttribute + { + public ushort NameIndex = 0; + public string Name = ""; + public Int32 Length = 0; + public byte[] Data; + private ClassRecord parent; + + public SubAttribute(ClassRecord paren) + { + parent = paren; + } + + public void ReadData(byte[] data, ref int pointer) + { + NameIndex = (ushort)((data[pointer++] << 8) + data[pointer++]); + Length = (Int32)((data[pointer++] << 24) + (data[pointer++] << 16) + (data[pointer++] << 8) + data[pointer++]); + Data = new byte[Length]; + for (int i = 0; i < Length; i++) + { + Data[i] = data[pointer++]; + } + } + + public void Print() + { + Console.WriteLine("SubAttribute: NameIndex: " + NameIndex + " // " + ((PoolUtf8)this.parent._constantsPool[NameIndex - 1]).Value); + } + + } + } + + } + private class InterfaceInfo + { + public void ReadData(byte[] data, ref int i) + { + + } + } + private class FieldInfo + { + public void ReadData(byte[] data, ref int i) + { + + } + } + private class AttributeInfo + { + public void ReadData(byte[] data, ref int i) + { + + } + } + #endregion + + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Heap.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Heap.cs index 1a97b7d..c6423fc 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Heap.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Heap.cs @@ -1,43 +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.Region.Scripting.EmbeddedJVM -{ - public class Heap - { - public List ClassObjects = new List(); - - public Heap() - { - - } - } -} +/* +* 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.EmbeddedJVM +{ + public class Heap + { + public List ClassObjects = new List(); + + public Heap() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Logic.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Logic.cs index ef6b805..56135d3 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Logic.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Logic.cs @@ -1,427 +1,427 @@ -/* -* 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.Region.Scripting.EmbeddedJVM.Types; -using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - partial class Thread - { - private partial class Interpreter - { - private bool IsLogicOpCode(byte opcode) - { - bool result = false; - switch (opcode) - { - case 2: - Int m_int= new Int(); - m_int.mValue = -1; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 3: - m_int= new Int(); - m_int.mValue = 0; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 4: - m_int = new Int(); - m_int.mValue = 1; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 5: - m_int = new Int(); - m_int.mValue = 2; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 6: - m_int = new Int(); - m_int.mValue = 3; - this._mThread.currentFrame.OpStack.Push(m_int); - break; - case 7: - m_int = new Int(); - m_int.mValue = 4; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 8: - m_int = new Int(); - m_int.mValue = 5; - this._mThread.currentFrame.OpStack.Push(m_int); - result = true; - break; - case 11: - Float m_float = new Float(); - m_float.mValue = 0.0f; - this._mThread.currentFrame.OpStack.Push(m_float); - result = true; - break; - case 12: - m_float = new Float(); - m_float.mValue = 1.0f; - this._mThread.currentFrame.OpStack.Push(m_float); - result = true; - break; - case 13: - m_float = new Float(); - m_float.mValue = 2.0f; - this._mThread.currentFrame.OpStack.Push(m_float); - result = true; - break; - case 16: - int pushvalue = (int)GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]; - Int pushInt = new Int(); - pushInt.mValue = pushvalue; - this._mThread.currentFrame.OpStack.Push(pushInt); - this._mThread.PC++; - result = true; - break; - case 17: - short pushvalue2 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); - Int pushInt2 = new Int(); - pushInt2.mValue = pushvalue2; - this._mThread.currentFrame.OpStack.Push(pushInt2); - this._mThread.PC += 2; - result = true; - break; - case 23: - short findex1 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC])); - Float fload = new Float(); - if (this._mThread.currentFrame.LocalVariables[findex1] != null) - { - if (this._mThread.currentFrame.LocalVariables[findex1] is Float) - { - fload.mValue = ((Float)this._mThread.currentFrame.LocalVariables[findex1]).mValue; - this._mThread.currentFrame.OpStack.Push(fload); - } - } - this._mThread.PC++; - result = true; - break; - case 26: - if (this._mThread.currentFrame.LocalVariables[0] != null) - { - if (this._mThread.currentFrame.LocalVariables[0] is Int) - { - Int newInt = new Int(); - newInt.mValue = ((Int)this._mThread.currentFrame.LocalVariables[0]).mValue; - this._mThread.currentFrame.OpStack.Push(newInt); - } - } - result = true; - break; - case 27: - if (this._mThread.currentFrame.LocalVariables[1] != null) - { - if (this._mThread.currentFrame.LocalVariables[1] is Int) - { - Int newInt = new Int(); - newInt.mValue = ((Int)this._mThread.currentFrame.LocalVariables[1]).mValue; - this._mThread.currentFrame.OpStack.Push(newInt); - } - } - result = true; - break; - case 34: - if (this._mThread.currentFrame.LocalVariables[0] != null) - { - if (this._mThread.currentFrame.LocalVariables[0] is Float) - { - Float newfloat = new Float(); - newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[0]).mValue; - this._mThread.currentFrame.OpStack.Push(newfloat); - } - } - result = true; - break; - case 35: - if (this._mThread.currentFrame.LocalVariables[1] != null) - { - if (this._mThread.currentFrame.LocalVariables[1] is Float) - { - Float newfloat = new Float(); - newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[1]).mValue; - this._mThread.currentFrame.OpStack.Push(newfloat); - } - } - result = true; - break; - case 36: - if (this._mThread.currentFrame.LocalVariables[2] != null) - { - if (this._mThread.currentFrame.LocalVariables[2] is Float) - { - Float newfloat = new Float(); - newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[2]).mValue; - this._mThread.currentFrame.OpStack.Push(newfloat); - } - } - result = true; - break; - case 37: - if (this._mThread.currentFrame.LocalVariables[3] != null) - { - if (this._mThread.currentFrame.LocalVariables[3] is Float) - { - Float newfloat = new Float(); - newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[3]).mValue; - this._mThread.currentFrame.OpStack.Push(newfloat); - } - } - result = true; - break; - case 56: - short findex = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] )); - BaseType fstor = this._mThread.currentFrame.OpStack.Pop(); - if (fstor is Float) - { - this._mThread.currentFrame.LocalVariables[findex] = (Float)fstor; - } - this._mThread.PC++; - result = true; - break; - case 59: - BaseType baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Int) - { - this._mThread.currentFrame.LocalVariables[0] = (Int)baset; - } - result = true; - break; - case 60: - baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Int) - { - this._mThread.currentFrame.LocalVariables[1] = (Int)baset; - } - result = true; - break; - case 67: - baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Float) - { - this._mThread.currentFrame.LocalVariables[0] = (Float)baset; - } - result = true; - break; - case 68: - baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Float) - { - this._mThread.currentFrame.LocalVariables[1] = (Float)baset; - } - result = true; - break; - case 69: - baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Float) - { - this._mThread.currentFrame.LocalVariables[2] = (Float)baset; - } - result = true; - break; - case 70: - baset = this._mThread.currentFrame.OpStack.Pop(); - if (baset is Float) - { - this._mThread.currentFrame.LocalVariables[3] = (Float)baset; - } - result = true; - break; - case 87: - this._mThread.currentFrame.OpStack.Pop(); - result = true; - break; - case 98: - BaseType bf2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType bf1 = this._mThread.currentFrame.OpStack.Pop(); - if (bf1 is Float && bf2 is Float) - { - Float nflt = new Float(); - nflt.mValue = ((Float)bf1).mValue + ((Float)bf2).mValue; - this._mThread.currentFrame.OpStack.Push(nflt); - } - result = true; - break; - case 102: - BaseType bsf2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType bsf1 = this._mThread.currentFrame.OpStack.Pop(); - if (bsf1 is Float && bsf2 is Float) - { - Float resf = new Float(); - resf.mValue = ((Float)bsf1).mValue - ((Float)bsf2).mValue; - this._mThread.currentFrame.OpStack.Push(resf); - } - result = true; - break; - case 104: //check the order of the two values off the stack is correct - BaseType bs2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType bs1 = this._mThread.currentFrame.OpStack.Pop(); - if (bs1 is Int && bs2 is Int) - { - Int nInt = new Int(); - nInt.mValue = ((Int)bs1).mValue * ((Int)bs2).mValue; - this._mThread.currentFrame.OpStack.Push(nInt); - } - result = true; - break; - case 132: - if (this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]] != null) - { - if (this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]] is Int) - { - ((Int)this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]]).mValue += (sbyte) GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]; - } - } - this._mThread.PC += 2; - result = true; - break; - case 139: - BaseType conv1 = this._mThread.currentFrame.OpStack.Pop(); - if (conv1 is Float) - { - Int newconv = new Int(); - newconv.mValue = (int)((Float)conv1).mValue; - this._mThread.currentFrame.OpStack.Push(newconv); - } - result = true; - break; - case 149: - BaseType flcom2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType flcom1 = this._mThread.currentFrame.OpStack.Pop(); - if (flcom1 is Float && flcom2 is Float) - { - Int compres = new Int(); - if (((Float)flcom1).mValue < ((Float)flcom2).mValue) - { - compres.mValue = -1; - } - else if (((Float)flcom1).mValue > ((Float)flcom2).mValue) - { - compres.mValue = 1; - } - else - { - compres.mValue = 0; - } - this._mThread.currentFrame.OpStack.Push(compres); - } - result = true; - break; - case 158: - short compareoffset1 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); - BaseType comp1 = this._mThread.currentFrame.OpStack.Pop(); - if (comp1 is Int) - { - if (((Int)comp1).mValue <= 0) - { - this._mThread.PC += -1 + compareoffset1; - } - else - { - this._mThread.PC += 2; - } - } - else - { - this._mThread.PC += 2; - } - result = true; - break; - case 162: - short compareoffset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); - BaseType bc2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType bc1 = this._mThread.currentFrame.OpStack.Pop(); - if (bc1 is Int && bc2 is Int) - { - //Console.WriteLine("comparing " + ((Int)bc1).mValue + " and " + ((Int)bc2).mValue); - if (((Int)bc1).mValue >= ((Int)bc2).mValue) - { - // Console.WriteLine("branch compare true , offset is " +compareoffset); - // Console.WriteLine("current PC is " + this._mThread.PC); - this._mThread.PC += -1 + compareoffset; - //Console.WriteLine("new PC is " + this._mThread.PC); - } - else - { - //Console.WriteLine("branch compare false"); - this._mThread.PC += 2; - } - } - else - { - this._mThread.PC += 2; - } - result = true; - break; - case 164: - short compareloffset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); - BaseType bcl2 = this._mThread.currentFrame.OpStack.Pop(); - BaseType bcl1 = this._mThread.currentFrame.OpStack.Pop(); - if (bcl1 is Int && bcl2 is Int) - { - //Console.WriteLine("comparing " + ((Int)bcl1).mValue + " and " + ((Int)bcl2).mValue); - if (((Int)bcl1).mValue <= ((Int)bcl2).mValue) - { - // Console.WriteLine("branch compare true , offset is " + compareloffset); - // Console.WriteLine("current PC is " + this._mThread.PC); - this._mThread.PC += -1 + compareloffset; - // Console.WriteLine("new PC is " + this._mThread.PC); - } - else - { - //Console.WriteLine("branch compare false"); - this._mThread.PC += 2; - } - } - else - { - this._mThread.PC += 2; - } - result = true; - break; - case 167: - short offset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC+1]); - this._mThread.PC += -1 + offset; - result = true; - break; - } - - return result; - } - } - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; +using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + partial class Thread + { + private partial class Interpreter + { + private bool IsLogicOpCode(byte opcode) + { + bool result = false; + switch (opcode) + { + case 2: + Int m_int= new Int(); + m_int.mValue = -1; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 3: + m_int= new Int(); + m_int.mValue = 0; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 4: + m_int = new Int(); + m_int.mValue = 1; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 5: + m_int = new Int(); + m_int.mValue = 2; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 6: + m_int = new Int(); + m_int.mValue = 3; + this._mThread.currentFrame.OpStack.Push(m_int); + break; + case 7: + m_int = new Int(); + m_int.mValue = 4; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 8: + m_int = new Int(); + m_int.mValue = 5; + this._mThread.currentFrame.OpStack.Push(m_int); + result = true; + break; + case 11: + Float m_float = new Float(); + m_float.mValue = 0.0f; + this._mThread.currentFrame.OpStack.Push(m_float); + result = true; + break; + case 12: + m_float = new Float(); + m_float.mValue = 1.0f; + this._mThread.currentFrame.OpStack.Push(m_float); + result = true; + break; + case 13: + m_float = new Float(); + m_float.mValue = 2.0f; + this._mThread.currentFrame.OpStack.Push(m_float); + result = true; + break; + case 16: + int pushvalue = (int)GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]; + Int pushInt = new Int(); + pushInt.mValue = pushvalue; + this._mThread.currentFrame.OpStack.Push(pushInt); + this._mThread.PC++; + result = true; + break; + case 17: + short pushvalue2 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); + Int pushInt2 = new Int(); + pushInt2.mValue = pushvalue2; + this._mThread.currentFrame.OpStack.Push(pushInt2); + this._mThread.PC += 2; + result = true; + break; + case 23: + short findex1 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC])); + Float fload = new Float(); + if (this._mThread.currentFrame.LocalVariables[findex1] != null) + { + if (this._mThread.currentFrame.LocalVariables[findex1] is Float) + { + fload.mValue = ((Float)this._mThread.currentFrame.LocalVariables[findex1]).mValue; + this._mThread.currentFrame.OpStack.Push(fload); + } + } + this._mThread.PC++; + result = true; + break; + case 26: + if (this._mThread.currentFrame.LocalVariables[0] != null) + { + if (this._mThread.currentFrame.LocalVariables[0] is Int) + { + Int newInt = new Int(); + newInt.mValue = ((Int)this._mThread.currentFrame.LocalVariables[0]).mValue; + this._mThread.currentFrame.OpStack.Push(newInt); + } + } + result = true; + break; + case 27: + if (this._mThread.currentFrame.LocalVariables[1] != null) + { + if (this._mThread.currentFrame.LocalVariables[1] is Int) + { + Int newInt = new Int(); + newInt.mValue = ((Int)this._mThread.currentFrame.LocalVariables[1]).mValue; + this._mThread.currentFrame.OpStack.Push(newInt); + } + } + result = true; + break; + case 34: + if (this._mThread.currentFrame.LocalVariables[0] != null) + { + if (this._mThread.currentFrame.LocalVariables[0] is Float) + { + Float newfloat = new Float(); + newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[0]).mValue; + this._mThread.currentFrame.OpStack.Push(newfloat); + } + } + result = true; + break; + case 35: + if (this._mThread.currentFrame.LocalVariables[1] != null) + { + if (this._mThread.currentFrame.LocalVariables[1] is Float) + { + Float newfloat = new Float(); + newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[1]).mValue; + this._mThread.currentFrame.OpStack.Push(newfloat); + } + } + result = true; + break; + case 36: + if (this._mThread.currentFrame.LocalVariables[2] != null) + { + if (this._mThread.currentFrame.LocalVariables[2] is Float) + { + Float newfloat = new Float(); + newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[2]).mValue; + this._mThread.currentFrame.OpStack.Push(newfloat); + } + } + result = true; + break; + case 37: + if (this._mThread.currentFrame.LocalVariables[3] != null) + { + if (this._mThread.currentFrame.LocalVariables[3] is Float) + { + Float newfloat = new Float(); + newfloat.mValue = ((Float)this._mThread.currentFrame.LocalVariables[3]).mValue; + this._mThread.currentFrame.OpStack.Push(newfloat); + } + } + result = true; + break; + case 56: + short findex = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] )); + BaseType fstor = this._mThread.currentFrame.OpStack.Pop(); + if (fstor is Float) + { + this._mThread.currentFrame.LocalVariables[findex] = (Float)fstor; + } + this._mThread.PC++; + result = true; + break; + case 59: + BaseType baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Int) + { + this._mThread.currentFrame.LocalVariables[0] = (Int)baset; + } + result = true; + break; + case 60: + baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Int) + { + this._mThread.currentFrame.LocalVariables[1] = (Int)baset; + } + result = true; + break; + case 67: + baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Float) + { + this._mThread.currentFrame.LocalVariables[0] = (Float)baset; + } + result = true; + break; + case 68: + baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Float) + { + this._mThread.currentFrame.LocalVariables[1] = (Float)baset; + } + result = true; + break; + case 69: + baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Float) + { + this._mThread.currentFrame.LocalVariables[2] = (Float)baset; + } + result = true; + break; + case 70: + baset = this._mThread.currentFrame.OpStack.Pop(); + if (baset is Float) + { + this._mThread.currentFrame.LocalVariables[3] = (Float)baset; + } + result = true; + break; + case 87: + this._mThread.currentFrame.OpStack.Pop(); + result = true; + break; + case 98: + BaseType bf2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType bf1 = this._mThread.currentFrame.OpStack.Pop(); + if (bf1 is Float && bf2 is Float) + { + Float nflt = new Float(); + nflt.mValue = ((Float)bf1).mValue + ((Float)bf2).mValue; + this._mThread.currentFrame.OpStack.Push(nflt); + } + result = true; + break; + case 102: + BaseType bsf2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType bsf1 = this._mThread.currentFrame.OpStack.Pop(); + if (bsf1 is Float && bsf2 is Float) + { + Float resf = new Float(); + resf.mValue = ((Float)bsf1).mValue - ((Float)bsf2).mValue; + this._mThread.currentFrame.OpStack.Push(resf); + } + result = true; + break; + case 104: //check the order of the two values off the stack is correct + BaseType bs2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType bs1 = this._mThread.currentFrame.OpStack.Pop(); + if (bs1 is Int && bs2 is Int) + { + Int nInt = new Int(); + nInt.mValue = ((Int)bs1).mValue * ((Int)bs2).mValue; + this._mThread.currentFrame.OpStack.Push(nInt); + } + result = true; + break; + case 132: + if (this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]] != null) + { + if (this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]] is Int) + { + ((Int)this._mThread.currentFrame.LocalVariables[GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC]]).mValue += (sbyte) GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]; + } + } + this._mThread.PC += 2; + result = true; + break; + case 139: + BaseType conv1 = this._mThread.currentFrame.OpStack.Pop(); + if (conv1 is Float) + { + Int newconv = new Int(); + newconv.mValue = (int)((Float)conv1).mValue; + this._mThread.currentFrame.OpStack.Push(newconv); + } + result = true; + break; + case 149: + BaseType flcom2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType flcom1 = this._mThread.currentFrame.OpStack.Pop(); + if (flcom1 is Float && flcom2 is Float) + { + Int compres = new Int(); + if (((Float)flcom1).mValue < ((Float)flcom2).mValue) + { + compres.mValue = -1; + } + else if (((Float)flcom1).mValue > ((Float)flcom2).mValue) + { + compres.mValue = 1; + } + else + { + compres.mValue = 0; + } + this._mThread.currentFrame.OpStack.Push(compres); + } + result = true; + break; + case 158: + short compareoffset1 = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); + BaseType comp1 = this._mThread.currentFrame.OpStack.Pop(); + if (comp1 is Int) + { + if (((Int)comp1).mValue <= 0) + { + this._mThread.PC += -1 + compareoffset1; + } + else + { + this._mThread.PC += 2; + } + } + else + { + this._mThread.PC += 2; + } + result = true; + break; + case 162: + short compareoffset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); + BaseType bc2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType bc1 = this._mThread.currentFrame.OpStack.Pop(); + if (bc1 is Int && bc2 is Int) + { + //Console.WriteLine("comparing " + ((Int)bc1).mValue + " and " + ((Int)bc2).mValue); + if (((Int)bc1).mValue >= ((Int)bc2).mValue) + { + // Console.WriteLine("branch compare true , offset is " +compareoffset); + // Console.WriteLine("current PC is " + this._mThread.PC); + this._mThread.PC += -1 + compareoffset; + //Console.WriteLine("new PC is " + this._mThread.PC); + } + else + { + //Console.WriteLine("branch compare false"); + this._mThread.PC += 2; + } + } + else + { + this._mThread.PC += 2; + } + result = true; + break; + case 164: + short compareloffset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC + 1]); + BaseType bcl2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType bcl1 = this._mThread.currentFrame.OpStack.Pop(); + if (bcl1 is Int && bcl2 is Int) + { + //Console.WriteLine("comparing " + ((Int)bcl1).mValue + " and " + ((Int)bcl2).mValue); + if (((Int)bcl1).mValue <= ((Int)bcl2).mValue) + { + // Console.WriteLine("branch compare true , offset is " + compareloffset); + // Console.WriteLine("current PC is " + this._mThread.PC); + this._mThread.PC += -1 + compareloffset; + // Console.WriteLine("new PC is " + this._mThread.PC); + } + else + { + //Console.WriteLine("branch compare false"); + this._mThread.PC += 2; + } + } + else + { + this._mThread.PC += 2; + } + result = true; + break; + case 167: + short offset = (short)((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC+1]); + this._mThread.PC += -1 + offset; + result = true; + break; + } + + return result; + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Methods.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Methods.cs index e2e2b7c..6b85fcc 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Methods.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Methods.cs @@ -1,96 +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 System.Text; -using OpenSim.Region.Scripting.EmbeddedJVM.Types; -using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - partial class Thread - { - private partial class Interpreter - { - private bool IsMethodOpCode(byte opcode) - { - bool result = false; - switch (opcode) - { - case 184: - short refIndex = (short) ((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC+1]); - if (this._mThread.currentClass._constantsPool[refIndex - 1] is ClassRecord.PoolMethodRef) - { - string typ = ((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Type.Value; - string typeparam = ""; - string typereturn = ""; - int firstbrak = 0; - int secondbrak = 0; - firstbrak = typ.LastIndexOf('('); - secondbrak = typ.LastIndexOf(')'); - typeparam = typ.Substring(firstbrak + 1, secondbrak - firstbrak - 1); - typereturn = typ.Substring(secondbrak + 1, typ.Length - secondbrak - 1); - if (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value == this._mThread.currentClass.mClass.Name.Value) - { - //calling a method in this class - if (typeparam.Length == 0) - { - this._mThread.JumpToStaticVoidMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, (this._mThread.PC + 2)); - } - else - { - this._mThread.JumpToStaticParamMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, typeparam, (this._mThread.PC + 2)); - } - } - else - { - //calling a method of a different class - - // OpenSimAPI Class - if (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value == "OpenSimAPI") - { - this._mThread.scriptInfo.api.CallMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, null); - } - } - } - else - { - this._mThread.PC += 2; - } - result = true; - break; - } - - return result; - } - } - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; +using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + partial class Thread + { + private partial class Interpreter + { + private bool IsMethodOpCode(byte opcode) + { + bool result = false; + switch (opcode) + { + case 184: + short refIndex = (short) ((GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC] << 8) + GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC+1]); + if (this._mThread.currentClass._constantsPool[refIndex - 1] is ClassRecord.PoolMethodRef) + { + string typ = ((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Type.Value; + string typeparam = ""; + string typereturn = ""; + int firstbrak = 0; + int secondbrak = 0; + firstbrak = typ.LastIndexOf('('); + secondbrak = typ.LastIndexOf(')'); + typeparam = typ.Substring(firstbrak + 1, secondbrak - firstbrak - 1); + typereturn = typ.Substring(secondbrak + 1, typ.Length - secondbrak - 1); + if (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value == this._mThread.currentClass.mClass.Name.Value) + { + //calling a method in this class + if (typeparam.Length == 0) + { + this._mThread.JumpToStaticVoidMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, (this._mThread.PC + 2)); + } + else + { + this._mThread.JumpToStaticParamMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, typeparam, (this._mThread.PC + 2)); + } + } + else + { + //calling a method of a different class + + // OpenSimAPI Class + if (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value == "OpenSimAPI") + { + this._mThread.scriptInfo.api.CallMethod(((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value, null); + } + } + } + else + { + this._mThread.PC += 2; + } + result = true; + break; + } + + return result; + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Return.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Return.cs index 6444776..3c18a11 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Return.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.Return.cs @@ -1,40 +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; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - partial class Thread - { - private partial class Interpreter - { - } - } -} +/* +* 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.EmbeddedJVM +{ + partial class Thread + { + private partial class Interpreter + { + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.cs index d44f315..9961cbd 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Interpreter.cs @@ -1,135 +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 OpenSim.Region.Scripting.EmbeddedJVM.Types; -using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - partial class Thread - { - private partial class Interpreter - { - private Thread _mThread; - - public Interpreter(Thread parentThread) - { - _mThread = parentThread; - } - - public bool Excute() - { - bool run = true; - byte currentOpCode = GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC++]; - // Console.WriteLine("opCode is: " + currentOpCode); - bool handled = false; - - handled = this.IsLogicOpCode(currentOpCode); - if (!handled) - { - handled = this.IsMethodOpCode(currentOpCode); - } - if (!handled) - { - if (currentOpCode == 172) - { - if (this._mThread.stack.StackFrames.Count > 1) - { - Console.WriteLine("returning int from function"); - int retPC1 = this._mThread.currentFrame.ReturnPC; - BaseType bas1 = this._mThread.currentFrame.OpStack.Pop(); - this._mThread.stack.StackFrames.Pop(); - this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); - this._mThread.PC = retPC1; - if (bas1 is Int) - { - this._mThread.currentFrame.OpStack.Push((Int)bas1); - } - } - else - { - // Console.WriteLine("No parent function so ending program"); - this._mThread.stack.StackFrames.Pop(); - run = false; - } - handled = true; - } - if (currentOpCode == 174) - { - if (this._mThread.stack.StackFrames.Count > 1) - { - Console.WriteLine("returning float from function"); - int retPC1 = this._mThread.currentFrame.ReturnPC; - BaseType bas1 = this._mThread.currentFrame.OpStack.Pop(); - this._mThread.stack.StackFrames.Pop(); - this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); - this._mThread.PC = retPC1; - if (bas1 is Float) - { - this._mThread.currentFrame.OpStack.Push((Float)bas1); - } - } - else - { - // Console.WriteLine("No parent function so ending program"); - this._mThread.stack.StackFrames.Pop(); - run = false; - } - handled = true; - } - if (currentOpCode == 177) - { - if (this._mThread.stack.StackFrames.Count > 1) - { - Console.WriteLine("returning from function"); - int retPC = this._mThread.currentFrame.ReturnPC; - this._mThread.stack.StackFrames.Pop(); - this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); - this._mThread.PC = retPC; - } - else - { - // Console.WriteLine("No parent function so ending program"); - this._mThread.stack.StackFrames.Pop(); - run = false; - } - handled = true; - } - } - if (!handled) - { - Console.WriteLine("opcode " + currentOpCode + " not been handled "); - } - return run; - - } - } - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; +using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + partial class Thread + { + private partial class Interpreter + { + private Thread _mThread; + + public Interpreter(Thread parentThread) + { + _mThread = parentThread; + } + + public bool Excute() + { + bool run = true; + byte currentOpCode = GlobalMemory.MethodArea.MethodBuffer[this._mThread.PC++]; + // Console.WriteLine("opCode is: " + currentOpCode); + bool handled = false; + + handled = this.IsLogicOpCode(currentOpCode); + if (!handled) + { + handled = this.IsMethodOpCode(currentOpCode); + } + if (!handled) + { + if (currentOpCode == 172) + { + if (this._mThread.stack.StackFrames.Count > 1) + { + Console.WriteLine("returning int from function"); + int retPC1 = this._mThread.currentFrame.ReturnPC; + BaseType bas1 = this._mThread.currentFrame.OpStack.Pop(); + this._mThread.stack.StackFrames.Pop(); + this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); + this._mThread.PC = retPC1; + if (bas1 is Int) + { + this._mThread.currentFrame.OpStack.Push((Int)bas1); + } + } + else + { + // Console.WriteLine("No parent function so ending program"); + this._mThread.stack.StackFrames.Pop(); + run = false; + } + handled = true; + } + if (currentOpCode == 174) + { + if (this._mThread.stack.StackFrames.Count > 1) + { + Console.WriteLine("returning float from function"); + int retPC1 = this._mThread.currentFrame.ReturnPC; + BaseType bas1 = this._mThread.currentFrame.OpStack.Pop(); + this._mThread.stack.StackFrames.Pop(); + this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); + this._mThread.PC = retPC1; + if (bas1 is Float) + { + this._mThread.currentFrame.OpStack.Push((Float)bas1); + } + } + else + { + // Console.WriteLine("No parent function so ending program"); + this._mThread.stack.StackFrames.Pop(); + run = false; + } + handled = true; + } + if (currentOpCode == 177) + { + if (this._mThread.stack.StackFrames.Count > 1) + { + Console.WriteLine("returning from function"); + int retPC = this._mThread.currentFrame.ReturnPC; + this._mThread.stack.StackFrames.Pop(); + this._mThread.currentFrame = this._mThread.stack.StackFrames.Peek(); + this._mThread.PC = retPC; + } + else + { + // Console.WriteLine("No parent function so ending program"); + this._mThread.stack.StackFrames.Pop(); + run = false; + } + handled = true; + } + } + if (!handled) + { + Console.WriteLine("opcode " + currentOpCode + " not been handled "); + } + return run; + + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MainMemory.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MainMemory.cs index addb6ff..7174975 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MainMemory.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MainMemory.cs @@ -1,45 +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; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class MainMemory - { - public Heap HeapArea; - public MethodMemory MethodArea; - - public MainMemory() - { - MethodArea = new MethodMemory(); - HeapArea = new Heap(); - } - } -} +/* +* 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.EmbeddedJVM +{ + public class MainMemory + { + public Heap HeapArea; + public MethodMemory MethodArea; + + public MainMemory() + { + MethodArea = new MethodMemory(); + HeapArea = new Heap(); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MethodMemory.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MethodMemory.cs index 7d69e91..5f29091 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MethodMemory.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/MethodMemory.cs @@ -1,46 +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; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class MethodMemory - { - public byte[] MethodBuffer; - public List Classes = new List(); - public int NextMethodPC = 0; - public int Methodcount = 0; - - public MethodMemory() - { - MethodBuffer = new byte[20000]; - } - } -} +/* +* 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.EmbeddedJVM +{ + public class MethodMemory + { + public byte[] MethodBuffer; + public List Classes = new List(); + public int NextMethodPC = 0; + public int Methodcount = 0; + + public MethodMemory() + { + MethodBuffer = new byte[20000]; + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Object.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Object.cs index 6a0a1a4..8acb2bd 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Object.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Object.cs @@ -1,37 +1,37 @@ -/* -* 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.EmbeddedJVM -{ - public class Object - { - } -} +/* +* 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.EmbeddedJVM +{ + public class Object + { + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Stack.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Stack.cs index 74f0a7f..7c12678 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Stack.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Stack.cs @@ -1,42 +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.Region.Scripting.EmbeddedJVM -{ - public class Stack - { - public Stack StackFrames = new Stack(); - - public Stack() - { - } - } -} +/* +* 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.EmbeddedJVM +{ + public class Stack + { + public Stack StackFrames = new Stack(); + + public Stack() + { + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/StackFrame.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/StackFrame.cs index 1072395..76257b8 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/StackFrame.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/StackFrame.cs @@ -1,49 +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 OpenSim.Region.Scripting.EmbeddedJVM.Types; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class StackFrame - { - public BaseType[] LocalVariables; - public Stack OpStack = new Stack(); - - public int ReturnPC = 0; - public ClassRecord CallingClass = null; - - public StackFrame() - { - LocalVariables = new BaseType[20]; - } - - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + public class StackFrame + { + public BaseType[] LocalVariables; + public Stack OpStack = new Stack(); + + public int ReturnPC = 0; + public ClassRecord CallingClass = null; + + public StackFrame() + { + LocalVariables = new BaseType[20]; + } + + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Thread.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Thread.cs index 59f3042..eda2640 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Thread.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JVM/Thread.cs @@ -1,119 +1,119 @@ -/* -* 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.Region.Scripting.EmbeddedJVM.Types; -using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; -using OpenSim.Framework; -using OpenSim.Framework.Interfaces; -using OpenSim.Region.Environment.Scenes; -using OpenSim.Region.Scripting; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public partial class Thread - { - // Is this smart? - public static MainMemory GlobalMemory; - public static Scene World; - private int PC = 0; - private Stack stack; - private Interpreter mInterpreter; - public ClassRecord currentClass; - public ClassInstance currentInstance; - private StackFrame currentFrame; - public int excutionCounter = 0; - public bool running = false; - - public ScriptInfo scriptInfo; - - public Thread() - { - this.mInterpreter = new Interpreter(this); - this.stack = new Stack(); - } - - public void SetPC(int methodpointer) - { - //Console.WriteLine("Thread PC has been set to " + methodpointer); - PC = methodpointer; - } - - public void StartMethod(ClassRecord rec, string methName) - { - currentFrame = new StackFrame(); - this.stack.StackFrames.Push(currentFrame); - this.currentClass = rec; - currentClass.StartMethod(this, methName); - } - - public void StartMethod( string methName) - { - currentFrame = new StackFrame(); - this.stack.StackFrames.Push(currentFrame); - currentClass.StartMethod(this, methName); - } - - public void JumpToStaticVoidMethod(string methName, int returnPC) - { - currentFrame = new StackFrame(); - currentFrame.ReturnPC = returnPC; - this.stack.StackFrames.Push(currentFrame); - currentClass.StartMethod(this, methName); - } - - public void JumpToStaticParamMethod(string methName, string param, int returnPC) - { - if (param == "I") - { - BaseType bs1 = currentFrame.OpStack.Pop(); - currentFrame = new StackFrame(); - currentFrame.ReturnPC = returnPC; - this.stack.StackFrames.Push(currentFrame); - currentFrame.LocalVariables[0] = ((Int)bs1); - currentClass.StartMethod(this, methName); - } - if (param == "F") - { - - } - } - - public void JumpToClassStaticVoidMethod(string className, string methName, int returnPC) - { - - } - - public bool Excute() - { - excutionCounter++; - return this.mInterpreter.Excute(); - } - } -} +/* +* 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.Region.Scripting.EmbeddedJVM.Types; +using OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.Scripting; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + public partial class Thread + { + // Is this smart? + public static MainMemory GlobalMemory; + public static Scene World; + private int PC = 0; + private Stack stack; + private Interpreter mInterpreter; + public ClassRecord currentClass; + public ClassInstance currentInstance; + private StackFrame currentFrame; + public int excutionCounter = 0; + public bool running = false; + + public ScriptInfo scriptInfo; + + public Thread() + { + this.mInterpreter = new Interpreter(this); + this.stack = new Stack(); + } + + public void SetPC(int methodpointer) + { + //Console.WriteLine("Thread PC has been set to " + methodpointer); + PC = methodpointer; + } + + public void StartMethod(ClassRecord rec, string methName) + { + currentFrame = new StackFrame(); + this.stack.StackFrames.Push(currentFrame); + this.currentClass = rec; + currentClass.StartMethod(this, methName); + } + + public void StartMethod( string methName) + { + currentFrame = new StackFrame(); + this.stack.StackFrames.Push(currentFrame); + currentClass.StartMethod(this, methName); + } + + public void JumpToStaticVoidMethod(string methName, int returnPC) + { + currentFrame = new StackFrame(); + currentFrame.ReturnPC = returnPC; + this.stack.StackFrames.Push(currentFrame); + currentClass.StartMethod(this, methName); + } + + public void JumpToStaticParamMethod(string methName, string param, int returnPC) + { + if (param == "I") + { + BaseType bs1 = currentFrame.OpStack.Pop(); + currentFrame = new StackFrame(); + currentFrame.ReturnPC = returnPC; + this.stack.StackFrames.Push(currentFrame); + currentFrame.LocalVariables[0] = ((Int)bs1); + currentClass.StartMethod(this, methName); + } + if (param == "F") + { + + } + } + + public void JumpToClassStaticVoidMethod(string className, string methName, int returnPC) + { + + } + + public bool Excute() + { + excutionCounter++; + return this.mInterpreter.Excute(); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JavaEngine.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JavaEngine.cs index a884e2b..58cdf49 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JavaEngine.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/JavaEngine.cs @@ -1,29 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using OpenSim.Region.Scripting; -using OpenSim.Region.Scripting.EmbeddedJVM; - -namespace OpenSim.Region.Scripting -{ - public class JavaEngine : IScriptCompiler - { - public string FileExt() - { - return ".java"; - } - - public Dictionary compile(string filename) - { - JVMScript script = new JVMScript(); - Dictionary returns = new Dictionary(); - - script.LoadScript(filename); - - returns.Add(filename, script); - - return returns; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +using OpenSim.Region.Scripting; +using OpenSim.Region.Scripting.EmbeddedJVM; + +namespace OpenSim.Region.Scripting +{ + public class JavaEngine : IScriptCompiler + { + public string FileExt() + { + return ".java"; + } + + public Dictionary compile(string filename) + { + JVMScript script = new JVMScript(); + Dictionary returns = new Dictionary(); + + script.LoadScript(filename); + + returns.Add(filename, script); + + return returns; + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/OpenSimJVM.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/OpenSimJVM.cs index 8b38951..78c6f67 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/OpenSimJVM.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/OpenSimJVM.cs @@ -1,170 +1,170 @@ -/* -* 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.Threading; -using OpenSim.Framework; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Utilities; -using OpenSim.Region.Scripting; -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Scripting.EmbeddedJVM -{ - public class JVMScript : IScript - { - private List _threads = new List(); - private BlockingQueue CompileScripts = new BlockingQueue(); - private MainMemory _mainMemory; - - ScriptInfo scriptInfo; - - public void Initialise(ScriptInfo info) - { - scriptInfo = info; - - _mainMemory = new MainMemory(); - Thread.GlobalMemory = this._mainMemory; - Thread.World = info.world; - CompileScript(); - - scriptInfo.events.OnFrame += new EventManager.OnFrameDelegate(events_OnFrame); - scriptInfo.events.OnNewPresence += new EventManager.OnNewPresenceDelegate(events_OnNewPresence); - } - - void events_OnNewPresence(ScenePresence presence) - { - for (int i = 0; i < this._threads.Count; i++) - { - if (!this._threads[i].running) - { - this._threads[i].StartMethod("OnNewPresence"); - bool run = true; - while (run) - { - run = this._threads[i].Excute(); - } - } - } - } - - void events_OnFrame() - { - for (int i = 0; i < this._threads.Count; i++) - { - if (!this._threads[i].running) - { - this._threads[i].StartMethod("OnFrame"); - bool run = true; - while (run) - { - run = this._threads[i].Excute(); - } - } - } - } - - public string getName() - { - return "JVM Scripting Engine"; - } - - public void LoadScript(string script) - { - Console.WriteLine("OpenSimJVM - loading new script: " + script); - CompileInfo comp = new CompileInfo(); - comp.script = script; - comp.scriptName = script; - this.CompileScripts.Enqueue(comp); - } - - public void CompileScript() - { - CompileInfo comp = this.CompileScripts.Dequeue(); - string script = comp.script; - string scriptName = comp.scriptName; - try - { - //need to compile the script into a java class file - - //first save it to a java source file - TextWriter tw = new StreamWriter(scriptName + ".java"); - tw.WriteLine(script); - tw.Close(); - - //now compile - System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("javac.exe", "*.java"); - // psi.RedirectStandardOutput = true; - psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; - psi.UseShellExecute = false; - - System.Diagnostics.Process javacomp; - javacomp = System.Diagnostics.Process.Start(psi); - javacomp.WaitForExit(); - - - //now load in class file - ClassRecord class1 = new ClassRecord(); - class1.LoadClassFromFile(scriptName + ".class"); - class1.PrintToConsole(); - //Console.WriteLine(); - this._mainMemory.MethodArea.Classes.Add(class1); - class1.AddMethodsToMemory(this._mainMemory.MethodArea); - - Thread newThread = new Thread(); - this._threads.Add(newThread); - newThread.currentClass = class1; - newThread.scriptInfo = scriptInfo; - - //now delete the created files - System.IO.File.Delete(scriptName + ".java"); - System.IO.File.Delete(scriptName + ".class"); - //this.OnFrame(); - } - catch (Exception e) - { - Console.WriteLine("exception"); - Console.WriteLine(e.StackTrace); - Console.WriteLine(e.Message); - } - } - - private class CompileInfo - { - public string script; - public string scriptName; - - public CompileInfo() - { - - } - } - } -} +/* +* 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.Threading; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using OpenSim.Region.Scripting; +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Scripting.EmbeddedJVM +{ + public class JVMScript : IScript + { + private List _threads = new List(); + private BlockingQueue CompileScripts = new BlockingQueue(); + private MainMemory _mainMemory; + + ScriptInfo scriptInfo; + + public void Initialise(ScriptInfo info) + { + scriptInfo = info; + + _mainMemory = new MainMemory(); + Thread.GlobalMemory = this._mainMemory; + Thread.World = info.world; + CompileScript(); + + scriptInfo.events.OnFrame += new EventManager.OnFrameDelegate(events_OnFrame); + scriptInfo.events.OnNewPresence += new EventManager.OnNewPresenceDelegate(events_OnNewPresence); + } + + void events_OnNewPresence(ScenePresence presence) + { + for (int i = 0; i < this._threads.Count; i++) + { + if (!this._threads[i].running) + { + this._threads[i].StartMethod("OnNewPresence"); + bool run = true; + while (run) + { + run = this._threads[i].Excute(); + } + } + } + } + + void events_OnFrame() + { + for (int i = 0; i < this._threads.Count; i++) + { + if (!this._threads[i].running) + { + this._threads[i].StartMethod("OnFrame"); + bool run = true; + while (run) + { + run = this._threads[i].Excute(); + } + } + } + } + + public string getName() + { + return "JVM Scripting Engine"; + } + + public void LoadScript(string script) + { + Console.WriteLine("OpenSimJVM - loading new script: " + script); + CompileInfo comp = new CompileInfo(); + comp.script = script; + comp.scriptName = script; + this.CompileScripts.Enqueue(comp); + } + + public void CompileScript() + { + CompileInfo comp = this.CompileScripts.Dequeue(); + string script = comp.script; + string scriptName = comp.scriptName; + try + { + //need to compile the script into a java class file + + //first save it to a java source file + TextWriter tw = new StreamWriter(scriptName + ".java"); + tw.WriteLine(script); + tw.Close(); + + //now compile + System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("javac.exe", "*.java"); + // psi.RedirectStandardOutput = true; + psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + psi.UseShellExecute = false; + + System.Diagnostics.Process javacomp; + javacomp = System.Diagnostics.Process.Start(psi); + javacomp.WaitForExit(); + + + //now load in class file + ClassRecord class1 = new ClassRecord(); + class1.LoadClassFromFile(scriptName + ".class"); + class1.PrintToConsole(); + //Console.WriteLine(); + this._mainMemory.MethodArea.Classes.Add(class1); + class1.AddMethodsToMemory(this._mainMemory.MethodArea); + + Thread newThread = new Thread(); + this._threads.Add(newThread); + newThread.currentClass = class1; + newThread.scriptInfo = scriptInfo; + + //now delete the created files + System.IO.File.Delete(scriptName + ".java"); + System.IO.File.Delete(scriptName + ".class"); + //this.OnFrame(); + } + catch (Exception e) + { + Console.WriteLine("exception"); + Console.WriteLine(e.StackTrace); + Console.WriteLine(e.Message); + } + } + + private class CompileInfo + { + public string script; + public string scriptName; + + public CompileInfo() + { + + } + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ArrayReference.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ArrayReference.cs index 40e2e22..0c4d623 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ArrayReference.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ArrayReference.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types -{ - public class ArrayReference :BaseType - { - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types +{ + public class ArrayReference :BaseType + { + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/BaseType.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/BaseType.cs index 4ee1720..7fc0a4f 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/BaseType.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/BaseType.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types -{ - public class BaseType : Object - { - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types +{ + public class BaseType : Object + { + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ObjectReference.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ObjectReference.cs index 75d8e41..7718765 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ObjectReference.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/ObjectReference.cs @@ -1,16 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types -{ - public class ObjectReference : BaseType - { - public ushort Reference; - - public ObjectReference() - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types +{ + public class ObjectReference : BaseType + { + public ushort Reference; + + public ObjectReference() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Byte.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Byte.cs index f5446dc..5a7b780 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Byte.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Byte.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes -{ - public class Byte : BaseType - { - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Byte : BaseType + { + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Char.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Char.cs index 89824b4..c87ee8f 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Char.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Char.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes -{ - public class Char : BaseType - { - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Char : BaseType + { + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Float.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Float.cs index 2638c20..982e748 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Float.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Float.cs @@ -1,16 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes -{ - public class Float : BaseType - { - public float mValue = 0; - - public Float() - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Float : BaseType + { + public float mValue = 0; + + public Float() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Int.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Int.cs index 0155e72..073a9b3 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Int.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/JVMEngine/Types/PrimitiveTypes/Int.cs @@ -1,16 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes -{ - public class Int : BaseType - { - public int mValue = 0; - - public Int() - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Region.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Int : BaseType + { + public int mValue = 0; + + public Int() + { + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/Engine.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/Engine.cs index 8b957d3..012a00e 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/Engine.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/Engine.cs @@ -1,140 +1,140 @@ -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Threading; - -using OpenSim.Region.Scripting; - -namespace OpenSim.ScriptEngines.LSL -{ - - - public class Engine - { - public void Start(ScriptInfo WorldAPI) - { - - - - // Create Assembly Name - AssemblyName asmName = new AssemblyName(); - asmName.Name = "TestAssembly"; - - // Create Assembly - AssemblyBuilder asmBuilder = - Thread.GetDomain().DefineDynamicAssembly - (asmName, AssemblyBuilderAccess.RunAndSave); - - // Create a module (and save to disk) - ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule - (asmName.Name, asmName.Name + ".dll"); - - // Create a Class (/Type) - TypeBuilder typeBuilder = modBuilder.DefineType( - "MyClass", - TypeAttributes.Public, - typeof(object), - new Type[] { typeof(LSL_CLRInterface.LSLScript) }); - - - - /* - * Generate the IL itself - */ - - GenerateIL(WorldAPI, typeBuilder); - - - /* - * Done generating, create a type and run it. - */ - - // Create type object for the class (after defining fields and methods) - Type type = typeBuilder.CreateType(); - - asmBuilder.Save("TestAssembly.dll"); - - // Create an instance we can play with - //LSLScript hello = (LSLScript)Activator.CreateInstance(type); - LSL_CLRInterface.LSLScript MyScript = (LSL_CLRInterface.LSLScript)Activator.CreateInstance(type); - - // Play with it - MyScript.event_state_entry("Test"); - } - - private void GenerateIL(ScriptInfo WorldAPI, TypeBuilder typeBuilder) - { - - - // For debug - LSO_Parser LSOP = new LSO_Parser(); - LSOP.ParseFile("LSO\\CloseToDefault.lso", WorldAPI, ref typeBuilder); - return; - - - // Override a Method / Function - MethodBuilder methodBuilder = typeBuilder.DefineMethod("event_state_entry", - MethodAttributes.Private | MethodAttributes.Virtual, - typeof(void), - new Type[] { typeof(object) }); - - typeBuilder.DefineMethodOverride(methodBuilder, - typeof(LSL_CLRInterface.LSLScript).GetMethod("event_state_entry")); - - // Create the IL generator - ILGenerator il = methodBuilder.GetILGenerator(); - - - /* - * TRY - */ - il.BeginExceptionBlock(); - - // Push "Hello World!" string to stack - il.Emit(OpCodes.Ldstr, "Hello World!"); - - // Push Console.WriteLine command to stack ... Console.WriteLine("Hello World!"); - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("WriteLine", new Type[] { typeof(string) })); - - //il.EmitCall(OpCodes.Callvirt - //il.Emit(OpCodes.Call, typeof(WorldAPI).GetMethod - //("TestFunction")); - - - //il.ThrowException(typeof(NotSupportedException)); - - - /* - * CATCH - */ - il.BeginCatchBlock(typeof(Exception)); - - // Push "Hello World!" string to stack - il.Emit(OpCodes.Ldstr, "Something went wrong: "); - - //call void [mscorlib]System.Console::WriteLine(string) - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("Write", new Type[] { typeof(string) })); - - //callvirt instance string [mscorlib]System.Exception::get_Message() - il.Emit(OpCodes.Callvirt, typeof(Exception).GetMethod - ("get_Message")); - - //call void [mscorlib]System.Console::WriteLine(string) - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("WriteLine", new Type[] { typeof(string) })); - - /* - * END TRY - */ - il.EndExceptionBlock(); - - - // Push "Return from current method, with return value if present" to stack - il.Emit(OpCodes.Ret); - - - } - } -} +using System; +using System.Reflection; +using System.Reflection.Emit; +using System.Threading; + +using OpenSim.Region.Scripting; + +namespace OpenSim.ScriptEngines.LSL +{ + + + public class Engine + { + public void Start(ScriptInfo WorldAPI) + { + + + + // Create Assembly Name + AssemblyName asmName = new AssemblyName(); + asmName.Name = "TestAssembly"; + + // Create Assembly + AssemblyBuilder asmBuilder = + Thread.GetDomain().DefineDynamicAssembly + (asmName, AssemblyBuilderAccess.RunAndSave); + + // Create a module (and save to disk) + ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule + (asmName.Name, asmName.Name + ".dll"); + + // Create a Class (/Type) + TypeBuilder typeBuilder = modBuilder.DefineType( + "MyClass", + TypeAttributes.Public, + typeof(object), + new Type[] { typeof(LSL_CLRInterface.LSLScript) }); + + + + /* + * Generate the IL itself + */ + + GenerateIL(WorldAPI, typeBuilder); + + + /* + * Done generating, create a type and run it. + */ + + // Create type object for the class (after defining fields and methods) + Type type = typeBuilder.CreateType(); + + asmBuilder.Save("TestAssembly.dll"); + + // Create an instance we can play with + //LSLScript hello = (LSLScript)Activator.CreateInstance(type); + LSL_CLRInterface.LSLScript MyScript = (LSL_CLRInterface.LSLScript)Activator.CreateInstance(type); + + // Play with it + MyScript.event_state_entry("Test"); + } + + private void GenerateIL(ScriptInfo WorldAPI, TypeBuilder typeBuilder) + { + + + // For debug + LSO_Parser LSOP = new LSO_Parser(); + LSOP.ParseFile("LSO\\CloseToDefault.lso", WorldAPI, ref typeBuilder); + return; + + + // Override a Method / Function + MethodBuilder methodBuilder = typeBuilder.DefineMethod("event_state_entry", + MethodAttributes.Private | MethodAttributes.Virtual, + typeof(void), + new Type[] { typeof(object) }); + + typeBuilder.DefineMethodOverride(methodBuilder, + typeof(LSL_CLRInterface.LSLScript).GetMethod("event_state_entry")); + + // Create the IL generator + ILGenerator il = methodBuilder.GetILGenerator(); + + + /* + * TRY + */ + il.BeginExceptionBlock(); + + // Push "Hello World!" string to stack + il.Emit(OpCodes.Ldstr, "Hello World!"); + + // Push Console.WriteLine command to stack ... Console.WriteLine("Hello World!"); + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("WriteLine", new Type[] { typeof(string) })); + + //il.EmitCall(OpCodes.Callvirt + //il.Emit(OpCodes.Call, typeof(WorldAPI).GetMethod + //("TestFunction")); + + + //il.ThrowException(typeof(NotSupportedException)); + + + /* + * CATCH + */ + il.BeginCatchBlock(typeof(Exception)); + + // Push "Hello World!" string to stack + il.Emit(OpCodes.Ldstr, "Something went wrong: "); + + //call void [mscorlib]System.Console::WriteLine(string) + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("Write", new Type[] { typeof(string) })); + + //callvirt instance string [mscorlib]System.Exception::get_Message() + il.Emit(OpCodes.Callvirt, typeof(Exception).GetMethod + ("get_Message")); + + //call void [mscorlib]System.Console::WriteLine(string) + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("WriteLine", new Type[] { typeof(string) })); + + /* + * END TRY + */ + il.EndExceptionBlock(); + + + // Push "Return from current method, with return value if present" to stack + il.Emit(OpCodes.Ret); + + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSL_CLRInterface.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSL_CLRInterface.cs index dc612ff..57bbf11 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSL_CLRInterface.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSL_CLRInterface.cs @@ -1,51 +1,51 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.ScriptEngines.LSL -{ - public class LSL_CLRInterface - { - public interface LSLScript - { - //public virtual void Run(object arg) - //{ - //} - //void Run(object arg); - - void event_state_entry(object arg); - //void event_state_exit(); - void event_touch_start(object arg); - //void event_touch(); - //void event_touch_end(); - //void event_collision_start(); - //void event_collision(); - //void event_collision_end(); - //void event_land_collision_start(); - //void event_land_collision(); - //void event_land_collision_end(); - //void event_timer(); - //void event_listen(); - //void event_on_rez(); - //void event_sensor(); - //void event_no_sensor(); - //void event_control(); - //void event_money(); - //void event_email(); - //void event_at_target(); - //void event_not_at_target(); - //void event_at_rot_target(); - //void event_not_at_rot_target(); - //void event_run_time_permissions(); - //void event_changed(); - //void event_attach(); - //void event_dataserver(); - //void event_link_message(); - //void event_moving_start(); - //void event_moving_end(); - //void event_object_rez(); - //void event_remote_data(); - //void event_http_response(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.ScriptEngines.LSL +{ + public class LSL_CLRInterface + { + public interface LSLScript + { + //public virtual void Run(object arg) + //{ + //} + //void Run(object arg); + + void event_state_entry(object arg); + //void event_state_exit(); + void event_touch_start(object arg); + //void event_touch(); + //void event_touch_end(); + //void event_collision_start(); + //void event_collision(); + //void event_collision_end(); + //void event_land_collision_start(); + //void event_land_collision(); + //void event_land_collision_end(); + //void event_timer(); + //void event_listen(); + //void event_on_rez(); + //void event_sensor(); + //void event_no_sensor(); + //void event_control(); + //void event_money(); + //void event_email(); + //void event_at_target(); + //void event_not_at_target(); + //void event_at_rot_target(); + //void event_not_at_rot_target(); + //void event_run_time_permissions(); + //void event_changed(); + //void event_attach(); + //void event_dataserver(); + //void event_link_message(); + //void event_moving_start(); + //void event_moving_end(); + //void event_object_rez(); + //void event_remote_data(); + //void event_http_response(); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Enums.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Enums.cs index edeccdd..b45abe0 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Enums.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Enums.cs @@ -1,485 +1,485 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.ScriptEngines.LSL -{ - static class LSO_Enums - { - - public enum Variable_Type_Codes - { - Void = 0, - Integer = 1, - Float = 2, - String = 3, - Key = 4, - Vector = 5, - Rotation = 6, - List = 7 - } - public enum Event_Mask_Values - { - state_entry = 0, - state_exit = 1, - touch_start = 2, - touch = 3, - touch_end = 4, - collision_start = 5, - collision = 6, - collision_end = 7, - land_collision_start = 8, - land_collision = 9, - land_collision_end = 10, - timer = 11, - listen = 12, - on_rez = 13, - sensor = 14, - no_sensor = 15, - control = 16, - money = 17, - email = 18, - at_target = 19, - not_at_target = 20, - at_rot_target = 21, - not_at_rot_target = 22, - run_time_permissions = 23, - changed = 24, - attach = 25, - dataserver = 26, - link_message = 27, - moving_start = 28, - moving_end = 29, - object_rez = 30, - remote_data = 31, - http_response = 32 - } - public enum Operation_Table - { - NOOP = 0x0, - POP = 0x1, - POPS = 0x2, - POPL = 0x3, - POPV = 0x4, - POPQ = 0x5, - POPARG = 0x6, - POPIP = 0x7, - POPBP = 0x8, - POPSP = 0x9, - POPSLR = 0xa, - DUP = 0x20, - DUPS = 0x21, - DUPL = 0x22, - DUPV = 0x23, - DUPQ = 0x24, - STORE = 0x30, - STORES = 0x31, - STOREL = 0x32, - STOREV = 0x33, - STOREQ = 0x34, - STOREG = 0x35, - STOREGS = 0x36, - STOREGL = 0x37, - STOREGV = 0x38, - STOREGQ = 0x39, - LOADP = 0x3a, - LOADSP = 0x3b, - LOADLP = 0x3c, - LOADVP = 0x3d, - LOADQP = 0x3e, - LOADGP = 0x3f, - LOADGSP = 0x40, - LOADGLP = 0x41, - LOADGVP = 0x42, - LOADGQP = 0x43, - PUSH = 0x50, - PUSHS = 0x51, - PUSHL = 0x52, - PUSHV = 0x53, - PUSHQ = 0x54, - PUSHG = 0x55, - PUSHGS = 0x56, - PUSHGL = 0x57, - PUSHGV = 0x58, - PUSHGQ = 0x59, - PUSHIP = 0x5a, - PUSHBP = 0x5b, - PUSHSP = 0x5c, - PUSHARGB = 0x5d, - PUSHARGI = 0x5e, - PUSHARGF = 0x5f, - PUSHARGS = 0x60, - PUSHARGV = 0x61, - PUSHARGQ = 0x62, - PUSHE = 0x63, - PUSHEV = 0x64, - PUSHEQ = 0x65, - PUSHARGE = 0x66, - ADD = 0x70, - SUB = 0x71, - MUL = 0x72, - DIV = 0x73, - MOD = 0x74, - EQ = 0x75, - NEQ = 0x76, - LEQ = 0x77, - GEQ = 0x78, - LESS = 0x79, - GREATER = 0x7a, - BITAND = 0x7b, - BITOR = 0x7c, - BITXOR = 0x7d, - BOOLAND = 0x7e, - BOOLOR = 0x7f, - NEG = 0x80, - BITNOT = 0x81, - BOOLNOT = 0x82, - JUMP = 0x90, - JUMPIF = 0x91, - JUMPNIF = 0x92, - STATE = 0x93, - CALL = 0x94, - RETURN = 0x95, - CAST = 0xa0, - STACKTOS = 0xb0, - STACKTOL = 0xb1, - PRINT = 0xc0, - CALLLIB = 0xd0, - CALLLIB_TWO_BYTE = 0xd1, - SHL = 0xe0, - SHR = 0xe1 - } - public enum BuiltIn_Functions - { - llSin = 0, - llCos = 1, - llTan = 2, - llAtan2 = 3, - llSqrt = 4, - llPow = 5, - llAbs = 6, - llFabs = 7, - llFrand = 8, - llFloor = 9, - llCeil = 10, - llRound = 11, - llVecMag = 12, - llVecNorm = 13, - llVecDist = 14, - llRot2Euler = 15, - llEuler2Rot = 16, - llAxes2Rot = 17, - llRot2Fwd = 18, - llRot2Left = 19, - llRot2Up = 20, - llRotBetween = 21, - llWhisper = 22, - llSay = 23, - llShout = 24, - llListen = 25, - llListenControl = 26, - llListenRemove = 27, - llSensor = 28, - llSensorRepeat = 29, - llSensorRemove = 30, - llDetectedName = 31, - llDetectedKey = 32, - llDetectedOwner = 33, - llDetectedType = 34, - llDetectedPos = 35, - llDetectedVel = 36, - llDetectedGrab = 37, - llDetectedRot = 38, - llDetectedGroup = 39, - llDetectedLinkNumber = 40, - llDie = 41, - llGround = 42, - llCloud = 43, - llWind = 44, - llSetStatus = 45, - llGetStatus = 46, - llSetScale = 47, - llGetScale = 48, - llSetColor = 49, - llGetAlpha = 50, - llSetAlpha = 51, - llGetColor = 52, - llSetTexture = 53, - llScaleTexture = 54, - llOffsetTexture = 55, - llRotateTexture = 56, - llGetTexture = 57, - llSetPos = 58, - llGetPos = 59, - llGetLocalPos = 60, - llSetRot = 61, - llGetRot = 62, - llGetLocalRot = 63, - llSetForce = 64, - llGetForce = 65, - llTarget = 66, - llTargetRemove = 67, - llRotTarget = 68, - llRotTargetRemove = 69, - llMoveToTarget = 70, - llStopMoveToTarget = 71, - llApplyImpulse = 72, - llApplyRotationalImpulse = 73, - llSetTorque = 74, - llGetTorque = 75, - llSetForceAndTorque = 76, - llGetVel = 77, - llGetAccel = 78, - llGetOmega = 79, - llGetTimeOfDay = 80, - llGetWallclock = 81, - llGetTime = 82, - llResetTime = 83, - llGetAndResetTime = 84, - llSound = 85, - llPlaySound = 86, - llLoopSound = 87, - llLoopSoundMaster = 88, - llLoopSoundSlave = 89, - llPlaySoundSlave = 90, - llTriggerSound = 91, - llStopSound = 92, - llPreloadSound = 93, - llGetSubString = 94, - llDeleteSubString = 95, - llInsertString = 96, - llToUpper = 97, - llToLower = 98, - llGiveMoney = 99, - llMakeExplosion = 100, - llMakeFountain = 101, - llMakeSmoke = 102, - llMakeFire = 103, - llRezObject = 104, - llLookAt = 105, - llStopLookAt = 106, - llSetTimerEvent = 107, - llSleep = 108, - llGetMass = 109, - llCollisionFilter = 110, - llTakeControls = 111, - llReleaseControls = 112, - llAttachToAvatar = 113, - llDetachFromAvatar = 114, - llTakeCamera = 115, - llReleaseCamera = 116, - llGetOwner = 117, - llInstantMessage = 118, - llEmail = 119, - llGetNextEmail = 120, - llGetKey = 121, - llSetBuoyancy = 122, - llSetHoverHeight = 123, - llStopHover = 124, - llMinEventDelay = 125, - llSoundPreload = 126, - llRotLookAt = 127, - llStringLength = 128, - llStartAnimation = 129, - llStopAnimation = 130, - llPointAt = 131, - llStopPointAt = 132, - llTargetOmega = 133, - llGetStartParameter = 134, - llGodLikeRezObject = 135, - llRequestPermissions = 136, - llGetPermissionsKey = 137, - llGetPermissions = 138, - llGetLinkNumber = 139, - llSetLinkColor = 140, - llCreateLink = 141, - llBreakLink = 142, - llBreakAllLinks = 143, - llGetLinkKey = 144, - llGetLinkName = 145, - llGetInventoryNumber = 146, - llGetInventoryName = 147, - llSetScriptState = 148, - llGetEnergy = 149, - llGiveInventory = 150, - llRemoveInventory = 151, - llSetText = 152, - llWater = 153, - llPassTouches = 154, - llRequestAgentData = 155, - llRequestInventoryData = 156, - llSetDamage = 157, - llTeleportAgentHome = 158, - llModifyLand = 159, - llCollisionSound = 160, - llCollisionSprite = 161, - llGetAnimation = 162, - llResetScript = 163, - llMessageLinked = 164, - llPushObject = 165, - llPassCollisions = 166, - llGetScriptName = 167, - llGetNumberOfSides = 168, - llAxisAngle2Rot = 169, - llRot2Axis = 170, - llRot2Angle = 171, - llAcos = 172, - llAsin = 173, - llAngleBetween = 174, - llGetInventoryKey = 175, - llAllowInventoryDrop = 176, - llGetSunDirection = 177, - llGetTextureOffset = 178, - llGetTextureScale = 179, - llGetTextureRot = 180, - llSubStringIndex = 181, - llGetOwnerKey = 182, - llGetCenterOfMass = 183, - llListSort = 184, - llGetListLength = 185, - llList2Integer = 186, - llList2Float = 187, - llList2String = 188, - llList2Key = 189, - llList2Vector = 190, - llList2Rot = 191, - llList2List = 192, - llDeleteSubList = 193, - llGetListEntryType = 194, - llList2CSV = 195, - llCSV2List = 196, - llListRandomize = 197, - llList2ListStrided = 198, - llGetRegionCorner = 199, - llListInsertList = 200, - llListFindList = 201, - llGetObjectName = 202, - llSetObjectName = 203, - llGetDate = 204, - llEdgeOfWorld = 205, - llGetAgentInfo = 206, - llAdjustSoundVolume = 207, - llSetSoundQueueing = 208, - llSetSoundRadius = 209, - llKey2Name = 210, - llSetTextureAnim = 211, - llTriggerSoundLimited = 212, - llEjectFromLand = 213, - llParseString2List = 214, - llOverMyLand = 215, - llGetLandOwnerAt = 216, - llGetNotecardLine = 217, - llGetAgentSize = 218, - llSameGroup = 219, - llUnSit = 220, - llGroundSlope = 221, - llGroundNormal = 222, - llGroundContour = 223, - llGetAttached = 224, - llGetFreeMemory = 225, - llGetRegionName = 226, - llGetRegionTimeDilation = 227, - llGetRegionFPS = 228, - llParticleSystem = 229, - llGroundRepel = 230, - llGiveInventoryList = 231, - llSetVehicleType = 232, - llSetVehicleFloatParam = 233, - llSetVehicleVectorParam = 234, - llSetVehicleRotationParam = 235, - llSetVehicleFlags = 236, - llRemoveVehicleFlags = 237, - llSitTarget = 238, - llAvatarOnSitTarget = 239, - llAddToLandPassList = 240, - llSetTouchText = 241, - llSetSitText = 242, - llSetCameraEyeOffset = 243, - llSetCameraAtOffset = 244, - llDumpList2String = 245, - llScriptDanger = 246, - llDialog = 247, - llVolumeDetect = 248, - llResetOtherScript = 249, - llGetScriptState = 250, - llRemoteLoadScript = 251, - llSetRemoteScriptAccessPin = 252, - llRemoteLoadScriptPin = 253, - llOpenRemoteDataChannel = 254, - llSendRemoteData = 255, - llRemoteDataReply = 256, - llCloseRemoteDataChannel = 257, - llMD5String = 258, - llSetPrimitiveParams = 259, - llStringToBase64 = 260, - llBase64ToString = 261, - llXorBase64Strings = 262, - llRemoteDataSetRegion = 263, - llLog10 = 264, - llLog = 265, - llGetAnimationList = 266, - llSetParcelMusicURL = 267, - llGetRootPosition = 268, - llGetRootRotation = 269, - llGetObjectDesc = 270, - llSetObjectDesc = 271, - llGetCreator = 272, - llGetTimestamp = 273, - llSetLinkAlpha = 274, - llGetNumberOfPrims = 275, - llGetNumberOfNotecardLines = 276, - llGetBoundingBox = 277, - llGetGeometricCenter = 278, - llGetPrimitiveParams = 279, - llIntegerToBase64 = 280, - llBase64ToInteger = 281, - llGetGMTclock = 282, - llGetSimulatorHostname = 283, - llSetLocalRot = 284, - llParseStringKeepNulls = 285, - llRezAtRoot = 286, - llGetObjectPermMask = 287, - llSetObjectPermMask = 288, - llGetInventoryPermMask = 289, - llSetInventoryPermMask = 290, - llGetInventoryCreator = 291, - llOwnerSay = 292, - llRequestSimulatorData = 293, - llForceMouselook = 294, - llGetObjectMass = 295, - llListReplaceList = 296, - llLoadURL = 297, - llParcelMediaCommandList = 298, - llParcelMediaQuery = 299, - llModPow = 300, - llGetInventoryType = 301, - llSetPayPrice = 302, - llGetCameraPos = 303, - llGetCameraRot = 304, - llSetPrimURL = 305, - llRefreshPrimURL = 306, - llEscapeURL = 307, - llUnescapeURL = 308, - llMapDestination = 309, - llAddToLandBanList = 310, - llRemoveFromLandPassList = 311, - llRemoveFromLandBanList = 312, - llSetCameraParams = 313, - llClearCameraParams = 314, - llListStatistics = 315, - llGetUnixTime = 316, - llGetParcelFlags = 317, - llGetRegionFlags = 318, - llXorBase64StringsCorrect = 319, - llHTTPRequest = 320, - llResetLandBanList = 321, - llResetLandPassList = 322, - llGetParcelPrimCount = 323, - llGetParcelPrimOwners = 324, - llGetObjectPrimCount = 325, - llGetParcelMaxPrims = 326, - llGetParcelDetails = 327 - } - - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.ScriptEngines.LSL +{ + static class LSO_Enums + { + + public enum Variable_Type_Codes + { + Void = 0, + Integer = 1, + Float = 2, + String = 3, + Key = 4, + Vector = 5, + Rotation = 6, + List = 7 + } + public enum Event_Mask_Values + { + state_entry = 0, + state_exit = 1, + touch_start = 2, + touch = 3, + touch_end = 4, + collision_start = 5, + collision = 6, + collision_end = 7, + land_collision_start = 8, + land_collision = 9, + land_collision_end = 10, + timer = 11, + listen = 12, + on_rez = 13, + sensor = 14, + no_sensor = 15, + control = 16, + money = 17, + email = 18, + at_target = 19, + not_at_target = 20, + at_rot_target = 21, + not_at_rot_target = 22, + run_time_permissions = 23, + changed = 24, + attach = 25, + dataserver = 26, + link_message = 27, + moving_start = 28, + moving_end = 29, + object_rez = 30, + remote_data = 31, + http_response = 32 + } + public enum Operation_Table + { + NOOP = 0x0, + POP = 0x1, + POPS = 0x2, + POPL = 0x3, + POPV = 0x4, + POPQ = 0x5, + POPARG = 0x6, + POPIP = 0x7, + POPBP = 0x8, + POPSP = 0x9, + POPSLR = 0xa, + DUP = 0x20, + DUPS = 0x21, + DUPL = 0x22, + DUPV = 0x23, + DUPQ = 0x24, + STORE = 0x30, + STORES = 0x31, + STOREL = 0x32, + STOREV = 0x33, + STOREQ = 0x34, + STOREG = 0x35, + STOREGS = 0x36, + STOREGL = 0x37, + STOREGV = 0x38, + STOREGQ = 0x39, + LOADP = 0x3a, + LOADSP = 0x3b, + LOADLP = 0x3c, + LOADVP = 0x3d, + LOADQP = 0x3e, + LOADGP = 0x3f, + LOADGSP = 0x40, + LOADGLP = 0x41, + LOADGVP = 0x42, + LOADGQP = 0x43, + PUSH = 0x50, + PUSHS = 0x51, + PUSHL = 0x52, + PUSHV = 0x53, + PUSHQ = 0x54, + PUSHG = 0x55, + PUSHGS = 0x56, + PUSHGL = 0x57, + PUSHGV = 0x58, + PUSHGQ = 0x59, + PUSHIP = 0x5a, + PUSHBP = 0x5b, + PUSHSP = 0x5c, + PUSHARGB = 0x5d, + PUSHARGI = 0x5e, + PUSHARGF = 0x5f, + PUSHARGS = 0x60, + PUSHARGV = 0x61, + PUSHARGQ = 0x62, + PUSHE = 0x63, + PUSHEV = 0x64, + PUSHEQ = 0x65, + PUSHARGE = 0x66, + ADD = 0x70, + SUB = 0x71, + MUL = 0x72, + DIV = 0x73, + MOD = 0x74, + EQ = 0x75, + NEQ = 0x76, + LEQ = 0x77, + GEQ = 0x78, + LESS = 0x79, + GREATER = 0x7a, + BITAND = 0x7b, + BITOR = 0x7c, + BITXOR = 0x7d, + BOOLAND = 0x7e, + BOOLOR = 0x7f, + NEG = 0x80, + BITNOT = 0x81, + BOOLNOT = 0x82, + JUMP = 0x90, + JUMPIF = 0x91, + JUMPNIF = 0x92, + STATE = 0x93, + CALL = 0x94, + RETURN = 0x95, + CAST = 0xa0, + STACKTOS = 0xb0, + STACKTOL = 0xb1, + PRINT = 0xc0, + CALLLIB = 0xd0, + CALLLIB_TWO_BYTE = 0xd1, + SHL = 0xe0, + SHR = 0xe1 + } + public enum BuiltIn_Functions + { + llSin = 0, + llCos = 1, + llTan = 2, + llAtan2 = 3, + llSqrt = 4, + llPow = 5, + llAbs = 6, + llFabs = 7, + llFrand = 8, + llFloor = 9, + llCeil = 10, + llRound = 11, + llVecMag = 12, + llVecNorm = 13, + llVecDist = 14, + llRot2Euler = 15, + llEuler2Rot = 16, + llAxes2Rot = 17, + llRot2Fwd = 18, + llRot2Left = 19, + llRot2Up = 20, + llRotBetween = 21, + llWhisper = 22, + llSay = 23, + llShout = 24, + llListen = 25, + llListenControl = 26, + llListenRemove = 27, + llSensor = 28, + llSensorRepeat = 29, + llSensorRemove = 30, + llDetectedName = 31, + llDetectedKey = 32, + llDetectedOwner = 33, + llDetectedType = 34, + llDetectedPos = 35, + llDetectedVel = 36, + llDetectedGrab = 37, + llDetectedRot = 38, + llDetectedGroup = 39, + llDetectedLinkNumber = 40, + llDie = 41, + llGround = 42, + llCloud = 43, + llWind = 44, + llSetStatus = 45, + llGetStatus = 46, + llSetScale = 47, + llGetScale = 48, + llSetColor = 49, + llGetAlpha = 50, + llSetAlpha = 51, + llGetColor = 52, + llSetTexture = 53, + llScaleTexture = 54, + llOffsetTexture = 55, + llRotateTexture = 56, + llGetTexture = 57, + llSetPos = 58, + llGetPos = 59, + llGetLocalPos = 60, + llSetRot = 61, + llGetRot = 62, + llGetLocalRot = 63, + llSetForce = 64, + llGetForce = 65, + llTarget = 66, + llTargetRemove = 67, + llRotTarget = 68, + llRotTargetRemove = 69, + llMoveToTarget = 70, + llStopMoveToTarget = 71, + llApplyImpulse = 72, + llApplyRotationalImpulse = 73, + llSetTorque = 74, + llGetTorque = 75, + llSetForceAndTorque = 76, + llGetVel = 77, + llGetAccel = 78, + llGetOmega = 79, + llGetTimeOfDay = 80, + llGetWallclock = 81, + llGetTime = 82, + llResetTime = 83, + llGetAndResetTime = 84, + llSound = 85, + llPlaySound = 86, + llLoopSound = 87, + llLoopSoundMaster = 88, + llLoopSoundSlave = 89, + llPlaySoundSlave = 90, + llTriggerSound = 91, + llStopSound = 92, + llPreloadSound = 93, + llGetSubString = 94, + llDeleteSubString = 95, + llInsertString = 96, + llToUpper = 97, + llToLower = 98, + llGiveMoney = 99, + llMakeExplosion = 100, + llMakeFountain = 101, + llMakeSmoke = 102, + llMakeFire = 103, + llRezObject = 104, + llLookAt = 105, + llStopLookAt = 106, + llSetTimerEvent = 107, + llSleep = 108, + llGetMass = 109, + llCollisionFilter = 110, + llTakeControls = 111, + llReleaseControls = 112, + llAttachToAvatar = 113, + llDetachFromAvatar = 114, + llTakeCamera = 115, + llReleaseCamera = 116, + llGetOwner = 117, + llInstantMessage = 118, + llEmail = 119, + llGetNextEmail = 120, + llGetKey = 121, + llSetBuoyancy = 122, + llSetHoverHeight = 123, + llStopHover = 124, + llMinEventDelay = 125, + llSoundPreload = 126, + llRotLookAt = 127, + llStringLength = 128, + llStartAnimation = 129, + llStopAnimation = 130, + llPointAt = 131, + llStopPointAt = 132, + llTargetOmega = 133, + llGetStartParameter = 134, + llGodLikeRezObject = 135, + llRequestPermissions = 136, + llGetPermissionsKey = 137, + llGetPermissions = 138, + llGetLinkNumber = 139, + llSetLinkColor = 140, + llCreateLink = 141, + llBreakLink = 142, + llBreakAllLinks = 143, + llGetLinkKey = 144, + llGetLinkName = 145, + llGetInventoryNumber = 146, + llGetInventoryName = 147, + llSetScriptState = 148, + llGetEnergy = 149, + llGiveInventory = 150, + llRemoveInventory = 151, + llSetText = 152, + llWater = 153, + llPassTouches = 154, + llRequestAgentData = 155, + llRequestInventoryData = 156, + llSetDamage = 157, + llTeleportAgentHome = 158, + llModifyLand = 159, + llCollisionSound = 160, + llCollisionSprite = 161, + llGetAnimation = 162, + llResetScript = 163, + llMessageLinked = 164, + llPushObject = 165, + llPassCollisions = 166, + llGetScriptName = 167, + llGetNumberOfSides = 168, + llAxisAngle2Rot = 169, + llRot2Axis = 170, + llRot2Angle = 171, + llAcos = 172, + llAsin = 173, + llAngleBetween = 174, + llGetInventoryKey = 175, + llAllowInventoryDrop = 176, + llGetSunDirection = 177, + llGetTextureOffset = 178, + llGetTextureScale = 179, + llGetTextureRot = 180, + llSubStringIndex = 181, + llGetOwnerKey = 182, + llGetCenterOfMass = 183, + llListSort = 184, + llGetListLength = 185, + llList2Integer = 186, + llList2Float = 187, + llList2String = 188, + llList2Key = 189, + llList2Vector = 190, + llList2Rot = 191, + llList2List = 192, + llDeleteSubList = 193, + llGetListEntryType = 194, + llList2CSV = 195, + llCSV2List = 196, + llListRandomize = 197, + llList2ListStrided = 198, + llGetRegionCorner = 199, + llListInsertList = 200, + llListFindList = 201, + llGetObjectName = 202, + llSetObjectName = 203, + llGetDate = 204, + llEdgeOfWorld = 205, + llGetAgentInfo = 206, + llAdjustSoundVolume = 207, + llSetSoundQueueing = 208, + llSetSoundRadius = 209, + llKey2Name = 210, + llSetTextureAnim = 211, + llTriggerSoundLimited = 212, + llEjectFromLand = 213, + llParseString2List = 214, + llOverMyLand = 215, + llGetLandOwnerAt = 216, + llGetNotecardLine = 217, + llGetAgentSize = 218, + llSameGroup = 219, + llUnSit = 220, + llGroundSlope = 221, + llGroundNormal = 222, + llGroundContour = 223, + llGetAttached = 224, + llGetFreeMemory = 225, + llGetRegionName = 226, + llGetRegionTimeDilation = 227, + llGetRegionFPS = 228, + llParticleSystem = 229, + llGroundRepel = 230, + llGiveInventoryList = 231, + llSetVehicleType = 232, + llSetVehicleFloatParam = 233, + llSetVehicleVectorParam = 234, + llSetVehicleRotationParam = 235, + llSetVehicleFlags = 236, + llRemoveVehicleFlags = 237, + llSitTarget = 238, + llAvatarOnSitTarget = 239, + llAddToLandPassList = 240, + llSetTouchText = 241, + llSetSitText = 242, + llSetCameraEyeOffset = 243, + llSetCameraAtOffset = 244, + llDumpList2String = 245, + llScriptDanger = 246, + llDialog = 247, + llVolumeDetect = 248, + llResetOtherScript = 249, + llGetScriptState = 250, + llRemoteLoadScript = 251, + llSetRemoteScriptAccessPin = 252, + llRemoteLoadScriptPin = 253, + llOpenRemoteDataChannel = 254, + llSendRemoteData = 255, + llRemoteDataReply = 256, + llCloseRemoteDataChannel = 257, + llMD5String = 258, + llSetPrimitiveParams = 259, + llStringToBase64 = 260, + llBase64ToString = 261, + llXorBase64Strings = 262, + llRemoteDataSetRegion = 263, + llLog10 = 264, + llLog = 265, + llGetAnimationList = 266, + llSetParcelMusicURL = 267, + llGetRootPosition = 268, + llGetRootRotation = 269, + llGetObjectDesc = 270, + llSetObjectDesc = 271, + llGetCreator = 272, + llGetTimestamp = 273, + llSetLinkAlpha = 274, + llGetNumberOfPrims = 275, + llGetNumberOfNotecardLines = 276, + llGetBoundingBox = 277, + llGetGeometricCenter = 278, + llGetPrimitiveParams = 279, + llIntegerToBase64 = 280, + llBase64ToInteger = 281, + llGetGMTclock = 282, + llGetSimulatorHostname = 283, + llSetLocalRot = 284, + llParseStringKeepNulls = 285, + llRezAtRoot = 286, + llGetObjectPermMask = 287, + llSetObjectPermMask = 288, + llGetInventoryPermMask = 289, + llSetInventoryPermMask = 290, + llGetInventoryCreator = 291, + llOwnerSay = 292, + llRequestSimulatorData = 293, + llForceMouselook = 294, + llGetObjectMass = 295, + llListReplaceList = 296, + llLoadURL = 297, + llParcelMediaCommandList = 298, + llParcelMediaQuery = 299, + llModPow = 300, + llGetInventoryType = 301, + llSetPayPrice = 302, + llGetCameraPos = 303, + llGetCameraRot = 304, + llSetPrimURL = 305, + llRefreshPrimURL = 306, + llEscapeURL = 307, + llUnescapeURL = 308, + llMapDestination = 309, + llAddToLandBanList = 310, + llRemoveFromLandPassList = 311, + llRemoveFromLandBanList = 312, + llSetCameraParams = 313, + llClearCameraParams = 314, + llListStatistics = 315, + llGetUnixTime = 316, + llGetParcelFlags = 317, + llGetRegionFlags = 318, + llXorBase64StringsCorrect = 319, + llHTTPRequest = 320, + llResetLandBanList = 321, + llResetLandPassList = 322, + llGetParcelPrimCount = 323, + llGetParcelPrimOwners = 324, + llGetObjectPrimCount = 325, + llGetParcelMaxPrims = 326, + llGetParcelDetails = 327 + } + + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Parser.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Parser.cs index 2da1189..ebe4465 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Parser.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Parser.cs @@ -1,608 +1,608 @@ - using System; - using System.Collections.Generic; - using System.Text; - using System.IO; - using System.Reflection; - using System.Reflection.Emit; -using OpenSim.Region.Scripting; - - namespace OpenSim.ScriptEngines.LSL - { - class LSO_Parser - { - private bool Debug = true; - private FileStream fs; - private BinaryReader br; - private LSO_Struct.Header myHeader; - - private TypeBuilder typeBuilder; - private ScriptInfo WorldAPI; - - /// - /// Parse LSO file. - /// Reads LSO ByteCode into memory structures. - /// TODO: What else does it do? - /// - /// FileName of LSO ByteCode file - public void ParseFile(string FileName, ScriptInfo _WorldAPI, ref TypeBuilder _typeBuilder) - { - typeBuilder = _typeBuilder; - WorldAPI = _WorldAPI; - // Open - SendToDebug("Opening filename: " + FileName); - fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read); - br = new BinaryReader(fs, Encoding.BigEndianUnicode); - - - // The LSO Format consist of 6 major blocks: header, statics, functions, states, heap, and stack. - - - // HEADER BLOCK - SendToDebug("Reading HEADER BLOCK at: 0"); - fs.Seek(0, SeekOrigin.Begin); - myHeader = new LSO_Struct.Header(); - myHeader.TM = BitConverter.ToUInt32(br_read(4), 0); - myHeader.IP = BitConverter.ToUInt32(br_read(4), 0); - myHeader.VN = BitConverter.ToUInt32(br_read(4), 0); - myHeader.BP = BitConverter.ToUInt32(br_read(4), 0); - myHeader.SP = BitConverter.ToUInt32(br_read(4), 0); - myHeader.HR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.HP = BitConverter.ToUInt32(br_read(4), 0); - myHeader.CS = BitConverter.ToUInt32(br_read(4), 0); - myHeader.NS = BitConverter.ToUInt32(br_read(4), 0); - myHeader.CE = BitConverter.ToUInt32(br_read(4), 0); - myHeader.IE = BitConverter.ToUInt32(br_read(4), 0); - myHeader.ER = BitConverter.ToUInt32(br_read(4), 0); - myHeader.FR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.SLR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.GVR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.GFR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.PR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.ESR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.SR = BitConverter.ToUInt32(br_read(4), 0); - myHeader.NCE = BitConverter.ToUInt64(br_read(8), 0); - myHeader.NIE = BitConverter.ToUInt64(br_read(8), 0); - myHeader.NER = BitConverter.ToUInt64(br_read(8), 0); - - // Print Header Block to debug - SendToDebug("TM - Top of memory (size): " + myHeader.TM); - SendToDebug("IP - Instruction Pointer (0=not running): " + myHeader.IP); - SendToDebug("VN - Version number: " + myHeader.VN); - SendToDebug("BP - Local Frame Pointer: " + myHeader.BP); - SendToDebug("SP - Stack Pointer: " + myHeader.SP); - SendToDebug("HR - Heap Register: " + myHeader.HR); - SendToDebug("HP - Heap Pointer: " + myHeader.HP); - SendToDebug("CS - Current State: " + myHeader.CS); - SendToDebug("NS - Next State: " + myHeader.NS); - SendToDebug("CE - Current Events: " + myHeader.CE); - SendToDebug("IE - In Event: " + myHeader.IE); - SendToDebug("ER - Event Register: " + myHeader.ER); - SendToDebug("FR - Fault Register: " + myHeader.FR); - SendToDebug("SLR - Sleep Register: " + myHeader.SLR); - SendToDebug("GVR - Global Variable Register: " + myHeader.GVR); - SendToDebug("GFR - Global Function Register: " + myHeader.GFR); - SendToDebug("PR - Parameter Register: " + myHeader.PR); - SendToDebug("ESR - Energy Supply Register: " + myHeader.ESR); - SendToDebug("SR - State Register: " + myHeader.SR); - SendToDebug("NCE - 64-bit Current Events: " + myHeader.NCE); - SendToDebug("NIE - 64-bit In Events: " + myHeader.NIE); - SendToDebug("NER - 64-bit Event Register: " + myHeader.NER); - SendToDebug("Read position when exiting HEADER BLOCK: " + fs.Position); - - // STATIC BLOCK - SendToDebug("Reading STATIC BLOCK at: " + myHeader.GVR); - fs.Seek(myHeader.GVR, SeekOrigin.Begin); - int StaticBlockCount = 0; - // Read function blocks until we hit GFR - while (fs.Position < myHeader.GFR) - { - StaticBlockCount++; - SendToDebug("Reading Static Block " + StaticBlockCount + " at: " + fs.Position); - //fs.Seek(myHeader.GVR, SeekOrigin.Begin); - LSO_Struct.StaticBlock myStaticBlock = new LSO_Struct.StaticBlock(); - myStaticBlock.Static_Chunk_Header_Size = BitConverter.ToUInt32(br_read(4), 0); - myStaticBlock.ObjectType = br_read(1)[0]; - SendToDebug("Static Block ObjectType: " + ((LSO_Enums.Variable_Type_Codes)myStaticBlock.ObjectType).ToString()); - myStaticBlock.Unknown = br_read(1)[0]; - // Size of datatype varies - if (myStaticBlock.ObjectType != 0) - myStaticBlock.BlockVariable = br_read(getObjectSize(myStaticBlock.ObjectType)); - } - SendToDebug("Number of Static Blocks read: " + StaticBlockCount); - - - // FUNCTION BLOCK - // Always right after STATIC BLOCK - LSO_Struct.FunctionBlock myFunctionBlock = new LSO_Struct.FunctionBlock(); - if (myHeader.GFR == myHeader.SR) - { - // If GFR and SR are at same position then there is no fuction block - SendToDebug("No FUNCTION BLOCK found"); - } else { - SendToDebug("Reading FUNCTION BLOCK at: " + myHeader.GFR); - fs.Seek(myHeader.GFR, SeekOrigin.Begin); - myFunctionBlock.FunctionCount = BitConverter.ToUInt32(br_read(4), 0); - SendToDebug("Number of functions in Fuction Block: " + myFunctionBlock.FunctionCount); - if (myFunctionBlock.FunctionCount > 0) - { - myFunctionBlock.CodeChunkPointer = new UInt32[myFunctionBlock.FunctionCount]; - for (int i = 0; i < myFunctionBlock.FunctionCount; i++) - { - SendToDebug("Reading function " + i + " at: " + fs.Position); - // TODO: ADD TO FUNCTION LIST (How do we identify it later?) - // Note! Absolute position - myFunctionBlock.CodeChunkPointer[i] = BitConverter.ToUInt32(br_read(4), 0) + myHeader.GFR; - SendToDebug("Fuction " + i + " code chunk position: " + myFunctionBlock.CodeChunkPointer[i]); - } - } - } - - - // STATE FRAME BLOCK - // Always right after FUNCTION BLOCK - SendToDebug("Reading STATE BLOCK at: " + myHeader.SR); - fs.Seek(myHeader.SR, SeekOrigin.Begin); - LSO_Struct.StateFrameBlock myStateFrameBlock = new LSO_Struct.StateFrameBlock(); - myStateFrameBlock.StateCount = BitConverter.ToUInt32(br_read(4), 0); - if (myStateFrameBlock.StateCount > 0) - { - // Initialize array - myStateFrameBlock.StatePointer = new LSO_Struct.StatePointerBlock[myStateFrameBlock.StateCount]; - for (int i = 0; i < myStateFrameBlock.StateCount; i++) - { - SendToDebug("Reading STATE POINTER BLOCK " + (i+1) + " at: " + fs.Position); - // Position is relative to state frame - myStateFrameBlock.StatePointer[i].Location = myHeader.SR + BitConverter.ToUInt32(br_read(4), 0); - myStateFrameBlock.StatePointer[i].EventMask = new System.Collections.BitArray(br_read(8)); - SendToDebug("Pointer: " + myStateFrameBlock.StatePointer[i].Location); - SendToDebug("Total potential EventMask bits: " + myStateFrameBlock.StatePointer[i].EventMask.Count); - - //// Read STATE BLOCK - //long CurPos = fs.Position; - //fs.Seek(CurPos, SeekOrigin.Begin); - - } - } - - - // STATE BLOCK - // For each StateFrameBlock there is one StateBlock with multiple event handlers - - if (myStateFrameBlock.StateCount > 0) - { - // Go through all State Frame Pointers found - for (int i = 0; i < myStateFrameBlock.StateCount; i++) - { - - fs.Seek(myStateFrameBlock.StatePointer[i].Location, SeekOrigin.Begin); - SendToDebug("Reading STATE BLOCK " + (i + 1) + " at: " + fs.Position); - - // READ: STATE BLOCK HEADER - myStateFrameBlock.StatePointer[i].StateBlock = new LSO_Struct.StateBlock(); - myStateFrameBlock.StatePointer[i].StateBlock.StartPos = (UInt32)fs.Position; // Note - myStateFrameBlock.StatePointer[i].StateBlock.HeaderSize = BitConverter.ToUInt32(br_read(4), 0); - myStateFrameBlock.StatePointer[i].StateBlock.Unknown = br_read(1)[0]; - myStateFrameBlock.StatePointer[i].StateBlock.EndPos = (UInt32)fs.Position; // Note - SendToDebug("State block Start Pos: " + myStateFrameBlock.StatePointer[i].StateBlock.StartPos); - SendToDebug("State block Header Size: " + myStateFrameBlock.StatePointer[i].StateBlock.HeaderSize); - SendToDebug("State block Header End Pos: " + myStateFrameBlock.StatePointer[i].StateBlock.EndPos); - - // We need to count number of bits flagged in EventMask? - - - // for each bit in myStateFrameBlock.StatePointer[i].EventMask - - // ADDING TO ALL RIGHT NOW, SHOULD LIMIT TO ONLY THE ONES IN USE - //TODO: Create event hooks - myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers = new LSO_Struct.StateBlockHandler[myStateFrameBlock.StatePointer[i].EventMask.Count - 1]; - for (int ii = 0; ii < myStateFrameBlock.StatePointer[i].EventMask.Count - 1; ii++) - { - - if (myStateFrameBlock.StatePointer[i].EventMask.Get(ii) == true) - { - // We got an event - // READ: STATE BLOCK HANDLER - SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER matching EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") at: " + fs.Position); - myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer = myStateFrameBlock.StatePointer[i].StateBlock.EndPos + BitConverter.ToUInt32(br_read(4), 0); - myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CallFrameSize = BitConverter.ToUInt32(br_read(4), 0); - SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") Code Chunk Pointer: " + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer); - SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") Call Frame Size: " + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CallFrameSize ); - } - } - } - } - - - - - //// READ FUNCTION CODE CHUNKS - //// Functions + Function start pos (GFR) - //// TODO: Somehow be able to identify and reference this - //LSO_Struct.CodeChunk[] myFunctionCodeChunk; - //if (myFunctionBlock.FunctionCount > 0) - //{ - // myFunctionCodeChunk = new LSO_Struct.CodeChunk[myFunctionBlock.FunctionCount]; - // for (int i = 0; i < myFunctionBlock.FunctionCount; i++) - // { - // SendToDebug("Reading Function Code Chunk " + i); - // myFunctionCodeChunk[i] = GetCodeChunk((UInt32)myFunctionBlock.CodeChunkPointer[i]); - // } - - //} - // READ EVENT CODE CHUNKS - LSO_Struct.CodeChunk[] myEventCodeChunk; - if (myStateFrameBlock.StateCount > 0) - { - myEventCodeChunk = new LSO_Struct.CodeChunk[myStateFrameBlock.StateCount]; - for (int i = 0; i < myStateFrameBlock.StateCount; i++) - { - // TODO: Somehow organize events and functions so they can be found again, - // two level search ain't no good - for (int ii = 0; ii < myStateFrameBlock.StatePointer[i].EventMask.Count - 1; ii++) - { - - - if (myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer > 0) - { - SendToDebug("Reading Event Code Chunk state " + i + ", event " + (LSO_Enums.Event_Mask_Values)ii); - - - // Override a Method / Function - string eventname = "event_" + (LSO_Enums.Event_Mask_Values)ii; - SendToDebug("CLR:" + eventname + ":MethodBuilder methodBuilder = typeBuilder.DefineMethod..."); - MethodBuilder methodBuilder = typeBuilder.DefineMethod(eventname, - MethodAttributes.Private | MethodAttributes.Virtual, - typeof(void), - new Type[] { typeof(object) }); - - SendToDebug("CLR:" + eventname + ":typeBuilder.DefineMethodOverride(methodBuilder..."); - typeBuilder.DefineMethodOverride(methodBuilder, - typeof(LSL_CLRInterface.LSLScript).GetMethod(eventname)); - - // Create the IL generator - - SendToDebug("CLR:" + eventname + ":ILGenerator il = methodBuilder.GetILGenerator();"); - ILGenerator il = methodBuilder.GetILGenerator(); - - - LSO_Struct.CodeChunk myECC = - GetCodeChunk(myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer, il, eventname); - } - - } - } - - } - - - // Close - br.Close(); - fs.Close(); - - } - - private LSO_Struct.HeapBlock GetHeap(UInt32 pos) - { - // HEAP BLOCK - // TODO:? Special read for strings/keys (null terminated) and lists (pointers to other HEAP entries) - SendToDebug("Reading HEAP BLOCK at: " + pos); - fs.Seek(pos, SeekOrigin.Begin); - - LSO_Struct.HeapBlock myHeapBlock = new LSO_Struct.HeapBlock(); - myHeapBlock.DataBlockSize = BitConverter.ToUInt32(br_read(4), 0); - myHeapBlock.ObjectType = br_read(1)[0]; - myHeapBlock.ReferenceCount = BitConverter.ToUInt16(br_read(2), 0); - myHeapBlock.Data = br_read(getObjectSize(myHeapBlock.ObjectType)); - - SendToDebug("Heap Block Data Block Size: " + myHeapBlock.DataBlockSize); - SendToDebug("Heap Block ObjectType: " + ((LSO_Enums.Variable_Type_Codes)myHeapBlock.ObjectType).ToString()); - SendToDebug("Heap Block Reference Count: " + myHeapBlock.ReferenceCount); - - return myHeapBlock; - } - - - - private byte[] br_read(int len) - { - if (len <= 0) - return null; - - try - { - byte[] bytes = new byte[len]; - for (int i = len - 1; i > -1; i--) - bytes[i] = br.ReadByte(); - return bytes; - } - catch (Exception e) - { - SendToDebug("Exception: " + e.ToString()); - throw (e); - } - } - //private byte[] br_read_smallendian(int len) - //{ - // byte[] bytes = new byte[len]; - // br.Read(bytes,0, len); - // return bytes; - //} - - private int getObjectSize(byte ObjectType) - { - switch (ObjectType) - { - case 1: - case 2: - case 3: - case 4: - case 7: - return 4; - case 5: - return 12; - case 6: - return 16; - default: - return 0; - } - } - private void SendToDebug(string Message) - { - if (Debug == true) - Console.WriteLine("Debug: " + Message); - } - - - private string Read_String() - { - string ret = ""; - byte reader = br_read(1)[0]; - while (reader != 0x000) - { - ret += (char)reader; - reader = br_read(1)[0]; - } - return ret; - } - - /// - /// Reads a code chunk into structure and returns it. - /// - /// Absolute position in file. REMEMBER TO ADD myHeader.GFR! - /// - private LSO_Struct.CodeChunk GetCodeChunk(UInt32 pos, ILGenerator il, string eventname) - { - - /* - * CLR TRY - */ - //SendToDebug("CLR:" + eventname + ":il.BeginExceptionBlock()"); - il.BeginExceptionBlock(); - - // Push "Hello World!" string to stack - //SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Ldstr..."); - il.Emit(OpCodes.Ldstr, "Starting CLR dynamic execution of: " + eventname); - - // Push Console.WriteLine command to stack ... Console.WriteLine("Hello World!"); - //SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("WriteLine", new Type[] { typeof(string) })); - - - LSO_Struct.CodeChunk myCodeChunk = new LSO_Struct.CodeChunk(); - - SendToDebug("Reading Function Code Chunk at: " + pos); - fs.Seek(pos, SeekOrigin.Begin); - myCodeChunk.CodeChunkHeaderSize = BitConverter.ToUInt32(br_read(4), 0); - SendToDebug("CodeChunk Header Size: " + myCodeChunk.CodeChunkHeaderSize ); - // Read until null - myCodeChunk.Comment = Read_String(); - SendToDebug("Function comment: " + myCodeChunk.Comment); - myCodeChunk.ReturnType = br_read(1)[0]; - SendToDebug("Return type: " + (LSO_Enums.Variable_Type_Codes)myCodeChunk.ReturnType); - // TODO: How to determine number of codechunks -- does this method work? - myCodeChunk.CodeChunkArguments = new System.Collections.Generic.List(); - byte reader = br_read(1)[0]; - reader = br_read(1)[0]; - int ccount = 0; - while (reader != 0x000) - { - ccount++; - SendToDebug("Reading Code Chunk Argument " + ccount); - LSO_Struct.CodeChunkArgument CCA = new LSO_Struct.CodeChunkArgument(); - CCA.FunctionReturnType = reader; - reader = br_read(1)[0]; - CCA.NullString = reader; - myCodeChunk.CodeChunkArguments.Add(CCA); - SendToDebug("Code Chunk Argument " + ccount + " return type: " + (LSO_Enums.Variable_Type_Codes)CCA.FunctionReturnType); - } - // End marker is 0x000 - myCodeChunk.EndMarker = reader; - // TODO: How to read and identify following code - // TODO: Code is read until a return of some sort is found - bool FoundRet = false; - while (FoundRet == false) - { - //reader = br_read(1)[0]; - //UInt16 opcode = BitConverter.ToUInt16(br_read(1),0); - UInt16 opcode = br_read(1)[0]; - //long rPos = fs.Position; - SendToDebug("OPCODE: " + ((LSO_Enums.Operation_Table)opcode).ToString()); - switch (opcode) - { - // LONG - case (UInt16)LSO_Enums.Operation_Table.POPARG: - case (UInt16)LSO_Enums.Operation_Table.STORE: - case (UInt16)LSO_Enums.Operation_Table.STORES: - case (UInt16)LSO_Enums.Operation_Table.STOREL: - case (UInt16)LSO_Enums.Operation_Table.STOREV: - case (UInt16)LSO_Enums.Operation_Table.STOREQ: - case (UInt16)LSO_Enums.Operation_Table.STOREG: - case (UInt16)LSO_Enums.Operation_Table.STOREGS: - case (UInt16)LSO_Enums.Operation_Table.STOREGL: - case (UInt16)LSO_Enums.Operation_Table.STOREGV: - case (UInt16)LSO_Enums.Operation_Table.STOREGQ: - case (UInt16)LSO_Enums.Operation_Table.LOADP: - case (UInt16)LSO_Enums.Operation_Table.LOADSP: - case (UInt16)LSO_Enums.Operation_Table.LOADLP: - case (UInt16)LSO_Enums.Operation_Table.LOADVP: - case (UInt16)LSO_Enums.Operation_Table.LOADQP: - case (UInt16)LSO_Enums.Operation_Table.PUSH: - case (UInt16)LSO_Enums.Operation_Table.PUSHS: - case (UInt16)LSO_Enums.Operation_Table.PUSHL: - case (UInt16)LSO_Enums.Operation_Table.PUSHV: - case (UInt16)LSO_Enums.Operation_Table.PUSHQ: - case (UInt16)LSO_Enums.Operation_Table.PUSHG: - case (UInt16)LSO_Enums.Operation_Table.PUSHGS: - case (UInt16)LSO_Enums.Operation_Table.PUSHGL: - case (UInt16)LSO_Enums.Operation_Table.PUSHGV: - case (UInt16)LSO_Enums.Operation_Table.PUSHGQ: - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // BYTE - case (UInt16)LSO_Enums.Operation_Table.PUSHARGB: - SendToDebug("Param1: " + br_read(1)[0]); - break; - // INTEGER - case (UInt16)LSO_Enums.Operation_Table.PUSHARGI: - // TODO: What is size of integer? - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // FLOAT - case (UInt16)LSO_Enums.Operation_Table.PUSHARGF: - // TODO: What is size of float? - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // STRING - case (UInt16)LSO_Enums.Operation_Table.PUSHARGS: - string s = Read_String(); - SendToDebug("Param1: " + s); - il.Emit(OpCodes.Ldstr, s); - break; - // VECTOR z,y,x - case (UInt16)LSO_Enums.Operation_Table.PUSHARGV: - SendToDebug("Param1 Z: " + BitConverter.ToUInt32(br_read(4),0)); - SendToDebug("Param1 Y: " + BitConverter.ToUInt32(br_read(4),0)); - SendToDebug("Param1 X: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // ROTATION s,z,y,x - case (UInt16)LSO_Enums.Operation_Table.PUSHARGQ: - SendToDebug("Param1 S: " + BitConverter.ToUInt32(br_read(4),0)); - SendToDebug("Param1 Z: " + BitConverter.ToUInt32(br_read(4),0)); - SendToDebug("Param1 Y: " + BitConverter.ToUInt32(br_read(4),0)); - SendToDebug("Param1 X: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // LONG - case (UInt16)LSO_Enums.Operation_Table.PUSHARGE: - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // BYTE - case (UInt16)LSO_Enums.Operation_Table.ADD: - case (UInt16)LSO_Enums.Operation_Table.SUB: - case (UInt16)LSO_Enums.Operation_Table.MUL: - case (UInt16)LSO_Enums.Operation_Table.DIV: - case (UInt16)LSO_Enums.Operation_Table.MOD: - case (UInt16)LSO_Enums.Operation_Table.EQ: - case (UInt16)LSO_Enums.Operation_Table.NEQ: - case (UInt16)LSO_Enums.Operation_Table.LEQ: - case (UInt16)LSO_Enums.Operation_Table.GEQ: - case (UInt16)LSO_Enums.Operation_Table.LESS: - case (UInt16)LSO_Enums.Operation_Table.GREATER: - case (UInt16)LSO_Enums.Operation_Table.BOOLOR: - SendToDebug("Param1: " + br_read(1)[0]); - break; - // LONG - case (UInt16)LSO_Enums.Operation_Table.JUMP: - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // BYTE, LONG - case (UInt16)LSO_Enums.Operation_Table.JUMPIF: - case (UInt16)LSO_Enums.Operation_Table.JUMPNIF: - SendToDebug("Param1: " + br_read(1)[0]); - SendToDebug("Param2: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // LONG - case (UInt16)LSO_Enums.Operation_Table.STATE: - case (UInt16)LSO_Enums.Operation_Table.CALL: - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // BYTE - case (UInt16)LSO_Enums.Operation_Table.CAST: - SendToDebug("Param1: " + br_read(1)[0]); - break; - // LONG - case (UInt16)LSO_Enums.Operation_Table.STACKTOS: - case (UInt16)LSO_Enums.Operation_Table.STACKTOL: - SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); - break; - // BYTE - case (UInt16)LSO_Enums.Operation_Table.PRINT: - case (UInt16)LSO_Enums.Operation_Table.CALLLIB: - SendToDebug("Param1: " + br_read(1)[0]); - break; - // SHORT - case (UInt16)LSO_Enums.Operation_Table.CALLLIB_TWO_BYTE: - // TODO: What is size of short? - UInt16 _i = BitConverter.ToUInt16(br_read(2), 0); - SendToDebug("Param1: " + _i); - switch (_i) - { - case (UInt16)LSO_Enums.BuiltIn_Functions.llSay: - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("WriteLine", new Type[] { typeof(string) })); - break; - } - break; - - - // RETURN - case (UInt16)LSO_Enums.Operation_Table.RETURN: - SendToDebug("Last OPCODE was return command. Code chunk execution complete."); - FoundRet = true; - break; - } - //fs.Seek(rPos, SeekOrigin.Begin); - - } - - - /* - * CATCH - */ - SendToDebug("CLR:" + eventname + ":il.BeginCatchBlock(typeof(Exception));"); - il.BeginCatchBlock(typeof(Exception)); - - // Push "Hello World!" string to stack - SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Ldstr..."); - il.Emit(OpCodes.Ldstr, "Execption executing dynamic CLR function " + eventname + ": "); - - //call void [mscorlib]System.Console::WriteLine(string) - SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("Write", new Type[] { typeof(string) })); - - //callvirt instance string [mscorlib]System.Exception::get_Message() - SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Callvirt..."); - il.Emit(OpCodes.Callvirt, typeof(Exception).GetMethod - ("get_Message")); - - //call void [mscorlib]System.Console::WriteLine(string) - SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); - il.Emit(OpCodes.Call, typeof(Console).GetMethod - ("WriteLine", new Type[] { typeof(string) })); - - /* - * CLR END TRY - */ - //SendToDebug("CLR:" + eventname + ":il.EndExceptionBlock();"); - il.EndExceptionBlock(); - // Push "Return from current method, with return value if present" to stack - il.Emit(OpCodes.Ret); - - - - return myCodeChunk; - - } - } -} + using System; + using System.Collections.Generic; + using System.Text; + using System.IO; + using System.Reflection; + using System.Reflection.Emit; +using OpenSim.Region.Scripting; + + namespace OpenSim.ScriptEngines.LSL + { + class LSO_Parser + { + private bool Debug = true; + private FileStream fs; + private BinaryReader br; + private LSO_Struct.Header myHeader; + + private TypeBuilder typeBuilder; + private ScriptInfo WorldAPI; + + /// + /// Parse LSO file. + /// Reads LSO ByteCode into memory structures. + /// TODO: What else does it do? + /// + /// FileName of LSO ByteCode file + public void ParseFile(string FileName, ScriptInfo _WorldAPI, ref TypeBuilder _typeBuilder) + { + typeBuilder = _typeBuilder; + WorldAPI = _WorldAPI; + // Open + SendToDebug("Opening filename: " + FileName); + fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read); + br = new BinaryReader(fs, Encoding.BigEndianUnicode); + + + // The LSO Format consist of 6 major blocks: header, statics, functions, states, heap, and stack. + + + // HEADER BLOCK + SendToDebug("Reading HEADER BLOCK at: 0"); + fs.Seek(0, SeekOrigin.Begin); + myHeader = new LSO_Struct.Header(); + myHeader.TM = BitConverter.ToUInt32(br_read(4), 0); + myHeader.IP = BitConverter.ToUInt32(br_read(4), 0); + myHeader.VN = BitConverter.ToUInt32(br_read(4), 0); + myHeader.BP = BitConverter.ToUInt32(br_read(4), 0); + myHeader.SP = BitConverter.ToUInt32(br_read(4), 0); + myHeader.HR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.HP = BitConverter.ToUInt32(br_read(4), 0); + myHeader.CS = BitConverter.ToUInt32(br_read(4), 0); + myHeader.NS = BitConverter.ToUInt32(br_read(4), 0); + myHeader.CE = BitConverter.ToUInt32(br_read(4), 0); + myHeader.IE = BitConverter.ToUInt32(br_read(4), 0); + myHeader.ER = BitConverter.ToUInt32(br_read(4), 0); + myHeader.FR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.SLR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.GVR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.GFR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.PR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.ESR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.SR = BitConverter.ToUInt32(br_read(4), 0); + myHeader.NCE = BitConverter.ToUInt64(br_read(8), 0); + myHeader.NIE = BitConverter.ToUInt64(br_read(8), 0); + myHeader.NER = BitConverter.ToUInt64(br_read(8), 0); + + // Print Header Block to debug + SendToDebug("TM - Top of memory (size): " + myHeader.TM); + SendToDebug("IP - Instruction Pointer (0=not running): " + myHeader.IP); + SendToDebug("VN - Version number: " + myHeader.VN); + SendToDebug("BP - Local Frame Pointer: " + myHeader.BP); + SendToDebug("SP - Stack Pointer: " + myHeader.SP); + SendToDebug("HR - Heap Register: " + myHeader.HR); + SendToDebug("HP - Heap Pointer: " + myHeader.HP); + SendToDebug("CS - Current State: " + myHeader.CS); + SendToDebug("NS - Next State: " + myHeader.NS); + SendToDebug("CE - Current Events: " + myHeader.CE); + SendToDebug("IE - In Event: " + myHeader.IE); + SendToDebug("ER - Event Register: " + myHeader.ER); + SendToDebug("FR - Fault Register: " + myHeader.FR); + SendToDebug("SLR - Sleep Register: " + myHeader.SLR); + SendToDebug("GVR - Global Variable Register: " + myHeader.GVR); + SendToDebug("GFR - Global Function Register: " + myHeader.GFR); + SendToDebug("PR - Parameter Register: " + myHeader.PR); + SendToDebug("ESR - Energy Supply Register: " + myHeader.ESR); + SendToDebug("SR - State Register: " + myHeader.SR); + SendToDebug("NCE - 64-bit Current Events: " + myHeader.NCE); + SendToDebug("NIE - 64-bit In Events: " + myHeader.NIE); + SendToDebug("NER - 64-bit Event Register: " + myHeader.NER); + SendToDebug("Read position when exiting HEADER BLOCK: " + fs.Position); + + // STATIC BLOCK + SendToDebug("Reading STATIC BLOCK at: " + myHeader.GVR); + fs.Seek(myHeader.GVR, SeekOrigin.Begin); + int StaticBlockCount = 0; + // Read function blocks until we hit GFR + while (fs.Position < myHeader.GFR) + { + StaticBlockCount++; + SendToDebug("Reading Static Block " + StaticBlockCount + " at: " + fs.Position); + //fs.Seek(myHeader.GVR, SeekOrigin.Begin); + LSO_Struct.StaticBlock myStaticBlock = new LSO_Struct.StaticBlock(); + myStaticBlock.Static_Chunk_Header_Size = BitConverter.ToUInt32(br_read(4), 0); + myStaticBlock.ObjectType = br_read(1)[0]; + SendToDebug("Static Block ObjectType: " + ((LSO_Enums.Variable_Type_Codes)myStaticBlock.ObjectType).ToString()); + myStaticBlock.Unknown = br_read(1)[0]; + // Size of datatype varies + if (myStaticBlock.ObjectType != 0) + myStaticBlock.BlockVariable = br_read(getObjectSize(myStaticBlock.ObjectType)); + } + SendToDebug("Number of Static Blocks read: " + StaticBlockCount); + + + // FUNCTION BLOCK + // Always right after STATIC BLOCK + LSO_Struct.FunctionBlock myFunctionBlock = new LSO_Struct.FunctionBlock(); + if (myHeader.GFR == myHeader.SR) + { + // If GFR and SR are at same position then there is no fuction block + SendToDebug("No FUNCTION BLOCK found"); + } else { + SendToDebug("Reading FUNCTION BLOCK at: " + myHeader.GFR); + fs.Seek(myHeader.GFR, SeekOrigin.Begin); + myFunctionBlock.FunctionCount = BitConverter.ToUInt32(br_read(4), 0); + SendToDebug("Number of functions in Fuction Block: " + myFunctionBlock.FunctionCount); + if (myFunctionBlock.FunctionCount > 0) + { + myFunctionBlock.CodeChunkPointer = new UInt32[myFunctionBlock.FunctionCount]; + for (int i = 0; i < myFunctionBlock.FunctionCount; i++) + { + SendToDebug("Reading function " + i + " at: " + fs.Position); + // TODO: ADD TO FUNCTION LIST (How do we identify it later?) + // Note! Absolute position + myFunctionBlock.CodeChunkPointer[i] = BitConverter.ToUInt32(br_read(4), 0) + myHeader.GFR; + SendToDebug("Fuction " + i + " code chunk position: " + myFunctionBlock.CodeChunkPointer[i]); + } + } + } + + + // STATE FRAME BLOCK + // Always right after FUNCTION BLOCK + SendToDebug("Reading STATE BLOCK at: " + myHeader.SR); + fs.Seek(myHeader.SR, SeekOrigin.Begin); + LSO_Struct.StateFrameBlock myStateFrameBlock = new LSO_Struct.StateFrameBlock(); + myStateFrameBlock.StateCount = BitConverter.ToUInt32(br_read(4), 0); + if (myStateFrameBlock.StateCount > 0) + { + // Initialize array + myStateFrameBlock.StatePointer = new LSO_Struct.StatePointerBlock[myStateFrameBlock.StateCount]; + for (int i = 0; i < myStateFrameBlock.StateCount; i++) + { + SendToDebug("Reading STATE POINTER BLOCK " + (i+1) + " at: " + fs.Position); + // Position is relative to state frame + myStateFrameBlock.StatePointer[i].Location = myHeader.SR + BitConverter.ToUInt32(br_read(4), 0); + myStateFrameBlock.StatePointer[i].EventMask = new System.Collections.BitArray(br_read(8)); + SendToDebug("Pointer: " + myStateFrameBlock.StatePointer[i].Location); + SendToDebug("Total potential EventMask bits: " + myStateFrameBlock.StatePointer[i].EventMask.Count); + + //// Read STATE BLOCK + //long CurPos = fs.Position; + //fs.Seek(CurPos, SeekOrigin.Begin); + + } + } + + + // STATE BLOCK + // For each StateFrameBlock there is one StateBlock with multiple event handlers + + if (myStateFrameBlock.StateCount > 0) + { + // Go through all State Frame Pointers found + for (int i = 0; i < myStateFrameBlock.StateCount; i++) + { + + fs.Seek(myStateFrameBlock.StatePointer[i].Location, SeekOrigin.Begin); + SendToDebug("Reading STATE BLOCK " + (i + 1) + " at: " + fs.Position); + + // READ: STATE BLOCK HEADER + myStateFrameBlock.StatePointer[i].StateBlock = new LSO_Struct.StateBlock(); + myStateFrameBlock.StatePointer[i].StateBlock.StartPos = (UInt32)fs.Position; // Note + myStateFrameBlock.StatePointer[i].StateBlock.HeaderSize = BitConverter.ToUInt32(br_read(4), 0); + myStateFrameBlock.StatePointer[i].StateBlock.Unknown = br_read(1)[0]; + myStateFrameBlock.StatePointer[i].StateBlock.EndPos = (UInt32)fs.Position; // Note + SendToDebug("State block Start Pos: " + myStateFrameBlock.StatePointer[i].StateBlock.StartPos); + SendToDebug("State block Header Size: " + myStateFrameBlock.StatePointer[i].StateBlock.HeaderSize); + SendToDebug("State block Header End Pos: " + myStateFrameBlock.StatePointer[i].StateBlock.EndPos); + + // We need to count number of bits flagged in EventMask? + + + // for each bit in myStateFrameBlock.StatePointer[i].EventMask + + // ADDING TO ALL RIGHT NOW, SHOULD LIMIT TO ONLY THE ONES IN USE + //TODO: Create event hooks + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers = new LSO_Struct.StateBlockHandler[myStateFrameBlock.StatePointer[i].EventMask.Count - 1]; + for (int ii = 0; ii < myStateFrameBlock.StatePointer[i].EventMask.Count - 1; ii++) + { + + if (myStateFrameBlock.StatePointer[i].EventMask.Get(ii) == true) + { + // We got an event + // READ: STATE BLOCK HANDLER + SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER matching EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") at: " + fs.Position); + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer = myStateFrameBlock.StatePointer[i].StateBlock.EndPos + BitConverter.ToUInt32(br_read(4), 0); + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CallFrameSize = BitConverter.ToUInt32(br_read(4), 0); + SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") Code Chunk Pointer: " + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer); + SendToDebug("Reading STATE BLOCK " + (i + 1) + " HANDLER EVENT MASK " + ii + " (" + ((LSO_Enums.Event_Mask_Values)ii).ToString() + ") Call Frame Size: " + myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CallFrameSize ); + } + } + } + } + + + + + //// READ FUNCTION CODE CHUNKS + //// Functions + Function start pos (GFR) + //// TODO: Somehow be able to identify and reference this + //LSO_Struct.CodeChunk[] myFunctionCodeChunk; + //if (myFunctionBlock.FunctionCount > 0) + //{ + // myFunctionCodeChunk = new LSO_Struct.CodeChunk[myFunctionBlock.FunctionCount]; + // for (int i = 0; i < myFunctionBlock.FunctionCount; i++) + // { + // SendToDebug("Reading Function Code Chunk " + i); + // myFunctionCodeChunk[i] = GetCodeChunk((UInt32)myFunctionBlock.CodeChunkPointer[i]); + // } + + //} + // READ EVENT CODE CHUNKS + LSO_Struct.CodeChunk[] myEventCodeChunk; + if (myStateFrameBlock.StateCount > 0) + { + myEventCodeChunk = new LSO_Struct.CodeChunk[myStateFrameBlock.StateCount]; + for (int i = 0; i < myStateFrameBlock.StateCount; i++) + { + // TODO: Somehow organize events and functions so they can be found again, + // two level search ain't no good + for (int ii = 0; ii < myStateFrameBlock.StatePointer[i].EventMask.Count - 1; ii++) + { + + + if (myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer > 0) + { + SendToDebug("Reading Event Code Chunk state " + i + ", event " + (LSO_Enums.Event_Mask_Values)ii); + + + // Override a Method / Function + string eventname = "event_" + (LSO_Enums.Event_Mask_Values)ii; + SendToDebug("CLR:" + eventname + ":MethodBuilder methodBuilder = typeBuilder.DefineMethod..."); + MethodBuilder methodBuilder = typeBuilder.DefineMethod(eventname, + MethodAttributes.Private | MethodAttributes.Virtual, + typeof(void), + new Type[] { typeof(object) }); + + SendToDebug("CLR:" + eventname + ":typeBuilder.DefineMethodOverride(methodBuilder..."); + typeBuilder.DefineMethodOverride(methodBuilder, + typeof(LSL_CLRInterface.LSLScript).GetMethod(eventname)); + + // Create the IL generator + + SendToDebug("CLR:" + eventname + ":ILGenerator il = methodBuilder.GetILGenerator();"); + ILGenerator il = methodBuilder.GetILGenerator(); + + + LSO_Struct.CodeChunk myECC = + GetCodeChunk(myStateFrameBlock.StatePointer[i].StateBlock.StateBlockHandlers[ii].CodeChunkPointer, il, eventname); + } + + } + } + + } + + + // Close + br.Close(); + fs.Close(); + + } + + private LSO_Struct.HeapBlock GetHeap(UInt32 pos) + { + // HEAP BLOCK + // TODO:? Special read for strings/keys (null terminated) and lists (pointers to other HEAP entries) + SendToDebug("Reading HEAP BLOCK at: " + pos); + fs.Seek(pos, SeekOrigin.Begin); + + LSO_Struct.HeapBlock myHeapBlock = new LSO_Struct.HeapBlock(); + myHeapBlock.DataBlockSize = BitConverter.ToUInt32(br_read(4), 0); + myHeapBlock.ObjectType = br_read(1)[0]; + myHeapBlock.ReferenceCount = BitConverter.ToUInt16(br_read(2), 0); + myHeapBlock.Data = br_read(getObjectSize(myHeapBlock.ObjectType)); + + SendToDebug("Heap Block Data Block Size: " + myHeapBlock.DataBlockSize); + SendToDebug("Heap Block ObjectType: " + ((LSO_Enums.Variable_Type_Codes)myHeapBlock.ObjectType).ToString()); + SendToDebug("Heap Block Reference Count: " + myHeapBlock.ReferenceCount); + + return myHeapBlock; + } + + + + private byte[] br_read(int len) + { + if (len <= 0) + return null; + + try + { + byte[] bytes = new byte[len]; + for (int i = len - 1; i > -1; i--) + bytes[i] = br.ReadByte(); + return bytes; + } + catch (Exception e) + { + SendToDebug("Exception: " + e.ToString()); + throw (e); + } + } + //private byte[] br_read_smallendian(int len) + //{ + // byte[] bytes = new byte[len]; + // br.Read(bytes,0, len); + // return bytes; + //} + + private int getObjectSize(byte ObjectType) + { + switch (ObjectType) + { + case 1: + case 2: + case 3: + case 4: + case 7: + return 4; + case 5: + return 12; + case 6: + return 16; + default: + return 0; + } + } + private void SendToDebug(string Message) + { + if (Debug == true) + Console.WriteLine("Debug: " + Message); + } + + + private string Read_String() + { + string ret = ""; + byte reader = br_read(1)[0]; + while (reader != 0x000) + { + ret += (char)reader; + reader = br_read(1)[0]; + } + return ret; + } + + /// + /// Reads a code chunk into structure and returns it. + /// + /// Absolute position in file. REMEMBER TO ADD myHeader.GFR! + /// + private LSO_Struct.CodeChunk GetCodeChunk(UInt32 pos, ILGenerator il, string eventname) + { + + /* + * CLR TRY + */ + //SendToDebug("CLR:" + eventname + ":il.BeginExceptionBlock()"); + il.BeginExceptionBlock(); + + // Push "Hello World!" string to stack + //SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Ldstr..."); + il.Emit(OpCodes.Ldstr, "Starting CLR dynamic execution of: " + eventname); + + // Push Console.WriteLine command to stack ... Console.WriteLine("Hello World!"); + //SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("WriteLine", new Type[] { typeof(string) })); + + + LSO_Struct.CodeChunk myCodeChunk = new LSO_Struct.CodeChunk(); + + SendToDebug("Reading Function Code Chunk at: " + pos); + fs.Seek(pos, SeekOrigin.Begin); + myCodeChunk.CodeChunkHeaderSize = BitConverter.ToUInt32(br_read(4), 0); + SendToDebug("CodeChunk Header Size: " + myCodeChunk.CodeChunkHeaderSize ); + // Read until null + myCodeChunk.Comment = Read_String(); + SendToDebug("Function comment: " + myCodeChunk.Comment); + myCodeChunk.ReturnType = br_read(1)[0]; + SendToDebug("Return type: " + (LSO_Enums.Variable_Type_Codes)myCodeChunk.ReturnType); + // TODO: How to determine number of codechunks -- does this method work? + myCodeChunk.CodeChunkArguments = new System.Collections.Generic.List(); + byte reader = br_read(1)[0]; + reader = br_read(1)[0]; + int ccount = 0; + while (reader != 0x000) + { + ccount++; + SendToDebug("Reading Code Chunk Argument " + ccount); + LSO_Struct.CodeChunkArgument CCA = new LSO_Struct.CodeChunkArgument(); + CCA.FunctionReturnType = reader; + reader = br_read(1)[0]; + CCA.NullString = reader; + myCodeChunk.CodeChunkArguments.Add(CCA); + SendToDebug("Code Chunk Argument " + ccount + " return type: " + (LSO_Enums.Variable_Type_Codes)CCA.FunctionReturnType); + } + // End marker is 0x000 + myCodeChunk.EndMarker = reader; + // TODO: How to read and identify following code + // TODO: Code is read until a return of some sort is found + bool FoundRet = false; + while (FoundRet == false) + { + //reader = br_read(1)[0]; + //UInt16 opcode = BitConverter.ToUInt16(br_read(1),0); + UInt16 opcode = br_read(1)[0]; + //long rPos = fs.Position; + SendToDebug("OPCODE: " + ((LSO_Enums.Operation_Table)opcode).ToString()); + switch (opcode) + { + // LONG + case (UInt16)LSO_Enums.Operation_Table.POPARG: + case (UInt16)LSO_Enums.Operation_Table.STORE: + case (UInt16)LSO_Enums.Operation_Table.STORES: + case (UInt16)LSO_Enums.Operation_Table.STOREL: + case (UInt16)LSO_Enums.Operation_Table.STOREV: + case (UInt16)LSO_Enums.Operation_Table.STOREQ: + case (UInt16)LSO_Enums.Operation_Table.STOREG: + case (UInt16)LSO_Enums.Operation_Table.STOREGS: + case (UInt16)LSO_Enums.Operation_Table.STOREGL: + case (UInt16)LSO_Enums.Operation_Table.STOREGV: + case (UInt16)LSO_Enums.Operation_Table.STOREGQ: + case (UInt16)LSO_Enums.Operation_Table.LOADP: + case (UInt16)LSO_Enums.Operation_Table.LOADSP: + case (UInt16)LSO_Enums.Operation_Table.LOADLP: + case (UInt16)LSO_Enums.Operation_Table.LOADVP: + case (UInt16)LSO_Enums.Operation_Table.LOADQP: + case (UInt16)LSO_Enums.Operation_Table.PUSH: + case (UInt16)LSO_Enums.Operation_Table.PUSHS: + case (UInt16)LSO_Enums.Operation_Table.PUSHL: + case (UInt16)LSO_Enums.Operation_Table.PUSHV: + case (UInt16)LSO_Enums.Operation_Table.PUSHQ: + case (UInt16)LSO_Enums.Operation_Table.PUSHG: + case (UInt16)LSO_Enums.Operation_Table.PUSHGS: + case (UInt16)LSO_Enums.Operation_Table.PUSHGL: + case (UInt16)LSO_Enums.Operation_Table.PUSHGV: + case (UInt16)LSO_Enums.Operation_Table.PUSHGQ: + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // BYTE + case (UInt16)LSO_Enums.Operation_Table.PUSHARGB: + SendToDebug("Param1: " + br_read(1)[0]); + break; + // INTEGER + case (UInt16)LSO_Enums.Operation_Table.PUSHARGI: + // TODO: What is size of integer? + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // FLOAT + case (UInt16)LSO_Enums.Operation_Table.PUSHARGF: + // TODO: What is size of float? + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // STRING + case (UInt16)LSO_Enums.Operation_Table.PUSHARGS: + string s = Read_String(); + SendToDebug("Param1: " + s); + il.Emit(OpCodes.Ldstr, s); + break; + // VECTOR z,y,x + case (UInt16)LSO_Enums.Operation_Table.PUSHARGV: + SendToDebug("Param1 Z: " + BitConverter.ToUInt32(br_read(4),0)); + SendToDebug("Param1 Y: " + BitConverter.ToUInt32(br_read(4),0)); + SendToDebug("Param1 X: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // ROTATION s,z,y,x + case (UInt16)LSO_Enums.Operation_Table.PUSHARGQ: + SendToDebug("Param1 S: " + BitConverter.ToUInt32(br_read(4),0)); + SendToDebug("Param1 Z: " + BitConverter.ToUInt32(br_read(4),0)); + SendToDebug("Param1 Y: " + BitConverter.ToUInt32(br_read(4),0)); + SendToDebug("Param1 X: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // LONG + case (UInt16)LSO_Enums.Operation_Table.PUSHARGE: + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // BYTE + case (UInt16)LSO_Enums.Operation_Table.ADD: + case (UInt16)LSO_Enums.Operation_Table.SUB: + case (UInt16)LSO_Enums.Operation_Table.MUL: + case (UInt16)LSO_Enums.Operation_Table.DIV: + case (UInt16)LSO_Enums.Operation_Table.MOD: + case (UInt16)LSO_Enums.Operation_Table.EQ: + case (UInt16)LSO_Enums.Operation_Table.NEQ: + case (UInt16)LSO_Enums.Operation_Table.LEQ: + case (UInt16)LSO_Enums.Operation_Table.GEQ: + case (UInt16)LSO_Enums.Operation_Table.LESS: + case (UInt16)LSO_Enums.Operation_Table.GREATER: + case (UInt16)LSO_Enums.Operation_Table.BOOLOR: + SendToDebug("Param1: " + br_read(1)[0]); + break; + // LONG + case (UInt16)LSO_Enums.Operation_Table.JUMP: + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // BYTE, LONG + case (UInt16)LSO_Enums.Operation_Table.JUMPIF: + case (UInt16)LSO_Enums.Operation_Table.JUMPNIF: + SendToDebug("Param1: " + br_read(1)[0]); + SendToDebug("Param2: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // LONG + case (UInt16)LSO_Enums.Operation_Table.STATE: + case (UInt16)LSO_Enums.Operation_Table.CALL: + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // BYTE + case (UInt16)LSO_Enums.Operation_Table.CAST: + SendToDebug("Param1: " + br_read(1)[0]); + break; + // LONG + case (UInt16)LSO_Enums.Operation_Table.STACKTOS: + case (UInt16)LSO_Enums.Operation_Table.STACKTOL: + SendToDebug("Param1: " + BitConverter.ToUInt32(br_read(4),0)); + break; + // BYTE + case (UInt16)LSO_Enums.Operation_Table.PRINT: + case (UInt16)LSO_Enums.Operation_Table.CALLLIB: + SendToDebug("Param1: " + br_read(1)[0]); + break; + // SHORT + case (UInt16)LSO_Enums.Operation_Table.CALLLIB_TWO_BYTE: + // TODO: What is size of short? + UInt16 _i = BitConverter.ToUInt16(br_read(2), 0); + SendToDebug("Param1: " + _i); + switch (_i) + { + case (UInt16)LSO_Enums.BuiltIn_Functions.llSay: + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("WriteLine", new Type[] { typeof(string) })); + break; + } + break; + + + // RETURN + case (UInt16)LSO_Enums.Operation_Table.RETURN: + SendToDebug("Last OPCODE was return command. Code chunk execution complete."); + FoundRet = true; + break; + } + //fs.Seek(rPos, SeekOrigin.Begin); + + } + + + /* + * CATCH + */ + SendToDebug("CLR:" + eventname + ":il.BeginCatchBlock(typeof(Exception));"); + il.BeginCatchBlock(typeof(Exception)); + + // Push "Hello World!" string to stack + SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Ldstr..."); + il.Emit(OpCodes.Ldstr, "Execption executing dynamic CLR function " + eventname + ": "); + + //call void [mscorlib]System.Console::WriteLine(string) + SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("Write", new Type[] { typeof(string) })); + + //callvirt instance string [mscorlib]System.Exception::get_Message() + SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Callvirt..."); + il.Emit(OpCodes.Callvirt, typeof(Exception).GetMethod + ("get_Message")); + + //call void [mscorlib]System.Console::WriteLine(string) + SendToDebug("CLR:" + eventname + ":il.Emit(OpCodes.Call..."); + il.Emit(OpCodes.Call, typeof(Console).GetMethod + ("WriteLine", new Type[] { typeof(string) })); + + /* + * CLR END TRY + */ + //SendToDebug("CLR:" + eventname + ":il.EndExceptionBlock();"); + il.EndExceptionBlock(); + // Push "Return from current method, with return value if present" to stack + il.Emit(OpCodes.Ret); + + + + return myCodeChunk; + + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Struct.cs b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Struct.cs index 3b91e9f..66c6c5e 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Struct.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Engines/LSLEngine/LSLHandler/LSO_Struct.cs @@ -1,105 +1,105 @@ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenSim.ScriptEngines.LSL -{ - static class LSO_Struct - { - - public struct Header - { - public UInt32 TM; - public UInt32 IP; - public UInt32 VN; - public UInt32 BP; - public UInt32 SP; - public UInt32 HR; - public UInt32 HP; - public UInt32 CS; - public UInt32 NS; - public UInt32 CE; - public UInt32 IE; - public UInt32 ER; - public UInt32 FR; - public UInt32 SLR; - public UInt32 GVR; - public UInt32 GFR; - public UInt32 PR; - public UInt32 ESR; - public UInt32 SR; - public UInt64 NCE; - public UInt64 NIE; - public UInt64 NER; - } - - public struct StaticBlock - { - public UInt32 Static_Chunk_Header_Size; - public byte ObjectType; - public byte Unknown; - public byte[] BlockVariable; - } - /* Not actually a structure - public struct StaticBlockVariable - { - public UInt32 Integer1; - public UInt32 Float1; - public UInt32 HeapPointer_String; - public UInt32 HeapPointer_Key; - public byte[] Vector_12; - public byte[] Rotation_16; - public UInt32 Pointer_List_Structure; - } */ - public struct HeapBlock - { - public UInt32 DataBlockSize; - public byte ObjectType; - public UInt16 ReferenceCount; - public byte[] Data; - } - public struct StateFrameBlock - { - public UInt32 StateCount; - public StatePointerBlock[] StatePointer; - } - public struct StatePointerBlock - { - public UInt32 Location; - public System.Collections.BitArray EventMask; - public StateBlock StateBlock; - } - public struct StateBlock - { - public UInt32 StartPos; - public UInt32 EndPos; - public UInt32 HeaderSize; - public byte Unknown; - public StateBlockHandler[] StateBlockHandlers; - } - public struct StateBlockHandler - { - public UInt32 CodeChunkPointer; - public UInt32 CallFrameSize; - } - public struct FunctionBlock - { - public UInt32 FunctionCount; - public UInt32[] CodeChunkPointer; - } - public struct CodeChunk - { - public UInt32 CodeChunkHeaderSize; - public string Comment; - public System.Collections.Generic.List CodeChunkArguments; - public byte EndMarker; - public byte ReturnType; - } - public struct CodeChunkArgument - { - public byte FunctionReturnType; - public byte NullString; - } - } -} + +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.ScriptEngines.LSL +{ + static class LSO_Struct + { + + public struct Header + { + public UInt32 TM; + public UInt32 IP; + public UInt32 VN; + public UInt32 BP; + public UInt32 SP; + public UInt32 HR; + public UInt32 HP; + public UInt32 CS; + public UInt32 NS; + public UInt32 CE; + public UInt32 IE; + public UInt32 ER; + public UInt32 FR; + public UInt32 SLR; + public UInt32 GVR; + public UInt32 GFR; + public UInt32 PR; + public UInt32 ESR; + public UInt32 SR; + public UInt64 NCE; + public UInt64 NIE; + public UInt64 NER; + } + + public struct StaticBlock + { + public UInt32 Static_Chunk_Header_Size; + public byte ObjectType; + public byte Unknown; + public byte[] BlockVariable; + } + /* Not actually a structure + public struct StaticBlockVariable + { + public UInt32 Integer1; + public UInt32 Float1; + public UInt32 HeapPointer_String; + public UInt32 HeapPointer_Key; + public byte[] Vector_12; + public byte[] Rotation_16; + public UInt32 Pointer_List_Structure; + } */ + public struct HeapBlock + { + public UInt32 DataBlockSize; + public byte ObjectType; + public UInt16 ReferenceCount; + public byte[] Data; + } + public struct StateFrameBlock + { + public UInt32 StateCount; + public StatePointerBlock[] StatePointer; + } + public struct StatePointerBlock + { + public UInt32 Location; + public System.Collections.BitArray EventMask; + public StateBlock StateBlock; + } + public struct StateBlock + { + public UInt32 StartPos; + public UInt32 EndPos; + public UInt32 HeaderSize; + public byte Unknown; + public StateBlockHandler[] StateBlockHandlers; + } + public struct StateBlockHandler + { + public UInt32 CodeChunkPointer; + public UInt32 CallFrameSize; + } + public struct FunctionBlock + { + public UInt32 FunctionCount; + public UInt32[] CodeChunkPointer; + } + public struct CodeChunk + { + public UInt32 CodeChunkHeaderSize; + public string Comment; + public System.Collections.Generic.List CodeChunkArguments; + public byte EndMarker; + public byte ReturnType; + } + public struct CodeChunkArgument + { + public byte FunctionReturnType; + public byte NullString; + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/Script.cs b/OpenSim/Region/Environment/Scenes/scripting/Script.cs index 99d7d04..40825c0 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/Script.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/Script.cs @@ -1,64 +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 OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Scripting -{ - public interface IScript - { - void Initialise(ScriptInfo scriptInfo); - string getName(); - } - - public class TestScript : IScript - { - ScriptInfo script; - - public string getName() - { - return "TestScript 0.1"; - } - - public void Initialise(ScriptInfo scriptInfo) - { - script = scriptInfo; - script.events.OnFrame += new EventManager.OnFrameDelegate(events_OnFrame); - script.events.OnNewPresence += new EventManager.OnNewPresenceDelegate(events_OnNewPresence); - } - - void events_OnNewPresence(ScenePresence presence) - { - script.logger.Verbose("Hello " + presence.firstname.ToString() + "!"); - } - - void events_OnFrame() - { - //script.logger.Verbose("Hello World!"); - } - } -} +/* +* 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 OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Scripting +{ + public interface IScript + { + void Initialise(ScriptInfo scriptInfo); + string getName(); + } + + public class TestScript : IScript + { + ScriptInfo script; + + public string getName() + { + return "TestScript 0.1"; + } + + public void Initialise(ScriptInfo scriptInfo) + { + script = scriptInfo; + script.events.OnFrame += new EventManager.OnFrameDelegate(events_OnFrame); + script.events.OnNewPresence += new EventManager.OnNewPresenceDelegate(events_OnNewPresence); + } + + void events_OnNewPresence(ScenePresence presence) + { + script.logger.Verbose("Hello " + presence.firstname.ToString() + "!"); + } + + void events_OnFrame() + { + //script.logger.Verbose("Hello World!"); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/ScriptAPI.cs b/OpenSim/Region/Environment/Scenes/scripting/ScriptAPI.cs index a8f6aa5..b4f6a05 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/ScriptAPI.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/ScriptAPI.cs @@ -1,32 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Key = libsecondlife.LLUUID; -using Rotation = libsecondlife.LLQuaternion; -using Vector = libsecondlife.LLVector3; -using LSLList = System.Collections.Generic.List; - - -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Scripting -{ - // This class is to be used for engines which may not be able to access the Scene directly. - // Scene access is preffered, but obviously not possible on some non-.NET languages. - public class ScriptAPI - { - Scene scene; - ScriptInterpretedAPI interpretedAPI; - - public ScriptAPI(Scene world) - { - scene = world; - interpretedAPI = new ScriptInterpretedAPI(); - } - - public Object CallMethod(String method, Object[] args) - { - return null; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using Key = libsecondlife.LLUUID; +using Rotation = libsecondlife.LLQuaternion; +using Vector = libsecondlife.LLVector3; +using LSLList = System.Collections.Generic.List; + + +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Scripting +{ + // This class is to be used for engines which may not be able to access the Scene directly. + // Scene access is preffered, but obviously not possible on some non-.NET languages. + public class ScriptAPI + { + Scene scene; + ScriptInterpretedAPI interpretedAPI; + + public ScriptAPI(Scene world) + { + scene = world; + interpretedAPI = new ScriptInterpretedAPI(); + } + + public Object CallMethod(String method, Object[] args) + { + return null; + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/ScriptInfo.cs b/OpenSim/Region/Environment/Scenes/scripting/ScriptInfo.cs index c3be22a..4a6086c 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/ScriptInfo.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/ScriptInfo.cs @@ -1,58 +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 OpenSim.Framework.Console; -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.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; - - // API Access - public ScriptAPI api; - - public ScriptInfo(Scene scene) - { - world = scene; - events = world.EventManager; - logger = MainLog.Instance; - api = new ScriptAPI(scene); - } - } -} +/* +* 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 OpenSim.Framework.Console; +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.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; + + // API Access + public ScriptAPI api; + + public ScriptInfo(Scene scene) + { + world = scene; + events = world.EventManager; + logger = MainLog.Instance; + api = new ScriptAPI(scene); + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedAPI.cs b/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedAPI.cs index 085d97e..b4a6019 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedAPI.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedAPI.cs @@ -1,206 +1,206 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Key = libsecondlife.LLUUID; -using Rotation = libsecondlife.LLQuaternion; -using Vector = libsecondlife.LLVector3; -using LSLList = System.Collections.Generic.List; - -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Scripting -{ - /// - /// A class inteded to act as an API for LSL-styled interpreted languages - /// - /// Avoid at all costs. This should ONLY be used for LSL. - class ScriptInterpretedAPI - { - public int osAbs(int val) - { - return Math.Abs(val); - } - - public float osAcos(float val) - { - return (float)Math.Acos(val); - } - - [Obsolete("Unimplemented")] - public void osAddToLandPassList(Key avatar, float hours) - { - OpenSim.Framework.Console.MainLog.Instance.Warn("Unimplemented function called by script: osAddToLandPassList(Key avatar, float hours)"); - return; - } - - [Obsolete("Unimplemented")] - public void osAdjustSoundVolume(float volume) - { - OpenSim.Framework.Console.MainLog.Instance.Warn("Unimplemented function called by script: osAdjustSoundVolume(float volume)"); - return; - } - - [Obsolete("Unimplemented")] - public void osAllowInventoryDrop(int add) - { - return; - } - - [Obsolete("Unimplemented")] - public float osAngleBetween(Rotation a, Rotation b) - { - Axiom.Math.Quaternion axA = new Axiom.Math.Quaternion(a.W, a.X, a.Y, a.Z); - Axiom.Math.Quaternion axB = new Axiom.Math.Quaternion(b.W, b.X, b.Y, b.Z); - - return 0; - } - - [Obsolete("Unimplemented")] - public void osApplyImpulse(Vector force, int local) - { - return; - } - - [Obsolete("Unimplemented")] - public void osApplyRotationalImpulse(Vector force, int local) - { - return; - } - - public float osAsin(float val) - { - return (float)Math.Asin(val); - } - - public float osAtan2(float x, float y) - { - return (float)Math.Atan2(x, y); - } - - [Obsolete("Unimplemented")] - public void osAttachToAvatar(Key avatar, int attachmentPoint) - { - return; - } - - [Obsolete("Unimplemented")] - public Key osAvatarOnSitTarget() - { - return Key.Zero; - } - - public Rotation osAxes2Rot(Vector fwd, Vector left, Vector up) - { - Axiom.Math.Quaternion axQ = new Axiom.Math.Quaternion(); - Axiom.Math.Vector3 axFwd = new Axiom.Math.Vector3(fwd.X, fwd.Y, fwd.Z); - Axiom.Math.Vector3 axLeft = new Axiom.Math.Vector3(left.X, left.Y, left.Z); - Axiom.Math.Vector3 axUp = new Axiom.Math.Vector3(up.X, up.Y, up.Z); - - axQ.FromAxes(axFwd, axLeft, axUp); - - return new Rotation(axQ.x, axQ.y, axQ.z, axQ.w); - } - - public Rotation osAxisAngle2Rot(Vector axis, float angle) - { - Axiom.Math.Quaternion axQ = Axiom.Math.Quaternion.FromAngleAxis(angle, new Axiom.Math.Vector3(axis.X, axis.Y, axis.Z)); - - return new Rotation(axQ.x, axQ.y, axQ.z, axQ.w); - } - - public string osBase64ToString(string str) - { - Encoding enc = System.Text.Encoding.UTF8; - return enc.GetString(Convert.FromBase64String(str)); - } - - [Obsolete("Unimplemented")] - public void osBreakAllLinks() - { - return; - } - - [Obsolete("Unimplemented")] - public void osBreakLink() - { - return; - } - - public LSLList osCSV2List(string src) - { - LSLList retVal = new LSLList(); - retVal.AddRange(src.Split(',')); - - return retVal; - } - - public int osCeil(float val) - { - return (int)Math.Ceiling(val); - } - - [Obsolete("Unimplemented")] - public void osCloseRemoteDataChannel(Key channel) - { - return; - } - - [Obsolete("Unimplemented")] - public float osCloud(Vector offset) - { - return 0.0f; - } - - [Obsolete("Unimplemented")] - public void osCollisionFilter(string name, Key id, int accept) - { - return; - } - - [Obsolete("Unimplemented")] - public void osCollisionSprite(string impact_sprite) - { - return; - } - - public float osCos(float theta) - { - return (float)Math.Cos(theta); - } - - [Obsolete("Unimplemented")] - public void osCreateLink(Key target, int parent) - { - return; - } - - [Obsolete("Partially Unimplemented")] - public LSLList osDeleteSubList(LSLList src, int start, int end) - { - if (start < 0 || end < 0) - { - throw new Exception("Unsupported at this time."); - } - - src.RemoveRange(start, start - end + 1); - return src; - } - - [Obsolete("Partially Unimplemented")] - public string osDeleteSubString(string src, int start, int end) - { - if (start < 0 || end < 0) - { - throw new Exception("Unsupported at this time."); - } - - return src.Remove(start, start - end + 1); - } - - [Obsolete("Unimplemented")] - public void osDetachFromAvatar(Key avatar) - { - return; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using Key = libsecondlife.LLUUID; +using Rotation = libsecondlife.LLQuaternion; +using Vector = libsecondlife.LLVector3; +using LSLList = System.Collections.Generic.List; + +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Scripting +{ + /// + /// A class inteded to act as an API for LSL-styled interpreted languages + /// + /// Avoid at all costs. This should ONLY be used for LSL. + class ScriptInterpretedAPI + { + public int osAbs(int val) + { + return Math.Abs(val); + } + + public float osAcos(float val) + { + return (float)Math.Acos(val); + } + + [Obsolete("Unimplemented")] + public void osAddToLandPassList(Key avatar, float hours) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Unimplemented function called by script: osAddToLandPassList(Key avatar, float hours)"); + return; + } + + [Obsolete("Unimplemented")] + public void osAdjustSoundVolume(float volume) + { + OpenSim.Framework.Console.MainLog.Instance.Warn("Unimplemented function called by script: osAdjustSoundVolume(float volume)"); + return; + } + + [Obsolete("Unimplemented")] + public void osAllowInventoryDrop(int add) + { + return; + } + + [Obsolete("Unimplemented")] + public float osAngleBetween(Rotation a, Rotation b) + { + Axiom.Math.Quaternion axA = new Axiom.Math.Quaternion(a.W, a.X, a.Y, a.Z); + Axiom.Math.Quaternion axB = new Axiom.Math.Quaternion(b.W, b.X, b.Y, b.Z); + + return 0; + } + + [Obsolete("Unimplemented")] + public void osApplyImpulse(Vector force, int local) + { + return; + } + + [Obsolete("Unimplemented")] + public void osApplyRotationalImpulse(Vector force, int local) + { + return; + } + + public float osAsin(float val) + { + return (float)Math.Asin(val); + } + + public float osAtan2(float x, float y) + { + return (float)Math.Atan2(x, y); + } + + [Obsolete("Unimplemented")] + public void osAttachToAvatar(Key avatar, int attachmentPoint) + { + return; + } + + [Obsolete("Unimplemented")] + public Key osAvatarOnSitTarget() + { + return Key.Zero; + } + + public Rotation osAxes2Rot(Vector fwd, Vector left, Vector up) + { + Axiom.Math.Quaternion axQ = new Axiom.Math.Quaternion(); + Axiom.Math.Vector3 axFwd = new Axiom.Math.Vector3(fwd.X, fwd.Y, fwd.Z); + Axiom.Math.Vector3 axLeft = new Axiom.Math.Vector3(left.X, left.Y, left.Z); + Axiom.Math.Vector3 axUp = new Axiom.Math.Vector3(up.X, up.Y, up.Z); + + axQ.FromAxes(axFwd, axLeft, axUp); + + return new Rotation(axQ.x, axQ.y, axQ.z, axQ.w); + } + + public Rotation osAxisAngle2Rot(Vector axis, float angle) + { + Axiom.Math.Quaternion axQ = Axiom.Math.Quaternion.FromAngleAxis(angle, new Axiom.Math.Vector3(axis.X, axis.Y, axis.Z)); + + return new Rotation(axQ.x, axQ.y, axQ.z, axQ.w); + } + + public string osBase64ToString(string str) + { + Encoding enc = System.Text.Encoding.UTF8; + return enc.GetString(Convert.FromBase64String(str)); + } + + [Obsolete("Unimplemented")] + public void osBreakAllLinks() + { + return; + } + + [Obsolete("Unimplemented")] + public void osBreakLink() + { + return; + } + + public LSLList osCSV2List(string src) + { + LSLList retVal = new LSLList(); + retVal.AddRange(src.Split(',')); + + return retVal; + } + + public int osCeil(float val) + { + return (int)Math.Ceiling(val); + } + + [Obsolete("Unimplemented")] + public void osCloseRemoteDataChannel(Key channel) + { + return; + } + + [Obsolete("Unimplemented")] + public float osCloud(Vector offset) + { + return 0.0f; + } + + [Obsolete("Unimplemented")] + public void osCollisionFilter(string name, Key id, int accept) + { + return; + } + + [Obsolete("Unimplemented")] + public void osCollisionSprite(string impact_sprite) + { + return; + } + + public float osCos(float theta) + { + return (float)Math.Cos(theta); + } + + [Obsolete("Unimplemented")] + public void osCreateLink(Key target, int parent) + { + return; + } + + [Obsolete("Partially Unimplemented")] + public LSLList osDeleteSubList(LSLList src, int start, int end) + { + if (start < 0 || end < 0) + { + throw new Exception("Unsupported at this time."); + } + + src.RemoveRange(start, start - end + 1); + return src; + } + + [Obsolete("Partially Unimplemented")] + public string osDeleteSubString(string src, int start, int end) + { + if (start < 0 || end < 0) + { + throw new Exception("Unsupported at this time."); + } + + return src.Remove(start, start - end + 1); + } + + [Obsolete("Unimplemented")] + public void osDetachFromAvatar(Key avatar) + { + return; + } + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedEvents.cs b/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedEvents.cs index 7743186..d6456a6 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedEvents.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/ScriptInterpretedEvents.cs @@ -1,16 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Region.Environment.Scenes; -using libsecondlife; -using Key = libsecondlife.LLUUID; - -namespace OpenSim.Region.Scripting -{ - - public class ScriptInterpretedEvents - { - public delegate void OnTouchStartDelegate(Key user); - public event OnTouchStartDelegate OnTouchStart; - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Region.Environment.Scenes; +using libsecondlife; +using Key = libsecondlife.LLUUID; + +namespace OpenSim.Region.Scripting +{ + + public class ScriptInterpretedEvents + { + public delegate void OnTouchStartDelegate(Key user); + public event OnTouchStartDelegate OnTouchStart; + } +} diff --git a/OpenSim/Region/Environment/Scenes/scripting/ScriptManager.cs b/OpenSim/Region/Environment/Scenes/scripting/ScriptManager.cs index 7a08735..27e831b 100644 --- a/OpenSim/Region/Environment/Scenes/scripting/ScriptManager.cs +++ b/OpenSim/Region/Environment/Scenes/scripting/ScriptManager.cs @@ -1,107 +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.Collections.Generic; -using OpenSim.Framework.Console; -using OpenSim.Region.Environment.Scenes; - -namespace OpenSim.Region.Scripting -{ - public class ScriptManager - { - List scripts = new List(); - Scene scene; - Dictionary compilers = new Dictionary(); - - private void LoadFromCompiler(Dictionary compiledscripts) - { - foreach (KeyValuePair script in compiledscripts) - { - ScriptInfo scriptInfo = new ScriptInfo(scene); // Since each script could potentially corrupt their access with a stray assignment, making a new one for each script. - MainLog.Instance.Verbose("Loading " + script.Key); - script.Value.Initialise(scriptInfo); - scripts.Add(script.Value); - } - MainLog.Instance.Verbose("Finished loading " + compiledscripts.Count.ToString() + " script(s)"); - } - - public ScriptManager(Scene world) - { - scene = world; - - // Default Engines - CSharpScriptEngine csharpCompiler = new CSharpScriptEngine(); - compilers.Add(csharpCompiler.FileExt(),csharpCompiler); - - JScriptEngine jscriptCompiler = new JScriptEngine(); - compilers.Add(jscriptCompiler.FileExt(), jscriptCompiler); - - JavaEngine javaCompiler = new JavaEngine(); - compilers.Add(javaCompiler.FileExt(), javaCompiler); - } - - public void Compile(string filename) - { - foreach (KeyValuePair compiler in compilers) - { - if (filename.EndsWith(compiler.Key)) - { - LoadFromCompiler(compiler.Value.compile(filename)); - break; - } - } - } - - public void RunScriptCmd(string[] args) - { - switch (args[0]) - { - case "load": - Compile(args[1]); - break; - - default: - MainLog.Instance.Error("Unknown script command"); - break; - } - } - - public void AddPreCompiledScript(IScript script) - { - MainLog.Instance.Verbose("Loading script " + script.getName()); - ScriptInfo scriptInfo = new ScriptInfo(scene); // Since each script could potentially corrupt their access with a stray assignment, making a new one for each script. - script.Initialise(scriptInfo); - scripts.Add(script); - } - } - - interface IScriptCompiler - { - Dictionary compile(string filename); - string FileExt(); - } -} +/* +* 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.Collections.Generic; +using OpenSim.Framework.Console; +using OpenSim.Region.Environment.Scenes; + +namespace OpenSim.Region.Scripting +{ + public class ScriptManager + { + List scripts = new List(); + Scene scene; + Dictionary compilers = new Dictionary(); + + private void LoadFromCompiler(Dictionary compiledscripts) + { + foreach (KeyValuePair script in compiledscripts) + { + ScriptInfo scriptInfo = new ScriptInfo(scene); // Since each script could potentially corrupt their access with a stray assignment, making a new one for each script. + MainLog.Instance.Verbose("Loading " + script.Key); + script.Value.Initialise(scriptInfo); + scripts.Add(script.Value); + } + MainLog.Instance.Verbose("Finished loading " + compiledscripts.Count.ToString() + " script(s)"); + } + + public ScriptManager(Scene world) + { + scene = world; + + // Default Engines + CSharpScriptEngine csharpCompiler = new CSharpScriptEngine(); + compilers.Add(csharpCompiler.FileExt(),csharpCompiler); + + JScriptEngine jscriptCompiler = new JScriptEngine(); + compilers.Add(jscriptCompiler.FileExt(), jscriptCompiler); + + JavaEngine javaCompiler = new JavaEngine(); + compilers.Add(javaCompiler.FileExt(), javaCompiler); + } + + public void Compile(string filename) + { + foreach (KeyValuePair compiler in compilers) + { + if (filename.EndsWith(compiler.Key)) + { + LoadFromCompiler(compiler.Value.compile(filename)); + break; + } + } + } + + public void RunScriptCmd(string[] args) + { + switch (args[0]) + { + case "load": + Compile(args[1]); + break; + + default: + MainLog.Instance.Error("Unknown script command"); + break; + } + } + + public void AddPreCompiledScript(IScript script) + { + MainLog.Instance.Verbose("Loading script " + script.getName()); + ScriptInfo scriptInfo = new ScriptInfo(scene); // Since each script could potentially corrupt their access with a stray assignment, making a new one for each script. + script.Initialise(scriptInfo); + scripts.Add(script); + } + } + + interface IScriptCompiler + { + Dictionary compile(string filename); + string FileExt(); + } +} diff --git a/OpenSim/Region/Environment/StorageManager.cs b/OpenSim/Region/Environment/StorageManager.cs index 8f8ac97..fb12c4d 100644 --- a/OpenSim/Region/Environment/StorageManager.cs +++ b/OpenSim/Region/Environment/StorageManager.cs @@ -1,60 +1,60 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; -using OpenSim.Region.Capabilities; -using OpenSim.Region.Environment.Scenes; -using OpenSim.Region.Interfaces; - -using System.Reflection; - -namespace OpenSim.Region.Environment -{ - public class StorageManager - { - private IRegionDataStore m_dataStore; - - public IRegionDataStore DataStore - { - get - { - return m_dataStore; - } - } - - public StorageManager(IRegionDataStore storage) - { - m_dataStore = storage; - } - - public StorageManager(string dllName, string dataStoreFile, string dataStoreDB) - { - Assembly pluginAssembly = Assembly.LoadFrom(dllName); - - foreach (Type pluginType in pluginAssembly.GetTypes()) - { - if (pluginType.IsPublic) - { - Type typeInterface = pluginType.GetInterface("IRegionDataStore", true); - - if (typeInterface != null) - { - IRegionDataStore plug = (IRegionDataStore)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); - plug.Initialise(dataStoreFile, dataStoreDB); - - m_dataStore = plug; - } - - typeInterface = null; - } - } - - pluginAssembly = null; - - //TODO: Add checking and warning to make sure it initialised. - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; +using OpenSim.Region.Capabilities; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.Interfaces; + +using System.Reflection; + +namespace OpenSim.Region.Environment +{ + public class StorageManager + { + private IRegionDataStore m_dataStore; + + public IRegionDataStore DataStore + { + get + { + return m_dataStore; + } + } + + public StorageManager(IRegionDataStore storage) + { + m_dataStore = storage; + } + + public StorageManager(string dllName, string dataStoreFile, string dataStoreDB) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + Type typeInterface = pluginType.GetInterface("IRegionDataStore", true); + + if (typeInterface != null) + { + IRegionDataStore plug = (IRegionDataStore)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Initialise(dataStoreFile, dataStoreDB); + + m_dataStore = plug; + } + + typeInterface = null; + } + } + + pluginAssembly = null; + + //TODO: Add checking and warning to make sure it initialised. + } + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/MyNpcCharacter.cs b/OpenSim/Region/Examples/SimpleApp/MyNpcCharacter.cs index 7e6b1af..28c9b9a 100644 --- a/OpenSim/Region/Examples/SimpleApp/MyNpcCharacter.cs +++ b/OpenSim/Region/Examples/SimpleApp/MyNpcCharacter.cs @@ -1,184 +1,184 @@ -using System.Collections.Generic; -using System.Net; -using System.Timers; -using System; -using System.Text; - -using libsecondlife; -using libsecondlife.Packets; - -using OpenSim.Framework; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Data; -using OpenSim.Framework.Utilities; - -namespace SimpleApp -{ - public class MyNpcCharacter : IClientAPI - { - private uint movementFlag = 0; - private short flyState = 0; - private LLQuaternion bodyDirection = LLQuaternion.Identity; - private short count = 0; - - public event ImprovedInstantMessage OnInstantMessage; - public event ChatFromViewer OnChatFromViewer; - public event RezObject OnRezObject; - public event ModifyTerrain OnModifyTerrain; - public event SetAppearance OnSetAppearance; - public event StartAnim OnStartAnim; - public event LinkObjects OnLinkObjects; - public event RequestMapBlocks OnRequestMapBlocks; - public event TeleportLocationRequest OnTeleportLocationRequest; - - public event GenericCall4 OnDeRezObject; - public event GenericCall OnRegionHandShakeReply; - public event GenericCall OnRequestWearables; - public event GenericCall2 OnCompleteMovementToRegion; - public event UpdateAgent OnAgentUpdate; - public event GenericCall OnRequestAvatarsData; - public event AddNewPrim OnAddPrim; - public event ObjectDuplicate OnObjectDuplicate; - public event UpdateVector OnGrapObject; - public event ObjectSelect OnDeGrapObject; - public event MoveObject OnGrapUpdate; - - public event UpdateShape OnUpdatePrimShape; - public event ObjectSelect OnObjectSelect; - public event GenericCall7 OnObjectDescription; - public event GenericCall7 OnObjectName; - public event UpdatePrimFlags OnUpdatePrimFlags; - public event UpdatePrimTexture OnUpdatePrimTexture; - public event UpdateVector OnUpdatePrimGroupPosition; - public event UpdateVector OnUpdatePrimSinglePosition; - public event UpdatePrimRotation OnUpdatePrimGroupRotation; - public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; - public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; - public event UpdateVector OnUpdatePrimScale; - public event StatusChange OnChildAgentStatus; - public event GenericCall2 OnStopMovement; - public event NewAvatar OnNewAvatar; - public event GenericCall6 OnRemoveAvatar; - - public event UUIDNameRequest OnNameFromUUIDRequest; - - public event ParcelPropertiesRequest OnParcelPropertiesRequest; - public event ParcelDivideRequest OnParcelDivideRequest; - public event ParcelJoinRequest OnParcelJoinRequest; - public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; - - public event ParcelSelectObjects OnParcelSelectObjects; - public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; - public event ObjectDeselect OnObjectDeselect; - public event EstateOwnerMessageRequest OnEstateOwnerMessage; - - private LLUUID myID = LLUUID.Random(); - public MyNpcCharacter() - { - - } - - public virtual LLVector3 StartPos - { - get { return new LLVector3(128, 100, 2); } - set { } - } - - public virtual LLUUID AgentId - { - get { return myID; } - } - - public virtual string FirstName - { - get { return "Annoying"; } - } - - public virtual string LastName - { - get { return "NPC"; } - } - - public virtual void OutPacket(Packet newPack) { } - public virtual void SendWearables(AvatarWearable[] wearables) { } - public virtual void SendStartPingCheck(byte seq) { } - public virtual void SendKillObject(ulong regionHandle, uint avatarLocalID) { } - public virtual void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId) { } - public virtual void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) { } - public virtual void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) { } - public virtual void SendInstantMessage(string message, LLUUID target, string fromName) { } - public virtual void SendLayerData(float[] map) { } - public virtual void SendLayerData(int px, int py, float[] map) { } - public virtual void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look) { } - public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } - public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } - public virtual void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint) { } - public virtual void SendMapBlock(List mapBlocks) { } - public virtual void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags) { } - public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags) { } - public virtual void SendTeleportCancel() { } - public virtual void SendTeleportLocationStart() { } - public virtual void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance) { } - - public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry) { } - public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity) { } - - public virtual void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint) { } - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID, uint flags) { } - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID, uint flags) { } - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) { } - public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) { } - public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation) { } - - public virtual void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items) { } - public virtual void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item) { } - public virtual void SendNameReply(LLUUID profileId, string firstname, string lastname) { } - - public virtual void SendRegionHandshake(RegionInfo regionInfo) - { - this.OnRegionHandShakeReply(this); - this.OnCompleteMovementToRegion(); - this.StartMovement(); - } - - public void StartMovement() - { - Timer timer = new Timer(); - timer.Enabled = true; - timer.Interval = 500; - timer.Elapsed += new ElapsedEventHandler(this.Heartbeat); - } - - public void Heartbeat(object sender, EventArgs e) - { - Encoding enc = Encoding.ASCII; - - this.OnAgentUpdate(this, movementFlag, bodyDirection); - - if (this.flyState == 0) - { - movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY | (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_NEG; - flyState = 1; - } - else if (this.flyState == 1) - { - movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY | (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_POS; - flyState = 2; - } - else - { - movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY; - flyState = 0; - } - - if (count >= 40) - { - this.OnChatFromViewer(enc.GetBytes("Kind of quiet around here, isn't it! \0"), 2, new LLVector3(128, 128, 26), this.FirstName + " " + this.LastName, this.AgentId); - count = -1; - } - - count++; - } - } -} +using System.Collections.Generic; +using System.Net; +using System.Timers; +using System; +using System.Text; + +using libsecondlife; +using libsecondlife.Packets; + +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Data; +using OpenSim.Framework.Utilities; + +namespace SimpleApp +{ + public class MyNpcCharacter : IClientAPI + { + private uint movementFlag = 0; + private short flyState = 0; + private LLQuaternion bodyDirection = LLQuaternion.Identity; + private short count = 0; + + public event ImprovedInstantMessage OnInstantMessage; + public event ChatFromViewer OnChatFromViewer; + public event RezObject OnRezObject; + public event ModifyTerrain OnModifyTerrain; + public event SetAppearance OnSetAppearance; + public event StartAnim OnStartAnim; + public event LinkObjects OnLinkObjects; + public event RequestMapBlocks OnRequestMapBlocks; + public event TeleportLocationRequest OnTeleportLocationRequest; + + public event GenericCall4 OnDeRezObject; + public event GenericCall OnRegionHandShakeReply; + public event GenericCall OnRequestWearables; + public event GenericCall2 OnCompleteMovementToRegion; + public event UpdateAgent OnAgentUpdate; + public event GenericCall OnRequestAvatarsData; + public event AddNewPrim OnAddPrim; + public event ObjectDuplicate OnObjectDuplicate; + public event UpdateVector OnGrapObject; + public event ObjectSelect OnDeGrapObject; + public event MoveObject OnGrapUpdate; + + public event UpdateShape OnUpdatePrimShape; + public event ObjectSelect OnObjectSelect; + public event GenericCall7 OnObjectDescription; + public event GenericCall7 OnObjectName; + public event UpdatePrimFlags OnUpdatePrimFlags; + public event UpdatePrimTexture OnUpdatePrimTexture; + public event UpdateVector OnUpdatePrimGroupPosition; + public event UpdateVector OnUpdatePrimSinglePosition; + public event UpdatePrimRotation OnUpdatePrimGroupRotation; + public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; + public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; + public event UpdateVector OnUpdatePrimScale; + public event StatusChange OnChildAgentStatus; + public event GenericCall2 OnStopMovement; + public event NewAvatar OnNewAvatar; + public event GenericCall6 OnRemoveAvatar; + + public event UUIDNameRequest OnNameFromUUIDRequest; + + public event ParcelPropertiesRequest OnParcelPropertiesRequest; + public event ParcelDivideRequest OnParcelDivideRequest; + public event ParcelJoinRequest OnParcelJoinRequest; + public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; + + public event ParcelSelectObjects OnParcelSelectObjects; + public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; + public event ObjectDeselect OnObjectDeselect; + public event EstateOwnerMessageRequest OnEstateOwnerMessage; + + private LLUUID myID = LLUUID.Random(); + public MyNpcCharacter() + { + + } + + public virtual LLVector3 StartPos + { + get { return new LLVector3(128, 100, 2); } + set { } + } + + public virtual LLUUID AgentId + { + get { return myID; } + } + + public virtual string FirstName + { + get { return "Annoying"; } + } + + public virtual string LastName + { + get { return "NPC"; } + } + + public virtual void OutPacket(Packet newPack) { } + public virtual void SendWearables(AvatarWearable[] wearables) { } + public virtual void SendStartPingCheck(byte seq) { } + public virtual void SendKillObject(ulong regionHandle, uint avatarLocalID) { } + public virtual void SendAnimation(LLUUID animID, int seq, LLUUID sourceAgentId) { } + public virtual void SendChatMessage(string message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) { } + public virtual void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) { } + public virtual void SendInstantMessage(string message, LLUUID target, string fromName) { } + public virtual void SendLayerData(float[] map) { } + public virtual void SendLayerData(int px, int py, float[] map) { } + public virtual void MoveAgentIntoRegion(RegionInfo regInfo, LLVector3 pos, LLVector3 look) { } + public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } + public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } + public virtual void CrossRegion(ulong newRegionHandle, LLVector3 pos, LLVector3 lookAt, IPEndPoint newRegionExternalEndPoint) { } + public virtual void SendMapBlock(List mapBlocks) { } + public virtual void SendLocalTeleport(LLVector3 position, LLVector3 lookAt, uint flags) { } + public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags) { } + public virtual void SendTeleportCancel() { } + public virtual void SendTeleportLocationStart() { } + public virtual void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance) { } + + public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, LLUUID avatarID, uint avatarLocalID, LLVector3 Pos, byte[] textureEntry) { } + public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLVector3 velocity) { } + + public virtual void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint) { } + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLQuaternion rotation, LLUUID textureID, uint flags) { } + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimData primData, LLVector3 pos, LLUUID textureID, uint flags) { } + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, LLQuaternion rotation, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) { } + public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, uint parentID) { } + public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, LLVector3 position, LLQuaternion rotation) { } + + public virtual void SendInventoryFolderDetails(LLUUID ownerID, LLUUID folderID, List items) { } + public virtual void SendInventoryItemDetails(LLUUID ownerID, LLUUID folderID, InventoryItemBase item) { } + public virtual void SendNameReply(LLUUID profileId, string firstname, string lastname) { } + + public virtual void SendRegionHandshake(RegionInfo regionInfo) + { + this.OnRegionHandShakeReply(this); + this.OnCompleteMovementToRegion(); + this.StartMovement(); + } + + public void StartMovement() + { + Timer timer = new Timer(); + timer.Enabled = true; + timer.Interval = 500; + timer.Elapsed += new ElapsedEventHandler(this.Heartbeat); + } + + public void Heartbeat(object sender, EventArgs e) + { + Encoding enc = Encoding.ASCII; + + this.OnAgentUpdate(this, movementFlag, bodyDirection); + + if (this.flyState == 0) + { + movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY | (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_NEG; + flyState = 1; + } + else if (this.flyState == 1) + { + movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY | (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_POS; + flyState = 2; + } + else + { + movementFlag = (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY; + flyState = 0; + } + + if (count >= 40) + { + this.OnChatFromViewer(enc.GetBytes("Kind of quiet around here, isn't it! \0"), 2, new LLVector3(128, 128, 26), this.FirstName + " " + this.LastName, this.AgentId); + count = -1; + } + + count++; + } + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/MySceneObject.cs b/OpenSim/Region/Examples/SimpleApp/MySceneObject.cs index aab52cc..f5c6a0f 100644 --- a/OpenSim/Region/Examples/SimpleApp/MySceneObject.cs +++ b/OpenSim/Region/Examples/SimpleApp/MySceneObject.cs @@ -1,40 +1,40 @@ -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Region.Environment.Scenes; -using libsecondlife; -using OpenSim.Framework.Types; -using System.Timers; -using System.Diagnostics; - -namespace SimpleApp -{ - public class MySceneObject : SceneObject - { - private PerformanceCounter m_counter; - - public MySceneObject(Scene world, EventManager eventManager, LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) - : base(world, eventManager, ownerID, localID, pos, shape ) - { - String objectName = "Processor"; - String counterName = "% Processor Time"; - String instanceName = "_Total"; - - m_counter = new PerformanceCounter(objectName, counterName, instanceName); - - Timer timer = new Timer(); - timer.Enabled = true; - timer.Interval = 100; - timer.Elapsed += new ElapsedEventHandler(this.Heartbeat); - - } - - public void Heartbeat(object sender, EventArgs e) - { - float cpu = m_counter.NextValue() / 40f; - LLVector3 size = new LLVector3(cpu, cpu, cpu); - rootPrimitive.ResizeGoup( size ); - update(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Region.Environment.Scenes; +using libsecondlife; +using OpenSim.Framework.Types; +using System.Timers; +using System.Diagnostics; + +namespace SimpleApp +{ + public class MySceneObject : SceneObject + { + private PerformanceCounter m_counter; + + public MySceneObject(Scene world, EventManager eventManager, LLUUID ownerID, uint localID, LLVector3 pos, PrimitiveBaseShape shape) + : base(world, eventManager, ownerID, localID, pos, shape ) + { + String objectName = "Processor"; + String counterName = "% Processor Time"; + String instanceName = "_Total"; + + m_counter = new PerformanceCounter(objectName, counterName, instanceName); + + Timer timer = new Timer(); + timer.Enabled = true; + timer.Interval = 100; + timer.Elapsed += new ElapsedEventHandler(this.Heartbeat); + + } + + public void Heartbeat(object sender, EventArgs e) + { + float cpu = m_counter.NextValue() / 40f; + LLVector3 size = new LLVector3(cpu, cpu, cpu); + rootPrimitive.ResizeGoup( size ); + update(); + } + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/MyWorld.cs b/OpenSim/Region/Examples/SimpleApp/MyWorld.cs index 29b255b..4fe3c7a 100644 --- a/OpenSim/Region/Examples/SimpleApp/MyWorld.cs +++ b/OpenSim/Region/Examples/SimpleApp/MyWorld.cs @@ -1,97 +1,97 @@ -using System.Collections.Generic; -using libsecondlife; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.Region.Caches; -using OpenSim.Region.Environment.Scenes; -using OpenSim.Region.Terrain; -using OpenSim.Region.Environment; - -using Avatar=OpenSim.Region.Environment.Scenes.ScenePresence; - -namespace SimpleApp -{ - public class MyWorld : Scene - { - private List m_avatars; - - public MyWorld( RegionInfo regionInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, StorageManager storeMan, BaseHttpServer httpServer) - : base( regionInfo, authen, commsMan, assetCach, storeMan, httpServer) - { - m_avatars = new List(); - } - - public override void LoadWorldMap() - { - float[] map = new float[65536]; - - for (int i = 0; i < 65536; i++) - { - int x = i % 256; - int y = i / 256; - - map[i] = 25f; - } - - this.Terrain.setHeights1D(map); - this.CreateTerrainTexture(); - } - - #region IWorld Members - - override public void AddNewClient(IClientAPI client, 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.OnChatFromViewer += this.SimChat; - client.OnAddPrim += AddNewPrim; - client.OnUpdatePrimGroupPosition += this.UpdatePrimPosition; - client.OnRequestMapBlocks += this.RequestMapBlocks; - client.OnTeleportLocationRequest += this.RequestTeleportLocation; - client.OnGrapUpdate += this.MoveObject; - client.OnNameFromUUIDRequest += this.commsManager.HandleUUIDNameRequest; - - client.OnCompleteMovementToRegion += delegate() - { - client.SendChatMessage("Welcome to My World.", 1, pos, "System", LLUUID.Zero ); - }; - - client.SendRegionHandshake(m_regInfo); - - ScenePresence avatar = CreateAndAddScenePresence(client); - avatar.Pos = new LLVector3(128, 128, 26); - } - - public override void Update() - { - foreach (LLUUID UUID in Entities.Keys) - { - Entities[UUID].updateMovement(); - } - - lock (this.m_syncRoot) - { - this.phyScene.Simulate(timeStep); - } - - foreach (LLUUID UUID in Entities.Keys) - { - Entities[UUID].update(); - } - } - - #endregion - } -} +using System.Collections.Generic; +using libsecondlife; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.Region.Caches; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.Terrain; +using OpenSim.Region.Environment; + +using Avatar=OpenSim.Region.Environment.Scenes.ScenePresence; + +namespace SimpleApp +{ + public class MyWorld : Scene + { + private List m_avatars; + + public MyWorld( RegionInfo regionInfo, AuthenticateSessionsBase authen, CommunicationsManager commsMan, AssetCache assetCach, StorageManager storeMan, BaseHttpServer httpServer) + : base( regionInfo, authen, commsMan, assetCach, storeMan, httpServer) + { + m_avatars = new List(); + } + + public override void LoadWorldMap() + { + float[] map = new float[65536]; + + for (int i = 0; i < 65536; i++) + { + int x = i % 256; + int y = i / 256; + + map[i] = 25f; + } + + this.Terrain.setHeights1D(map); + this.CreateTerrainTexture(); + } + + #region IWorld Members + + override public void AddNewClient(IClientAPI client, 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.OnChatFromViewer += this.SimChat; + client.OnAddPrim += AddNewPrim; + client.OnUpdatePrimGroupPosition += this.UpdatePrimPosition; + client.OnRequestMapBlocks += this.RequestMapBlocks; + client.OnTeleportLocationRequest += this.RequestTeleportLocation; + client.OnGrapUpdate += this.MoveObject; + client.OnNameFromUUIDRequest += this.commsManager.HandleUUIDNameRequest; + + client.OnCompleteMovementToRegion += delegate() + { + client.SendChatMessage("Welcome to My World.", 1, pos, "System", LLUUID.Zero ); + }; + + client.SendRegionHandshake(m_regInfo); + + ScenePresence avatar = CreateAndAddScenePresence(client); + avatar.Pos = new LLVector3(128, 128, 26); + } + + public override void Update() + { + foreach (LLUUID UUID in Entities.Keys) + { + Entities[UUID].updateMovement(); + } + + lock (this.m_syncRoot) + { + this.phyScene.Simulate(timeStep); + } + + foreach (LLUUID UUID in Entities.Keys) + { + Entities[UUID].update(); + } + } + + #endregion + } +} diff --git a/OpenSim/Region/Examples/SimpleApp/Program.cs b/OpenSim/Region/Examples/SimpleApp/Program.cs index c3edf0c..f82bdcb 100644 --- a/OpenSim/Region/Examples/SimpleApp/Program.cs +++ b/OpenSim/Region/Examples/SimpleApp/Program.cs @@ -1,126 +1,126 @@ -using System; -using System.Net; -using libsecondlife; -using OpenSim.Assets; -using OpenSim.Framework; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Types; -using OpenSim.Physics.Manager; -using OpenSim.Region.Caches; -using OpenSim.Region.Capabilities; -using OpenSim.Region.ClientStack; -using OpenSim.Region.Communications.Local; -using OpenSim.Region.GridInterfaces.Local; -using System.Timers; -using OpenSim.Region.Environment.Scenes; -using OpenSim.Framework.Data; - -namespace SimpleApp -{ - class Program : conscmd_callback - { - private LogBase m_log; - AuthenticateSessionsBase m_circuitManager; - uint m_localId; - public MyWorld world; - private SceneObject m_sceneObject; - public MyNpcCharacter m_character; - - private void Run() - { - m_log = new LogBase(null, "SimpleApp", this, false); - MainLog.Instance = m_log; - - // CheckSumServer checksumServer = new CheckSumServer(12036); - // checksumServer.ServerListener(); - - IPEndPoint internalEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000); - - m_circuitManager = new AuthenticateSessionsBase(); - - InventoryCache inventoryCache = new InventoryCache(); - - LocalAssetServer assetServer = new LocalAssetServer(); - assetServer.SetServerInfo("http://127.0.0.1:8003/", ""); - - AssetCache assetCache = new AssetCache(assetServer); - - ScenePresence.LoadTextureFile("avatar-texture.dat"); - ScenePresence.PhysicsEngineFlying = true; - - PhysicsManager physManager = new PhysicsManager(); - physManager.LoadPlugins(); - - UDPServer udpServer = new UDPServer(internalEndPoint.Port, assetCache, inventoryCache, m_log, m_circuitManager); - PacketServer packetServer = new PacketServer(udpServer); - - ClientView.TerrainManager = new TerrainManager(new SecondLife()); - BaseHttpServer httpServer = new BaseHttpServer(internalEndPoint.Port); - - NetworkServersInfo serverInfo = new NetworkServersInfo(); - CommunicationsLocal communicationsManager = new CommunicationsLocal(serverInfo, httpServer); - - RegionInfo regionInfo = new RegionInfo(1000, 1000, internalEndPoint, "127.0.0.1"); - - OpenSim.Region.Environment.StorageManager storeMan = new OpenSim.Region.Environment.StorageManager("OpenSim.DataStore.NullStorage.dll", "simpleapp.yap", "simpleapp"); - - world = new MyWorld( regionInfo, m_circuitManager, communicationsManager, assetCache, storeMan, httpServer); - world.PhysScene = physManager.GetPhysicsScene("basicphysics"); //PhysicsScene.Null; - - world.LoadWorldMap(); - world.PhysScene.SetTerrain(world.Terrain.getHeights1D()); - world.performParcelPrimCountUpdate(); - - udpServer.LocalWorld = world; - - httpServer.Start(); - udpServer.ServerListener(); - - UserProfileData masterAvatar = communicationsManager.UserServer.SetupMasterUser("Test", "User", "test"); - if (masterAvatar != null) - { - world.RegionInfo.MasterAvatarAssignedUUID = masterAvatar.UUID; - world.ParcelManager.NoParcelDataFromStorage(); - } - - world.StartTimer(); - - PrimitiveBaseShape shape = PrimitiveBaseShape.DefaultBox(); - shape.Scale = new LLVector3(0.5f, 0.5f, 0.5f); - LLVector3 pos = new LLVector3(138, 129, 27); - - m_sceneObject = new MySceneObject(world, world.EventManager, LLUUID.Zero, world.PrimIDAllocate(), pos, shape); - world.AddEntity(m_sceneObject); - - m_character = new MyNpcCharacter(); - world.AddNewClient(m_character, false); - - m_log.WriteLine(LogPriority.NORMAL, "Press enter to quit."); - m_log.ReadLine(); - - } - - #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(); - } - } -} +using System; +using System.Net; +using libsecondlife; +using OpenSim.Assets; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Types; +using OpenSim.Physics.Manager; +using OpenSim.Region.Caches; +using OpenSim.Region.Capabilities; +using OpenSim.Region.ClientStack; +using OpenSim.Region.Communications.Local; +using OpenSim.Region.GridInterfaces.Local; +using System.Timers; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Framework.Data; + +namespace SimpleApp +{ + class Program : conscmd_callback + { + private LogBase m_log; + AuthenticateSessionsBase m_circuitManager; + uint m_localId; + public MyWorld world; + private SceneObject m_sceneObject; + public MyNpcCharacter m_character; + + private void Run() + { + m_log = new LogBase(null, "SimpleApp", this, false); + MainLog.Instance = m_log; + + // CheckSumServer checksumServer = new CheckSumServer(12036); + // checksumServer.ServerListener(); + + IPEndPoint internalEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000); + + m_circuitManager = new AuthenticateSessionsBase(); + + InventoryCache inventoryCache = new InventoryCache(); + + LocalAssetServer assetServer = new LocalAssetServer(); + assetServer.SetServerInfo("http://127.0.0.1:8003/", ""); + + AssetCache assetCache = new AssetCache(assetServer); + + ScenePresence.LoadTextureFile("avatar-texture.dat"); + ScenePresence.PhysicsEngineFlying = true; + + PhysicsManager physManager = new PhysicsManager(); + physManager.LoadPlugins(); + + UDPServer udpServer = new UDPServer(internalEndPoint.Port, assetCache, inventoryCache, m_log, m_circuitManager); + PacketServer packetServer = new PacketServer(udpServer); + + ClientView.TerrainManager = new TerrainManager(new SecondLife()); + BaseHttpServer httpServer = new BaseHttpServer(internalEndPoint.Port); + + NetworkServersInfo serverInfo = new NetworkServersInfo(); + CommunicationsLocal communicationsManager = new CommunicationsLocal(serverInfo, httpServer); + + RegionInfo regionInfo = new RegionInfo(1000, 1000, internalEndPoint, "127.0.0.1"); + + OpenSim.Region.Environment.StorageManager storeMan = new OpenSim.Region.Environment.StorageManager("OpenSim.DataStore.NullStorage.dll", "simpleapp.yap", "simpleapp"); + + world = new MyWorld( regionInfo, m_circuitManager, communicationsManager, assetCache, storeMan, httpServer); + world.PhysScene = physManager.GetPhysicsScene("basicphysics"); //PhysicsScene.Null; + + world.LoadWorldMap(); + world.PhysScene.SetTerrain(world.Terrain.getHeights1D()); + world.performParcelPrimCountUpdate(); + + udpServer.LocalWorld = world; + + httpServer.Start(); + udpServer.ServerListener(); + + UserProfileData masterAvatar = communicationsManager.UserServer.SetupMasterUser("Test", "User", "test"); + if (masterAvatar != null) + { + world.RegionInfo.MasterAvatarAssignedUUID = masterAvatar.UUID; + world.ParcelManager.NoParcelDataFromStorage(); + } + + world.StartTimer(); + + PrimitiveBaseShape shape = PrimitiveBaseShape.DefaultBox(); + shape.Scale = new LLVector3(0.5f, 0.5f, 0.5f); + LLVector3 pos = new LLVector3(138, 129, 27); + + m_sceneObject = new MySceneObject(world, world.EventManager, LLUUID.Zero, world.PrimIDAllocate(), pos, shape); + world.AddEntity(m_sceneObject); + + m_character = new MyNpcCharacter(); + world.AddNewClient(m_character, false); + + m_log.WriteLine(LogPriority.NORMAL, "Press enter to quit."); + m_log.ReadLine(); + + } + + #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 index 3b0de8a..2250613 100644 --- a/OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Examples/SimpleApp/Properties/AssemblyInfo.cs @@ -1,31 +1,31 @@ -using System.Reflection; -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")] +using System.Reflection; +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/GridInterfaces/Local/AssemblyInfo.cs b/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs index b5fc1ef..61adf80 100644 --- a/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs +++ b/OpenSim/Region/GridInterfaces/Local/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index 1023820..f3d7a2c 100644 --- a/OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs +++ b/OpenSim/Region/GridInterfaces/Local/LocalAssetServer.cs @@ -1,311 +1,311 @@ -/* -* 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.Threading; -using Db4objects.Db4o; -using Db4objects.Db4o.Query; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Region.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 = File.Exists("regionassets.yap"); - - MainLog.Instance.Verbose( "Local Asset Server class created"); - try - { - db = Db4oFactory.OpenFile("regionassets.yap"); - MainLog.Instance.Verbose( "Db4 Asset database creation"); - } - catch (Exception e) - { - db.Close(); - MainLog.Instance.WriteLine(LogPriority.MEDIUM, "Db4 Asset server :Constructor - Exception occured"); - 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) - { - 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 - { - - 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("exception loading default assets into database"); - 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(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); - } - } - -} +/* +* 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.Threading; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Region.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 = File.Exists("regionassets.yap"); + + MainLog.Instance.Verbose( "Local Asset Server class created"); + try + { + db = Db4oFactory.OpenFile("regionassets.yap"); + MainLog.Instance.Verbose( "Db4 Asset database creation"); + } + catch (Exception e) + { + db.Close(); + MainLog.Instance.WriteLine(LogPriority.MEDIUM, "Db4 Asset server :Constructor - Exception occured"); + 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) + { + 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 + { + + 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("exception loading default assets into database"); + 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(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/Remote/AssemblyInfo.cs b/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs index 1e15c5e..a658f2f 100644 --- a/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs +++ b/OpenSim/Region/GridInterfaces/Remote/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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/RemoteAssetServer.cs b/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs index 8643736..f81bb8d 100644 --- a/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs +++ b/OpenSim/Region/GridInterfaces/Remote/RemoteAssetServer.cs @@ -1,133 +1,133 @@ -/* -* 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.IO; -using System.Net; -using System.Text; -using System.Threading; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; -using OpenSim.Framework.Utilities; - -namespace OpenSim.Region.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(); - 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()); - } - } - -} +/* +* 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.IO; +using System.Net; +using System.Text; +using System.Threading; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Region.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(); + 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/Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs index ce567a9..ecf8e68 100644 --- a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index f133045..ec406f1 100644 --- a/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs @@ -1,301 +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.Collections.Generic; -using Axiom.Math; -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) - { - if ((actor.Position.Y > 0 && actor.Position.Y < 256) && (actor.Position.X > 0 && actor.Position.X < 256)) - { - float height = _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 1.2f; - actor.Position.X = actor.Position.X + (actor.Velocity.X * timeStep); - actor.Position.Y = actor.Position.Y + (actor.Velocity.Y * timeStep); - if (actor.Flying) - { - if (actor.Position.Z + (actor.Velocity.Z * timeStep) < - _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 2) - { - actor.Position.Z = height; - actor.Velocity.Z = 0; - } - else - { - actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); - } - } - else - { - actor.Position.Z = height; - actor.Velocity.Z = 0; - } - } - 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 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 Quaternion Orientation - { - get - { - return 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) - { - - } - } - -} +/* +* 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.Collections.Generic; +using Axiom.Math; +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) + { + if ((actor.Position.Y > 0 && actor.Position.Y < 256) && (actor.Position.X > 0 && actor.Position.X < 256)) + { + float height = _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 1.2f; + actor.Position.X = actor.Position.X + (actor.Velocity.X * timeStep); + actor.Position.Y = actor.Position.Y + (actor.Velocity.Y * timeStep); + if (actor.Flying) + { + if (actor.Position.Z + (actor.Velocity.Z * timeStep) < + _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 2) + { + actor.Position.Z = height; + actor.Velocity.Z = 0; + } + else + { + actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); + } + } + else + { + actor.Position.Z = height; + actor.Velocity.Z = 0; + } + } + 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 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 Quaternion Orientation + { + get + { + return 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/BulletXPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BulletXPlugin/AssemblyInfo.cs index bda35f7..42ccdff 100644 --- a/OpenSim/Region/Physics/BulletXPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/BulletXPlugin/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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("BulletXPlugin")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BulletXPlugin")] -[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.0.0")] +/* +* 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.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("BulletXPlugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BulletXPlugin")] +[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.0.0")] diff --git a/OpenSim/Region/Physics/BulletXPlugin/BulletXPlugin.cs b/OpenSim/Region/Physics/BulletXPlugin/BulletXPlugin.cs index 1ca5efe..383dbc0 100644 --- a/OpenSim/Region/Physics/BulletXPlugin/BulletXPlugin.cs +++ b/OpenSim/Region/Physics/BulletXPlugin/BulletXPlugin.cs @@ -1,534 +1,534 @@ -/* -* 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. -* -*/ -#region References -using System; -using System.Collections.Generic; -using OpenSim.Physics.Manager; -using Axiom.Math; -//Specific References for BulletXPlugin -using MonoXnaCompactMaths; -using XnaDevRu.BulletX; -using XnaDevRu.BulletX.Dynamics; -#endregion - -namespace OpenSim.Region.Physics.BulletXPlugin -{ - /// - /// This Class converts objects and types for BulletX - /// - public class BulletXConversions - { - public static MonoXnaCompactMaths.Vector3 PhysicsVectorToXnaVector3(PhysicsVector physicsVector) - { - return new MonoXnaCompactMaths.Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z); - } - public static void PhysicsVectorToXnaVector3(PhysicsVector physicsVector, out MonoXnaCompactMaths.Vector3 XnaVector3) - { - XnaVector3.X = physicsVector.X; - XnaVector3.Y = physicsVector.Y; - XnaVector3.Z = physicsVector.Z; - } - public static PhysicsVector XnaVector3ToPhysicsVector(MonoXnaCompactMaths.Vector3 xnaVector3) - { - return new PhysicsVector(xnaVector3.X, xnaVector3.Y, xnaVector3.Z); - } - /*public static void XnaVector3ToPhysicsVector(MonoXnaCompactMaths.Vector3 xnaVector3, out PhysicsVector physicsVector) - { - xnaVector3.X = physicsVector.X; - xnaVector3.Y = physicsVector.Y; - xnaVector3.Z = physicsVector.Z; - }*/ - #region Axiom and Xna - ///// - ///// BTW maybe some conversions will be a simply converion that it doesn't require this class, but i don't know - ///// - ///// - ///// - //public static MonoXnaCompactMaths.Vector3 Vector3AxiomToXna(Axiom.Math.Vector3 AxiomVector3) - //{ - // return new MonoXnaCompactMaths.Vector3(AxiomVector3.x, AxiomVector3.y, AxiomVector3.z); - //} - #endregion - } - /// - /// PhysicsPlugin Class for BulletX - /// - public class BulletXPlugin : IPhysicsPlugin - { - private BulletXScene _mScene; - - public BulletXPlugin() - { - } - public bool Init() - { - return true; - } - public PhysicsScene GetScene() - { - if (_mScene == null) - { - _mScene = new BulletXScene(); - } - return (_mScene); - } - public string GetName() - { - return ("BulletXEngine"); - } - public void Dispose() - { - } - } - /// - /// PhysicsScene Class for BulletX - /// - public class BulletXScene : PhysicsScene - { - public DiscreteDynamicsWorld ddWorld; - private CollisionDispatcher cDispatcher; - private OverlappingPairCache opCache; - private SequentialImpulseConstraintSolver sicSolver; - - private const int minXY = 0; - private const int minZ = 0; - private const int maxXY = 256; - private const int maxZ = 4096; - private const int maxHandles = 32766; //Why? I don't know - private static float gravity = 9.8f; - private static float heightLevel0 = 77.0f; - private static float heightLevel1 = 200.0f; - private static float lowGravityFactor = 0.2f; - - private float[] _heightmap; - private List _characters = new List(); - - public static float Gravity { get { return gravity; } } - public static float HeightLevel0 { get { return heightLevel0; } } - public static float HeightLevel1 { get { return heightLevel1; } } - public static float LowGravityFactor { get { return lowGravityFactor; } } - - public BulletXScene() - { - cDispatcher = new CollisionDispatcher(); - MonoXnaCompactMaths.Vector3 worldMinDim = new MonoXnaCompactMaths.Vector3((float)minXY, (float)minXY, (float)minZ); - MonoXnaCompactMaths.Vector3 worldMaxDim = new MonoXnaCompactMaths.Vector3((float)maxXY, (float)maxXY, (float)maxZ); - opCache = new AxisSweep3(worldMinDim, worldMaxDim, maxHandles); - sicSolver = new SequentialImpulseConstraintSolver(); - - ddWorld = new DiscreteDynamicsWorld(cDispatcher, opCache, sicSolver); - ddWorld.Gravity = new MonoXnaCompactMaths.Vector3(0, 0, -gravity); - - this._heightmap = new float[65536]; - } - - public override PhysicsActor AddAvatar(PhysicsVector position) - { - PhysicsVector pos = new PhysicsVector(); - pos.X = position.X; - pos.Y = position.Y; - pos.Z = position.Z + 20; - BulletXCharacter newAv = new BulletXCharacter(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 BulletXPrim(); - } - - public override void Simulate(float timeStep) - { - foreach (BulletXCharacter actor in _characters) - { - actor.Move(timeStep); - - } - ddWorld.StepSimulation(timeStep, 0, timeStep); - foreach (BulletXCharacter actor in _characters) - { - actor.ValidateHeight(this._heightmap[ - (int)Math.Round(actor.RigidBodyHorizontalPosition.x) * 256 - + (int)Math.Round(actor.RigidBodyHorizontalPosition.y)]); - } - foreach (BulletXCharacter 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) - { - //As the same as ODE, heightmap (x,y) must be swapped for BulletX - 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] = heightMap[x * 256 + y]; - } - } - - public override void DeleteTerrain() - { - - } - } - /// - /// PhysicsActor Character Class for BulletX - /// - public class BulletXCharacter : PhysicsActor - { - private PhysicsVector _position; - private PhysicsVector _velocity; - private PhysicsVector _acceleration; - private bool flying; - private RigidBody rigidBody; - public Axiom.Math.Vector2 RigidBodyHorizontalPosition - { - get - { - return new Axiom.Math.Vector2(this.rigidBody.CenterOfMassPosition.X, this.rigidBody.CenterOfMassPosition.Y); - } - } - public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos) - { - _velocity = new PhysicsVector(); - _position = pos; - _acceleration = new PhysicsVector(); - float _mass = 50.0f; //This depends of avatar's dimensions - Matrix _startTransform = Matrix.Identity; - _startTransform.Translation = BulletXConversions.PhysicsVectorToXnaVector3(pos); - Matrix _centerOfMassOffset = Matrix.Identity; - CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(0.5f, 0.5f, 1.60f)); - DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset); - MonoXnaCompactMaths.Vector3 _localInertia = new MonoXnaCompactMaths.Vector3(); - _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0 - - //The next values might change - float _linearDamping = 0.0f; - float _angularDamping = 0.0f; - float _friction = 0.5f; - float _restitution = 0.0f; - - rigidBody = new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping, _friction, _restitution); - rigidBody.ActivationState = ActivationState.DisableDeactivation; - - parent_scene.ddWorld.AddRigidBody(rigidBody); - } - - 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.Math.Quaternion Orientation - { - get - { - return Axiom.Math.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) - { - MonoXnaCompactMaths.Vector3 vec = new MonoXnaCompactMaths.Vector3(); - //if (this._velocity.X == 0.0f) - // vec.X = this.rigidBody.LinearVelocity.X; //current velocity - //else - vec.X = this._velocity.X; //overrides current velocity - - //if (this._velocity.Y == 0.0f) - // vec.Y = this.rigidBody.LinearVelocity.Y; //current velocity - //else - vec.Y = this._velocity.Y; //overrides current velocity - - float nextZVelocity; - //if (this._velocity.Z == 0.0f) - // nextZVelocity = this.rigidBody.LinearVelocity.Z; //current velocity - //else - nextZVelocity = this._velocity.Z; //overrides current velocity - - if (flying) - { - //Antigravity with movement - if (this._position.Z <= BulletXScene.HeightLevel0) - { - vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep; - } - //Lowgravity with movement - else if((this._position.Z > BulletXScene.HeightLevel0) - && (this._position.Z <= BulletXScene.HeightLevel1)) - { - vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); - } - //Lowgravity with... - else if (this._position.Z > BulletXScene.HeightLevel1) - { - if(nextZVelocity > 0) //no movement - vec.Z = BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); - else - vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); - - } - } - else - { - vec.Z = nextZVelocity; - } - rigidBody.LinearVelocity = vec; - } - - public void UpdatePosition() - { - this._position = BulletXConversions.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition); - } - - //This validation is very basic - internal void ValidateHeight(float heighmapPositionValue) - { - if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue) - { - Matrix m = rigidBody.WorldTransform; - MonoXnaCompactMaths.Vector3 v3 = m.Translation; - v3.Z = heighmapPositionValue; - m.Translation = v3; - rigidBody.WorldTransform = m; - } - } - } - /// - /// PhysicsActor Prim Class for BulletX - /// - public class BulletXPrim : PhysicsActor - { - private PhysicsVector _position; - private PhysicsVector _velocity; - private PhysicsVector _acceleration; - - public BulletXPrim() - { - _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.Math.Quaternion Orientation - { - get - { - Axiom.Math.Quaternion res = new Axiom.Math.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) - { - - } - } -} +/* +* 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. +* +*/ +#region References +using System; +using System.Collections.Generic; +using OpenSim.Physics.Manager; +using Axiom.Math; +//Specific References for BulletXPlugin +using MonoXnaCompactMaths; +using XnaDevRu.BulletX; +using XnaDevRu.BulletX.Dynamics; +#endregion + +namespace OpenSim.Region.Physics.BulletXPlugin +{ + /// + /// This Class converts objects and types for BulletX + /// + public class BulletXConversions + { + public static MonoXnaCompactMaths.Vector3 PhysicsVectorToXnaVector3(PhysicsVector physicsVector) + { + return new MonoXnaCompactMaths.Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z); + } + public static void PhysicsVectorToXnaVector3(PhysicsVector physicsVector, out MonoXnaCompactMaths.Vector3 XnaVector3) + { + XnaVector3.X = physicsVector.X; + XnaVector3.Y = physicsVector.Y; + XnaVector3.Z = physicsVector.Z; + } + public static PhysicsVector XnaVector3ToPhysicsVector(MonoXnaCompactMaths.Vector3 xnaVector3) + { + return new PhysicsVector(xnaVector3.X, xnaVector3.Y, xnaVector3.Z); + } + /*public static void XnaVector3ToPhysicsVector(MonoXnaCompactMaths.Vector3 xnaVector3, out PhysicsVector physicsVector) + { + xnaVector3.X = physicsVector.X; + xnaVector3.Y = physicsVector.Y; + xnaVector3.Z = physicsVector.Z; + }*/ + #region Axiom and Xna + ///// + ///// BTW maybe some conversions will be a simply converion that it doesn't require this class, but i don't know + ///// + ///// + ///// + //public static MonoXnaCompactMaths.Vector3 Vector3AxiomToXna(Axiom.Math.Vector3 AxiomVector3) + //{ + // return new MonoXnaCompactMaths.Vector3(AxiomVector3.x, AxiomVector3.y, AxiomVector3.z); + //} + #endregion + } + /// + /// PhysicsPlugin Class for BulletX + /// + public class BulletXPlugin : IPhysicsPlugin + { + private BulletXScene _mScene; + + public BulletXPlugin() + { + } + public bool Init() + { + return true; + } + public PhysicsScene GetScene() + { + if (_mScene == null) + { + _mScene = new BulletXScene(); + } + return (_mScene); + } + public string GetName() + { + return ("BulletXEngine"); + } + public void Dispose() + { + } + } + /// + /// PhysicsScene Class for BulletX + /// + public class BulletXScene : PhysicsScene + { + public DiscreteDynamicsWorld ddWorld; + private CollisionDispatcher cDispatcher; + private OverlappingPairCache opCache; + private SequentialImpulseConstraintSolver sicSolver; + + private const int minXY = 0; + private const int minZ = 0; + private const int maxXY = 256; + private const int maxZ = 4096; + private const int maxHandles = 32766; //Why? I don't know + private static float gravity = 9.8f; + private static float heightLevel0 = 77.0f; + private static float heightLevel1 = 200.0f; + private static float lowGravityFactor = 0.2f; + + private float[] _heightmap; + private List _characters = new List(); + + public static float Gravity { get { return gravity; } } + public static float HeightLevel0 { get { return heightLevel0; } } + public static float HeightLevel1 { get { return heightLevel1; } } + public static float LowGravityFactor { get { return lowGravityFactor; } } + + public BulletXScene() + { + cDispatcher = new CollisionDispatcher(); + MonoXnaCompactMaths.Vector3 worldMinDim = new MonoXnaCompactMaths.Vector3((float)minXY, (float)minXY, (float)minZ); + MonoXnaCompactMaths.Vector3 worldMaxDim = new MonoXnaCompactMaths.Vector3((float)maxXY, (float)maxXY, (float)maxZ); + opCache = new AxisSweep3(worldMinDim, worldMaxDim, maxHandles); + sicSolver = new SequentialImpulseConstraintSolver(); + + ddWorld = new DiscreteDynamicsWorld(cDispatcher, opCache, sicSolver); + ddWorld.Gravity = new MonoXnaCompactMaths.Vector3(0, 0, -gravity); + + this._heightmap = new float[65536]; + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + PhysicsVector pos = new PhysicsVector(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z + 20; + BulletXCharacter newAv = new BulletXCharacter(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 BulletXPrim(); + } + + public override void Simulate(float timeStep) + { + foreach (BulletXCharacter actor in _characters) + { + actor.Move(timeStep); + + } + ddWorld.StepSimulation(timeStep, 0, timeStep); + foreach (BulletXCharacter actor in _characters) + { + actor.ValidateHeight(this._heightmap[ + (int)Math.Round(actor.RigidBodyHorizontalPosition.x) * 256 + + (int)Math.Round(actor.RigidBodyHorizontalPosition.y)]); + } + foreach (BulletXCharacter 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) + { + //As the same as ODE, heightmap (x,y) must be swapped for BulletX + 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] = heightMap[x * 256 + y]; + } + } + + public override void DeleteTerrain() + { + + } + } + /// + /// PhysicsActor Character Class for BulletX + /// + public class BulletXCharacter : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private bool flying; + private RigidBody rigidBody; + public Axiom.Math.Vector2 RigidBodyHorizontalPosition + { + get + { + return new Axiom.Math.Vector2(this.rigidBody.CenterOfMassPosition.X, this.rigidBody.CenterOfMassPosition.Y); + } + } + public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos) + { + _velocity = new PhysicsVector(); + _position = pos; + _acceleration = new PhysicsVector(); + float _mass = 50.0f; //This depends of avatar's dimensions + Matrix _startTransform = Matrix.Identity; + _startTransform.Translation = BulletXConversions.PhysicsVectorToXnaVector3(pos); + Matrix _centerOfMassOffset = Matrix.Identity; + CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(0.5f, 0.5f, 1.60f)); + DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset); + MonoXnaCompactMaths.Vector3 _localInertia = new MonoXnaCompactMaths.Vector3(); + _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0 + + //The next values might change + float _linearDamping = 0.0f; + float _angularDamping = 0.0f; + float _friction = 0.5f; + float _restitution = 0.0f; + + rigidBody = new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping, _friction, _restitution); + rigidBody.ActivationState = ActivationState.DisableDeactivation; + + parent_scene.ddWorld.AddRigidBody(rigidBody); + } + + 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.Math.Quaternion Orientation + { + get + { + return Axiom.Math.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) + { + MonoXnaCompactMaths.Vector3 vec = new MonoXnaCompactMaths.Vector3(); + //if (this._velocity.X == 0.0f) + // vec.X = this.rigidBody.LinearVelocity.X; //current velocity + //else + vec.X = this._velocity.X; //overrides current velocity + + //if (this._velocity.Y == 0.0f) + // vec.Y = this.rigidBody.LinearVelocity.Y; //current velocity + //else + vec.Y = this._velocity.Y; //overrides current velocity + + float nextZVelocity; + //if (this._velocity.Z == 0.0f) + // nextZVelocity = this.rigidBody.LinearVelocity.Z; //current velocity + //else + nextZVelocity = this._velocity.Z; //overrides current velocity + + if (flying) + { + //Antigravity with movement + if (this._position.Z <= BulletXScene.HeightLevel0) + { + vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep; + } + //Lowgravity with movement + else if((this._position.Z > BulletXScene.HeightLevel0) + && (this._position.Z <= BulletXScene.HeightLevel1)) + { + vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); + } + //Lowgravity with... + else if (this._position.Z > BulletXScene.HeightLevel1) + { + if(nextZVelocity > 0) //no movement + vec.Z = BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); + else + vec.Z = nextZVelocity + BulletXScene.Gravity * timeStep * (1.0f - BulletXScene.LowGravityFactor); + + } + } + else + { + vec.Z = nextZVelocity; + } + rigidBody.LinearVelocity = vec; + } + + public void UpdatePosition() + { + this._position = BulletXConversions.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition); + } + + //This validation is very basic + internal void ValidateHeight(float heighmapPositionValue) + { + if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue) + { + Matrix m = rigidBody.WorldTransform; + MonoXnaCompactMaths.Vector3 v3 = m.Translation; + v3.Z = heighmapPositionValue; + m.Translation = v3; + rigidBody.WorldTransform = m; + } + } + } + /// + /// PhysicsActor Prim Class for BulletX + /// + public class BulletXPrim : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + + public BulletXPrim() + { + _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.Math.Quaternion Orientation + { + get + { + Axiom.Math.Quaternion res = new Axiom.Math.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/Manager/AssemblyInfo.cs b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs index 9415db9..27b467f 100644 --- a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index da3b560..2c2c8dd 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -1,167 +1,167 @@ -/* -* 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 Axiom.Math; - -namespace OpenSim.Physics.Manager -{ - public delegate void PositionUpdate(PhysicsVector position); - public delegate void VelocityUpdate(PhysicsVector velocity); - public delegate void OrientationUpdate(Quaternion orientation); - - public abstract class PhysicsActor - { - public event PositionUpdate OnPositionUpdate; - public event VelocityUpdate OnVelocityUpdate; - public event OrientationUpdate OnOrientationUpdate; - - 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 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 Quaternion Orientation - { - get - { - return 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; - } - } -} +/* +* 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 Axiom.Math; + +namespace OpenSim.Physics.Manager +{ + public delegate void PositionUpdate(PhysicsVector position); + public delegate void VelocityUpdate(PhysicsVector velocity); + public delegate void OrientationUpdate(Quaternion orientation); + + public abstract class PhysicsActor + { + public event PositionUpdate OnPositionUpdate; + public event VelocityUpdate OnVelocityUpdate; + public event OrientationUpdate OnOrientationUpdate; + + 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 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 Quaternion Orientation + { + get + { + return 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 index 265bce6..7c475e7 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsManager.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsManager.cs @@ -1,115 +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.IO; -using System.Reflection; -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 PhysicsScene.Null; - } - - if(_plugins.ContainsKey(engineName)) - { - MainLog.Instance.WriteLine(LogPriority.LOW,"creating "+engineName); - return _plugins[engineName].GetScene(); - } - else - { - 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(AppDomain.CurrentDomain.BaseDirectory ,"Physics"); - string[] pluginFiles = Directory.GetFiles(path, "*.dll"); - - - for(int i= 0; i + /// Description of MyClass. + /// + public class PhysicsManager + { + private Dictionary _plugins=new Dictionary(); + + public PhysicsManager() + { + + } + + public PhysicsScene GetPhysicsScene(string engineName) + { + if (String.IsNullOrEmpty(engineName)) + { + return PhysicsScene.Null; + } + + if(_plugins.ContainsKey(engineName)) + { + MainLog.Instance.WriteLine(LogPriority.LOW,"creating "+engineName); + return _plugins[engineName].GetScene(); + } + else + { + 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(AppDomain.CurrentDomain.BaseDirectory ,"Physics"); + string[] pluginFiles = Directory.GetFiles(path, "*.dll"); + + + for(int i= 0; i"; - } - } -} +/* +* 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. +* +*/ +namespace OpenSim.Physics.Manager +{ + public class PhysicsVector + { + public float X; + public float Y; + public float Z; + + public PhysicsVector() + { + + } + + public PhysicsVector(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + } + + public static readonly PhysicsVector Zero = new PhysicsVector(0f, 0f, 0f); + + public override string ToString() + { + return "<" + this.X + "," + this.Y + "," + this.Z + ">"; + } + } +} diff --git a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs index ee10430..662b75a 100644 --- a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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/OdePlugin/OdePlugin.cs b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs index 2780188..486fa9e 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs @@ -1,457 +1,457 @@ -/* -* 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 Axiom.Math; -using Ode.NET; -using OpenSim.Physics.Manager; - -namespace OpenSim.Region.Physics.OdePlugin -{ - /// - /// 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(); - - Quaternion q1 =Quaternion.FromAngleAxis(1.5707f, new Vector3(1,0,0)); - Quaternion q2 =Quaternion.FromAngleAxis(1.5707f, new Vector3(0,1,0)); - //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1)); - - q1 = q1 * q2; - //q1 = q1 * q3; - Vector3 v3 = new 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 Quaternion Orientation - { - get - { - return 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 Quaternion Orientation - { - get - { - Quaternion res = new 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) - { - - } - - - } - -} +/* +* 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 Axiom.Math; +using Ode.NET; +using OpenSim.Physics.Manager; + +namespace OpenSim.Region.Physics.OdePlugin +{ + /// + /// 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(); + + Quaternion q1 =Quaternion.FromAngleAxis(1.5707f, new Vector3(1,0,0)); + Quaternion q2 =Quaternion.FromAngleAxis(1.5707f, new Vector3(0,1,0)); + //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1)); + + q1 = q1 * q2; + //q1 = q1 * q3; + Vector3 v3 = new 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 Quaternion Orientation + { + get + { + return 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 Quaternion Orientation + { + get + { + Quaternion res = new 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/PhysXPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs index ee10430..662b75a 100644 --- a/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/PhysXPlugin/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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/PhysXPlugin.cs b/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs index 4c82549..111d436 100644 --- a/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs +++ b/OpenSim/Region/Physics/PhysXPlugin/PhysXPlugin.cs @@ -1,425 +1,425 @@ -/*/* -* 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; -using Quaternion=Axiom.Math.Quaternion; - -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 Quaternion Orientation - { - get - { - return 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 Quaternion Orientation - { - get - { - Quaternion res = new 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) - { - - } - - - } - -} +/*/* +* 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; +using Quaternion=Axiom.Math.Quaternion; + +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 Quaternion Orientation + { + get + { + return 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 Quaternion Orientation + { + get + { + Quaternion res = new 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 index f5da4c0..d6debed 100644 --- a/OpenSim/Region/Scripting/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Scripting/Properties/AssemblyInfo.cs @@ -1,35 +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")] +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 index 0f4af00..0551ea0 100644 --- a/OpenSim/Region/Scripting/Script.cs +++ b/OpenSim/Region/Scripting/Script.cs @@ -1,32 +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!"); - } - } -} +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 index a9fede5..ce814a4 100644 --- a/OpenSim/Region/Scripting/ScriptAccess.cs +++ b/OpenSim/Region/Scripting/ScriptAccess.cs @@ -1,31 +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; - } - } -} +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/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs index 39ba6e4..0a88594 100644 --- a/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs +++ b/OpenSim/Region/Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs @@ -1,112 +1,112 @@ -/* -* 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 BerkeleyDb; -using libsecondlife; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.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, 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(); - } - } +/* +* 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 BerkeleyDb; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.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, 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/LocalStorageDb4o/AssemblyInfo.cs b/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs index 4463ac9..a3aac18 100644 --- a/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs +++ b/OpenSim/Region/Storage/LocalStorageDb4o/AssemblyInfo.cs @@ -1,56 +1,56 @@ -/* -* 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.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.*")] +/* +* 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.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 index 8214bc8..8d9f473 100644 --- a/OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs +++ b/OpenSim/Region/Storage/LocalStorageDb4o/Db4LocalStorage.cs @@ -1,267 +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 Db4objects.Db4o; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Storage.LocalStorageDb4o -{ - /// - /// - /// - public class Db4LocalStorage : ILocalStorage - { - private IObjectContainer db; - private string datastore; - - public Db4LocalStorage() - { - - } - - public void Initialise(string dfile) - { - MainLog.Instance.Warn("Db4LocalStorage Opening " + dfile); - datastore = dfile; - try - { - db = Db4oFactory.OpenFile(datastore); - MainLog.Instance.Verbose("Db4LocalStorage creation"); - } - catch (Exception e) - { - db.Close(); - MainLog.Instance.Warn("Db4LocalStorage :Constructor - Exception occured"); - 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)); - 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() - { - MainLog.Instance.Verbose("LoadWorld() - Loading world...."); - float[] heightmap = null; - MainLog.Instance.Verbose("LoadWorld() - Looking for a heightmap in local DB"); - IObjectSet world_result = db.Get(typeof(MapStorage)); - if (world_result.Count > 0) - { - 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) - { - 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(); - } - } +/* +* 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 Db4objects.Db4o; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.Storage.LocalStorageDb4o +{ + /// + /// + /// + public class Db4LocalStorage : ILocalStorage + { + private IObjectContainer db; + private string datastore; + + public Db4LocalStorage() + { + + } + + public void Initialise(string dfile) + { + MainLog.Instance.Warn("Db4LocalStorage Opening " + dfile); + datastore = dfile; + try + { + db = Db4oFactory.OpenFile(datastore); + MainLog.Instance.Verbose("Db4LocalStorage creation"); + } + catch (Exception e) + { + db.Close(); + MainLog.Instance.Warn("Db4LocalStorage :Constructor - Exception occured"); + 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)); + 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() + { + MainLog.Instance.Verbose("LoadWorld() - Loading world...."); + float[] heightmap = null; + MainLog.Instance.Verbose("LoadWorld() - Looking for a heightmap in local DB"); + IObjectSet world_result = db.Get(typeof(MapStorage)); + if (world_result.Count > 0) + { + 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) + { + 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 index ec82d02..3a5dd19 100644 --- a/OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs +++ b/OpenSim/Region/Storage/LocalStorageDb4o/MapStorage.cs @@ -1,39 +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. -* -*/ -namespace OpenSim.Region.Storage.LocalStorageDb4o -{ - public class MapStorage - { - public float[] Map; - - public MapStorage() - { - - } - } +/* +* 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. +* +*/ +namespace OpenSim.Region.Storage.LocalStorageDb4o +{ + public class MapStorage + { + public float[] Map; + + public MapStorage() + { + + } + } } \ No newline at end of file diff --git a/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs index 6e6768c..debaa88 100644 --- a/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs +++ b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDParcelQuery.cs @@ -1,47 +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 Db4objects.Db4o.Query; -using libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Storage.LocalStorageDb4o -{ - public class UUIDParcelQuery : Predicate - { - private LLUUID globalIDSearch; - - public UUIDParcelQuery(LLUUID find) - { - globalIDSearch = find; - } - public bool Match(ParcelData parcel) - { - return (parcel.globalID == globalIDSearch); - } - } -} +/* +* 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 Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.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 index eb309cb..d5077ff 100644 --- a/OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs +++ b/OpenSim/Region/Storage/LocalStorageDb4o/UUIDPrimQuery.cs @@ -1,47 +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 Db4objects.Db4o.Query; -using libsecondlife; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.Storage.LocalStorageDb4o -{ - public class UUIDPrimQuery : Predicate - { - private LLUUID _findID; - - public UUIDPrimQuery(LLUUID find) - { - _findID = find; - } - public bool Match(PrimData prim) - { - return (prim.FullID == _findID); - } - } -} +/* +* 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 Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.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/Properties/AssemblyInfo.cs b/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs index 7bc1cc5..6bbaf0f 100644 --- a/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs @@ -1,60 +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.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.Region.Storage.LocalStorageSQLite")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.Region.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.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +/* +* 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.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.Region.Storage.LocalStorageSQLite")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Region.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.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs b/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs index 9900a98..599ff6c 100644 --- a/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs +++ b/OpenSim/Region/Storage/LocalStorageSQLite/SQLiteLocalStorage.cs @@ -1,198 +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.Data; -using System.Data.SQLite; -using libsecondlife; -using OpenSim.Framework.Console; -using OpenSim.Framework.Interfaces; -using OpenSim.Framework.Types; - -namespace OpenSim.Region.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(); - MainLog.Instance.Warn("SQLiteLocalStorage :Constructor - Exception occured"); - 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) - { - MainLog.Instance.Warn("SQLiteLocalStorage :StorePrim - Exception occured"); - 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) - { - MainLog.Instance.Warn("SQLiteLocalStorage :RemovePrim - Exception occured"); - 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; - } - } +/* +* 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.Data; +using System.Data.SQLite; +using libsecondlife; +using OpenSim.Framework.Console; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Region.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(); + MainLog.Instance.Warn("SQLiteLocalStorage :Constructor - Exception occured"); + 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) + { + MainLog.Instance.Warn("SQLiteLocalStorage :StorePrim - Exception occured"); + 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) + { + MainLog.Instance.Warn("SQLiteLocalStorage :RemovePrim - Exception occured"); + 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/Storage/OpenSim.DataStore.NullStorage/NullDataStore.cs b/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/NullDataStore.cs index 7c8bd07..3ce0967 100644 --- a/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/NullDataStore.cs +++ b/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/NullDataStore.cs @@ -1,65 +1,66 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using OpenSim.Region.Environment.Scenes; -using OpenSim.Region.Environment; -using OpenSim.Region.Interfaces; -using OpenSim.Framework.Console; -using libsecondlife; - -namespace OpenSim.DataStore.NullStorage -{ - public class NullDataStore : IRegionDataStore - { - public void Initialise(string dbfile, string dbname) - { - return; - } - - public void StoreObject(SceneObject obj) - { - - } - - public void RemoveObject(LLUUID obj) - { - - } - - public List LoadObjects() - { - return new List(); - } - - public void StoreTerrain(double[,] ter) - { - - } - - public double[,] LoadTerrain() - { - return null; - } - - public void RemoveParcel(uint id) - { - - } - - public void StoreParcel(OpenSim.Region.Environment.Parcel parcel) - { - - } - - public List LoadParcels() - { - return new List(); - } - - public void Shutdown() - { - - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.Environment; +using OpenSim.Region.Interfaces; +using OpenSim.Framework.Console; +using libsecondlife; + +namespace OpenSim.DataStore.NullStorage +{ + public class NullDataStore : IRegionDataStore + { + + public void Initialise(string dbfile, string dbname) + { + return; + } + + public void StoreObject(SceneObject obj) + { + + } + + public void RemoveObject(LLUUID obj) + { + + } + + public List LoadObjects() + { + return new List(); + } + + public void StoreTerrain(double[,] ter) + { + + } + + public double[,] LoadTerrain() + { + return null; + } + + public void RemoveParcel(uint id) + { + + } + + public void StoreParcel(OpenSim.Region.Environment.Parcel parcel) + { + + } + + public List LoadParcels() + { + return new List(); + } + + public void Shutdown() + { + + } + } +} diff --git a/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/Properties/AssemblyInfo.cs b/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/Properties/AssemblyInfo.cs index c0bd46d..fd86315 100644 --- a/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Storage/OpenSim.DataStore.NullStorage/Properties/AssemblyInfo.cs @@ -1,35 +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.DataStore.NullStorage")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.DataStore.NullStorage")] -[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("b4a1656d-de22-4080-a970-fd8166acbf16")] - -// 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")] +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.DataStore.NullStorage")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.DataStore.NullStorage")] +[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("b4a1656d-de22-4080-a970-fd8166acbf16")] + +// 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/Properties/AssemblyInfo.cs b/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs index 9c721d1..c523cd6 100644 --- a/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Terrain.BasicTerrain/Properties/AssemblyInfo.cs @@ -1,60 +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.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.Region.Terrain.BasicTerrain")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OpenSim.Region.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")] +/* +* 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.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.Region.Terrain.BasicTerrain")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Region.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 index f017e44..6f3afea 100644 --- a/OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs +++ b/OpenSim/Region/Terrain.BasicTerrain/TerrainEngine.cs @@ -1,954 +1,954 @@ -/* -* 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.Drawing; -using System.Drawing.Imaging; -using System.IO; -using libTerrain; -using OpenJPEGNet; - -namespace OpenSim.Region.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; - } - - /// - /// Converts the heightmap to a 256x256 value 2D floating point array. Double precision version. - /// - /// An array of 256,256 values containing the heightmap - public double[,] getHeights2DD() - { - return heightmap.map; - } - - /// - /// 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++; - } - - /// - /// Loads a 2D array of values into the heightmap (Double Precision Version) - /// - /// An array of 256,256 float values - public void setHeights2D(double[,] heights) - { - int x, y; - for (x = 0; x < w; x++) - { - for (y = 0; y < h; y++) - { - heightmap.set(x, y, 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 simName) - { - 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', 'PNG', 'RAW' or 'HIRAW'\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": - args[2].Replace("%name%", simName); - 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": - args[2].Replace("%name%", simName); - 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; - - case "raw": - writeToFileRAW(args[2]); - break; - - case "hiraw": - writeToFileHiRAW(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) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.Open, FileAccess.Read); - BinaryReader bs = new 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) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.Open, FileAccess.Read); - BinaryReader bs = new 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) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.Open, FileAccess.Read); - BinaryReader bs = new 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) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); - BinaryWriter bs = new 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) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); - BinaryWriter bs = new 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(); - } - - /// - /// A very fast LL-RAW file output mechanism - lower precision mechanism but wont take 5 minutes to run either. - /// (is also editable in an image application) - /// - /// Filename to write to - public void writeToFileRAW(string filename) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); - BinaryWriter bs = new BinaryWriter(s); - - int x, y; - - // Used for the 'green' channel. - byte avgMultiplier = (byte)heightmap.avg(); - byte backupMultiplier = (byte)revertmap.avg(); - - // Limit the multiplier so it can represent points >64m. - if (avgMultiplier > 196) - avgMultiplier = 196; - if(backupMultiplier > 196) - backupMultiplier = 196; - // Make sure it's at least one to prevent a div by zero - if (avgMultiplier < 1) - avgMultiplier = 1; - if(backupMultiplier < 1) - backupMultiplier = 1; - - for (x = 0; x < w; x++) - { - for (y = 0; y < h; y++) - { - byte red = (byte)(heightmap.get(x, y) / ((double)avgMultiplier / 128.0)); - byte green = avgMultiplier; - byte blue = (byte)watermap.get(x, y); - byte alpha1 = 0; // Land Parcels - byte alpha2 = 0; // For Sale Land - byte alpha3 = 0; // Public Edit Object - byte alpha4 = 0; // Public Edit Land - byte alpha5 = 255; // Safe Land - byte alpha6 = 255; // Flying Allowed - byte alpha7 = 255; // Create Landmark - byte alpha8 = 255; // Outside Scripts - byte alpha9 = (byte)(revertmap.get(x, y) / ((double)backupMultiplier / 128.0)); - byte alpha10 = backupMultiplier; - - bs.Write(red); - bs.Write(green); - bs.Write(blue); - bs.Write(alpha1); - bs.Write(alpha2); - bs.Write(alpha3); - bs.Write(alpha4); - bs.Write(alpha5); - bs.Write(alpha6); - bs.Write(alpha7); - bs.Write(alpha8); - bs.Write(alpha9); - bs.Write(alpha10); - } - } - bs.Close(); - s.Close(); - } - - /// - /// Outputs to a LL compatible RAW in the most efficient manner possible - /// - /// Does not calculate the revert map - /// The filename to output to - public void writeToFileHiRAW(string filename) - { - FileInfo file = new FileInfo(filename); - FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); - BinaryWriter bs = new BinaryWriter(s); - - // Generate a smegging big lookup table to speed the operation up (it needs it) - double[] lookupTable = new double[65536]; - int i, j, x, y; - for (i = 0; i < 256; i++) - { - for (j = 0; j < 256; j++) - { - lookupTable[i + (j * 256)] = ((double)i * ((double)j / 127.0)); - } - } - - // Output the calculated raw - for (x = 0; x < w; x++) - { - for (y = 0; y < h; y++) - { - double t = heightmap.get(x, y); - double min = double.MaxValue; - int index = 0; - - for (i = 0; i < 65536; i++) - { - if (Math.Abs(t - lookupTable[i]) < min) - { - min = Math.Abs(t - lookupTable[i]); - index = i; - } - } - - byte red = (byte)(index & 0xFF); - byte green = (byte)((index >> 8) & 0xFF); - byte blue = (byte)watermap.get(x, y); - byte alpha1 = 0; // Land Parcels - byte alpha2 = 0; // For Sale Land - byte alpha3 = 0; // Public Edit Object - byte alpha4 = 0; // Public Edit Land - byte alpha5 = 255; // Safe Land - byte alpha6 = 255; // Flying Allowed - byte alpha7 = 255; // Create Landmark - byte alpha8 = 255; // Outside Scripts - byte alpha9 = red; - byte alpha10 = green; - - bs.Write(red); - bs.Write(green); - bs.Write(blue); - bs.Write(alpha1); - bs.Write(alpha2); - bs.Write(alpha3); - bs.Write(alpha4); - bs.Write(alpha5); - bs.Write(alpha6); - bs.Write(alpha7); - bs.Write(alpha8); - bs.Write(alpha9); - bs.Write(alpha10); - } - } - - 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++; - } - - /// - /// Wrapper to heightmap.get() - /// - /// X coord - /// Y coord - /// Height at specified coordinates - public double get(int x, int y) - { - return heightmap.get(x, y); - } - - /// - /// Multiplies the heightfield by val - /// - /// The heightfield - /// The multiplier - /// - public static TerrainEngine operator *(TerrainEngine meep, Double val) - { - meep.heightmap *= val; - meep.tainted++; - return meep; - } - - /// - /// 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, 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 = OpenJPEG.EncodeFromImage(bmp, true ); - - } - catch (Exception e) - { - Console.WriteLine("Failed generating terrain map: " + e.ToString()); - } - - return imageData; - } - } +/* +* 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.Drawing; +using System.Drawing.Imaging; +using System.IO; +using libTerrain; +using OpenJPEGNet; + +namespace OpenSim.Region.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; + } + + /// + /// Converts the heightmap to a 256x256 value 2D floating point array. Double precision version. + /// + /// An array of 256,256 values containing the heightmap + public double[,] getHeights2DD() + { + return heightmap.map; + } + + /// + /// 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++; + } + + /// + /// Loads a 2D array of values into the heightmap (Double Precision Version) + /// + /// An array of 256,256 float values + public void setHeights2D(double[,] heights) + { + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.set(x, y, 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 simName) + { + 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', 'PNG', 'RAW' or 'HIRAW'\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": + args[2].Replace("%name%", simName); + 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": + args[2].Replace("%name%", simName); + 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; + + case "raw": + writeToFileRAW(args[2]); + break; + + case "hiraw": + writeToFileHiRAW(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) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.Open, FileAccess.Read); + BinaryReader bs = new 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) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.Open, FileAccess.Read); + BinaryReader bs = new 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) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.Open, FileAccess.Read); + BinaryReader bs = new 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) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); + BinaryWriter bs = new 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) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); + BinaryWriter bs = new 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(); + } + + /// + /// A very fast LL-RAW file output mechanism - lower precision mechanism but wont take 5 minutes to run either. + /// (is also editable in an image application) + /// + /// Filename to write to + public void writeToFileRAW(string filename) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); + BinaryWriter bs = new BinaryWriter(s); + + int x, y; + + // Used for the 'green' channel. + byte avgMultiplier = (byte)heightmap.avg(); + byte backupMultiplier = (byte)revertmap.avg(); + + // Limit the multiplier so it can represent points >64m. + if (avgMultiplier > 196) + avgMultiplier = 196; + if(backupMultiplier > 196) + backupMultiplier = 196; + // Make sure it's at least one to prevent a div by zero + if (avgMultiplier < 1) + avgMultiplier = 1; + if(backupMultiplier < 1) + backupMultiplier = 1; + + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + byte red = (byte)(heightmap.get(x, y) / ((double)avgMultiplier / 128.0)); + byte green = avgMultiplier; + byte blue = (byte)watermap.get(x, y); + byte alpha1 = 0; // Land Parcels + byte alpha2 = 0; // For Sale Land + byte alpha3 = 0; // Public Edit Object + byte alpha4 = 0; // Public Edit Land + byte alpha5 = 255; // Safe Land + byte alpha6 = 255; // Flying Allowed + byte alpha7 = 255; // Create Landmark + byte alpha8 = 255; // Outside Scripts + byte alpha9 = (byte)(revertmap.get(x, y) / ((double)backupMultiplier / 128.0)); + byte alpha10 = backupMultiplier; + + bs.Write(red); + bs.Write(green); + bs.Write(blue); + bs.Write(alpha1); + bs.Write(alpha2); + bs.Write(alpha3); + bs.Write(alpha4); + bs.Write(alpha5); + bs.Write(alpha6); + bs.Write(alpha7); + bs.Write(alpha8); + bs.Write(alpha9); + bs.Write(alpha10); + } + } + bs.Close(); + s.Close(); + } + + /// + /// Outputs to a LL compatible RAW in the most efficient manner possible + /// + /// Does not calculate the revert map + /// The filename to output to + public void writeToFileHiRAW(string filename) + { + FileInfo file = new FileInfo(filename); + FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); + BinaryWriter bs = new BinaryWriter(s); + + // Generate a smegging big lookup table to speed the operation up (it needs it) + double[] lookupTable = new double[65536]; + int i, j, x, y; + for (i = 0; i < 256; i++) + { + for (j = 0; j < 256; j++) + { + lookupTable[i + (j * 256)] = ((double)i * ((double)j / 127.0)); + } + } + + // Output the calculated raw + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + double t = heightmap.get(x, y); + double min = double.MaxValue; + int index = 0; + + for (i = 0; i < 65536; i++) + { + if (Math.Abs(t - lookupTable[i]) < min) + { + min = Math.Abs(t - lookupTable[i]); + index = i; + } + } + + byte red = (byte)(index & 0xFF); + byte green = (byte)((index >> 8) & 0xFF); + byte blue = (byte)watermap.get(x, y); + byte alpha1 = 0; // Land Parcels + byte alpha2 = 0; // For Sale Land + byte alpha3 = 0; // Public Edit Object + byte alpha4 = 0; // Public Edit Land + byte alpha5 = 255; // Safe Land + byte alpha6 = 255; // Flying Allowed + byte alpha7 = 255; // Create Landmark + byte alpha8 = 255; // Outside Scripts + byte alpha9 = red; + byte alpha10 = green; + + bs.Write(red); + bs.Write(green); + bs.Write(blue); + bs.Write(alpha1); + bs.Write(alpha2); + bs.Write(alpha3); + bs.Write(alpha4); + bs.Write(alpha5); + bs.Write(alpha6); + bs.Write(alpha7); + bs.Write(alpha8); + bs.Write(alpha9); + bs.Write(alpha10); + } + } + + 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++; + } + + /// + /// Wrapper to heightmap.get() + /// + /// X coord + /// Y coord + /// Height at specified coordinates + public double get(int x, int y) + { + return heightmap.get(x, y); + } + + /// + /// Multiplies the heightfield by val + /// + /// The heightfield + /// The multiplier + /// + public static TerrainEngine operator *(TerrainEngine meep, Double val) + { + meep.heightmap *= val; + meep.tainted++; + return meep; + } + + /// + /// 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, 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 = OpenJPEG.EncodeFromImage(bmp, true ); + + } + 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 index a38be07..a80ac85 100644 --- a/OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs +++ b/OpenSim/Region/Terrain.BasicTerrain/TerrainFilter.cs @@ -1,126 +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.CodeDom.Compiler; -using System.Collections.Generic; -using libTerrain; -using Microsoft.CSharp; -using Microsoft.JScript; - -namespace OpenSim.Region.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(CodeDomProvider 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, filename); - } - - public void LoadFilterJScript(string filename) - { - JScriptCodeProvider compiler = new JScriptCodeProvider(); - LoadFilter(compiler, filename); - } - } -} +/* +* 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.CodeDom.Compiler; +using System.Collections.Generic; +using libTerrain; +using Microsoft.CSharp; +using Microsoft.JScript; + +namespace OpenSim.Region.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(CodeDomProvider 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, filename); + } + + public void LoadFilterJScript(string filename) + { + JScriptCodeProvider compiler = new JScriptCodeProvider(); + LoadFilter(compiler, filename); + } + } +} -- cgit v1.1