From f95b6081cba084d1b067acea99c0effa2b3bf42c Mon Sep 17 00:00:00 2001 From: MW Date: Thu, 24 May 2007 12:35:32 +0000 Subject: Renamed the new Directories. (removed the "-Source" from the end of them) --- .../OpenSim.GridInterfaces/Local/AssemblyInfo.cs | 31 + .../Local/LocalAssetServer.cs | 271 +++++++++ .../Local/LocalGridServer.cs | 157 +++++ .../Local/OpenSim.GridInterfaces.Local.csproj | 110 ++++ .../Local/OpenSim.GridInterfaces.Local.csproj.user | 12 + .../Local/OpenSim.GridInterfaces.Local.dll.build | 46 ++ .../OpenSim.GridInterfaces/Remote/AssemblyInfo.cs | 31 + .../Remote/OpenSim.GridInterfaces.Remote.csproj | 112 ++++ .../OpenSim.GridInterfaces.Remote.csproj.user | 12 + .../Remote/OpenSim.GridInterfaces.Remote.dll.build | 46 ++ .../Remote/RemoteAssetServer.cs | 108 ++++ .../Remote/RemoteGridServer.cs | 210 +++++++ .../BasicPhysicsPlugin/AssemblyInfo.cs | 31 + .../BasicPhysicsPlugin/BasicPhysicsPlugin.cs | 277 +++++++++ .../OpenSim.Physics.BasicPhysicsPlugin.csproj | 93 +++ .../OpenSim.Physics.BasicPhysicsPlugin.csproj.user | 12 + .../OpenSim.Physics.BasicPhysicsPlugin.dll.build | 42 ++ OpenSim/OpenSim.Physics/Manager/AssemblyInfo.cs | 31 + .../Manager/OpenSim.Physics.Manager.csproj | 112 ++++ .../Manager/OpenSim.Physics.Manager.csproj.user | 12 + .../Manager/OpenSim.Physics.Manager.dll.build | 47 ++ OpenSim/OpenSim.Physics/Manager/PhysicsActor.cs | 161 +++++ OpenSim/OpenSim.Physics/Manager/PhysicsManager.cs | 116 ++++ OpenSim/OpenSim.Physics/Manager/PhysicsScene.cs | 113 ++++ OpenSim/OpenSim.Physics/Manager/PhysicsVector.cs | 54 ++ OpenSim/OpenSim.Physics/OdePlugin/AssemblyInfo.cs | 31 + OpenSim/OpenSim.Physics/OdePlugin/OdePlugin.cs | 452 ++++++++++++++ .../OdePlugin/OpenSim.Physics.OdePlugin.csproj | 97 +++ .../OpenSim.Physics.OdePlugin.csproj.user | 12 + .../OdePlugin/OpenSim.Physics.OdePlugin.dll.build | 43 ++ .../OpenSim.Physics/PhysXPlugin/AssemblyInfo.cs | 31 + .../PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj | 97 +++ .../OpenSim.Physics.PhysXPlugin.csproj.user | 12 + .../OpenSim.Physics.PhysXPlugin.dll.build | 43 ++ OpenSim/OpenSim.Physics/PhysXPlugin/PhysXPlugin.cs | 449 ++++++++++++++ OpenSim/OpenSim.RegionServer/AgentAssetUpload.cs | 232 ++++++++ OpenSim/OpenSim.RegionServer/Assets/AssetCache.cs | 574 ++++++++++++++++++ .../OpenSim.RegionServer/Assets/InventoryCache.cs | 336 +++++++++++ .../AuthenticateSessionsBase.cs | 105 ++++ .../AuthenticateSessionsLocal.cs | 31 + .../AuthenticateSessionsRemote.cs | 46 ++ OpenSim/OpenSim.RegionServer/CAPS/AdminWebFront.cs | 256 ++++++++ OpenSim/OpenSim.RegionServer/ClientView.Grid.cs | 157 +++++ .../ClientView.PacketHandlers.cs | 163 +++++ .../ClientView.ProcessPackets.cs | 453 ++++++++++++++ OpenSim/OpenSim.RegionServer/ClientView.cs | 439 ++++++++++++++ OpenSim/OpenSim.RegionServer/ClientViewBase.cs | 299 ++++++++++ OpenSim/OpenSim.RegionServer/Grid.cs | 90 +++ .../OpenSim.RegionServer.csproj | 258 ++++++++ .../OpenSim.RegionServer.csproj.user | 12 + .../OpenSim.RegionServer.dll.build | 90 +++ OpenSim/OpenSim.RegionServer/OpenSimMain.cs | 531 +++++++++++++++++ .../OpenSim.RegionServer/OpenSimNetworkHandler.cs | 18 + OpenSim/OpenSim.RegionServer/PacketServer.cs | 89 +++ OpenSim/OpenSim.RegionServer/RegionInfo.cs | 261 ++++++++ OpenSim/OpenSim.RegionServer/RegionInfoBase.cs | 32 + OpenSim/OpenSim.RegionServer/RegionServerBase.cs | 103 ++++ OpenSim/OpenSim.RegionServer/UDPServer.cs | 205 +++++++ OpenSim/OpenSim.RegionServer/VersionInfo.cs | 37 ++ OpenSim/OpenSim.RegionServer/types/Mesh.cs | 28 + OpenSim/OpenSim.RegionServer/types/Triangle.cs | 28 + .../OpenSim.RegionServer/world/Avatar.Client.cs | 33 ++ .../OpenSim.RegionServer/world/Avatar.Update.cs | 317 ++++++++++ OpenSim/OpenSim.RegionServer/world/Avatar.cs | 418 +++++++++++++ .../OpenSim.RegionServer/world/AvatarAnimations.cs | 163 +++++ OpenSim/OpenSim.RegionServer/world/Entity.cs | 124 ++++ OpenSim/OpenSim.RegionServer/world/Primitive.cs | 570 ++++++++++++++++++ OpenSim/OpenSim.RegionServer/world/Primitive2.cs | 491 +++++++++++++++ OpenSim/OpenSim.RegionServer/world/SceneObject.cs | 77 +++ .../world/World.PacketHandlers.cs | 368 ++++++++++++ .../OpenSim.RegionServer/world/World.Scripting.cs | 124 ++++ OpenSim/OpenSim.RegionServer/world/World.cs | 656 +++++++++++++++++++++ OpenSim/OpenSim.RegionServer/world/WorldBase.cs | 176 ++++++ .../world/scripting/IScriptContext.cs | 13 + .../world/scripting/IScriptEntity.cs | 19 + .../world/scripting/IScriptHandler.cs | 98 +++ .../OpenSim.RegionServer/world/scripting/Script.cs | 26 + .../world/scripting/ScriptFactory.cs | 8 + .../world/scripting/Scripts/FollowRandomAvatar.cs | 37 ++ .../OpenSim.Scripting/EmbeddedJVM/ClassInstance.cs | 18 + .../OpenSim.Scripting/EmbeddedJVM/ClassRecord.cs | 476 +++++++++++++++ OpenSim/OpenSim.Scripting/EmbeddedJVM/Heap.cs | 16 + .../OpenSim.Scripting/EmbeddedJVM/Interpreter.cs | 108 ++++ .../EmbeddedJVM/InterpreterLogic.cs | 400 +++++++++++++ .../EmbeddedJVM/InterpreterMethods.cs | 141 +++++ .../EmbeddedJVM/InterpreterReturn.cs | 13 + .../OpenSim.Scripting/EmbeddedJVM/MainMemory.cs | 18 + .../OpenSim.Scripting/EmbeddedJVM/MethodMemory.cs | 19 + OpenSim/OpenSim.Scripting/EmbeddedJVM/Object.cs | 10 + .../OpenSim.Scripting.EmbeddedJVM.csproj | 153 +++++ .../OpenSim.Scripting.EmbeddedJVM.csproj.user | 12 + .../OpenSim.Scripting.EmbeddedJVM.dll.build | 62 ++ .../OpenSim.Scripting/EmbeddedJVM/OpenSimJVM.cs | 134 +++++ .../EmbeddedJVM/Properties/AssemblyInfo.cs | 33 ++ OpenSim/OpenSim.Scripting/EmbeddedJVM/Stack.cs | 15 + .../OpenSim.Scripting/EmbeddedJVM/StackFrame.cs | 22 + OpenSim/OpenSim.Scripting/EmbeddedJVM/Thread.cs | 88 +++ .../EmbeddedJVM/Types/ArrayReference.cs | 10 + .../EmbeddedJVM/Types/BaseType.cs | 10 + .../EmbeddedJVM/Types/ObjectReference.cs | 16 + .../EmbeddedJVM/Types/PrimitiveTypes/Byte.cs | 10 + .../EmbeddedJVM/Types/PrimitiveTypes/Char.cs | 10 + .../EmbeddedJVM/Types/PrimitiveTypes/Float.cs | 16 + .../EmbeddedJVM/Types/PrimitiveTypes/Int.cs | 16 + .../LocalStorageBerkeleyDB/BDBLocalStorage.cs | 95 +++ .../OpenSim.Storage.LocalStorageBerkeleyDB.csproj | 112 ++++ ...nSim.Storage.LocalStorageBerkeleyDB.csproj.user | 12 + ...penSim.Storage.LocalStorageBerkeleyDB.dll.build | 46 ++ .../LocalStorageDb4o/AssemblyInfo.cs | 31 + .../LocalStorageDb4o/Db4LocalStorage.cs | 182 ++++++ .../OpenSim.Storage/LocalStorageDb4o/MapStorage.cs | 16 + .../OpenSim.Storage.LocalStorageDb4o.csproj | 113 ++++ .../OpenSim.Storage.LocalStorageDb4o.csproj.user | 12 + .../OpenSim.Storage.LocalStorageDb4o.dll.build | 47 ++ .../OpenSim.Storage/LocalStorageDb4o/UUIDQuery.cs | 25 + .../OpenSim.Storage.LocalStorageSQLite.csproj | 111 ++++ .../OpenSim.Storage.LocalStorageSQLite.csproj.user | 12 + .../OpenSim.Storage.LocalStorageSQLite.dll.build | 46 ++ .../LocalStorageSQLite/Properties/AssemblyInfo.cs | 35 ++ .../LocalStorageSQLite/SQLiteLocalStorage.cs | 176 ++++++ .../OpenSim.Terrain.BasicTerrain.csproj | 95 +++ .../OpenSim.Terrain.BasicTerrain.csproj.user | 12 + .../OpenSim.Terrain.BasicTerrain.dll.build | 43 ++ .../Properties/AssemblyInfo.cs | 35 ++ .../OpenSim.Terrain.BasicTerrain/TerrainEngine.cs | 453 ++++++++++++++ OpenSim/OpenSim/Application.cs | 95 +++ OpenSim/OpenSim/OpenSim.csproj | 147 +++++ OpenSim/OpenSim/OpenSim.csproj.user | 13 + OpenSim/OpenSim/OpenSim.exe.build | 52 ++ OpenSim/OpenSim/OpenSimMain.cs | 533 +++++++++++++++++ 130 files changed, 16480 insertions(+) create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/LocalAssetServer.cs create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/LocalGridServer.cs create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj.user create mode 100644 OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.dll.build create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj.user create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.dll.build create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/RemoteAssetServer.cs create mode 100644 OpenSim/OpenSim.GridInterfaces/Remote/RemoteGridServer.cs create mode 100644 OpenSim/OpenSim.Physics/BasicPhysicsPlugin/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs create mode 100644 OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj create mode 100644 OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj.user create mode 100644 OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.dll.build create mode 100644 OpenSim/OpenSim.Physics/Manager/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj create mode 100644 OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj.user create mode 100644 OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.dll.build create mode 100644 OpenSim/OpenSim.Physics/Manager/PhysicsActor.cs create mode 100644 OpenSim/OpenSim.Physics/Manager/PhysicsManager.cs create mode 100644 OpenSim/OpenSim.Physics/Manager/PhysicsScene.cs create mode 100644 OpenSim/OpenSim.Physics/Manager/PhysicsVector.cs create mode 100644 OpenSim/OpenSim.Physics/OdePlugin/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Physics/OdePlugin/OdePlugin.cs create mode 100644 OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj create mode 100644 OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj.user create mode 100644 OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.dll.build create mode 100644 OpenSim/OpenSim.Physics/PhysXPlugin/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj create mode 100644 OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj.user create mode 100644 OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.dll.build create mode 100644 OpenSim/OpenSim.Physics/PhysXPlugin/PhysXPlugin.cs create mode 100644 OpenSim/OpenSim.RegionServer/AgentAssetUpload.cs create mode 100644 OpenSim/OpenSim.RegionServer/Assets/AssetCache.cs create mode 100644 OpenSim/OpenSim.RegionServer/Assets/InventoryCache.cs create mode 100644 OpenSim/OpenSim.RegionServer/AuthenticateSessionsBase.cs create mode 100644 OpenSim/OpenSim.RegionServer/AuthenticateSessionsLocal.cs create mode 100644 OpenSim/OpenSim.RegionServer/AuthenticateSessionsRemote.cs create mode 100644 OpenSim/OpenSim.RegionServer/CAPS/AdminWebFront.cs create mode 100644 OpenSim/OpenSim.RegionServer/ClientView.Grid.cs create mode 100644 OpenSim/OpenSim.RegionServer/ClientView.PacketHandlers.cs create mode 100644 OpenSim/OpenSim.RegionServer/ClientView.ProcessPackets.cs create mode 100644 OpenSim/OpenSim.RegionServer/ClientView.cs create mode 100644 OpenSim/OpenSim.RegionServer/ClientViewBase.cs create mode 100644 OpenSim/OpenSim.RegionServer/Grid.cs create mode 100644 OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj create mode 100644 OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj.user create mode 100644 OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.dll.build create mode 100644 OpenSim/OpenSim.RegionServer/OpenSimMain.cs create mode 100644 OpenSim/OpenSim.RegionServer/OpenSimNetworkHandler.cs create mode 100644 OpenSim/OpenSim.RegionServer/PacketServer.cs create mode 100644 OpenSim/OpenSim.RegionServer/RegionInfo.cs create mode 100644 OpenSim/OpenSim.RegionServer/RegionInfoBase.cs create mode 100644 OpenSim/OpenSim.RegionServer/RegionServerBase.cs create mode 100644 OpenSim/OpenSim.RegionServer/UDPServer.cs create mode 100644 OpenSim/OpenSim.RegionServer/VersionInfo.cs create mode 100644 OpenSim/OpenSim.RegionServer/types/Mesh.cs create mode 100644 OpenSim/OpenSim.RegionServer/types/Triangle.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Avatar.Client.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Avatar.Update.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Avatar.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/AvatarAnimations.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Entity.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Primitive.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/Primitive2.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/SceneObject.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/World.PacketHandlers.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/World.Scripting.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/World.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/WorldBase.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/IScriptContext.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/IScriptEntity.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/IScriptHandler.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/Script.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/ScriptFactory.cs create mode 100644 OpenSim/OpenSim.RegionServer/world/scripting/Scripts/FollowRandomAvatar.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassInstance.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassRecord.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Heap.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Interpreter.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterLogic.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterMethods.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterReturn.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/MainMemory.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/MethodMemory.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Object.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj.user create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.dll.build create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSimJVM.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Properties/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Stack.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/StackFrame.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Thread.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ArrayReference.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/BaseType.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ObjectReference.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Byte.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Char.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Float.cs create mode 100644 OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Int.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj create mode 100644 OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj.user create mode 100644 OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/Db4LocalStorage.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/MapStorage.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj.user create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.dll.build create mode 100644 OpenSim/OpenSim.Storage/LocalStorageDb4o/UUIDQuery.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj create mode 100644 OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj.user create mode 100644 OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build create mode 100644 OpenSim/OpenSim.Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Storage/LocalStorageSQLite/SQLiteLocalStorage.cs create mode 100644 OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj create mode 100644 OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj.user create mode 100644 OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.dll.build create mode 100644 OpenSim/OpenSim.Terrain.BasicTerrain/Properties/AssemblyInfo.cs create mode 100644 OpenSim/OpenSim.Terrain.BasicTerrain/TerrainEngine.cs create mode 100644 OpenSim/OpenSim/Application.cs create mode 100644 OpenSim/OpenSim/OpenSim.csproj create mode 100644 OpenSim/OpenSim/OpenSim.csproj.user create mode 100644 OpenSim/OpenSim/OpenSim.exe.build create mode 100644 OpenSim/OpenSim/OpenSimMain.cs (limited to 'OpenSim') diff --git a/OpenSim/OpenSim.GridInterfaces/Local/AssemblyInfo.cs b/OpenSim/OpenSim.GridInterfaces/Local/AssemblyInfo.cs new file mode 100644 index 0000000..103b49a --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("LocalGridServers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LocalGridServers")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.GridInterfaces/Local/LocalAssetServer.cs b/OpenSim/OpenSim.GridInterfaces/Local/LocalAssetServer.cs new file mode 100644 index 0000000..5f75821 --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/LocalAssetServer.cs @@ -0,0 +1,271 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.IO; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Console; +using libsecondlife; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; + +namespace OpenSim.GridInterfaces.Local +{ + public class LocalAssetPlugin : IAssetPlugin + { + public LocalAssetPlugin() + { + + } + + public IAssetServer GetAssetServer() + { + return (new LocalAssetServer()); + } + } + + public class LocalAssetServer : IAssetServer + { + private IAssetReceiver _receiver; + private BlockingQueue _assetRequests; + private IObjectContainer db; + private Thread _localAssetServerThread; + + public LocalAssetServer() + { + bool yapfile; + this._assetRequests = new BlockingQueue(); + yapfile = System.IO.File.Exists("assets.yap"); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE,"Local Asset Server class created"); + try + { + db = Db4oFactory.OpenFile("assets.yap"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE,"Db4 Asset database creation"); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.MEDIUM,"Db4 Asset server :Constructor - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, e.ToString()); + } + if (!yapfile) + { + this.SetUpAssetDatabase(); + } + this._localAssetServerThread = new Thread(new ThreadStart(RunRequests)); + this._localAssetServerThread.IsBackground = true; + this._localAssetServerThread.Start(); + + } + + public void SetReceiver(IAssetReceiver receiver) + { + this._receiver = receiver; + } + + public void RequestAsset(LLUUID assetID, bool isTexture) + { + ARequest req = new ARequest(); + req.AssetID = assetID; + req.IsTexture = isTexture; + this._assetRequests.Enqueue(req); + } + + public void UpdateAsset(AssetBase asset) + { + + } + + public void UploadNewAsset(AssetBase asset) + { + AssetStorage store = new AssetStorage(); + store.Data = asset.Data; + store.Name = asset.Name; + store.UUID = asset.FullID; + db.Set(store); + db.Commit(); + } + + public void SetServerInfo(string ServerUrl, string ServerKey) + { + + } + public void Close() + { + if (db != null) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE, "Closing local asset server database"); + db.Close(); + } + } + + private void RunRequests() + { + while (true) + { + byte[] idata = null; + bool found = false; + AssetStorage foundAsset = null; + ARequest req = this._assetRequests.Dequeue(); + IObjectSet result = db.Query(new AssetUUIDQuery(req.AssetID)); + if (result.Count > 0) + { + foundAsset = (AssetStorage)result.Next(); + found = true; + } + + AssetBase asset = new AssetBase(); + if (found) + { + asset.FullID = foundAsset.UUID; + asset.Type = foundAsset.Type; + asset.InvType = foundAsset.Type; + asset.Name = foundAsset.Name; + idata = foundAsset.Data; + } + else + { + asset.FullID = LLUUID.Zero; + } + asset.Data = idata; + _receiver.AssetReceived(asset, req.IsTexture); + } + + } + + private void SetUpAssetDatabase() + { + try + { + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE, "Setting up asset database"); + + AssetBase Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000001"); + Image.Name = "Bricks"; + this.LoadAsset(Image, true, "bricks.jp2"); + AssetStorage store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000002"); + Image.Name = "Plywood"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000003"); + Image.Name = "Rocks"; + this.LoadAsset(Image, true, "rocks.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000004"); + Image.Name = "Granite"; + this.LoadAsset(Image, true, "granite.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000005"); + Image.Name = "Hardwood"; + this.LoadAsset(Image, true, "hardwood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-5005-000000000005"); + Image.Name = "Prim Base Texture"; + this.LoadAsset(Image, true, "plywood.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000006"); + Image.Name = "Map Base Texture"; + this.LoadAsset(Image, true, "map_base.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000007"); + Image.Name = "Map Texture"; + this.LoadAsset(Image, true, "map1.jp2"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + + Image = new AssetBase(); + Image.FullID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73"); + Image.Name = "Shape"; + this.LoadAsset(Image, false, "base_shape.dat"); + store = new AssetStorage(); + store.Data = Image.Data; + store.Name = Image.Name; + store.UUID = Image.FullID; + db.Set(store); + db.Commit(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + } + + private void LoadAsset(AssetBase info, bool image, string filename) + { + //should request Asset from storage manager + //but for now read from file + + string dataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "assets"); //+ folder; + string fileName = Path.Combine(dataPath, filename); + FileInfo fInfo = new FileInfo(fileName); + long numBytes = fInfo.Length; + FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + byte[] idata = new byte[numBytes]; + BinaryReader br = new BinaryReader(fStream); + idata = br.ReadBytes((int)numBytes); + br.Close(); + fStream.Close(); + info.Data = idata; + //info.loaded=true; + } + } +} diff --git a/OpenSim/OpenSim.GridInterfaces/Local/LocalGridServer.cs b/OpenSim/OpenSim.GridInterfaces/Local/LocalGridServer.cs new file mode 100644 index 0000000..fdd6ba4 --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/LocalGridServer.cs @@ -0,0 +1,157 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR 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.IO; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Console; +using libsecondlife; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using System.Collections; + +namespace OpenSim.GridInterfaces.Local +{ + /// + /// + /// + /// + public class LocalGridPlugin : IGridPlugin + { + public LocalGridPlugin() + { + + } + + public IGridServer GetGridServer() + { + return(new LocalGridServer()); + } + } + + public class LocalGridServer : LocalGridBase + { + public List Sessions = new List(); + + public LocalGridServer() + { + Sessions = new List(); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE,"Local Grid Server class created"); + } + + public override bool RequestConnection(LLUUID SimUUID, string sim_ip, uint sim_port) + { + return true; + } + + public override string GetName() + { + return "Local"; + } + + public override AuthenticateResponse AuthenticateSession(LLUUID sessionID, LLUUID agentID, uint circuitCode) + { + //we are running local + AuthenticateResponse user = new AuthenticateResponse(); + + lock(this.Sessions) + { + + for(int i = 0; i < Sessions.Count; i++) + { + if((Sessions[i].Agent == agentID) && (Sessions[i].Session == sessionID)) + { + user.Authorised = true; + user.LoginInfo = Sessions[i]; + } + } + } + return(user); + } + + public override bool LogoutSession(LLUUID sessionID, LLUUID agentID, uint circuitCode) + { + return(true); + } + + public override UUIDBlock RequestUUIDBlock() + { + UUIDBlock uuidBlock = new UUIDBlock(); + return(uuidBlock); + } + + public override NeighbourInfo[] RequestNeighbours() + { + return null; + } + + public override void SetServerInfo(string ServerUrl, string SendKey, string RecvKey) + { + + } + + public override IList RequestMapBlocks(int minX, int minY, int maxX, int maxY) + { + return new ArrayList(); + } + + + public override void Close() + { + + } + + /// + /// used by the local login server to inform us of new sessions + /// + /// + public override void AddNewSession(Login session) + { + lock(this.Sessions) + { + this.Sessions.Add(session); + } + } + } + + 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/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj new file mode 100644 index 0000000..1aec5aa --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj @@ -0,0 +1,110 @@ + + + Local + 8.0.50727 + 2.0 + {546099CD-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.GridInterfaces.Local + JScript + Grid + IE50 + false + Library + + OpenSim.GridInterfaces.Local + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\bin\libsecondlife.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj.user b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.dll.build b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.dll.build new file mode 100644 index 0000000..6bf398e --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Local/OpenSim.GridInterfaces.Local.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Remote/AssemblyInfo.cs b/OpenSim/OpenSim.GridInterfaces/Remote/AssemblyInfo.cs new file mode 100644 index 0000000..0fa7d6e --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("RemoteGridServers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RemoteGridServers")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj new file mode 100644 index 0000000..b004c10 --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {B55C0B5D-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.GridInterfaces.Remote + JScript + Grid + IE50 + false + Library + + OpenSim.GridInterfaces.Remote + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\bin\libsecondlife.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + XMLRPC + {8E81D43C-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj.user b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.dll.build b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.dll.build new file mode 100644 index 0000000..96272dd --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/OpenSim.GridInterfaces.Remote.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.GridInterfaces/Remote/RemoteAssetServer.cs b/OpenSim/OpenSim.GridInterfaces/Remote/RemoteAssetServer.cs new file mode 100644 index 0000000..7432dee --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/RemoteAssetServer.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.IO; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.GridInterfaces.Remote +{ + public class RemoteAssetServer : IAssetServer + { + private IAssetReceiver _receiver; + private BlockingQueue _assetRequests; + private Thread _remoteAssetServerThread; + private string AssetServerUrl; + private string AssetSendKey; + + public RemoteAssetServer() + { + this._assetRequests = new BlockingQueue(); + this._remoteAssetServerThread = new Thread(new ThreadStart(RunRequests)); + this._remoteAssetServerThread.IsBackground = true; + this._remoteAssetServerThread.Start(); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"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.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW," 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/OpenSim.GridInterfaces/Remote/RemoteGridServer.cs b/OpenSim/OpenSim.GridInterfaces/Remote/RemoteGridServer.cs new file mode 100644 index 0000000..7f911d8 --- /dev/null +++ b/OpenSim/OpenSim.GridInterfaces/Remote/RemoteGridServer.cs @@ -0,0 +1,210 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR 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.Threading; +using System.Net; +using System.Net.Sockets; +using System.IO; +using libsecondlife; +using Nwc.XmlRpc; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.GridInterfaces.Remote +{ + public class RemoteGridServer : RemoteGridBase + { + private string GridServerUrl; + private string GridSendKey; + private string GridRecvKey; + private Dictionary AgentCircuits = new Dictionary(); + private ArrayList simneighbours = new ArrayList(); + private Hashtable griddatahash; + + public override Dictionary agentcircuits + { + get { return AgentCircuits; } + set { AgentCircuits = value; } + } + + public override ArrayList neighbours + { + get { return simneighbours; } + set { simneighbours = value; } + } + + public override Hashtable GridData + { + get { return griddatahash; } + set { griddatahash = value; } + } + + + public RemoteGridServer() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Remote Grid Server class created"); + } + + public override bool RequestConnection(LLUUID SimUUID, string sim_ip, uint sim_port) + { + Hashtable GridParams = new Hashtable(); + GridParams["authkey"] = GridSendKey; + GridParams["UUID"] = SimUUID.ToString(); + GridParams["sim_ip"] = sim_ip; + GridParams["sim_port"] = sim_port.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(GridParams); + + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams); + XmlRpcResponse GridResp = GridReq.Send(this.GridServerUrl, 3000); + Hashtable GridRespData = (Hashtable)GridResp.Value; + this.griddatahash = GridRespData; + + if (GridRespData.ContainsKey("error")) + { + string errorstring = (string)GridRespData["error"]; + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "Error connecting to grid:"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, errorstring); + return false; + } + this.neighbours = (ArrayList)GridRespData["neighbours"]; + Console.WriteLine(simneighbours.Count); + return true; + } + + public override 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)) + { + // YAY! Valid login + 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; + } + else + { + // Invalid + user.Authorised = false; + } + + return (user); + } + + public override bool LogoutSession(LLUUID sessionID, LLUUID agentID, uint circuitCode) + { + WebRequest DeleteSession = WebRequest.Create(GridServerUrl + "/usersessions/" + sessionID.ToString()); + DeleteSession.Method = "DELETE"; + DeleteSession.ContentType = "text/plaintext"; + DeleteSession.ContentLength = 0; + + StreamWriter stOut = new StreamWriter(DeleteSession.GetRequestStream(), System.Text.Encoding.ASCII); + stOut.Write(""); + stOut.Close(); + + StreamReader stIn = new StreamReader(DeleteSession.GetResponse().GetResponseStream()); + string GridResponse = stIn.ReadToEnd(); + stIn.Close(); + return (true); + } + + public override UUIDBlock RequestUUIDBlock() + { + UUIDBlock uuidBlock = new UUIDBlock(); + return (uuidBlock); + } + + public override NeighbourInfo[] RequestNeighbours() + { + return null; + } + + public override IList RequestMapBlocks(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(GridServerUrl, 3000); + Hashtable respData = (Hashtable)resp.Value; + return (IList)respData["sim-profiles"]; + } + + public override void SetServerInfo(string ServerUrl, string SendKey, string RecvKey) + { + this.GridServerUrl = ServerUrl; + this.GridSendKey = SendKey; + this.GridRecvKey = RecvKey; + } + + public override string GetName() + { + return "Remote"; + } + + public override void Close() + { + + } + } + + public class RemoteGridPlugin : IGridPlugin + { + public RemoteGridPlugin() + { + + } + + public IGridServer GetGridServer() + { + return (new RemoteGridServer()); + } + } + +} diff --git a/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/AssemblyInfo.cs new file mode 100644 index 0000000..0c9c06c --- /dev/null +++ b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("PhysXplugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PhysXplugin")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs new file mode 100644 index 0000000..c37acc8 --- /dev/null +++ b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/BasicPhysicsPlugin.cs @@ -0,0 +1,277 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Physics.Manager; + +namespace OpenSim.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() + { + if(_mScene == null) + { + _mScene = new BasicScene(); + } + return(_mScene); + } + + public string GetName() + { + return("basicphysics"); + } + + public void Dispose() + { + + } + } + + public class BasicScene :PhysicsScene + { + private List _actors = new List(); + private float[] _heightMap; + + public BasicScene() + { + + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + BasicActor act = new BasicActor(); + act.Position = position; + _actors.Add(act); + return act; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + BasicActor act = (BasicActor)actor; + if(_actors.Contains(act)) + { + _actors.Remove(act); + } + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + return null; + } + + public override void Simulate(float timeStep) + { + foreach (BasicActor actor in _actors) + { + actor.Position.X = actor.Position.X + (actor.Velocity.X * timeStep); + actor.Position.Y = actor.Position.Y + (actor.Velocity.Y * timeStep); + actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); + /*if(actor.Flying) + { + actor.Position.Z = actor.Position.Z + (actor.Velocity.Z * timeStep); + } + else + { + actor.Position.Z = actor.Position.Z + ((-9.8f + actor.Velocity.Z) * timeStep); + } + if(actor.Position.Z < (_heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X]+1)) + {*/ + if ((actor.Position.Y > 0 && actor.Position.Y < 256) && (actor.Position.X > 0 && actor.Position.X < 256)) + { + actor.Position.Z = _heightMap[(int)actor.Position.Y * 256 + (int)actor.Position.X] + 1; + } + //} + + + + // This code needs sorting out - border crossings etc +/* if(actor.Position.X<0) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.X = 0; + actor.Velocity.X = 0; + } + if(actor.Position.Y < 0) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.Y = 0; + actor.Velocity.Y = 0; + } + if(actor.Position.X > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.X = 255; + actor.Velocity.X = 0; + } + if(actor.Position.Y > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this.Position.X,this.Position.Y,this.Position.Z)); + actor.Position.Y = 255; + actor.Velocity.X = 0; + }*/ + } + } + + public override void GetResults() + { + + } + + public override bool IsThreaded + { + get + { + return(false); // for now we won't be multithreaded + } + } + + public override void SetTerrain(float[] heightMap) + { + this._heightMap = heightMap; + } + + public override void DeleteTerrain() + { + + } + } + + public class BasicActor : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private bool flying; + public BasicActor() + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + } + + public override bool Flying + { + get + { + return false; + } + set + { + flying= value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + + public override bool Kinematic + { + get + { + return true; + } + set + { + + } + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + } + +} diff --git a/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj new file mode 100644 index 0000000..6d5b4d0 --- /dev/null +++ b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj @@ -0,0 +1,93 @@ + + + Local + 8.0.50727 + 2.0 + {4F874463-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Physics.BasicPhysicsPlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Physics.BasicPhysicsPlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\Physics\ + False + False + False + 4 + + + + + System.dll + False + + + ..\..\bin\Axiom.MathLib.dll + False + + + + + OpenSim.Physics.Manager + {8BE16150-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj.user b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.dll.build b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.dll.build new file mode 100644 index 0000000..3497a55 --- /dev/null +++ b/OpenSim/OpenSim.Physics/BasicPhysicsPlugin/OpenSim.Physics.BasicPhysicsPlugin.dll.build @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/Manager/AssemblyInfo.cs b/OpenSim/OpenSim.Physics/Manager/AssemblyInfo.cs new file mode 100644 index 0000000..57a8913 --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("PhysicsManager")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PhysicsManager")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj new file mode 100644 index 0000000..294e005 --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {8BE16150-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Physics.Manager + JScript + Grid + IE50 + false + Library + + OpenSim.Physics.Manager + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\bin\Axiom.MathLib.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj.user b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.dll.build b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.dll.build new file mode 100644 index 0000000..4b5ee51 --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/OpenSim.Physics.Manager.dll.build @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/Manager/PhysicsActor.cs b/OpenSim/OpenSim.Physics/Manager/PhysicsActor.cs new file mode 100644 index 0000000..a0b6c21 --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/PhysicsActor.cs @@ -0,0 +1,161 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Physics.Manager +{ + public abstract class PhysicsActor + { + public static PhysicsActor Null + { + get + { + return new NullPhysicsActor(); + } + } + + public abstract PhysicsVector Position + { + get; + set; + } + + public abstract PhysicsVector Velocity + { + get; + set; + } + + public abstract PhysicsVector Acceleration + { + get; + } + + public abstract Axiom.MathLib.Quaternion Orientation + { + get; + set; + } + + public abstract bool Flying + { + get; + set; + } + + public abstract bool Kinematic + { + get; + set; + } + + public abstract void AddForce(PhysicsVector force); + + public abstract void SetMomentum(PhysicsVector momentum); + } + + public class NullPhysicsActor : PhysicsActor + { + public override PhysicsVector Position + { + get + { + return PhysicsVector.Zero; + } + set + { + return; + } + } + + public override PhysicsVector Velocity + { + get + { + return PhysicsVector.Zero; + } + set + { + return; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get { return PhysicsVector.Zero; } + } + + public override bool Flying + { + get + { + return false; + } + set + { + return; + } + } + + public override bool Kinematic + { + get + { + return true; + } + set + { + return; + } + } + + public override void AddForce(PhysicsVector force) + { + return; + } + + public override void SetMomentum(PhysicsVector momentum) + { + return; + } + } +} diff --git a/OpenSim/OpenSim.Physics/Manager/PhysicsManager.cs b/OpenSim/OpenSim.Physics/Manager/PhysicsManager.cs new file mode 100644 index 0000000..291fc7e --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/PhysicsManager.cs @@ -0,0 +1,116 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System.Reflection; +using Axiom.MathLib; +using OpenSim.Framework.Console; + +namespace OpenSim.Physics.Manager +{ + /// + /// Description of MyClass. + /// + public class PhysicsManager + { + private Dictionary _plugins=new Dictionary(); + + public PhysicsManager() + { + + } + + public PhysicsScene GetPhysicsScene(string engineName) + { + if (String.IsNullOrEmpty(engineName)) + { + return new NullPhysicsScene(); + } + + if(_plugins.ContainsKey(engineName)) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.LOW,"creating "+engineName); + return _plugins[engineName].GetScene(); + } + else + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.MEDIUM,"couldn't find physicsEngine: {0}",engineName); + throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}",engineName)); + } + } + + public void LoadPlugins() + { + string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory ,"Physics"); + string[] pluginFiles = Directory.GetFiles(path, "*.dll"); + + + for(int i= 0; i nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Framework.Console; + +namespace OpenSim.Physics.Manager +{ + public abstract class PhysicsScene + { + public static PhysicsScene Null + { + get + { + return new NullPhysicsScene(); + } + } + + public abstract PhysicsActor AddAvatar(PhysicsVector position); + + public abstract void RemoveAvatar(PhysicsActor actor); + + public abstract PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size); + + public abstract void Simulate(float timeStep); + + public abstract void GetResults(); + + public abstract void SetTerrain(float[] heightMap); + + public abstract void DeleteTerrain(); + + public abstract bool IsThreaded + { + get; + } + } + + public class NullPhysicsScene : PhysicsScene + { + private static int m_workIndicator; + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE,"NullPhysicsScene : AddAvatar({0})", position); + return PhysicsActor.Null; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE, "NullPhysicsScene : AddPrim({0},{1})", position, size); + return PhysicsActor.Null; + } + + public override void Simulate(float timeStep) + { + m_workIndicator = (m_workIndicator + 1) % 10; + + //OpenSim.Framework.Console.MainConsole.Instance.SetStatus(m_workIndicator.ToString()); + } + + public override void GetResults() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE, "NullPhysicsScene : GetResults()"); + } + + public override void SetTerrain(float[] heightMap) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(LogPriority.VERBOSE, "NullPhysicsScene : SetTerrain({0} items)", heightMap.Length); + } + + public override void DeleteTerrain() + { + + } + + public override bool IsThreaded + { + get { return false; } + } + } +} diff --git a/OpenSim/OpenSim.Physics/Manager/PhysicsVector.cs b/OpenSim/OpenSim.Physics/Manager/PhysicsVector.cs new file mode 100644 index 0000000..3c824d0 --- /dev/null +++ b/OpenSim/OpenSim.Physics/Manager/PhysicsVector.cs @@ -0,0 +1,54 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Physics.Manager +{ + public 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); + } +} diff --git a/OpenSim/OpenSim.Physics/OdePlugin/AssemblyInfo.cs b/OpenSim/OpenSim.Physics/OdePlugin/AssemblyInfo.cs new file mode 100644 index 0000000..913aae7 --- /dev/null +++ b/OpenSim/OpenSim.Physics/OdePlugin/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("RealPhysXplugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RealPhysXplugin")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.Physics/OdePlugin/OdePlugin.cs b/OpenSim/OpenSim.Physics/OdePlugin/OdePlugin.cs new file mode 100644 index 0000000..599dea8 --- /dev/null +++ b/OpenSim/OpenSim.Physics/OdePlugin/OdePlugin.cs @@ -0,0 +1,452 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR 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 Ode.NET; + +namespace OpenSim.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) + { + //Console.WriteLine("collision callback"); + 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]; + } + IntPtr HeightmapData = d.GeomHeightfieldDataCreate(); + d.GeomHeightfieldDataBuildDouble(HeightmapData, _heightmap, 0, 256, 256, 256, 256, 1.0f, 0.0f, 2.0f, 0); + d.GeomHeightfieldDataSetBounds(HeightmapData, 256, 256); + LandGeom = d.CreateHeightfield(space, HeightmapData, 1); + d.Matrix3 R = new d.Matrix3(); + + Axiom.MathLib.Quaternion q1 =Axiom.MathLib.Quaternion.FromAngleAxis(1.5707f, new Axiom.MathLib.Vector3(1,0,0)); + Axiom.MathLib.Quaternion q2 =Axiom.MathLib.Quaternion.FromAngleAxis(1.5707f, new Axiom.MathLib.Vector3(0,1,0)); + //Axiom.MathLib.Quaternion q3 = Axiom.MathLib.Quaternion.FromAngleAxis(3.14f, new Axiom.MathLib.Vector3(0, 0, 1)); + + q1 = q1 * q2; + //q1 = q1 * q3; + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(); + float angle = 0; + q1.ToAngleAxis(ref angle, ref v3); + + d.RFromAxisAndAngle(out R, v3.x, v3.y, v3.z, angle); + d.GeomSetRotation(LandGeom, ref R); + d.GeomSetPosition(LandGeom, 128, 128, 0); + } + + public override void DeleteTerrain() + { + + } + } + + public class OdeCharacter : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private bool flying; + //private float gravityAccel; + private IntPtr BoundingCapsule; + IntPtr capsule_geom; + d.Mass capsule_mass; + + public OdeCharacter(OdeScene parent_scene, PhysicsVector pos) + { + _velocity = new PhysicsVector(); + _position = pos; + _acceleration = new PhysicsVector(); + d.MassSetCapsule(out capsule_mass, 5.0f, 3, 0.5f, 2f); + capsule_geom = d.CreateCapsule(OdeScene.space, 0.5f, 2f); + this.BoundingCapsule = d.BodyCreate(OdeScene.world); + d.BodySetMass(BoundingCapsule, ref capsule_mass); + d.BodySetPosition(BoundingCapsule, pos.X, pos.Y, pos.Z); + d.GeomSetBody(capsule_geom, BoundingCapsule); + } + + public override bool Flying + { + get + { + return flying; + } + set + { + flying = value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + } + set + { + + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration(PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + public void Move(float timeStep) + { + PhysicsVector vec = new PhysicsVector(); + vec.X = this._velocity.X * timeStep; + vec.Y = this._velocity.Y * timeStep; + if (flying) + { + vec.Z = (this._velocity.Z + 0.5f) * timeStep; + } + d.BodySetLinearVel(this.BoundingCapsule, vec.X, vec.Y, vec.Z); + } + + public void UpdatePosition() + { + d.Vector3 vec = d.BodyGetPosition(BoundingCapsule); + this._position.X = vec.X; + this._position.Y = vec.Y; + this._position.Z = vec.Z; + } + } + + public class OdePrim : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + + public OdePrim() + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + } + public override bool Flying + { + get + { + return false; //no flying prims for you + } + set + { + + } + } + public override PhysicsVector Position + { + get + { + PhysicsVector pos = new PhysicsVector(); + // PhysicsVector vec = this._prim.Position; + //pos.X = vec.X; + //pos.Y = vec.Y; + //pos.Z = vec.Z; + return pos; + + } + set + { + /*PhysicsVector vec = value; + PhysicsVector pos = new PhysicsVector(); + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + this._prim.Position = pos;*/ + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + //return this._prim.Kinematic; + } + set + { + //this._prim.Kinematic = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + Axiom.MathLib.Quaternion res = new Axiom.MathLib.Quaternion(); + return res; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration(PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + + } + +} diff --git a/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj new file mode 100644 index 0000000..68f1aa1 --- /dev/null +++ b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj @@ -0,0 +1,97 @@ + + + Local + 8.0.50727 + 2.0 + {63A05FE9-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Physics.OdePlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Physics.OdePlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\Physics\ + False + False + False + 4 + + + + + System.dll + False + + + ..\..\bin\Axiom.MathLib.dll + False + + + ..\..\bin\Ode.NET.dll + False + + + + + OpenSim.Physics.Manager + {8BE16150-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj.user b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.dll.build b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.dll.build new file mode 100644 index 0000000..f25361a --- /dev/null +++ b/OpenSim/OpenSim.Physics/OdePlugin/OpenSim.Physics.OdePlugin.dll.build @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/PhysXPlugin/AssemblyInfo.cs b/OpenSim/OpenSim.Physics/PhysXPlugin/AssemblyInfo.cs new file mode 100644 index 0000000..913aae7 --- /dev/null +++ b/OpenSim/OpenSim.Physics/PhysXPlugin/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("RealPhysXplugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RealPhysXplugin")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj new file mode 100644 index 0000000..efe9c79 --- /dev/null +++ b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj @@ -0,0 +1,97 @@ + + + Local + 8.0.50727 + 2.0 + {988F0AC4-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Physics.PhysXPlugin + JScript + Grid + IE50 + false + Library + + OpenSim.Physics.PhysXPlugin + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\Physics\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\Physics\ + False + False + False + 4 + + + + + System.dll + False + + + ..\..\bin\Axiom.MathLib.dll + False + + + ..\..\bin\PhysX_Wrapper_Dotnet.dll + False + + + + + OpenSim.Physics.Manager + {8BE16150-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj.user b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.dll.build b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.dll.build new file mode 100644 index 0000000..5ab70bb --- /dev/null +++ b/OpenSim/OpenSim.Physics/PhysXPlugin/OpenSim.Physics.PhysXPlugin.dll.build @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Physics/PhysXPlugin/PhysXPlugin.cs b/OpenSim/OpenSim.Physics/PhysXPlugin/PhysXPlugin.cs new file mode 100644 index 0000000..dff1ee2 --- /dev/null +++ b/OpenSim/OpenSim.Physics/PhysXPlugin/PhysXPlugin.cs @@ -0,0 +1,449 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using OpenSim.Physics.Manager; +using PhysXWrapper; + +namespace OpenSim.Physics.PhysXPlugin +{ + /// + /// Will be the PhysX plugin but for now will be a very basic physics engine + /// + public class PhysXPlugin : IPhysicsPlugin + { + private PhysXScene _mScene; + + public PhysXPlugin() + { + + } + + public bool Init() + { + return true; + } + + public PhysicsScene GetScene() + { + if(_mScene == null) + { + _mScene = new PhysXScene(); + } + return(_mScene); + } + + public string GetName() + { + return("RealPhysX"); + } + + public void Dispose() + { + + } + } + + public class PhysXScene :PhysicsScene + { + private List _characters = new List(); + private List _prims = new List(); + private float[] _heightMap = null; + private NxPhysicsSDK mySdk; + private NxScene scene; + + public PhysXScene() + { + mySdk = NxPhysicsSDK.CreateSDK(); + Console.WriteLine("Sdk created - now creating scene"); + scene = mySdk.CreateScene(); + + } + + public override PhysicsActor AddAvatar(PhysicsVector position) + { + Vec3 pos = new Vec3(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z; + PhysXCharacter act = new PhysXCharacter( scene.AddCharacter(pos)); + act.Position = position; + _characters.Add(act); + return act; + } + + public override void RemoveAvatar(PhysicsActor actor) + { + + } + + public override PhysicsActor AddPrim(PhysicsVector position, PhysicsVector size) + { + Vec3 pos = new Vec3(); + pos.X = position.X; + pos.Y = position.Y; + pos.Z = position.Z; + Vec3 siz = new Vec3(); + siz.X = size.X; + siz.Y = size.Y; + siz.Z = size.Z; + PhysXPrim act = new PhysXPrim( scene.AddNewBox(pos, siz)); + _prims.Add(act); + return act; + } + public override void Simulate(float timeStep) + { + try + { + foreach (PhysXCharacter actor in _characters) + { + actor.Move(timeStep); + } + scene.Simulate(timeStep); + scene.FetchResults(); + scene.UpdateControllers(); + + foreach (PhysXCharacter actor in _characters) + { + actor.UpdatePosition(); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + } + + public override void GetResults() + { + + } + + public override bool IsThreaded + { + get + { + return(false); // for now we won't be multithreaded + } + } + + public override void SetTerrain(float[] heightMap) + { + if (this._heightMap != null) + { + Console.WriteLine("PhysX - deleting old terrain"); + this.scene.DeleteTerrain(); + } + this._heightMap = heightMap; + this.scene.AddTerrain(heightMap); + } + + public override void DeleteTerrain() + { + this.scene.DeleteTerrain(); + } + } + + public class PhysXCharacter : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private NxCharacter _character; + private bool flying; + private float gravityAccel; + + public PhysXCharacter(NxCharacter character) + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + _character = character; + } + + public override bool Flying + { + get + { + return flying; + } + set + { + flying = value; + } + } + + public override PhysicsVector Position + { + get + { + return _position; + } + set + { + _position = value; + Vec3 ps = new Vec3(); + ps.X = value.X; + ps.Y = value.Y; + ps.Z = value.Z; + this._character.Position = ps; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return false; + } + set + { + + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + return Axiom.MathLib.Quaternion.Identity; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + public void Move(float timeStep) + { + Vec3 vec = new Vec3(); + vec.X = this._velocity.X * timeStep; + vec.Y = this._velocity.Y * timeStep; + if(flying) + { + vec.Z = ( this._velocity.Z) * timeStep; + } + else + { + gravityAccel+= -9.8f; + vec.Z = (gravityAccel + this._velocity.Z) * timeStep; + } + int res = this._character.Move(vec); + if(res == 1) + { + gravityAccel = 0; + } + } + + public void UpdatePosition() + { + Vec3 vec = this._character.Position; + this._position.X = vec.X; + this._position.Y = vec.Y; + this._position.Z = vec.Z; + } + } + + public class PhysXPrim : PhysicsActor + { + private PhysicsVector _position; + private PhysicsVector _velocity; + private PhysicsVector _acceleration; + private NxActor _prim; + + public PhysXPrim(NxActor prim) + { + _velocity = new PhysicsVector(); + _position = new PhysicsVector(); + _acceleration = new PhysicsVector(); + _prim = prim; + } + public override bool Flying + { + get + { + return false; //no flying prims for you + } + set + { + + } + } + public override PhysicsVector Position + { + get + { + PhysicsVector pos = new PhysicsVector(); + Vec3 vec = this._prim.Position; + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + return pos; + + } + set + { + PhysicsVector vec = value; + Vec3 pos = new Vec3(); + pos.X = vec.X; + pos.Y = vec.Y; + pos.Z = vec.Z; + this._prim.Position = pos; + } + } + + public override PhysicsVector Velocity + { + get + { + return _velocity; + } + set + { + _velocity = value; + } + } + + public override bool Kinematic + { + get + { + return this._prim.Kinematic; + } + set + { + this._prim.Kinematic = value; + } + } + + public override Axiom.MathLib.Quaternion Orientation + { + get + { + Axiom.MathLib.Quaternion res = new Axiom.MathLib.Quaternion(); + PhysXWrapper.Quaternion quat = this._prim.GetOrientation(); + res.w = quat.W; + res.x = quat.X; + res.y = quat.Y; + res.z = quat.Z; + return res; + } + set + { + + } + } + + public override PhysicsVector Acceleration + { + get + { + return _acceleration; + } + + } + public void SetAcceleration (PhysicsVector accel) + { + this._acceleration = accel; + } + + public override void AddForce(PhysicsVector force) + { + + } + + public override void SetMomentum(PhysicsVector momentum) + { + + } + + + } + +} diff --git a/OpenSim/OpenSim.RegionServer/AgentAssetUpload.cs b/OpenSim/OpenSim.RegionServer/AgentAssetUpload.cs new file mode 100644 index 0000000..dd2b2a9 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/AgentAssetUpload.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Assets; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim +{ + 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() + { + + } + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/Assets/AssetCache.cs b/OpenSim/OpenSim.RegionServer/Assets/AssetCache.cs new file mode 100644 index 0000000..ccebb24 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/Assets/AssetCache.cs @@ -0,0 +1,574 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR 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 libsecondlife; +using libsecondlife.Packets; +using OpenSim; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Utilities; + +namespace OpenSim.Assets +{ + /// + /// 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 + + 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 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) + { + if (asset.Type == 0) + { + 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; + + if (this.TextureRequests.Count < 5) + { + //lower than 5 so do all of them + num = this.TextureRequests.Count; + } + else + { + num = 5; + } + AssetRequest req; + for (int i = 0; i < num; i++) + { + req = (AssetRequest)this.TextureRequests[i]; + if (req.PacketCounter != req.NumPackets) + { + // 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.image_info.FullID); + } + 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: + } + } + else + { + //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); + } + } + } + + //remove requests that have been completed + int count = 0; + for (int i = 0; i < num; i++) + { + if (this.TextureRequests.Count > count) + { + req = (AssetRequest)this.TextureRequests[count]; + if (req.PacketCounter == req.NumPackets) + { + this.TextureRequests.Remove(req); + } + else + { + count++; + } + } + } + + } + 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(ClientView 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(ClientView userInfo, LLUUID imageID) + { + //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; + } + + 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 + + } + + public class AssetRequest + { + public ClientView 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; + } + } + +} diff --git a/OpenSim/OpenSim.RegionServer/Assets/InventoryCache.cs b/OpenSim/OpenSim.RegionServer/Assets/InventoryCache.cs new file mode 100644 index 0000000..64a7a32 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/Assets/InventoryCache.cs @@ -0,0 +1,336 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using libsecondlife; +using OpenSim; +using libsecondlife.Packets; +//using OpenSim.GridServers; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Types; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Assets +{ + /// + /// Description of InventoryManager. + /// + public class InventoryCache + { + private Dictionary _agentsInventory; + private List _serverRequests; //list of requests made to user server. + private System.Text.Encoding _enc = System.Text.Encoding.ASCII; + private const uint FULL_MASK_PERMISSIONS = 2147483647; + + public InventoryCache() + { + _agentsInventory = new Dictionary(); + _serverRequests = new List(); + } + + public void AddNewAgentsInventory(AgentInventory agentInventory) + { + if (!this._agentsInventory.ContainsKey(agentInventory.AgentID)) + { + this._agentsInventory.Add(agentInventory.AgentID, agentInventory); + } + } + + public AgentInventory FetchAgentsInventory(LLUUID agentID, IUserServer userserver) + { + AgentInventory res = null; + if (!this._agentsInventory.ContainsKey(agentID)) + { + res = userserver.RequestAgentsInventory(agentID); + this._agentsInventory.Add(agentID,res); + } + return res; + } + + public AgentInventory GetAgentsInventory(LLUUID agentID) + { + if (this._agentsInventory.ContainsKey(agentID)) + { + return this._agentsInventory[agentID]; + } + + return null; + } + + public void ClientLeaving(LLUUID clientID, IUserServer userserver) + { + if (this._agentsInventory.ContainsKey(clientID)) + { + if (userserver != null) + { + userserver.UpdateAgentsInventory(clientID, this._agentsInventory[clientID]); + } + this._agentsInventory.Remove(clientID); + } + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID) + { + return this.CreateNewInventoryFolder(remoteClient, folderID, 0); + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID, ushort type) + { + bool res = false; + if (folderID != LLUUID.Zero) //don't create a folder with a zero id + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].CreateNewFolder(folderID, type); + } + } + return res; + } + + public bool CreateNewInventoryFolder(ClientView remoteClient, LLUUID folderID, ushort type, string folderName, LLUUID parent) + { + bool res = false; + if (folderID != LLUUID.Zero) //don't create a folder with a zero id + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].CreateNewFolder(folderID, type, folderName, parent); + } + } + return res; + } + + public LLUUID AddNewInventoryItem(ClientView remoteClient, LLUUID folderID, OpenSim.Framework.Types.AssetBase asset) + { + LLUUID newItem = null; + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + newItem = this._agentsInventory[remoteClient.AgentID].AddToInventory(folderID, asset); + if (newItem != null) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[newItem]; + this.SendItemUpdateCreate(remoteClient, Item); + } + } + + return newItem; + } + public bool DeleteInventoryItem(ClientView remoteClient, LLUUID itemID) + { + bool res = false; + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + res = this._agentsInventory[remoteClient.AgentID].DeleteFromInventory(itemID); + if (res) + { + RemoveInventoryItemPacket remove = new RemoveInventoryItemPacket(); + remove.AgentData.AgentID = remoteClient.AgentID; + remove.AgentData.SessionID = remoteClient.SessionID; + remove.InventoryData = new RemoveInventoryItemPacket.InventoryDataBlock[1]; + remove.InventoryData[0] = new RemoveInventoryItemPacket.InventoryDataBlock(); + remove.InventoryData[0].ItemID = itemID; + remoteClient.OutPacket(remove); + } + } + + return res; + } + + public bool UpdateInventoryItemAsset(ClientView remoteClient, LLUUID itemID, OpenSim.Framework.Types.AssetBase asset) + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + bool res = _agentsInventory[remoteClient.AgentID].UpdateItemAsset(itemID, asset); + if (res) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[itemID]; + this.SendItemUpdateCreate(remoteClient, Item); + } + return res; + } + + return false; + } + + public bool UpdateInventoryItemDetails(ClientView remoteClient, LLUUID itemID, UpdateInventoryItemPacket.InventoryDataBlock packet) + { + if (this._agentsInventory.ContainsKey(remoteClient.AgentID)) + { + bool res = _agentsInventory[remoteClient.AgentID].UpdateItemDetails(itemID, packet); + if (res) + { + InventoryItem Item = this._agentsInventory[remoteClient.AgentID].InventoryItems[itemID]; + this.SendItemUpdateCreate(remoteClient, Item); + } + return res; + } + + return false; + } + + public void FetchInventoryDescendents(ClientView userInfo, FetchInventoryDescendentsPacket FetchDescend) + { + if (this._agentsInventory.ContainsKey(userInfo.AgentID)) + { + AgentInventory agentInventory = this._agentsInventory[userInfo.AgentID]; + if (FetchDescend.InventoryData.FetchItems) + { + if (agentInventory.InventoryFolders.ContainsKey(FetchDescend.InventoryData.FolderID)) + { + InventoryFolder Folder = agentInventory.InventoryFolders[FetchDescend.InventoryData.FolderID]; + InventoryDescendentsPacket Descend = new InventoryDescendentsPacket(); + Descend.AgentData.AgentID = userInfo.AgentID; + Descend.AgentData.OwnerID = Folder.OwnerID; + Descend.AgentData.FolderID = FetchDescend.InventoryData.FolderID; + Descend.AgentData.Descendents = Folder.Items.Count; + Descend.AgentData.Version = Folder.Items.Count; + + + Descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[Folder.Items.Count]; + for (int i = 0; i < Folder.Items.Count; i++) + { + + InventoryItem Item = Folder.Items[i]; + Descend.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock(); + Descend.ItemData[i].ItemID = Item.ItemID; + Descend.ItemData[i].AssetID = Item.AssetID; + Descend.ItemData[i].CreatorID = Item.CreatorID; + Descend.ItemData[i].BaseMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].CreationDate = 1000; + Descend.ItemData[i].Description = _enc.GetBytes(Item.Description + "\0"); + Descend.ItemData[i].EveryoneMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].Flags = 1; + Descend.ItemData[i].FolderID = Item.FolderID; + Descend.ItemData[i].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + Descend.ItemData[i].GroupMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].InvType = Item.InvType; + Descend.ItemData[i].Name = _enc.GetBytes(Item.Name + "\0"); + Descend.ItemData[i].NextOwnerMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].OwnerID = Item.OwnerID; + Descend.ItemData[i].OwnerMask = FULL_MASK_PERMISSIONS; + Descend.ItemData[i].SalePrice = 100; + Descend.ItemData[i].SaleType = 0; + Descend.ItemData[i].Type = Item.Type; + Descend.ItemData[i].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, Descend.ItemData[i].InvType, Descend.ItemData[i].Type, Descend.ItemData[i].AssetID, Descend.ItemData[i].GroupID, 100, Descend.ItemData[i].OwnerID, Descend.ItemData[i].CreatorID, Descend.ItemData[i].ItemID, Descend.ItemData[i].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + } + + userInfo.OutPacket(Descend); + + } + } + else + { + Console.WriteLine("fetch subfolders"); + } + } + } + + public void FetchInventory(ClientView userInfo, FetchInventoryPacket FetchItems) + { + if (this._agentsInventory.ContainsKey(userInfo.AgentID)) + { + AgentInventory agentInventory = this._agentsInventory[userInfo.AgentID]; + + for (int i = 0; i < FetchItems.InventoryData.Length; i++) + { + if (agentInventory.InventoryItems.ContainsKey(FetchItems.InventoryData[i].ItemID)) + { + InventoryItem Item = agentInventory.InventoryItems[FetchItems.InventoryData[i].ItemID]; + FetchInventoryReplyPacket InventoryReply = new FetchInventoryReplyPacket(); + InventoryReply.AgentData.AgentID = userInfo.AgentID; + InventoryReply.InventoryData = new FetchInventoryReplyPacket.InventoryDataBlock[1]; + InventoryReply.InventoryData[0] = new FetchInventoryReplyPacket.InventoryDataBlock(); + InventoryReply.InventoryData[0].ItemID = Item.ItemID; + InventoryReply.InventoryData[0].AssetID = Item.AssetID; + InventoryReply.InventoryData[0].CreatorID = Item.CreatorID; + InventoryReply.InventoryData[0].BaseMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].CreationDate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + InventoryReply.InventoryData[0].Description = _enc.GetBytes(Item.Description + "\0"); + InventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].Flags = 0; + InventoryReply.InventoryData[0].FolderID = Item.FolderID; + InventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + InventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].InvType = Item.InvType; + InventoryReply.InventoryData[0].Name = _enc.GetBytes(Item.Name + "\0"); + InventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].OwnerID = Item.OwnerID; + InventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].SalePrice = 100; + InventoryReply.InventoryData[0].SaleType = 0; + InventoryReply.InventoryData[0].Type = Item.Type; + InventoryReply.InventoryData[0].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, InventoryReply.InventoryData[0].InvType, InventoryReply.InventoryData[0].Type, InventoryReply.InventoryData[0].AssetID, InventoryReply.InventoryData[0].GroupID, 100, InventoryReply.InventoryData[0].OwnerID, InventoryReply.InventoryData[0].CreatorID, InventoryReply.InventoryData[0].ItemID, InventoryReply.InventoryData[0].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + userInfo.OutPacket(InventoryReply); + } + } + } + } + + private void SendItemUpdateCreate(ClientView remoteClient, InventoryItem Item) + { + + UpdateCreateInventoryItemPacket InventoryReply = new UpdateCreateInventoryItemPacket(); + InventoryReply.AgentData.AgentID = remoteClient.AgentID; + InventoryReply.AgentData.SimApproved = true; + InventoryReply.InventoryData = new UpdateCreateInventoryItemPacket.InventoryDataBlock[1]; + InventoryReply.InventoryData[0] = new UpdateCreateInventoryItemPacket.InventoryDataBlock(); + InventoryReply.InventoryData[0].ItemID = Item.ItemID; + InventoryReply.InventoryData[0].AssetID = Item.AssetID; + InventoryReply.InventoryData[0].CreatorID = Item.CreatorID; + InventoryReply.InventoryData[0].BaseMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].CreationDate = 1000; + InventoryReply.InventoryData[0].Description = _enc.GetBytes(Item.Description + "\0"); + InventoryReply.InventoryData[0].EveryoneMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].Flags = 0; + InventoryReply.InventoryData[0].FolderID = Item.FolderID; + InventoryReply.InventoryData[0].GroupID = new LLUUID("00000000-0000-0000-0000-000000000000"); + InventoryReply.InventoryData[0].GroupMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].InvType = Item.InvType; + InventoryReply.InventoryData[0].Name = _enc.GetBytes(Item.Name + "\0"); + InventoryReply.InventoryData[0].NextOwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].OwnerID = Item.OwnerID; + InventoryReply.InventoryData[0].OwnerMask = FULL_MASK_PERMISSIONS; + InventoryReply.InventoryData[0].SalePrice = 100; + InventoryReply.InventoryData[0].SaleType = 0; + InventoryReply.InventoryData[0].Type = Item.Type; + InventoryReply.InventoryData[0].CRC = libsecondlife.Helpers.InventoryCRC(1000, 0, InventoryReply.InventoryData[0].InvType, InventoryReply.InventoryData[0].Type, InventoryReply.InventoryData[0].AssetID, InventoryReply.InventoryData[0].GroupID, 100, InventoryReply.InventoryData[0].OwnerID, InventoryReply.InventoryData[0].CreatorID, InventoryReply.InventoryData[0].ItemID, InventoryReply.InventoryData[0].FolderID, FULL_MASK_PERMISSIONS, 1, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS, FULL_MASK_PERMISSIONS); + + remoteClient.OutPacket(InventoryReply); + } + } + + + + public class UserServerRequest + { + public UserServerRequest() + { + + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/AuthenticateSessionsBase.cs b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsBase.cs new file mode 100644 index 0000000..99b86d4 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsBase.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim +{ + 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; + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/AuthenticateSessionsLocal.cs b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsLocal.cs new file mode 100644 index 0000000..6c1c7d2 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsLocal.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Framework.Types; + +namespace OpenSim +{ + public class AuthenticateSessionsLocal : AuthenticateSessionsBase + { + public AuthenticateSessionsLocal() + { + + } + + public void AddNewSession(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); + this.AddNewCircuit(agent.circuitcode, agent); + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/AuthenticateSessionsRemote.cs b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsRemote.cs new file mode 100644 index 0000000..0802d75 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/AuthenticateSessionsRemote.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Xml; +using libsecondlife; +using OpenSim.Framework.Types; +using Nwc.XmlRpc; + +namespace OpenSim +{ + public class AuthenticateSessionsRemote : AuthenticateSessionsBase + { + public AuthenticateSessionsRemote() + { + + } + + public XmlRpcResponse ExpectUser(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + AgentCircuitData agentData = new AgentCircuitData(); + agentData.SessionID = new LLUUID((string)requestData["session_id"]); + agentData.SecureSessionID = new LLUUID((string)requestData["secure_session_id"]); + agentData.firstname = (string)requestData["firstname"]; + agentData.lastname = (string)requestData["lastname"]; + agentData.AgentID = new LLUUID((string)requestData["agent_id"]); + agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); + if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1")) + { + agentData.child = true; + } + else + { + agentData.startpos = new LLVector3(Convert.ToUInt32(requestData["startpos_x"]), Convert.ToUInt32(requestData["startpos_y"]), Convert.ToUInt32(requestData["startpos_z"])); + agentData.child = false; + // Console.WriteLine("expect user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z); + + } + + this.AddNewCircuit(agentData.circuitcode, agentData); + + return new XmlRpcResponse(); + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/CAPS/AdminWebFront.cs b/OpenSim/OpenSim.RegionServer/CAPS/AdminWebFront.cs new file mode 100644 index 0000000..2299fa4 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/CAPS/AdminWebFront.cs @@ -0,0 +1,256 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using OpenSim.world; +using OpenSim.UserServer; +using OpenSim.Servers; +using OpenSim.Assets; +using OpenSim.Framework.Inventory; +using libsecondlife; +using OpenSim.RegionServer.world.scripting; +using Avatar=libsecondlife.Avatar; + +namespace OpenSim.CAPS +{ + public class AdminWebFront + { + private string AdminPage; + private string NewAccountForm; + private string LoginForm; + private string passWord = "Admin"; + private World m_world; + private LoginServer _userServer; + private InventoryCache _inventoryCache; + + public AdminWebFront(string password, World world, InventoryCache inventoryCache, LoginServer userserver) + { + _inventoryCache = inventoryCache; + _userServer = userserver; + m_world = world; + passWord = password; + LoadAdminPage(); + } + + public void LoadMethods( BaseHttpServer server ) + { + server.AddRestHandler("GET", "/Admin", GetAdminPage); + server.AddRestHandler("GET", "/Admin/Welcome", GetWelcomePage); + server.AddRestHandler("GET", "/Admin/Accounts", GetAccountsPage ); + server.AddRestHandler("GET", "/Admin/Clients", GetConnectedClientsPage); + server.AddRestHandler("GET", "/Admin/Entities", GetEntitiesPage); + server.AddRestHandler("GET", "/Admin/Scripts", GetScriptsPage); + server.AddRestHandler("GET", "/Admin/AddTestScript", AddTestScript ); + server.AddRestHandler("GET", "/ClientInventory", GetClientsInventory); + + server.AddRestHandler("POST", "/Admin/NewAccount", PostNewAccount ); + server.AddRestHandler("POST", "/Admin/Login", PostLogin ); + } + + private string GetWelcomePage(string request, string path, string param) + { + string responseString; + responseString = "Welcome to the OpenSim Admin Page"; + responseString += "


" + LoginForm; + return responseString; + } + + private string PostLogin(string requestBody, string path, string param) + { + string responseString; +// Console.WriteLine(requestBody); + if (requestBody == passWord) + { + responseString = "

Login Successful

"; + } + else + { + responseString = "

Password Error

"; + responseString += "

Please Login with the correct password

"; + responseString += "

" + LoginForm; + } + return responseString; + } + + private string PostNewAccount(string requestBody, string path, string param) + { + string responseString; + string firstName = ""; + string secondName = ""; + string userPasswd = ""; + string[] comp; + string[] passw; + string[] line; + string delimStr = "&"; + char[] delimiter = delimStr.ToCharArray(); + string delimStr2 = "="; + char[] delimiter2 = delimStr2.ToCharArray(); + + //Console.WriteLine(requestBody); + comp = requestBody.Split(delimiter); + passw = comp[3].Split(delimiter2); + if (passw[1] == passWord) // check admin password is correct + { + + line = comp[0].Split(delimiter2); //split firstname + if (line.Length > 1) + { + firstName = line[1]; + } + line = comp[1].Split(delimiter2); //split secondname + if (line.Length > 1) + { + secondName = line[1]; + } + line = comp[2].Split(delimiter2); //split user password + if (line.Length > 1) + { + userPasswd = line[1]; + } + if (this._userServer != null) + { + this._userServer.CreateUserAccount(firstName, secondName, userPasswd); + } + responseString = "

New Account created

"; + } + else + { + responseString = "

Admin password is incorrect, please login with the correct password

"; + responseString += "

" + LoginForm; + } + return responseString; + } + + private string GetConnectedClientsPage(string request, string path, string param) + { + string responseString; + responseString = "

Listing connected Clients

"; + OpenSim.world.Avatar TempAv; + foreach (libsecondlife.LLUUID UUID in m_world.Entities.Keys) + { + if (m_world.Entities[UUID].ToString() == "OpenSim.world.Avatar") + { + TempAv = (OpenSim.world.Avatar)m_world.Entities[UUID]; + responseString += "

Client: "; + responseString += TempAv.firstname + " , " + TempAv.lastname + " , " + UUID + " , " + TempAv.ControllingClient.SessionID + " , " + TempAv.ControllingClient.CircuitCode + " , " + TempAv.ControllingClient.userEP.ToString(); + responseString += "

"; + } + } + return responseString; + } + + private string AddTestScript(string request, string path, string param) + { + int index = path.LastIndexOf('/'); + + string lluidStr = path.Substring(index+1); + + LLUUID id; + + if( LLUUID.TryParse( lluidStr, out id ) ) + { + // This is just here for concept purposes... Remove! + m_world.AddScript( m_world.Entities[id], new FollowRandomAvatar()); + return String.Format("Added new script to object [{0}]", id); + } + else + { + return String.Format("Couldn't parse [{0}]", lluidStr ); + } + } + + private string GetScriptsPage(string request, string path, string param) + { + return String.Empty; + } + + private string GetEntitiesPage(string request, string path, string param) + { + string responseString; + responseString = "

Listing current entities

    "; + + foreach (Entity entity in m_world.Entities.Values) + { + string testScriptLink = "javascript:loadXMLDoc('Admin/AddTestScript/" + entity.uuid.ToString() + "');"; + responseString += String.Format( "
  • [{0}] \"{1}\" @ {2} add test script
  • ", entity.uuid, entity.Name, entity.Pos, testScriptLink ); + } + responseString += "
"; + return responseString; + } + + private string GetClientsInventory(string request, string path, string param) + { + string[] line; + string delimStr = "/"; + char[] delimiter = delimStr.ToCharArray(); + string responseString; + responseString = "

Listing Inventory

"; + + line = path.Split(delimiter); + if (line.Length > 2) + { + if (line[1] == "ClientInventory") + { + AgentInventory inven = this._inventoryCache.GetAgentsInventory(new libsecondlife.LLUUID(line[2])); + responseString += "

Client: " + inven.AgentID.ToStringHyphenated() +"

"; + if (inven != null) + { + foreach (InventoryItem item in inven.InventoryItems.Values) + { + responseString += "

InventoryItem: "; + responseString += item.Name +" , "+ item.ItemID +" , "+ item.Type +" , "+ item.FolderID +" , "+ item.AssetID +" , "+ item.Description ; + responseString += "

"; + } + } + } + } + return responseString; + } + + private string GetCachedAssets(string request, string path, string param) + { + return ""; + } + + private string GetAccountsPage(string request, string path, string param) + { + string responseString; + responseString = "

Account management

"; + responseString += "
"; + responseString += "

Create New Account

"; + responseString += NewAccountForm; + return responseString; + } + + private string GetAdminPage(string request, string path, string param) + { + return AdminPage; + } + + private void LoadAdminPage() + { + try + { + StreamReader SR; + + SR = File.OpenText("testadmin.htm"); + AdminPage = SR.ReadToEnd(); + SR.Close(); + + SR = File.OpenText("newaccountform.htm"); + NewAccountForm = SR.ReadToEnd(); + SR.Close(); + + SR = File.OpenText("login.htm"); + LoginForm = SR.ReadToEnd(); + SR.Close(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + + } + + } +} diff --git a/OpenSim/OpenSim.RegionServer/ClientView.Grid.cs b/OpenSim/OpenSim.RegionServer/ClientView.Grid.cs new file mode 100644 index 0000000..a3b191c --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/ClientView.Grid.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.world; +using OpenSim.Assets; + +namespace OpenSim +{ + public partial class ClientView + { + + public void EnableNeighbours() + { + if ((this.m_gridServer.GetName() == "Remote") && (!this.m_child)) + { + Hashtable SimParams; + ArrayList SendParams; + XmlRpcRequest GridReq; + XmlRpcResponse GridResp; + List enablePackets = new List(); + + RemoteGridBase gridServer = (RemoteGridBase)this.m_gridServer; + + foreach (Hashtable neighbour in gridServer.neighbours) + { + string neighbourIPStr = (string)neighbour["sim_ip"]; + System.Net.IPAddress neighbourIP = System.Net.IPAddress.Parse(neighbourIPStr); + ushort neighbourPort = (ushort)Convert.ToInt32(neighbour["sim_port"]); + string reqUrl = "http://" + neighbourIPStr + ":" + neighbourPort.ToString(); + + Console.WriteLine(reqUrl); + + SimParams = new Hashtable(); + SimParams["session_id"] = this.SessionID.ToString(); + SimParams["secure_session_id"] = this.SecureSessionID.ToString(); + SimParams["firstname"] = this.ClientAvatar.firstname; + SimParams["lastname"] = this.ClientAvatar.lastname; + SimParams["agent_id"] = this.AgentID.ToString(); + SimParams["circuit_code"] = (Int32)this.CircuitCode; + SimParams["child_agent"] = "1"; + SendParams = new ArrayList(); + SendParams.Add(SimParams); + + GridReq = new XmlRpcRequest("expect_user", SendParams); + GridResp = GridReq.Send(reqUrl, 3000); + EnableSimulatorPacket enablesimpacket = new EnableSimulatorPacket(); + enablesimpacket.SimulatorInfo = new EnableSimulatorPacket.SimulatorInfoBlock(); + enablesimpacket.SimulatorInfo.Handle = Helpers.UIntsToLong((uint)(Convert.ToInt32(neighbour["region_locx"]) * 256), (uint)(Convert.ToInt32(neighbour["region_locy"]) * 256)); + + + 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; + enablePackets.Add(enablesimpacket); + } + Thread.Sleep(3000); + foreach (Packet enable in enablePackets) + { + this.OutPacket(enable); + } + enablePackets.Clear(); + + } + } + + public void CrossSimBorder(LLVector3 avatarpos) + { // VERY VERY BASIC + + LLVector3 newpos = avatarpos; + uint neighbourx = this.m_regionData.RegionLocX; + uint neighboury = this.m_regionData.RegionLocY; + + if (avatarpos.X < 0) + { + neighbourx -= 1; + newpos.X = 254; + } + if (avatarpos.X > 255) + { + neighbourx += 1; + newpos.X = 1; + } + if (avatarpos.Y < 0) + { + neighboury -= 1; + newpos.Y = 254; + } + if (avatarpos.Y > 255) + { + neighboury += 1; + newpos.Y = 1; + } + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "SimClient.cs:CrossSimBorder() - Crossing border to neighbouring sim at [" + neighbourx.ToString() + "," + neighboury.ToString() + "]"); + + Hashtable SimParams; + ArrayList SendParams; + XmlRpcRequest GridReq; + XmlRpcResponse GridResp; + foreach (Hashtable borderingSim in ((RemoteGridBase)m_gridServer).neighbours) + { + if (((string)borderingSim["region_locx"]).Equals(neighbourx.ToString()) && ((string)borderingSim["region_locy"]).Equals(neighboury.ToString())) + { + SimParams = new Hashtable(); + SimParams["firstname"] = this.ClientAvatar.firstname; + SimParams["lastname"] = this.ClientAvatar.lastname; + SimParams["circuit_code"] = this.CircuitCode.ToString(); + SimParams["pos_x"] = newpos.X.ToString(); + SimParams["pos_y"] = newpos.Y.ToString(); + SimParams["pos_z"] = newpos.Z.ToString(); + SendParams = new ArrayList(); + SendParams.Add(SimParams); + + GridReq = new XmlRpcRequest("agent_crossing", SendParams); + GridResp = GridReq.Send("http://" + borderingSim["sim_ip"] + ":" + borderingSim["sim_port"], 3000); + + 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 = newpos; + NewSimPack.Info.LookAt = new LLVector3(0.99f, 0.042f, 0); // copied from Avatar.cs - SHOULD BE DYNAMIC!!!!!!!!!! + NewSimPack.RegionData = new libsecondlife.Packets.CrossedRegionPacket.RegionDataBlock(); + NewSimPack.RegionData.RegionHandle = Helpers.UIntsToLong((uint)(Convert.ToInt32(borderingSim["region_locx"]) * 256), (uint)(Convert.ToInt32(borderingSim["region_locy"]) * 256)); + System.Net.IPAddress neighbourIP = System.Net.IPAddress.Parse((string)borderingSim["sim_ip"]); + byte[] byteIP = neighbourIP.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)Convert.ToInt32(borderingSim["sim_port"]); + NewSimPack.RegionData.SeedCapability = new byte[0]; + lock (PacketQueue) + { + ProcessOutPacket(NewSimPack); + DowngradeClient(); + } + } + } + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/ClientView.PacketHandlers.cs b/OpenSim/OpenSim.RegionServer/ClientView.PacketHandlers.cs new file mode 100644 index 0000000..75fcf18 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/ClientView.PacketHandlers.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.world; +using OpenSim.Assets; + +namespace OpenSim +{ + public partial class ClientView + { + protected virtual void RegisterLocalPacketHandlers() + { + this.AddLocalPacketHandler(PacketType.LogoutRequest, this.Logout); + this.AddLocalPacketHandler(PacketType.AgentCachedTexture, this.AgentTextureCached); + this.AddLocalPacketHandler(PacketType.MultipleObjectUpdate, this.MultipleObjUpdate); + } + + protected virtual bool Logout(ClientView simClient, Packet packet) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "OpenSimClient.cs:ProcessInPacket() - Got a logout request"); + //send reply to let the client logout + LogoutReplyPacket logReply = new LogoutReplyPacket(); + logReply.AgentData.AgentID = this.AgentID; + logReply.AgentData.SessionID = this.SessionID; + logReply.InventoryData = new LogoutReplyPacket.InventoryDataBlock[1]; + logReply.InventoryData[0] = new LogoutReplyPacket.InventoryDataBlock(); + logReply.InventoryData[0].ItemID = LLUUID.Zero; + OutPacket(logReply); + //tell all clients to kill our object + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + kill.ObjectData[0].ID = this.ClientAvatar.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + if (this.m_userServer != null) + { + this.m_inventoryCache.ClientLeaving(this.AgentID, this.m_userServer); + } + else + { + this.m_inventoryCache.ClientLeaving(this.AgentID, null); + } + + m_gridServer.LogoutSession(this.SessionID, this.AgentID, this.CircuitCode); + /*lock (m_world.Entities) + { + m_world.Entities.Remove(this.AgentID); + }*/ + m_world.RemoveViewerAgent(this); + //need to do other cleaning up here too + m_clientThreads.Remove(this.CircuitCode); + m_networkServer.RemoveClientCircuit(this.CircuitCode); + this.ClientThread.Abort(); + return true; + } + + protected bool AgentTextureCached(ClientView simclient, Packet packet) + { + // Console.WriteLine(packet.ToString()); + AgentCachedTexturePacket chechedtex = (AgentCachedTexturePacket)packet; + AgentCachedTextureResponsePacket cachedresp = new AgentCachedTextureResponsePacket(); + cachedresp.AgentData.AgentID = this.AgentID; + cachedresp.AgentData.SessionID = this.SessionID; + cachedresp.AgentData.SerialNum = this.cachedtextureserial; + this.cachedtextureserial++; + cachedresp.WearableData = new AgentCachedTextureResponsePacket.WearableDataBlock[chechedtex.WearableData.Length]; + for (int i = 0; i < chechedtex.WearableData.Length; i++) + { + cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock(); + cachedresp.WearableData[i].TextureIndex = chechedtex.WearableData[i].TextureIndex; + cachedresp.WearableData[i].TextureID = LLUUID.Zero; + cachedresp.WearableData[i].HostName = new byte[0]; + } + this.OutPacket(cachedresp); + return true; + } + + protected bool MultipleObjUpdate(ClientView simClient, Packet packet) + { + MultipleObjectUpdatePacket multipleupdate = (MultipleObjectUpdatePacket)packet; + for (int i = 0; i < multipleupdate.ObjectData.Length; i++) + { + if (multipleupdate.ObjectData[i].Type == 9) //change position + { + libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0); + OnUpdatePrimPosition(multipleupdate.ObjectData[i].ObjectLocalID, pos, this); + //should update stored position of the prim + } + else if (multipleupdate.ObjectData[i].Type == 10)//rotation + { + libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true); + OnUpdatePrimRotation(multipleupdate.ObjectData[i].ObjectLocalID, rot, this); + } + else if (multipleupdate.ObjectData[i].Type == 13)//scale + { + libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12); + OnUpdatePrimScale(multipleupdate.ObjectData[i].ObjectLocalID, scale, this); + } + } + return true; + } + + public void RequestMapLayer() //should be getting the map layer from the grid server + { + //send a layer covering the 800,800 - 1200,1200 area (should be covering the requested area) + MapLayerReplyPacket mapReply = new MapLayerReplyPacket(); + mapReply.AgentData.AgentID = this.AgentID; + mapReply.AgentData.Flags = 0; + mapReply.LayerData = new MapLayerReplyPacket.LayerDataBlock[1]; + mapReply.LayerData[0] = new MapLayerReplyPacket.LayerDataBlock(); + mapReply.LayerData[0].Bottom = 800; + mapReply.LayerData[0].Left = 800; + mapReply.LayerData[0].Top = 1200; + mapReply.LayerData[0].Right = 1200; + 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/OpenSim.RegionServer/ClientView.ProcessPackets.cs b/OpenSim/OpenSim.RegionServer/ClientView.ProcessPackets.cs new file mode 100644 index 0000000..a6ad8d2 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/ClientView.ProcessPackets.cs @@ -0,0 +1,453 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.world; +using OpenSim.Assets; + +namespace OpenSim +{ + public partial class ClientView + { + public delegate void GenericCall(ClientView 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, ClientView remoteClient); + public delegate void UpdateShape(uint localID, ObjectShapePacket.ObjectDataBlock shapeBlock); + public delegate void ObjectSelect(uint localID, ClientView remoteClient); + public delegate void UpdatePrimFlags(uint localID, Packet packet, ClientView remoteClient); + public delegate void UpdatePrimTexture(uint localID, byte[] texture, ClientView remoteClient); + public delegate void UpdatePrimVector(uint localID, LLVector3 pos, ClientView remoteClient); + public delegate void UpdatePrimRotation(uint localID, LLQuaternion rot, ClientView remoteClient); + + 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 GenericCall3 OnAgentUpdate; + public event StartAnim OnStartAnim; + public event GenericCall OnRequestAvatarsData; + public event LinkObjects OnLinkObjects; + public event GenericCall4 OnAddPrim; + public event UpdateShape OnUpdatePrimShape; + public event ObjectSelect OnObjectSelect; + public event UpdatePrimFlags OnUpdatePrimFlags; + public event UpdatePrimTexture OnUpdatePrimTexture; + public event UpdatePrimVector OnUpdatePrimPosition; + public event UpdatePrimRotation OnUpdatePrimRotation; + public event UpdatePrimVector OnUpdatePrimScale; + + protected override void ProcessInPacket(Packet Pack) + { + ack_pack(Pack); + if (debug) + { + if (Pack.Type != PacketType.AgentUpdate) + { + Console.WriteLine(Pack.Type.ToString()); + } + } + + if (this.ProcessPacketMethod(Pack)) + { + //there is a handler registered that handled this packet type + return; + } + else + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + + switch (Pack.Type) + { + case PacketType.ViewerEffect: + ViewerEffectPacket viewer = (ViewerEffectPacket)Pack; + foreach (ClientView client in m_clientThreads.Values) + { + if (client.AgentID != this.AgentID) + { + viewer.AgentData.AgentID = client.AgentID; + viewer.AgentData.SessionID = client.SessionID; + client.OutPacket(viewer); + } + } + break; + + #region New Event System - 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 = ClientAvatar.Pos; + LLUUID fromAgentID = AgentID; + this.OnChatFromViewer(message, type, fromPos, fromName, fromAgentID); + break; + case PacketType.RezObject: + RezObjectPacket rezPacket = (RezObjectPacket)Pack; + AgentInventory inven = this.m_inventoryCache.GetAgentsInventory(this.AgentID); + if (inven != null) + { + if (inven.InventoryItems.ContainsKey(rezPacket.InventoryData.ItemID)) + { + AssetBase asset = this.m_assetCache.GetAsset(inven.InventoryItems[rezPacket.InventoryData.ItemID].AssetID); + if (asset != null) + { + this.OnRezObject(asset, rezPacket.RezData.RayEnd); + this.m_inventoryCache.DeleteInventoryItem(this, rezPacket.InventoryData.ItemID); + } + } + } + break; + case PacketType.DeRezObject: + OnDeRezObject(Pack, this); + break; + case PacketType.ModifyLand: + ModifyLandPacket modify = (ModifyLandPacket)Pack; + if (modify.ParcelData.Length > 0) + { + OnModifyTerrain(modify.ModifyBlock.Action, modify.ParcelData[0].North, modify.ParcelData[0].West); + } + break; + case PacketType.RegionHandshakeReply: + OnRegionHandShakeReply(this); + break; + case PacketType.AgentWearablesRequest: + OnRequestWearables(this); + OnRequestAvatarsData(this); + break; + case PacketType.AgentSetAppearance: + AgentSetAppearancePacket appear = (AgentSetAppearancePacket)Pack; + OnSetAppearance(appear.ObjectData.TextureEntry, appear.VisualParam); + break; + case PacketType.CompleteAgentMovement: + if (this.m_child) this.UpgradeClient(); + OnCompleteMovementToRegion(); + this.EnableNeighbours(); + break; + case PacketType.AgentUpdate: + OnAgentUpdate(Pack); + 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) + { + OnStartAnim(AgentAni.AnimationList[i].AnimID, 1); + } + } + } + break; + + #endregion + + #region New Event System - Objects/Prims + case PacketType.ObjectLink: + // OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, 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); + } + } + OnLinkObjects(parentprimid, childrenprims); + break; + case PacketType.ObjectAdd: + m_world.AddNewPrim((ObjectAddPacket)Pack, this); + OnAddPrim(Pack, this); + break; + case PacketType.ObjectShape: + ObjectShapePacket shape = (ObjectShapePacket)Pack; + for (int i = 0; i < shape.ObjectData.Length; i++) + { + OnUpdatePrimShape(shape.ObjectData[i].ObjectLocalID, shape.ObjectData[i]); + } + break; + case PacketType.ObjectSelect: + ObjectSelectPacket incomingselect = (ObjectSelectPacket)Pack; + for (int i = 0; i < incomingselect.ObjectData.Length; i++) + { + OnObjectSelect(incomingselect.ObjectData[i].ObjectLocalID, this); + } + break; + case PacketType.ObjectFlagUpdate: + ObjectFlagUpdatePacket flags = (ObjectFlagUpdatePacket)Pack; + OnUpdatePrimFlags(flags.AgentData.ObjectLocalID, Pack, this); + break; + case PacketType.ObjectImage: + ObjectImagePacket imagePack = (ObjectImagePacket)Pack; + for (int i = 0; i < imagePack.ObjectData.Length; i++) + { + OnUpdatePrimTexture(imagePack.ObjectData[i].ObjectLocalID, imagePack.ObjectData[i].TextureEntry, this); + + } + break; + #endregion + + #region Inventory/Asset/Other related packets + case PacketType.RequestImage: + RequestImagePacket imageRequest = (RequestImagePacket)Pack; + for (int i = 0; i < imageRequest.RequestImage.Length; i++) + { + m_assetCache.AddTextureRequest(this, imageRequest.RequestImage[i].Image); + } + break; + case PacketType.TransferRequest: + //Console.WriteLine("OpenSimClient.cs:ProcessInPacket() - Got transfer request"); + TransferRequestPacket transfer = (TransferRequestPacket)Pack; + m_assetCache.AddAssetRequest(this, transfer); + break; + case PacketType.AssetUploadRequest: + AssetUploadRequestPacket request = (AssetUploadRequestPacket)Pack; + this.UploadAssets.HandleUploadPacket(request, request.AssetBlock.TransactionID.Combine(this.SecureSessionID)); + break; + case PacketType.RequestXfer: + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.SendXferPacket: + this.UploadAssets.HandleXferPacket((SendXferPacketPacket)Pack); + break; + case PacketType.CreateInventoryFolder: + CreateInventoryFolderPacket invFolder = (CreateInventoryFolderPacket)Pack; + m_inventoryCache.CreateNewInventoryFolder(this, invFolder.FolderData.FolderID, (ushort)invFolder.FolderData.Type, Util.FieldToString(invFolder.FolderData.Name), invFolder.FolderData.ParentID); + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.CreateInventoryItem: + //Console.WriteLine(Pack.ToString()); + CreateInventoryItemPacket createItem = (CreateInventoryItemPacket)Pack; + if (createItem.InventoryBlock.TransactionID != LLUUID.Zero) + { + this.UploadAssets.CreateInventoryItem(createItem); + } + else + { + // Console.Write(Pack.ToString()); + this.CreateInventoryItem(createItem); + } + break; + case PacketType.FetchInventory: + //Console.WriteLine("fetch item packet"); + FetchInventoryPacket FetchInventory = (FetchInventoryPacket)Pack; + m_inventoryCache.FetchInventory(this, FetchInventory); + break; + case PacketType.FetchInventoryDescendents: + FetchInventoryDescendentsPacket Fetch = (FetchInventoryDescendentsPacket)Pack; + m_inventoryCache.FetchInventoryDescendents(this, Fetch); + break; + case PacketType.UpdateInventoryItem: + UpdateInventoryItemPacket update = (UpdateInventoryItemPacket)Pack; + //Console.WriteLine(Pack.ToString()); + for (int i = 0; i < update.InventoryData.Length; i++) + { + if (update.InventoryData[i].TransactionID != LLUUID.Zero) + { + AssetBase asset = m_assetCache.GetAsset(update.InventoryData[i].TransactionID.Combine(this.SecureSessionID)); + if (asset != null) + { + // Console.WriteLine("updating inventory item, found asset" + asset.FullID.ToStringHyphenated() + " already in cache"); + m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset); + } + else + { + asset = this.UploadAssets.AddUploadToAssetCache(update.InventoryData[i].TransactionID); + if (asset != null) + { + //Console.WriteLine("updating inventory item, adding asset" + asset.FullID.ToStringHyphenated() + " to cache"); + m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset); + } + else + { + //Console.WriteLine("trying to update inventory item, but asset is null"); + } + } + } + else + { + m_inventoryCache.UpdateInventoryItemDetails(this, update.InventoryData[i].ItemID, update.InventoryData[i]); ; + } + } + break; + case PacketType.RequestTaskInventory: + // Console.WriteLine(Pack.ToString()); + RequestTaskInventoryPacket requesttask = (RequestTaskInventoryPacket)Pack; + ReplyTaskInventoryPacket replytask = new ReplyTaskInventoryPacket(); + bool foundent = false; + foreach (Entity ent in m_world.Entities.Values) + { + if (ent.localid == requesttask.InventoryData.LocalID) + { + replytask.InventoryData.TaskID = ent.uuid; + replytask.InventoryData.Serial = 0; + replytask.InventoryData.Filename = new byte[0]; + foundent = true; + } + } + if (foundent) + { + this.OutPacket(replytask); + } + break; + case PacketType.UpdateTaskInventory: + // Console.WriteLine(Pack.ToString()); + UpdateTaskInventoryPacket updatetask = (UpdateTaskInventoryPacket)Pack; + AgentInventory myinventory = this.m_inventoryCache.GetAgentsInventory(this.AgentID); + if (myinventory != null) + { + if (updatetask.UpdateData.Key == 0) + { + if (myinventory.InventoryItems[updatetask.InventoryData.ItemID] != null) + { + if (myinventory.InventoryItems[updatetask.InventoryData.ItemID].Type == 7) + { + LLUUID noteaid = myinventory.InventoryItems[updatetask.InventoryData.ItemID].AssetID; + AssetBase assBase = this.m_assetCache.GetAsset(noteaid); + if (assBase != null) + { + foreach (Entity ent in m_world.Entities.Values) + { + if (ent.localid == updatetask.UpdateData.LocalID) + { + if (ent is OpenSim.world.Primitive) + { + this.m_world.AddScript(ent, Util.FieldToString(assBase.Data)); + } + } + } + } + } + } + } + } + break; + case PacketType.MapLayerRequest: + this.RequestMapLayer(); + break; + case PacketType.MapBlockRequest: + MapBlockRequestPacket MapRequest = (MapBlockRequestPacket)Pack; + + this.RequestMapBlocks(MapRequest.PositionData.MinX, MapRequest.PositionData.MinY, MapRequest.PositionData.MaxX, MapRequest.PositionData.MaxY); + break; + case PacketType.TeleportLandmarkRequest: + TeleportLandmarkRequestPacket tpReq = (TeleportLandmarkRequestPacket)Pack; + + TeleportStartPacket tpStart = new TeleportStartPacket(); + tpStart.Info.TeleportFlags = 8; // tp via lm + this.OutPacket(tpStart); + + TeleportProgressPacket tpProgress = new TeleportProgressPacket(); + tpProgress.Info.Message = (new System.Text.ASCIIEncoding()).GetBytes("sending_landmark"); + tpProgress.Info.TeleportFlags = 8; + tpProgress.AgentData.AgentID = tpReq.Info.AgentID; + this.OutPacket(tpProgress); + + // Fetch landmark + LLUUID lmid = tpReq.Info.LandmarkID; + AssetBase lma = this.m_assetCache.GetAsset(lmid); + if (lma != null) + { + AssetLandmark lm = new AssetLandmark(lma); + + if (lm.RegionID == m_regionData.SimUUID) + { + TeleportLocalPacket tpLocal = new TeleportLocalPacket(); + + tpLocal.Info.AgentID = tpReq.Info.AgentID; + tpLocal.Info.TeleportFlags = 8; // Teleport via landmark + tpLocal.Info.LocationID = 2; + tpLocal.Info.Position = lm.Position; + OutPacket(tpLocal); + } + else + { + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.AgentID = tpReq.Info.AgentID; + tpCancel.Info.SessionID = tpReq.Info.SessionID; + OutPacket(tpCancel); + } + } + else + { + Console.WriteLine("Cancelling Teleport - fetch asset not yet implemented"); + + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.AgentID = tpReq.Info.AgentID; + tpCancel.Info.SessionID = tpReq.Info.SessionID; + OutPacket(tpCancel); + } + break; + case PacketType.TeleportLocationRequest: + TeleportLocationRequestPacket tpLocReq = (TeleportLocationRequestPacket)Pack; + Console.WriteLine(tpLocReq.ToString()); + + tpStart = new TeleportStartPacket(); + tpStart.Info.TeleportFlags = 16; // Teleport via location + Console.WriteLine(tpStart.ToString()); + OutPacket(tpStart); + + if (m_regionData.RegionHandle != tpLocReq.Info.RegionHandle) + { + /* m_gridServer.getRegion(tpLocReq.Info.RegionHandle); */ + Console.WriteLine("Inter-sim teleport not yet implemented"); + TeleportCancelPacket tpCancel = new TeleportCancelPacket(); + tpCancel.Info.SessionID = tpLocReq.AgentData.SessionID; + tpCancel.Info.AgentID = tpLocReq.AgentData.AgentID; + + OutPacket(tpCancel); + } + else + { + Console.WriteLine("Local teleport"); + TeleportLocalPacket tpLocal = new TeleportLocalPacket(); + tpLocal.Info.AgentID = tpLocReq.AgentData.AgentID; + tpLocal.Info.TeleportFlags = tpStart.Info.TeleportFlags; + tpLocal.Info.LocationID = 2; + tpLocal.Info.LookAt = tpLocReq.Info.LookAt; + tpLocal.Info.Position = tpLocReq.Info.Position; + OutPacket(tpLocal); + + } + break; + #endregion + + #region unimplemented handlers + case PacketType.AgentIsNowWearing: + // AgentIsNowWearingPacket wear = (AgentIsNowWearingPacket)Pack; + //Console.WriteLine(Pack.ToString()); + break; + case PacketType.ObjectScale: + //OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, Pack.ToString()); + break; + #endregion + } + } + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/ClientView.cs b/OpenSim/OpenSim.RegionServer/ClientView.cs new file mode 100644 index 0000000..e66b830 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/ClientView.cs @@ -0,0 +1,439 @@ +/* +Copyright (c) OpenSim project, http://osgrid.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using Nwc.XmlRpc; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.world; +using OpenSim.Assets; + +namespace OpenSim +{ + public delegate bool PacketMethod(ClientView simClient, Packet packet); + + /// + /// Handles new client connections + /// Constructor takes a single Packet and authenticates everything + /// + public partial class ClientView : ClientViewBase, IClientAPI + { + 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 bool m_child; + public world.Avatar ClientAvatar; + private UseCircuitCodePacket cirpack; + public Thread ClientThread; + public LLVector3 startpos; + + private AgentAssetUpload UploadAssets; + private LLUUID newAssetFolder = LLUUID.Zero; + private bool debug = false; + private World m_world; + private Dictionary m_clientThreads; + private AssetCache m_assetCache; + private IGridServer m_gridServer; + private IUserServer m_userServer = null; + private InventoryCache m_inventoryCache; + public bool m_sandboxMode; + private int cachedtextureserial = 0; + private RegionInfo m_regionData; + protected AuthenticateSessionsBase m_authenticateSessionsHandler; + + public IUserServer UserServer + { + set + { + this.m_userServer = value; + } + } + + public ClientView(EndPoint remoteEP, UseCircuitCodePacket initialcirpack, World world, Dictionary clientThreads, AssetCache assetCache, IGridServer gridServer, OpenSimNetworkHandler application, InventoryCache inventoryCache, bool sandboxMode, bool child, RegionInfo regionDat, AuthenticateSessionsBase authenSessions) + { + m_world = world; + m_clientThreads = clientThreads; + m_assetCache = assetCache; + m_gridServer = gridServer; + m_networkServer = application; + m_inventoryCache = inventoryCache; + m_sandboxMode = sandboxMode; + m_child = child; + m_regionData = regionDat; + m_authenticateSessionsHandler = authenSessions; + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "OpenSimClient.cs - Started up new client thread to handle incoming request"); + cirpack = initialcirpack; + userEP = remoteEP; + + if (m_gridServer.GetName() == "Remote") + { + this.m_child = m_authenticateSessionsHandler.GetAgentChildStatus(initialcirpack.CircuitCode.Code); + this.startpos = m_authenticateSessionsHandler.GetPosition(initialcirpack.CircuitCode.Code); + //Console.WriteLine("start pos is " + this.startpos.X + " , " + this.startpos.Y + " , " + this.startpos.Z); + } + else + { + this.startpos = new LLVector3(128, 128, m_world.Terrain[(int)128, (int)128] + 15.0f); // new LLVector3(128.0f, 128.0f, 60f); + } + + PacketQueue = new BlockingQueue(); + + this.UploadAssets = new AgentAssetUpload(this, m_assetCache, m_inventoryCache); + AckTimer = new System.Timers.Timer(500); + AckTimer.Elapsed += new ElapsedEventHandler(AckTimer_Elapsed); + AckTimer.Start(); + + this.RegisterLocalPacketHandlers(); + + ClientThread = new Thread(new ThreadStart(AuthUser)); + ClientThread.IsBackground = true; + ClientThread.Start(); + } + + # region Client Methods + public void UpgradeClient() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "SimClient.cs:UpgradeClient() - upgrading child to full agent"); + this.m_child = false; + this.m_world.RemoveViewerAgent(this); + if (!this.m_sandboxMode) + { + this.startpos = m_authenticateSessionsHandler.GetPosition(CircuitCode); + m_authenticateSessionsHandler.UpdateAgentChildStatus(CircuitCode, false); + } + this.InitNewClient(); + } + + public void DowngradeClient() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "SimClient.cs:UpgradeClient() - changing full agent to child"); + this.m_child = true; + this.m_world.RemoveViewerAgent(this); + this.m_world.AddViewerAgent(this); + } + + public void KillClient() + { + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + kill.ObjectData[0].ID = this.ClientAvatar.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + if (this.m_userServer != null) + { + this.m_inventoryCache.ClientLeaving(this.AgentID, this.m_userServer); + } + else + { + this.m_inventoryCache.ClientLeaving(this.AgentID, null); + } + + m_world.RemoveViewerAgent(this); + + m_clientThreads.Remove(this.CircuitCode); + m_networkServer.RemoveClientCircuit(this.CircuitCode); + this.ClientThread.Abort(); + } + #endregion + + # region Packet Handling + public static bool AddPacketHandler(PacketType packetType, PacketMethod handler) + { + bool result = false; + lock (PacketHandlers) + { + if (!PacketHandlers.ContainsKey(packetType)) + { + PacketHandlers.Add(packetType, handler); + result = true; + } + } + return result; + } + + public bool AddLocalPacketHandler(PacketType packetType, PacketMethod handler) + { + bool result = false; + lock (m_packetHandlers) + { + if (!m_packetHandlers.ContainsKey(packetType)) + { + m_packetHandlers.Add(packetType, handler); + result = true; + } + } + return result; + } + + protected virtual bool ProcessPacketMethod(Packet packet) + { + bool result = false; + bool found = false; + PacketMethod method; + if (m_packetHandlers.TryGetValue(packet.Type, out method)) + { + //there is a local handler for this packet type + result = method(this, packet); + } + else + { + //there is not a local handler so see if there is a Global handler + lock (PacketHandlers) + { + found = PacketHandlers.TryGetValue(packet.Type, out method); + } + if (found) + { + result = method(this, packet); + } + } + return result; + } + + protected virtual void ClientLoop() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "OpenSimClient.cs:ClientLoop() - Entered loop"); + while (true) + { + QueItem nextPacket = PacketQueue.Dequeue(); + if (nextPacket.Incoming) + { + //is a incoming packet + ProcessInPacket(nextPacket.Packet); + } + else + { + //is a out going packet + ProcessOutPacket(nextPacket.Packet); + } + } + } + # endregion + + # region Setup + + protected virtual void InitNewClient() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "OpenSimClient.cs:InitNewClient() - Adding viewer agent to world"); + + m_world.AddViewerAgent(this); + world.Entity tempent = m_world.Entities[this.AgentID]; + + this.ClientAvatar = (world.Avatar)tempent; + } + + protected virtual void AuthUser() + { + // AuthenticateResponse sessionInfo = m_gridServer.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code); + AuthenticateResponse sessionInfo = this.m_networkServer.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code); + if (!sessionInfo.Authorised) + { + //session/circuit not authorised + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.NORMAL, "OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString()); + ClientThread.Abort(); + } + else + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.NORMAL, "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; + InitNewClient(); //shouldn't be called here as we might be a child agent and not want a full avatar + this.ClientAvatar.firstname = sessionInfo.LoginInfo.First; + this.ClientAvatar.lastname = sessionInfo.LoginInfo.Last; + if (sessionInfo.LoginInfo.SecureSession != LLUUID.Zero) + { + this.SecureSessionID = sessionInfo.LoginInfo.SecureSession; + } + + // Create Inventory, currently only works for sandbox mode + if (m_sandboxMode) + { + this.SetupInventory(sessionInfo); + } + + ClientLoop(); + } + } + # endregion + + + protected override void KillThread() + { + this.ClientThread.Abort(); + } + + #region World/Avatar To Viewer Methods + + public void SendChatMessage(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + System.Text.Encoding enc = System.Text.Encoding.ASCII; + libsecondlife.Packets.ChatFromSimulatorPacket reply = new ChatFromSimulatorPacket(); + reply.ChatData.Audible = 1; + reply.ChatData.Message = message; + reply.ChatData.ChatType = type; + reply.ChatData.SourceType = 1; + reply.ChatData.Position = fromPos; + reply.ChatData.FromName = enc.GetBytes(fromName + "\0"); + reply.ChatData.OwnerID = fromAgentID; + reply.ChatData.SourceID = fromAgentID; + + this.OutPacket(reply); + } + + public void SendAppearance(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); + } + #endregion + + #region Inventory Creation + private void SetupInventory(AuthenticateResponse sessionInfo) + { + AgentInventory inventory = null; + if (sessionInfo.LoginInfo.InventoryFolder != null) + { + inventory = this.CreateInventory(sessionInfo.LoginInfo.InventoryFolder); + if (sessionInfo.LoginInfo.BaseFolder != null) + { + if (!inventory.HasFolder(sessionInfo.LoginInfo.BaseFolder)) + { + m_inventoryCache.CreateNewInventoryFolder(this, sessionInfo.LoginInfo.BaseFolder); + } + this.newAssetFolder = sessionInfo.LoginInfo.BaseFolder; + AssetBase[] inventorySet = m_assetCache.CreateNewInventorySet(this.AgentID); + if (inventorySet != null) + { + for (int i = 0; i < inventorySet.Length; i++) + { + if (inventorySet[i] != null) + { + m_inventoryCache.AddNewInventoryItem(this, sessionInfo.LoginInfo.BaseFolder, inventorySet[i]); + } + } + } + } + } + } + private AgentInventory CreateInventory(LLUUID baseFolder) + { + AgentInventory inventory = null; + if (this.m_userServer != null) + { + // a user server is set so request the inventory from it + Console.WriteLine("getting inventory from user server"); + inventory = m_inventoryCache.FetchAgentsInventory(this.AgentID, m_userServer); + } + else + { + inventory = new AgentInventory(); + inventory.AgentID = this.AgentID; + inventory.CreateRootFolder(this.AgentID, false); + m_inventoryCache.AddNewAgentsInventory(inventory); + m_inventoryCache.CreateNewInventoryFolder(this, baseFolder); + } + return inventory; + } + + private void CreateInventoryItem(CreateInventoryItemPacket packet) + { + if (!(packet.InventoryBlock.Type == 3 || packet.InventoryBlock.Type == 7)) + { + System.Console.WriteLine("Attempted to create " + Util.FieldToString(packet.InventoryBlock.Name) + " in inventory. Unsupported type"); + return; + } + + //lets try this out with creating a notecard + AssetBase asset = new AssetBase(); + + asset.Name = Util.FieldToString(packet.InventoryBlock.Name); + asset.Description = Util.FieldToString(packet.InventoryBlock.Description); + asset.InvType = packet.InventoryBlock.InvType; + asset.Type = packet.InventoryBlock.Type; + asset.FullID = LLUUID.Random(); + + switch (packet.InventoryBlock.Type) + { + case 7: // Notecard + asset.Data = new byte[0]; + break; + + case 3: // Landmark + String content; + content = "Landmark version 2\n"; + content += "region_id " + m_regionData.SimUUID + "\n"; + String strPos = String.Format("%.2f %.2f %.2f>", + this.ClientAvatar.Pos.X, + this.ClientAvatar.Pos.Y, + this.ClientAvatar.Pos.Z); + content += "local_pos " + strPos + "\n"; + asset.Data = (new System.Text.ASCIIEncoding()).GetBytes(content); + break; + default: + break; + } + m_assetCache.AddAsset(asset); + m_inventoryCache.AddNewInventoryItem(this, packet.InventoryBlock.FolderID, asset); + } + #endregion + + } +} diff --git a/OpenSim/OpenSim.RegionServer/ClientViewBase.cs b/OpenSim/OpenSim.RegionServer/ClientViewBase.cs new file mode 100644 index 0000000..572dbce --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/ClientViewBase.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using System.Net; +using System.Net.Sockets; +using System.IO; +using System.Threading; +using System.Timers; +using OpenSim.Framework.Utilities; +using OpenSim.Framework.Interfaces; + +namespace OpenSim +{ + public class ClientViewBase + { + protected BlockingQueue PacketQueue; + protected Dictionary PendingAcks = new Dictionary(); + protected Dictionary NeedAck = new Dictionary(); + + protected System.Timers.Timer AckTimer; + protected uint Sequence = 0; + protected object SequenceLock = new object(); + protected const int MAX_APPENDED_ACKS = 10; + protected const int RESEND_TIMEOUT = 4000; + protected const int MAX_SEQUENCE = 0xFFFFFF; + + public uint CircuitCode; + public EndPoint userEP; + + protected OpenSimNetworkHandler m_networkServer; + + public ClientViewBase() + { + + } + + protected virtual void ProcessInPacket(Packet Pack) + { + + } + + protected virtual void ProcessOutPacket(Packet Pack) + { + // Keep track of when this packet was sent out + Pack.TickCount = Environment.TickCount; + + if (!Pack.Header.Resent) + { + // Set the sequence number + lock (SequenceLock) + { + if (Sequence >= MAX_SEQUENCE) + Sequence = 1; + else + Sequence++; + Pack.Header.Sequence = Sequence; + } + + if (Pack.Header.Reliable) //DIRTY HACK + { + lock (NeedAck) + { + if (!NeedAck.ContainsKey(Pack.Header.Sequence)) + { + try + { + NeedAck.Add(Pack.Header.Sequence, Pack); + } + catch (Exception e) // HACKY + { + e.ToString(); + // Ignore + // Seems to throw a exception here occasionally + // of 'duplicate key' despite being locked. + // !?!?!? + } + } + else + { + // Client.Log("Attempted to add a duplicate sequence number (" + + // packet.Header.Sequence + ") to the NeedAck dictionary for packet type " + + // packet.Type.ToString(), Helpers.LogLevel.Warning); + } + } + + // Don't append ACKs to resent packets, in case that's what was causing the + // delivery to fail + if (!Pack.Header.Resent) + { + // Append any ACKs that need to be sent out to this packet + lock (PendingAcks) + { + if (PendingAcks.Count > 0 && PendingAcks.Count < MAX_APPENDED_ACKS && + Pack.Type != PacketType.PacketAck && + Pack.Type != PacketType.LogoutRequest) + { + Pack.Header.AckList = new uint[PendingAcks.Count]; + int i = 0; + + foreach (uint ack in PendingAcks.Values) + { + Pack.Header.AckList[i] = ack; + i++; + } + + PendingAcks.Clear(); + Pack.Header.AppendedAcks = true; + } + } + } + } + } + + byte[] ZeroOutBuffer = new byte[4096]; + byte[] sendbuffer; + sendbuffer = Pack.ToBytes(); + + try + { + if (Pack.Header.Zerocoded) + { + int packetsize = Helpers.ZeroEncode(sendbuffer, sendbuffer.Length, ZeroOutBuffer); + m_networkServer.SendPacketTo(ZeroOutBuffer, packetsize, SocketFlags.None, CircuitCode);//userEP); + } + else + { + m_networkServer.SendPacketTo(sendbuffer, sendbuffer.Length, SocketFlags.None, CircuitCode); //userEP); + } + } + catch (Exception) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "OpenSimClient.cs:ProcessOutPacket() - WARNING: Socket exception occurred on connection " + userEP.ToString() + " - killing thread"); + this.KillThread(); + } + + } + + public virtual void InPacket(Packet NewPack) + { + // Handle appended ACKs + if (NewPack.Header.AppendedAcks) + { + lock (NeedAck) + { + foreach (uint ack in NewPack.Header.AckList) + { + NeedAck.Remove(ack); + } + } + } + + // Handle PacketAck packets + if (NewPack.Type == PacketType.PacketAck) + { + PacketAckPacket ackPacket = (PacketAckPacket)NewPack; + + lock (NeedAck) + { + foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets) + { + NeedAck.Remove(block.ID); + } + } + } + else if ((NewPack.Type == PacketType.StartPingCheck)) + { + //reply to pingcheck + libsecondlife.Packets.StartPingCheckPacket startPing = (libsecondlife.Packets.StartPingCheckPacket)NewPack; + libsecondlife.Packets.CompletePingCheckPacket endPing = new CompletePingCheckPacket(); + endPing.PingID.PingID = startPing.PingID.PingID; + OutPacket(endPing); + } + else + { + QueItem item = new QueItem(); + item.Packet = NewPack; + item.Incoming = true; + this.PacketQueue.Enqueue(item); + } + + } + + public virtual void OutPacket(Packet NewPack) + { + QueItem item = new QueItem(); + item.Packet = NewPack; + item.Incoming = false; + this.PacketQueue.Enqueue(item); + } + + # region Low Level Packet Methods + + protected void ack_pack(Packet Pack) + { + if (Pack.Header.Reliable) + { + libsecondlife.Packets.PacketAckPacket ack_it = new PacketAckPacket(); + ack_it.Packets = new PacketAckPacket.PacketsBlock[1]; + ack_it.Packets[0] = new PacketAckPacket.PacketsBlock(); + ack_it.Packets[0].ID = Pack.Header.Sequence; + ack_it.Header.Reliable = false; + + OutPacket(ack_it); + + } + /* + if (Pack.Header.Reliable) + { + lock (PendingAcks) + { + uint sequence = (uint)Pack.Header.Sequence; + if (!PendingAcks.ContainsKey(sequence)) { PendingAcks[sequence] = sequence; } + } + }*/ + } + + protected void ResendUnacked() + { + int now = Environment.TickCount; + + lock (NeedAck) + { + foreach (Packet packet in NeedAck.Values) + { + if ((now - packet.TickCount > RESEND_TIMEOUT) && (!packet.Header.Resent)) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE, "Resending " + packet.Type.ToString() + " packet, " + + (now - packet.TickCount) + "ms have passed"); + + packet.Header.Resent = true; + OutPacket(packet); + } + } + } + } + + protected void SendAcks() + { + lock (PendingAcks) + { + if (PendingAcks.Count > 0) + { + if (PendingAcks.Count > 250) + { + // FIXME: Handle the odd case where we have too many pending ACKs queued up + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE, "Too many ACKs queued up!"); + return; + } + + //OpenSim.Framework.Console.MainConsole.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/OpenSim.RegionServer/Grid.cs b/OpenSim/OpenSim.RegionServer/Grid.cs new file mode 100644 index 0000000..db5b8fe --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/Grid.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using OpenSim.Framework.Interfaces; +using OpenSim.UserServer; + +namespace OpenSim +{ + public class Grid + { + public IAssetServer AssetServer; + public IGridServer GridServer; + public IUserServer UserServer; + public string AssetDll = ""; + public string GridDll = ""; + + public Grid() + { + } + + public virtual void Initialise() + { + //load the dlls + this.AssetServer = this.LoadAssetDll(this.AssetDll); + this.GridServer = this.LoadGridDll(this.GridDll); + } + public virtual void Close() + { + this.AssetServer.Close(); + this.GridServer.Close(); + } + + 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; + } + + private IGridServer LoadGridDll(string dllName) + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + IGridServer server = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IGridPlugin", true); + + if (typeInterface != null) + { + IGridPlugin plug = (IGridPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + server = plug.GetGridServer(); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + return server; + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj new file mode 100644 index 0000000..512ee88 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj @@ -0,0 +1,258 @@ + + + Local + 8.0.50727 + 2.0 + {632E1BFD-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.RegionServer + JScript + Grid + IE50 + false + Library + + OpenSim.RegionServer + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\bin\libsecondlife.dll + False + + + ..\bin\Axiom.MathLib.dll + False + + + ..\bin\Db4objects.Db4o.dll + False + + + + + OpenSim.Terrain.BasicTerrain + {2270B8FE-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.GenericConfig.Xml + {E88EF749-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Physics.Manager + {8BE16150-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Servers + {8BB20F0A-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + XMLRPC + {8E81D43C-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj.user b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.dll.build b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.dll.build new file mode 100644 index 0000000..4ec3537 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/OpenSim.RegionServer.dll.build @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.RegionServer/OpenSimMain.cs b/OpenSim/OpenSim.RegionServer/OpenSimMain.cs new file mode 100644 index 0000000..003412d --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/OpenSimMain.cs @@ -0,0 +1,531 @@ +/* +Copyright (c) OpenSim project, http://osgrid.org/ + +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.world; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.UserServer; +using OpenSim.Assets; +using OpenSim.CAPS; +using OpenSim.Framework.Console; +using OpenSim.Physics.Manager; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenSim +{ + //moved to the opensim main application project (do we want it there or here?) +/* + public class OpenSimMain : OpenSimApplicationBase , conscmd_callback + { + + 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_console = new ConsoleBase("region-console-" + Guid.NewGuid().ToString() + ".log", "Region", this, silent); + OpenSim.Framework.Console.MainConsole.Instance = m_console; + } + + /// + /// Performs initialisation of the world, such as loading configuration from disk. + /// + public override void StartUp() + { + this.regionData = new RegionInfo(); + try + { + this.localConfig = new XmlConfig(m_config); + this.localConfig.LoadData(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + if (this.configFileSetup) + { + this.SetupFromConfigFile(this.localConfig); + } + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Loading configuration"); + this.regionData.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 + + GridServers = new Grid(); + if (m_sandbox) + { + this.SetupLocalGridServers(); + //Authenticate Session Handler + AuthenticateSessionsLocal authen = new AuthenticateSessionsLocal(); + this.AuthenticateSessionsHandler = authen; + } + else + { + this.SetupRemoteGridServers(); + //Authenticate Session Handler + AuthenticateSessionsRemote authen = new AuthenticateSessionsRemote(); + this.AuthenticateSessionsHandler = authen; + } + + startuptime = DateTime.Now; + + try + { + AssetCache = new AssetCache(GridServers.AssetServer); + InventoryCache = new InventoryCache(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup local cache"); + Environment.Exit(1); + } + + m_udpServer = new UDPServer(this.regionData.IPListenPort, this.GridServers, this.AssetCache, this.InventoryCache, this.regionData, this.m_sandbox, this.user_accounts, this.m_console, this.AuthenticateSessionsHandler); + + //should be passing a IGenericConfig object to these so they can read the config data they want from it + GridServers.AssetServer.SetServerInfo(regionData.AssetURL, regionData.AssetSendKey); + IGridServer gridServer = GridServers.GridServer; + gridServer.SetServerInfo(regionData.GridURL, regionData.GridSendKey, regionData.GridRecvKey); + + if (!m_sandbox) + { + this.ConnectToRemoteGridServer(); + } + + this.SetupLocalWorld(); + + if (m_sandbox) + { + AssetCache.LoadDefaultTextureSet(); + } + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Initialising HTTP server"); + + this.SetupHttpListener(); + + LoginServer loginServer = null; + LoginServer adminLoginServer = null; + + bool sandBoxWithLoginServer = m_loginserver && m_sandbox; + if (sandBoxWithLoginServer) + { + loginServer = new LoginServer( regionData.IPListenAddr, regionData.IPListenPort, regionData.RegionLocX, regionData.RegionLocY, this.user_accounts); + loginServer.Startup(); + loginServer.SetSessionHandler(((AuthenticateSessionsLocal) this.AuthenticateSessionsHandler).AddNewSession); + + if (user_accounts) + { + //sandbox mode with loginserver using accounts + this.GridServers.UserServer = loginServer; + adminLoginServer = loginServer; + + httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.LocalUserManager.XmlRpcLoginMethod); + } + else + { + //sandbox mode with loginserver not using accounts + httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.XmlRpcLoginMethod); + } + } + + AdminWebFront adminWebFront = new AdminWebFront("Admin", LocalWorld, InventoryCache, adminLoginServer); + adminWebFront.LoadMethods(httpServer); + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Starting HTTP server"); + httpServer.Start(); + + //MainServerListener(); + this.m_udpServer.ServerListener(); + + m_heartbeatTimer.Enabled = true; + m_heartbeatTimer.Interval = 100; + m_heartbeatTimer.Elapsed += new ElapsedEventHandler(this.Heartbeat); + } + + # region Setup methods + protected virtual void SetupLocalGridServers() + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll"; + GridServers.GridDll = "OpenSim.GridInterfaces.Local.dll"; + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Starting in Sandbox mode"); + + try + { + GridServers.Initialise(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup the grid interface"); + Environment.Exit(1); + } + } + + protected virtual void SetupRemoteGridServers() + { + if (this.gridLocalAsset) + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll"; + } + else + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Remote.dll"; + } + GridServers.GridDll = "OpenSim.GridInterfaces.Remote.dll"; + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Starting in Grid mode"); + + try + { + GridServers.Initialise(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup the grid interface"); + Environment.Exit(1); + } + } + + protected virtual void SetupLocalWorld() + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.NORMAL, "Main.cs:Startup() - We are " + regionData.RegionName + " at " + regionData.RegionLocX.ToString() + "," + regionData.RegionLocY.ToString()); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Initialising world"); + m_console.componentname = "Region " + regionData.RegionName; + + m_localWorld = new World(this.m_udpServer.PacketServer.ClientThreads, regionData, regionData.RegionHandle, regionData.RegionName); + LocalWorld.InventoryCache = InventoryCache; + LocalWorld.AssetCache = AssetCache; + + this.m_udpServer.LocalWorld = LocalWorld; + this.m_udpServer.PacketServer.RegisterClientPacketHandlers(); + + this.physManager = new OpenSim.Physics.Manager.PhysicsManager(); + this.physManager.LoadPlugins(); + + LocalWorld.m_datastore = this.regionData.DataStore; + + LocalWorld.LoadStorageDLL("OpenSim.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded. + LocalWorld.LoadWorldMap(); + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Starting up messaging system"); + LocalWorld.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); + LocalWorld.PhysScene.SetTerrain(LocalWorld.Terrain.getHeights1D()); + LocalWorld.LoadPrimsFromStorage(); + } + + protected virtual void SetupHttpListener() + { + httpServer = new BaseHttpServer(regionData.IPListenPort); + + if (this.GridServers.GridServer.GetName() == "Remote") + { + + // we are in Grid mode so set a XmlRpc handler to handle "expect_user" calls from the user server + httpServer.AddXmlRPCHandler("expect_user", ((AuthenticateSessionsRemote)this.AuthenticateSessionsHandler).ExpectUser ); + + httpServer.AddXmlRPCHandler("agent_crossing", + delegate(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + AgentCircuitData agent_data = new AgentCircuitData(); + agent_data.firstname = (string)requestData["firstname"]; + agent_data.lastname = (string)requestData["lastname"]; + agent_data.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); + agent_data.startpos = new LLVector3(Single.Parse((string)requestData["pos_x"]), Single.Parse((string)requestData["pos_y"]), Single.Parse((string)requestData["pos_z"])); + + if (((RemoteGridBase)this.GridServers.GridServer).agentcircuits.ContainsKey((uint)agent_data.circuitcode)) + { + ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[(uint)agent_data.circuitcode].firstname = agent_data.firstname; + ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[(uint)agent_data.circuitcode].lastname = agent_data.lastname; + ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[(uint)agent_data.circuitcode].startpos = agent_data.startpos; + } + + return new XmlRpcResponse(); + }); + + httpServer.AddRestHandler("GET", "/simstatus/", + delegate(string request, string path, string param) + { + return "OK"; + }); + } + } + + protected virtual void ConnectToRemoteGridServer() + { + if (GridServers.GridServer.RequestConnection(regionData.SimUUID, regionData.IPListenAddr, (uint)regionData.IPListenPort)) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Success: Got a grid connection OK!"); + } + else + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.CRITICAL, "Main.cs:Startup() - FAILED: Unable to get connection to grid. Shutting down."); + Shutdown(); + } + + GridServers.AssetServer.SetServerInfo((string)((RemoteGridBase)GridServers.GridServer).GridData["asset_url"], (string)((RemoteGridBase)GridServers.GridServer).GridData["asset_sendkey"]); + + // If we are being told to load a file, load it. + string dataUri = (string)((RemoteGridBase)GridServers.GridServer).GridData["data_uri"]; + + if (!String.IsNullOrEmpty(dataUri)) + { + this.LocalWorld.m_datastore = dataUri; + } + + if (((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString() != "") + { + // The grid server has told us who we are + // We must obey the grid server. + try + { + regionData.RegionLocX = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locx"].ToString()); + regionData.RegionLocY = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locy"].ToString()); + regionData.RegionName = ((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.CRITICAL, e.Message + "\nBAD ERROR! THIS SHOULD NOT HAPPEN! Bad GridData from the grid interface!!!! ZOMG!!!"); + Environment.Exit(1); + } + } + } + + #endregion + + private void SetupFromConfigFile(IGenericConfig configData) + { + try + { + // SandBoxMode + string 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_console.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "Main.cs: SetupFromConfig() - Invalid value for PhysicsEngine attribute, terminating"); + Environment.Exit(1); + break; + + case "": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.world.Avatar.PhysicsEngineFlying = false; + break; + + case "basicphysics": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.world.Avatar.PhysicsEngineFlying = false; + break; + + case "RealPhysX": + this.m_physicsEngine = "RealPhysX"; + OpenSim.world.Avatar.PhysicsEngineFlying = true; + break; + + case "OpenDynamicsEngine": + this.m_physicsEngine = "OpenDynamicsEngine"; + OpenSim.world.Avatar.PhysicsEngineFlying = true; + break; + } + + configData.Commit(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine("\nSorry, a fatal error occurred while trying to initialise the configuration data"); + Console.WriteLine("Can not continue starting up"); + Environment.Exit(1); + } + } + + /// + /// Performs any last-minute sanity checking and shuts down the region server + /// + public virtual void Shutdown() + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Closing all threads"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Killing listener thread"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Killing clients"); + // IMPLEMENT THIS + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Closing console and terminating"); + LocalWorld.Close(); + GridServers.Close(); + m_console.Close(); + Environment.Exit(0); + } + + /// + /// Performs per-frame updates regularly + /// + /// + /// + void Heartbeat(object sender, System.EventArgs e) + { + LocalWorld.Update(); + } + + #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_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "show users - show info about connected users"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "shutdown - disconnect all clients and shutdown"); + break; + + case "show": + Show(cmdparams[0]); + break; + + case "terrain": + string result = ""; + if (!LocalWorld.Terrain.RunTerrainCmd(cmdparams, ref result)) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, result); + } + break; + + case "shutdown": + Shutdown(); + break; + + default: + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "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_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "OpenSim has been running since " + startuptime.ToString()); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "That is " + (DateTime.Now - startuptime).ToString()); + break; + case "users": + OpenSim.world.Avatar TempAv; + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP")); + foreach (libsecondlife.LLUUID UUID in LocalWorld.Entities.Keys) + { + if (LocalWorld.Entities[UUID].ToString() == "OpenSim.world.Avatar") + { + TempAv = (OpenSim.world.Avatar)LocalWorld.Entities[UUID]; + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.SessionID, TempAv.ControllingClient.CircuitCode, TempAv.ControllingClient.userEP.ToString())); + } + } + break; + } + } + #endregion + } + + */ +} diff --git a/OpenSim/OpenSim.RegionServer/OpenSimNetworkHandler.cs b/OpenSim/OpenSim.RegionServer/OpenSimNetworkHandler.cs new file mode 100644 index 0000000..15ee740 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/OpenSimNetworkHandler.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Net.Sockets; +using libsecondlife; +using OpenSim.Framework.Interfaces; + +namespace OpenSim +{ + public interface OpenSimNetworkHandler + { + void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode);// EndPoint packetSender); + void RemoveClientCircuit(uint circuitcode); + void RegisterPacketServer(PacketServer server); + AuthenticateResponse AuthenticateSession(LLUUID sessionID, LLUUID agentID, uint circuitCode); + } +} diff --git a/OpenSim/OpenSim.RegionServer/PacketServer.cs b/OpenSim/OpenSim.RegionServer/PacketServer.cs new file mode 100644 index 0000000..fb35723 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/PacketServer.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.world; +using libsecondlife.Packets; + +namespace OpenSim +{ + public class PacketServer + { + private OpenSimNetworkHandler _networkHandler; + private World _localWorld; + public Dictionary ClientThreads = new Dictionary(); + + public PacketServer(OpenSimNetworkHandler networkHandler) + { + _networkHandler = networkHandler; + _networkHandler.RegisterPacketServer(this); + } + + public World 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() + { + if (this._localWorld != null) + { + //ClientView.AddPacketHandler(PacketType.DeRezObject, _localWorld.DeRezObject); + ClientView.AddPacketHandler(PacketType.UUIDNameRequest, this.RequestUUIDName); + } + } + + #region Client Packet Handlers + + public bool RequestUUIDName(ClientView simClient, Packet packet) + { + System.Text.Encoding enc = System.Text.Encoding.ASCII; + Console.WriteLine(packet.ToString()); + UUIDNameRequestPacket nameRequest = (UUIDNameRequestPacket)packet; + UUIDNameReplyPacket nameReply = new UUIDNameReplyPacket(); + nameReply.UUIDNameBlock = new UUIDNameReplyPacket.UUIDNameBlockBlock[nameRequest.UUIDNameBlock.Length]; + + for (int i = 0; i < nameRequest.UUIDNameBlock.Length; i++) + { + nameReply.UUIDNameBlock[i] = new UUIDNameReplyPacket.UUIDNameBlockBlock(); + nameReply.UUIDNameBlock[i].ID = nameRequest.UUIDNameBlock[i].ID; + nameReply.UUIDNameBlock[i].FirstName = enc.GetBytes("Who\0"); //for now send any name + nameReply.UUIDNameBlock[i].LastName = enc.GetBytes("Knows\0"); //in future need to look it up + } + simClient.OutPacket(nameReply); + return true; + } + + #endregion + } +} diff --git a/OpenSim/OpenSim.RegionServer/RegionInfo.cs b/OpenSim/OpenSim.RegionServer/RegionInfo.cs new file mode 100644 index 0000000..f82495a --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/RegionInfo.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Web; +using System.IO; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using libsecondlife; + +namespace OpenSim +{ + public class RegionInfo : RegionInfoBase + { + //following should be removed and the GenericConfig object passed around, + //so each class (AssetServer, GridServer etc) can access what config data they want + 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 = ""; + private bool isSandbox; + + public string DataStore; + + public RegionInfo() + { + + } + + public void SaveToGrid() + { + //we really want to keep any server connection code out of here and out of the code code + // and put it in the server connection classes (those inheriting from IGridServer etc) + string reqtext; + reqtext = ""; + reqtext += "" + this.GridSendKey + ""; + reqtext += ""; + reqtext += "" + this.SimUUID.ToString() + ""; + reqtext += "" + this.RegionName + ""; + reqtext += "" + this.IPListenAddr + ""; + reqtext += "" + this.IPListenPort.ToString() + ""; + reqtext += "" + this.RegionLocX.ToString() + ""; + reqtext += "" + this.RegionLocY.ToString() + ""; + reqtext += "1"; + reqtext += ""; + reqtext += ""; + + byte[] reqdata = (new System.Text.ASCIIEncoding()).GetBytes(reqtext); + string newpath = ""; + if (this.GridURL.EndsWith("/")) + { + newpath = this.GridURL + "sims/"; + } + else + { + newpath = this.GridURL + "/sims/"; + } + + WebRequest GridSaveReq = WebRequest.Create(newpath + this.SimUUID.ToString()); + GridSaveReq.Method = "POST"; + GridSaveReq.ContentType = "application/x-www-form-urlencoded"; + GridSaveReq.ContentLength = reqdata.Length; + + Stream stOut = GridSaveReq.GetRequestStream(); + stOut.Write(reqdata, 0, reqdata.Length); + stOut.Close(); + + WebResponse gridresp = GridSaveReq.GetResponse(); + StreamReader stIn = new StreamReader(gridresp.GetResponseStream(), Encoding.ASCII); + string GridResponse = stIn.ReadToEnd(); + stIn.Close(); + gridresp.Close(); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"RegionInfo.CS:SaveToGrid() - Grid said: " + GridResponse); + } + + public void InitConfig(bool sandboxMode, IGenericConfig configData) + { + this.isSandbox = sandboxMode; + try + { + // Sim UUID + string attri = ""; + attri = configData.GetAttribute("SimUUID"); + if (attri == "") + { + this.SimUUID = LLUUID.Random(); + configData.SetAttribute("SimUUID", this.SimUUID.ToString()); + } + else + { + this.SimUUID = new LLUUID(attri); + } + + // Sim name + attri = ""; + attri = configData.GetAttribute("SimName"); + if (attri == "") + { + this.RegionName = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Name", "OpenSim test"); + configData.SetAttribute("SimName", this.RegionName); + } + else + { + this.RegionName = attri; + } + // Sim/Grid location X + attri = ""; + attri = configData.GetAttribute("SimLocationX"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Grid Location X", "997"); + configData.SetAttribute("SimLocationX", location); + this.RegionLocX = (uint)Convert.ToUInt32(location); + } + else + { + this.RegionLocX = (uint)Convert.ToUInt32(attri); + } + // Sim/Grid location Y + attri = ""; + attri = configData.GetAttribute("SimLocationY"); + if (attri == "") + { + string location = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Grid Location Y", "996"); + configData.SetAttribute("SimLocationY", location); + this.RegionLocY = (uint)Convert.ToUInt32(location); + } + else + { + this.RegionLocY = (uint)Convert.ToUInt32(attri); + } + + // Local storage datastore + attri = ""; + attri = configData.GetAttribute("Datastore"); + if (attri == "") + { + string datastore = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Filename for local storage", "localworld.yap"); + configData.SetAttribute("Datastore", datastore); + this.DataStore = datastore; + } + else + { + this.DataStore = attri; + } + + //Sim Listen Port + attri = ""; + attri = configData.GetAttribute("SimListenPort"); + if (attri == "") + { + string port = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("UDP port for client connections", "9000"); + configData.SetAttribute("SimListenPort", port); + this.IPListenPort = Convert.ToInt32(port); + } + else + { + this.IPListenPort = Convert.ToInt32(attri); + } + //Sim Listen Address + attri = ""; + attri = configData.GetAttribute("SimListenAddress"); + if (attri == "") + { + this.IPListenAddr = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("IP Address to listen on for client connections", "127.0.0.1"); + configData.SetAttribute("SimListenAddress", this.IPListenAddr); + } + else + { + this.IPListenAddr = attri; + } + + if (!isSandbox) + { + //shouldn't be reading this data in here, it should be up to the classes implementing the server interfaces to read what they need from the config object + + //Grid Server URL + attri = ""; + attri = configData.GetAttribute("GridServerURL"); + if (attri == "") + { + this.GridURL = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Grid server URL","http://127.0.0.1:8001/"); + configData.SetAttribute("GridServerURL", this.GridURL); + } + else + { + this.GridURL = attri; + } + + //Grid Send Key + attri = ""; + attri = configData.GetAttribute("GridSendKey"); + if (attri == "") + { + this.GridSendKey = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Key to send to grid server","null"); + configData.SetAttribute("GridSendKey", this.GridSendKey); + } + else + { + this.GridSendKey = attri; + } + + //Grid Receive Key + attri = ""; + attri = configData.GetAttribute("GridRecvKey"); + if (attri == "") + { + this.GridRecvKey = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Key to expect from grid server","null"); + configData.SetAttribute("GridRecvKey", this.GridRecvKey); + } + else + { + this.GridRecvKey = attri; + } + + attri = ""; + attri = configData.GetAttribute("AssetServerURL"); + if (attri == "") + { + this.AssetURL = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Asset server URL", "http://127.0.0.1:8003/"); + configData.SetAttribute("AssetServerURL", this.GridURL); + } + else + { + this.AssetURL = attri; + } + + } + this.RegionHandle = Util.UIntsToLong((RegionLocX * 256), (RegionLocY * 256)); + if (!this.isSandbox) + { + this.SaveToGrid(); + } + configData.Commit(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"Config.cs:InitConfig() - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,e.ToString()); + } + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"Sim settings loaded:"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "UUID: " + this.SimUUID.ToStringHyphenated()); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Name: " + this.RegionName); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Region Location: [" + this.RegionLocX.ToString() + "," + this.RegionLocY + "]"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Region Handle: " + this.RegionHandle.ToString()); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Listening on IP: " + this.IPListenAddr + ":" + this.IPListenPort); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Sandbox Mode? " + isSandbox.ToString()); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Asset URL: " + this.AssetURL); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Asset key: " + this.AssetSendKey); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Grid URL: " + this.GridURL); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Grid key: " + this.GridSendKey); + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/RegionInfoBase.cs b/OpenSim/OpenSim.RegionServer/RegionInfoBase.cs new file mode 100644 index 0000000..42d3030 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/RegionInfoBase.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Web; +using System.IO; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Utilities; +using libsecondlife; + +namespace OpenSim +{ + public class RegionInfoBase + { + public LLUUID SimUUID; + public string RegionName; + public uint RegionLocX; + public uint RegionLocY; + public ulong RegionHandle; + public ushort RegionWaterHeight = 20; + public bool RegionTerraform = true; + + public int IPListenPort; + public string IPListenAddr; + + public RegionInfoBase() + { + + } + } + +} diff --git a/OpenSim/OpenSim.RegionServer/RegionServerBase.cs b/OpenSim/OpenSim.RegionServer/RegionServerBase.cs new file mode 100644 index 0000000..69a8748 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/RegionServerBase.cs @@ -0,0 +1,103 @@ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.world; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.UserServer; +using OpenSim.Assets; +using OpenSim.CAPS; +using OpenSim.Framework.Console; +using OpenSim.Physics.Manager; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenSim +{ + public class RegionServerBase + { + protected IGenericConfig localConfig; + protected PhysicsManager physManager; + protected Grid GridServers; + protected AssetCache AssetCache; + protected InventoryCache InventoryCache; + protected Dictionary clientCircuits = new Dictionary(); + protected DateTime startuptime; + protected RegionInfo regionData; + + protected System.Timers.Timer m_heartbeatTimer = new System.Timers.Timer(); + 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 UDPServer m_udpServer; + protected BaseHttpServer httpServer; + protected AuthenticateSessionsBase AuthenticateSessionsHandler; + + protected ConsoleBase m_console; + + public RegionServerBase() + { + + } + + public RegionServerBase(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 SetupLocalWorld() + { + } + + protected virtual void SetupHttpListener() + { + } + + protected virtual void ConnectToRemoteGridServer() + { + + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/UDPServer.cs b/OpenSim/OpenSim.RegionServer/UDPServer.cs new file mode 100644 index 0000000..3a93e66 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/UDPServer.cs @@ -0,0 +1,205 @@ +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.world; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.UserServer; +using OpenSim.Assets; +using OpenSim.CAPS; +using OpenSim.Framework.Console; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenSim +{ + public delegate AuthenticateResponse AuthenticateSessionHandler(LLUUID sessionID, LLUUID agentID, uint circuitCode); + + public class UDPServer : OpenSimNetworkHandler + { + 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 Grid m_gridServers; + protected World m_localWorld; + protected AssetCache m_assetCache; + protected InventoryCache m_inventoryCache; + protected RegionInfo m_regionData; + protected bool m_sandbox = false; + protected bool user_accounts = false; + protected ConsoleBase m_console; + protected AuthenticateSessionsBase m_authenticateSessionsClass; + + public AuthenticateSessionHandler AuthenticateHandler; + + public PacketServer PacketServer + { + get + { + return _packetServer; + } + set + { + _packetServer = value; + } + } + + public World LocalWorld + { + set + { + this.m_localWorld = value; + this._packetServer.LocalWorld = this.m_localWorld; + } + } + + public UDPServer() + { + } + + public UDPServer(int port, Grid gridServers, AssetCache assetCache, InventoryCache inventoryCache, RegionInfo _regionData, bool sandbox, bool accounts, ConsoleBase console, AuthenticateSessionsBase authenticateClass) + { + listenPort = port; + this.m_gridServers = gridServers; + this.m_assetCache = assetCache; + this.m_inventoryCache = inventoryCache; + this.m_regionData = _regionData; + this.m_sandbox = sandbox; + this.user_accounts = accounts; + this.m_console = console; + this.m_authenticateSessionsClass = authenticateClass; + this.CreatePacketServer(); + + //set up delegate for authenticate sessions + this.AuthenticateHandler = new AuthenticateSessionHandler(this.m_authenticateSessionsClass.AuthenticateSession); + } + + protected virtual void CreatePacketServer() + { + PacketServer packetServer = new PacketServer(this); + } + + protected virtual void OnReceivedData(IAsyncResult result) + { + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + Packet packet = null; + int numBytes = Server.EndReceiveFrom(result, ref epSender); + int packetEnd = numBytes - 1; + + packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer); + + // do we already have a circuit for this endpoint + if (this.clientCircuits.ContainsKey(epSender)) + { + //if so then send packet to the packetserver + this._packetServer.ClientInPacket(this.clientCircuits[epSender], packet); + } + else if (packet.Type == PacketType.UseCircuitCode) + { + // new client + this.AddNewClient(packet); + } + else + { // invalid client + Console.Error.WriteLine("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); + bool isChildAgent = false; + + ClientView newuser = new ClientView(epSender, useCircuit, m_localWorld, _packetServer.ClientThreads, m_assetCache, m_gridServers.GridServer, this, m_inventoryCache, m_sandbox, isChildAgent, this.m_regionData, m_authenticateSessionsClass); + if ((this.m_gridServers.UserServer != null) && (user_accounts)) + { + newuser.UserServer = this.m_gridServers.UserServer; + } + //OpenSimRoot.Instance.ClientThreads.Add(epSender, newuser); + this._packetServer.ClientThreads.Add(useCircuit.CircuitCode.Code, newuser); + } + + public void ServerListener() + { + m_console.WriteLine("UDPServer.cs:ServerListener() - Opening UDP socket on " + listenPort); + + ServerIncoming = new IPEndPoint(IPAddress.Any, listenPort); + Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + Server.Bind(ServerIncoming); + + m_console.WriteLine("UDPServer.cs:ServerListener() - UDP socket bound, getting ready to listen"); + + ipeSender = new IPEndPoint(IPAddress.Any, 0); + epSender = (EndPoint)ipeSender; + ReceivedData = new AsyncCallback(this.OnReceivedData); + Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null); + + m_console.WriteLine("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; + } + } + } + + public virtual AuthenticateResponse AuthenticateSession(LLUUID sessionID, LLUUID agentID, uint circuitCode) + { + return this.AuthenticateHandler(sessionID, agentID, circuitCode); + } + } +} \ No newline at end of file diff --git a/OpenSim/OpenSim.RegionServer/VersionInfo.cs b/OpenSim/OpenSim.RegionServer/VersionInfo.cs new file mode 100644 index 0000000..49cc6a5 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/VersionInfo.cs @@ -0,0 +1,37 @@ +/* +Copyright (c) OpenSim project, http://osgrid.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +using System; + +namespace OpenSim +{ + /// + /// + public class VersionInfo + { + public static string Version = "0.2, SVN build - please use releng if you desire any form of support"; + } +} diff --git a/OpenSim/OpenSim.RegionServer/types/Mesh.cs b/OpenSim/OpenSim.RegionServer/types/Mesh.cs new file mode 100644 index 0000000..3e00c91 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/types/Mesh.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.types +{ + // TODO: This will need some performance tuning no doubt. + public class Mesh + { + public List mesh; + + public Mesh() + { + mesh = new List(); + } + + public void AddTri(Triangle tri) + { + mesh.Add(tri); + } + + public static Mesh operator +(Mesh a, Mesh b) + { + a.mesh.AddRange(b.mesh); + return a; + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/types/Triangle.cs b/OpenSim/OpenSim.RegionServer/types/Triangle.cs new file mode 100644 index 0000000..8dfea6e --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/types/Triangle.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Axiom.MathLib; + +namespace OpenSim.types +{ + public class Triangle + { + Vector3 a; + Vector3 b; + Vector3 c; + + public Triangle() + { + a = new Vector3(); + b = new Vector3(); + c = new Vector3(); + } + + public Triangle(Vector3 A, Vector3 B, Vector3 C) + { + a = A; + b = B; + c = C; + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Avatar.Client.cs b/OpenSim/OpenSim.RegionServer/world/Avatar.Client.cs new file mode 100644 index 0000000..7656a89 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Avatar.Client.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife.Packets; + +namespace OpenSim.world +{ + partial class Avatar + { + private List updateList = new List(); + private List interestList = new List(); + + public void SendPacketToViewer(Packet packet) + { + this.ControllingClient.OutPacket(packet); + } + + public void AddTerseUpdateToViewersList(ImprovedTerseObjectUpdatePacket.ObjectDataBlock terseBlock) + { + + } + + public void SendUpdateListToViewer() + { + + } + + private void UpdateInterestList() + { + + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Avatar.Update.cs b/OpenSim/OpenSim.RegionServer/world/Avatar.Update.cs new file mode 100644 index 0000000..e49fab3 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Avatar.Update.cs @@ -0,0 +1,317 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; + +namespace OpenSim.world +{ + partial class Avatar + { + public override void update() + { + if (this._physActor == null) + { + //HACKHACK: Note to work out why this entity does not have a physics actor + // and prehaps create one. + return; + } + libsecondlife.LLVector3 pos2 = new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z); + if (this.updateflag) + { + //need to send movement info + //so create the improvedterseobjectupdate packet + //use CreateTerseBlock() + ImprovedTerseObjectUpdatePacket.ObjectDataBlock terseBlock = CreateTerseBlock(); + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = m_regionHandle; // FIXME + terse.RegionData.TimeDilation = 64096; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = terseBlock; + List avList = this.m_world.RequestAvatarList(); + foreach (Avatar client in avList) + { + client.SendPacketToViewer(terse); + } + + updateflag = false; + //this._updateCount = 0; + } + else + { + + if ((pos2 != this.positionLastFrame) || (this.movementflag == 16)) + { + _updateCount++; + if (((!PhysicsEngineFlying) && (_updateCount > 3)) || (PhysicsEngineFlying) && (_updateCount > 0)) + { + //It has been a while since last update was sent so lets send one. + ImprovedTerseObjectUpdatePacket.ObjectDataBlock terseBlock = CreateTerseBlock(); + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = m_regionHandle; // FIXME + terse.RegionData.TimeDilation = 64096; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = terseBlock; + List avList = this.m_world.RequestAvatarList(); + foreach (Avatar client in avList) + { + client.SendPacketToViewer(terse); + } + _updateCount = 0; + } + + if (this.movementflag == 16) + { + movementflag = 0; + } + } + + } + this.positionLastFrame = pos2; + + if (!this.ControllingClient.m_sandboxMode) + { + if (pos2.X < 0) + { + ControllingClient.CrossSimBorder(new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z)); + } + + if (pos2.Y < 0) + { + ControllingClient.CrossSimBorder(new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z)); + } + + if (pos2.X > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z)); + } + + if (pos2.Y > 255) + { + ControllingClient.CrossSimBorder(new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z)); + } + } + + } + public void SendUpdateToOtherClient(Avatar remoteAvatar) + { + ObjectUpdatePacket objupdate = CreateUpdatePacket(); + remoteAvatar.SendPacketToViewer(objupdate); + } + + public ObjectUpdatePacket CreateUpdatePacket() + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + //send a objectupdate packet with information about the clients avatar + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = m_regionHandle; + objupdate.RegionData.TimeDilation = 64096; + objupdate.ObjectData = new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock[1]; + + objupdate.ObjectData[0] = AvatarTemplate; + //give this avatar object a local id and assign the user a name + objupdate.ObjectData[0].ID = this.localid; + objupdate.ObjectData[0].FullID = ControllingClient.AgentID; + objupdate.ObjectData[0].NameValue = _enc.GetBytes("FirstName STRING RW SV " + firstname + "\nLastName STRING RW SV " + lastname + " \0"); + + libsecondlife.LLVector3 pos2 = new LLVector3((float)this._physActor.Position.X, (float)this._physActor.Position.Y, (float)this._physActor.Position.Z); + + byte[] pb = pos2.GetBytes(); + + Array.Copy(pb, 0, objupdate.ObjectData[0].ObjectData, 16, pb.Length); + return objupdate; + } + + public void SendInitialPosition() + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + //send a objectupdate packet with information about the clients avatar + + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = m_regionHandle; + objupdate.RegionData.TimeDilation = 64096; + objupdate.ObjectData = new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock[1]; + objupdate.ObjectData[0] = AvatarTemplate; + //give this avatar object a local id and assign the user a name + + objupdate.ObjectData[0].ID = this.localid; + this.uuid = objupdate.ObjectData[0].FullID = ControllingClient.AgentID; + objupdate.ObjectData[0].NameValue = _enc.GetBytes("FirstName STRING RW SV " + firstname + "\nLastName STRING RW SV " + lastname + " \0"); + libsecondlife.LLVector3 pos2 = new LLVector3((float)this.Pos.X, (float)this.Pos.Y, (float)this.Pos.Z); + byte[] pb = pos2.GetBytes(); + Array.Copy(pb, 0, objupdate.ObjectData[0].ObjectData, 16, pb.Length); + m_world._localNumber++; + + List avList = this.m_world.RequestAvatarList(); + foreach (Avatar client in avList) + { + client.SendPacketToViewer(objupdate); + if (client.ControllingClient.AgentID != this.ControllingClient.AgentID) + { + SendAppearanceToOtherAgent(client); + } + } + } + + public void SendOurAppearance() + { + ControllingClient.SendAppearance(this.Wearables); + } + + public void SendOurAppearance(ClientView OurClient) + { + //event handler for wearables request + this.SendOurAppearance(); + } + + public void SendAppearanceToOtherAgent(Avatar avatarInfo) + { + AvatarAppearancePacket avp = new AvatarAppearancePacket(); + avp.VisualParam = new AvatarAppearancePacket.VisualParamBlock[218]; + avp.ObjectData.TextureEntry = this.avatarAppearanceTexture.ToBytes(); + + AvatarAppearancePacket.VisualParamBlock avblock = null; + for (int i = 0; i < 218; i++) + { + avblock = new AvatarAppearancePacket.VisualParamBlock(); + avblock.ParamValue = visualParams[i]; + avp.VisualParam[i] = avblock; + } + + avp.Sender.IsTrial = false; + avp.Sender.ID = ControllingClient.AgentID; + avatarInfo.SendPacketToViewer(avp); + } + + public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + { + LLObject.TextureEntry tex = new LLObject.TextureEntry(texture, 0, texture.Length); + this.avatarAppearanceTexture = tex; + + for (int i = 0; i < visualParam.Length; i++) + { + this.visualParams[i] = visualParam[i].ParamValue; + } + + List avList = this.m_world.RequestAvatarList(); + foreach (Avatar client in avList) + { + if (client.ControllingClient.AgentID != this.ControllingClient.AgentID) + { + SendAppearanceToOtherAgent(client); + } + } + } + + public ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateTerseBlock() + { + byte[] bytes = new byte[60]; + int i = 0; + ImprovedTerseObjectUpdatePacket.ObjectDataBlock dat = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock(); + + dat.TextureEntry = new byte[0];// AvatarTemplate.TextureEntry; + libsecondlife.LLVector3 pos2 = new LLVector3(0, 0, 0); + lock (m_world.LockPhysicsEngine) + { + pos2 = new LLVector3(this._physActor.Position.X, this._physActor.Position.Y, this._physActor.Position.Z); + } + + uint ID = this.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 = pos2.GetBytes(); + Array.Copy(pb, 0, bytes, i, pb.Length); + i += 12; + ushort InternVelocityX; + ushort InternVelocityY; + ushort InternVelocityZ; + Axiom.MathLib.Vector3 internDirec = new Axiom.MathLib.Vector3(0, 0, 0); + lock (m_world.LockPhysicsEngine) + { + internDirec = new Axiom.MathLib.Vector3(this._physActor.Velocity.X, this._physActor.Velocity.Y, this._physActor.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); + } + + // Sends animation update + public void SendAnimPack(LLUUID animID, int seq) + { + AvatarAnimationPacket ani = new AvatarAnimationPacket(); + ani.AnimationSourceList = new AvatarAnimationPacket.AnimationSourceListBlock[1]; + ani.AnimationSourceList[0] = new AvatarAnimationPacket.AnimationSourceListBlock(); + ani.AnimationSourceList[0].ObjectID = ControllingClient.AgentID; + ani.Sender = new AvatarAnimationPacket.SenderBlock(); + ani.Sender.ID = ControllingClient.AgentID; + ani.AnimationList = new AvatarAnimationPacket.AnimationListBlock[1]; + ani.AnimationList[0] = new AvatarAnimationPacket.AnimationListBlock(); + ani.AnimationList[0].AnimID = this.current_anim = animID; + ani.AnimationList[0].AnimSequenceID = this.anim_seq = seq; + + List avList = this.m_world.RequestAvatarList(); + foreach (Avatar client in avList) + { + client.SendPacketToViewer(ani); + } + + } + + public void SendAnimPack() + { + this.SendAnimPack(this.current_anim, this.anim_seq); + } + + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Avatar.cs b/OpenSim/OpenSim.RegionServer/world/Avatar.cs new file mode 100644 index 0000000..680d059 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Avatar.cs @@ -0,0 +1,418 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Interfaces; +using Axiom.MathLib; + +namespace OpenSim.world +{ + public partial class Avatar : Entity + { + public static bool PhysicsEngineFlying = false; + public static AvatarAnimations Animations; + public string firstname; + public string lastname; + public ClientView ControllingClient; + public LLUUID current_anim; + public int anim_seq; + private static libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock AvatarTemplate; + private bool updateflag = false; + private byte movementflag = 0; + private List forcesList = new List(); + private short _updateCount = 0; + private Axiom.MathLib.Quaternion bodyRot; + private LLObject.TextureEntry avatarAppearanceTexture = null; + private byte[] visualParams; + private AvatarWearable[] Wearables; + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + private ulong m_regionHandle; + //private Dictionary m_clientThreads; + private string m_regionName; + private ushort m_regionWaterHeight; + private bool m_regionTerraform; + //private bool childShadowAvatar = false; + + public Avatar(ClientView TheClient, World world, string regionName, Dictionary clientThreads, ulong regionHandle, bool regionTerraform, ushort regionWater) + { + m_world = world; + // m_clientThreads = clientThreads; + m_regionName = regionName; + m_regionHandle = regionHandle; + m_regionTerraform = regionTerraform; + m_regionWaterHeight = regionWater; + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"Avatar.cs - Loading details from grid (DUMMY)"); + ControllingClient = TheClient; + localid = 8880000 + (this.m_world._localNumber++); + Pos = ControllingClient.startpos; + visualParams = new byte[218]; + for (int i = 0; i < 218; i++) + { + visualParams[i] = 100; + } + Wearables = new AvatarWearable[13]; //should be 13 of these + for (int i = 0; i < 13; i++) + { + Wearables[i] = new AvatarWearable(); + } + this.Wearables[0].AssetID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73"); + this.Wearables[0].ItemID = LLUUID.Random(); + + this.avatarAppearanceTexture = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + + //register for events + ControllingClient.OnRequestWearables += new ClientView.GenericCall(this.SendOurAppearance); + ControllingClient.OnSetAppearance += new SetAppearance(this.SetAppearance); + ControllingClient.OnCompleteMovementToRegion += new ClientView.GenericCall2(this.CompleteMovement); + ControllingClient.OnCompleteMovementToRegion += new ClientView.GenericCall2(this.SendInitialPosition); + ControllingClient.OnAgentUpdate += new ClientView.GenericCall3(this.HandleAgentUpdate); + ControllingClient.OnStartAnim += new StartAnim(this.SendAnimPack); + + } + + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + get + { + return _physActor; + } + } + + public override void addForces() + { + lock (this.forcesList) + { + if (this.forcesList.Count > 0) + { + for (int i = 0; i < this.forcesList.Count; i++) + { + NewForce force = this.forcesList[i]; + PhysicsVector phyVector = new PhysicsVector(force.X, force.Y, force.Z); + lock (m_world.LockPhysicsEngine) + { + this._physActor.Velocity = phyVector; + } + this.updateflag = true; + this.velocity = new LLVector3(force.X, force.Y, force.Z); //shouldn't really be doing this + // but as we are setting the velocity (rather than using real forces) at the moment it is okay. + } + for (int i = 0; i < this.forcesList.Count; i++) + { + this.forcesList.RemoveAt(0); + } + } + } + } + + public static void SetupTemplate(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(); + + libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock objdata = new ObjectUpdatePacket.ObjectDataBlock(); // new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock(data1, ref i); + + SetDefaultPacketValues(objdata); + objdata.TextureEntry = data1; + 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; + System.Text.Encoding enc = System.Text.Encoding.ASCII; + libsecondlife.LLVector3 pos = new LLVector3(objdata.ObjectData, 16); + pos.X = 100f; + objdata.ID = 8880000; + objdata.NameValue = enc.GetBytes("FirstName STRING RW SV Test \nLastName STRING RW SV User \0"); + libsecondlife.LLVector3 pos2 = new LLVector3(100f, 100f, 23f); + //objdata.FullID=user.AgentID; + byte[] pb = pos.GetBytes(); + Array.Copy(pb, 0, objdata.ObjectData, 16, pb.Length); + + Avatar.AvatarTemplate = objdata; + } + + protected static void SetDefaultPacketValues(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; + + + } + + public void CompleteMovement() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE,"Avatar.cs:CompleteMovement() - Constructing AgentMovementComplete packet"); + AgentMovementCompletePacket mov = new AgentMovementCompletePacket(); + mov.AgentData.SessionID = this.ControllingClient.SessionID; + mov.AgentData.AgentID = this.ControllingClient.AgentID; + mov.Data.RegionHandle = this.m_regionHandle; + // TODO - dynamicalise this stuff + mov.Data.Timestamp = 1172750370; + mov.Data.Position = this.ControllingClient.startpos; + mov.Data.LookAt = new LLVector3(0.99f, 0.042f, 0); + + ControllingClient.OutPacket(mov); + } + + public void HandleAgentUpdate(Packet pack) + { + this.HandleUpdate((AgentUpdatePacket)pack); + } + + public void HandleUpdate(AgentUpdatePacket pack) + { + if (((uint)pack.AgentData.ControlFlags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_FLY) != 0) + { + if (this._physActor.Flying == false) + { + this.current_anim = Animations.AnimsLLUUID["ANIM_AGENT_FLY"]; + this.anim_seq = 1; + this.SendAnimPack(); + } + this._physActor.Flying = true; + + } + else + { + if (this._physActor.Flying == true) + { + this.current_anim = Animations.AnimsLLUUID["ANIM_AGENT_STAND"]; + this.anim_seq = 1; + this.SendAnimPack(); + } + this._physActor.Flying = false; + } + if (((uint)pack.AgentData.ControlFlags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_AT_POS) != 0) + { + Axiom.MathLib.Quaternion q = new Axiom.MathLib.Quaternion(pack.AgentData.BodyRotation.W, pack.AgentData.BodyRotation.X, pack.AgentData.BodyRotation.Y, pack.AgentData.BodyRotation.Z); + if (((movementflag & 1) == 0) || (q != this.bodyRot)) + { + + if (((movementflag & 1) == 0) && (!this._physActor.Flying)) + { + this.current_anim = Animations.AnimsLLUUID["ANIM_AGENT_WALK"]; + this.anim_seq = 1; + this.SendAnimPack(); + } + + + //we should add a new force to the list + // but for now we will deal with velocities + NewForce newVelocity = new NewForce(); + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(1, 0, 0); + Axiom.MathLib.Vector3 direc = q * v3; + direc.Normalize(); + + //work out velocity for sim physics system + 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); + movementflag = 1; + this.bodyRot = q; + } + } + else if ((((uint)pack.AgentData.ControlFlags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_POS) != 0) && (PhysicsEngineFlying)) + { + if (((movementflag & 2) == 0) && this._physActor.Flying) + { + //we should add a new force to the list + // but for now we will deal with velocities + NewForce newVelocity = new NewForce(); + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(0, 0, 1); + Axiom.MathLib.Vector3 direc = v3; + direc.Normalize(); + + //work out velocity for sim physics system + direc = direc * ((0.03f) * 128f * 2); + newVelocity.X = direc.x; + newVelocity.Y = direc.y; + newVelocity.Z = direc.z; + this.forcesList.Add(newVelocity); + movementflag = 2; + } + } + else if ((((uint)pack.AgentData.ControlFlags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) && (PhysicsEngineFlying)) + { + if (((movementflag & 4) == 0) && this._physActor.Flying) + { + //we should add a new force to the list + // but for now we will deal with velocities + NewForce newVelocity = new NewForce(); + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(0, 0, -1); + //Axiom.MathLib.Quaternion q = new Axiom.MathLib.Quaternion(pack.AgentData.BodyRotation.W, pack.AgentData.BodyRotation.X, pack.AgentData.BodyRotation.Y, pack.AgentData.BodyRotation.Z); + Axiom.MathLib.Vector3 direc = v3; + direc.Normalize(); + + //work out velocity for sim physics system + direc = direc * ((0.03f) * 128f * 2); + newVelocity.X = direc.x; + newVelocity.Y = direc.y; + newVelocity.Z = direc.z; + this.forcesList.Add(newVelocity); + movementflag = 4; + } + } + else if (((uint)pack.AgentData.ControlFlags & (uint)MainAvatar.ControlFlags.AGENT_CONTROL_AT_NEG) != 0) + { + Axiom.MathLib.Quaternion q = new Axiom.MathLib.Quaternion(pack.AgentData.BodyRotation.W, pack.AgentData.BodyRotation.X, pack.AgentData.BodyRotation.Y, pack.AgentData.BodyRotation.Z); + if (((movementflag & 8) == 0) || (q != this.bodyRot)) + { + //we should add a new force to the list + // but for now we will deal with velocities + NewForce newVelocity = new NewForce(); + Axiom.MathLib.Vector3 v3 = new Axiom.MathLib.Vector3(-1, 0, 0); + Axiom.MathLib.Vector3 direc = q * v3; + direc.Normalize(); + + //work out velocity for sim physics system + direc = direc * ((0.03f) * 128f); + if (this._physActor.Flying) + direc *= 2; + + newVelocity.X = direc.x; + newVelocity.Y = direc.y; + newVelocity.Z = direc.z; + this.forcesList.Add(newVelocity); + movementflag = 8; + this.bodyRot = q; + } + } + else + { + if (movementflag == 16) + { + movementflag = 0; + } + if ((movementflag) != 0) + { + NewForce newVelocity = new NewForce(); + newVelocity.X = 0; + newVelocity.Y = 0; + newVelocity.Z = 0; + this.forcesList.Add(newVelocity); + movementflag = 0; + // We're standing still, so make it show! + if (this._physActor.Flying == false) + { + this.current_anim = Animations.AnimsLLUUID["ANIM_AGENT_STAND"]; + this.anim_seq = 1; + this.SendAnimPack(); + } + this.movementflag = 16; + + } + } + } + + //really really should be moved somewhere else (RegionInfo.cs ?) + public void SendRegionHandshake(World regionInfo) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE,"Avatar.cs:SendRegionHandshake() - Creating empty RegionHandshake packet"); + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + RegionHandshakePacket handshake = new RegionHandshakePacket(); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE,"Avatar.cs:SendRegionhandshake() - Filling in RegionHandshake details"); + handshake.RegionInfo.BillableFactor = 0; + handshake.RegionInfo.IsEstateManager = false; + handshake.RegionInfo.TerrainHeightRange00 = 60; + handshake.RegionInfo.TerrainHeightRange01 = 60; + handshake.RegionInfo.TerrainHeightRange10 = 60; + handshake.RegionInfo.TerrainHeightRange11 = 60; + handshake.RegionInfo.TerrainStartHeight00 = 10; + handshake.RegionInfo.TerrainStartHeight01 = 10; + handshake.RegionInfo.TerrainStartHeight10 = 10; + handshake.RegionInfo.TerrainStartHeight11 = 10; + handshake.RegionInfo.SimAccess = 13; + handshake.RegionInfo.WaterHeight = m_regionWaterHeight; + uint regionFlags = 72458694; + if (this.m_regionTerraform) + { + regionFlags -= 64; + } + handshake.RegionInfo.RegionFlags = regionFlags; + handshake.RegionInfo.SimName = _enc.GetBytes(m_regionName + "\0"); + handshake.RegionInfo.SimOwner = new LLUUID("00000000-0000-0000-0000-000000000000"); + handshake.RegionInfo.TerrainBase0 = new LLUUID("b8d3965a-ad78-bf43-699b-bff8eca6c975"); + handshake.RegionInfo.TerrainBase1 = new LLUUID("abb783e6-3e93-26c0-248a-247666855da3"); + handshake.RegionInfo.TerrainBase2 = new LLUUID("179cdabd-398a-9b6b-1391-4dc333ba321f"); + handshake.RegionInfo.TerrainBase3 = new LLUUID("beb169c7-11ea-fff2-efe5-0f24dc881df2"); + handshake.RegionInfo.TerrainDetail0 = new LLUUID("00000000-0000-0000-0000-000000000000"); + handshake.RegionInfo.TerrainDetail1 = new LLUUID("00000000-0000-0000-0000-000000000000"); + handshake.RegionInfo.TerrainDetail2 = new LLUUID("00000000-0000-0000-0000-000000000000"); + handshake.RegionInfo.TerrainDetail3 = new LLUUID("00000000-0000-0000-0000-000000000000"); + handshake.RegionInfo.CacheID = new LLUUID("545ec0a5-5751-1026-8a0b-216e38a7ab37"); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE,"Avatar.cs:SendRegionHandshake() - Sending RegionHandshake packet"); + this.ControllingClient.OutPacket(handshake); + } + + public static void LoadAnims() + { + Avatar.Animations = new AvatarAnimations(); + Avatar.Animations.LoadAnims(); + } + + public override void LandRenegerated() + { + Pos = new LLVector3(100.0f, 100.0f, m_world.Terrain[(int)Pos.X, (int)Pos.Y] + 50.0f); + } + } + + public class NewForce + { + public float X; + public float Y; + public float Z; + + public NewForce() + { + + } + } + +} diff --git a/OpenSim/OpenSim.RegionServer/world/AvatarAnimations.cs b/OpenSim/OpenSim.RegionServer/world/AvatarAnimations.cs new file mode 100644 index 0000000..b554af8 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/AvatarAnimations.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.world +{ + public class AvatarAnimations + { + + public Dictionary AnimsLLUUID = new Dictionary(); + public Dictionary AnimsNames = new Dictionary(); + + public AvatarAnimations() + { + } + + public void LoadAnims() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"Avatar.cs:LoadAnims() - Loading avatar animations"); + AnimsLLUUID.Add("ANIM_AGENT_AFRAID", new LLUUID("6b61c8e8-4747-0d75-12d7-e49ff207a4ca")); + AnimsLLUUID.Add("ANIM_AGENT_AIM_BAZOOKA_R", new LLUUID("b5b4a67d-0aee-30d2-72cd-77b333e932ef")); + AnimsLLUUID.Add("ANIM_AGENT_AIM_BOW_L", new LLUUID("46bb4359-de38-4ed8-6a22-f1f52fe8f506")); + AnimsLLUUID.Add("ANIM_AGENT_AIM_HANDGUN_R", new LLUUID("3147d815-6338-b932-f011-16b56d9ac18b")); + AnimsLLUUID.Add("ANIM_AGENT_AIM_RIFLE_R", new LLUUID("ea633413-8006-180a-c3ba-96dd1d756720")); + AnimsLLUUID.Add("ANIM_AGENT_ANGRY", new LLUUID("5747a48e-073e-c331-f6f3-7c2149613d3e")); + AnimsLLUUID.Add("ANIM_AGENT_AWAY", new LLUUID("fd037134-85d4-f241-72c6-4f42164fedee")); + AnimsLLUUID.Add("ANIM_AGENT_BACKFLIP", new LLUUID("c4ca6188-9127-4f31-0158-23c4e2f93304")); + AnimsLLUUID.Add("ANIM_AGENT_BELLY_LAUGH", new LLUUID("18b3a4b5-b463-bd48-e4b6-71eaac76c515")); + AnimsLLUUID.Add("ANIM_AGENT_BLOW_KISS", new LLUUID("db84829b-462c-ee83-1e27-9bbee66bd624")); + AnimsLLUUID.Add("ANIM_AGENT_BORED", new LLUUID("b906c4ba-703b-1940-32a3-0c7f7d791510")); + AnimsLLUUID.Add("ANIM_AGENT_BOW", new LLUUID("82e99230-c906-1403-4d9c-3889dd98daba")); + AnimsLLUUID.Add("ANIM_AGENT_BRUSH", new LLUUID("349a3801-54f9-bf2c-3bd0-1ac89772af01")); + AnimsLLUUID.Add("ANIM_AGENT_BUSY", new LLUUID("efcf670c-2d18-8128-973a-034ebc806b67")); + AnimsLLUUID.Add("ANIM_AGENT_CLAP", new LLUUID("9b0c1c4e-8ac7-7969-1494-28c874c4f668")); + AnimsLLUUID.Add("ANIM_AGENT_COURTBOW", new LLUUID("9ba1c942-08be-e43a-fb29-16ad440efc50")); + AnimsLLUUID.Add("ANIM_AGENT_CROUCH", new LLUUID("201f3fdf-cb1f-dbec-201f-7333e328ae7c")); + AnimsLLUUID.Add("ANIM_AGENT_CROUCHWALK", new LLUUID("47f5f6fb-22e5-ae44-f871-73aaaf4a6022")); + AnimsLLUUID.Add("ANIM_AGENT_CRY", new LLUUID("92624d3e-1068-f1aa-a5ec-8244585193ed")); + AnimsLLUUID.Add("ANIM_AGENT_CUSTOMIZE", new LLUUID("038fcec9-5ebd-8a8e-0e2e-6e71a0a1ac53")); + AnimsLLUUID.Add("ANIM_AGENT_CUSTOMIZE_DONE", new LLUUID("6883a61a-b27b-5914-a61e-dda118a9ee2c")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE1", new LLUUID("b68a3d7c-de9e-fc87-eec8-543d787e5b0d")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE2", new LLUUID("928cae18-e31d-76fd-9cc9-2f55160ff818")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE3", new LLUUID("30047778-10ea-1af7-6881-4db7a3a5a114")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE4", new LLUUID("951469f4-c7b2-c818-9dee-ad7eea8c30b7")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE5", new LLUUID("4bd69a1d-1114-a0b4-625f-84e0a5237155")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE6", new LLUUID("cd28b69b-9c95-bb78-3f94-8d605ff1bb12")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE7", new LLUUID("a54d8ee2-28bb-80a9-7f0c-7afbbe24a5d6")); + AnimsLLUUID.Add("ANIM_AGENT_DANCE8", new LLUUID("b0dc417c-1f11-af36-2e80-7e7489fa7cdc")); + AnimsLLUUID.Add("ANIM_AGENT_DEAD", new LLUUID("57abaae6-1d17-7b1b-5f98-6d11a6411276")); + AnimsLLUUID.Add("ANIM_AGENT_DRINK", new LLUUID("0f86e355-dd31-a61c-fdb0-3a96b9aad05f")); + AnimsLLUUID.Add("ANIM_AGENT_EMBARRASSED", new LLUUID("514af488-9051-044a-b3fc-d4dbf76377c6")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_AFRAID", new LLUUID("aa2df84d-cf8f-7218-527b-424a52de766e")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_ANGER", new LLUUID("1a03b575-9634-b62a-5767-3a679e81f4de")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_BORED", new LLUUID("214aa6c1-ba6a-4578-f27c-ce7688f61d0d")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_CRY", new LLUUID("d535471b-85bf-3b4d-a542-93bea4f59d33")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_DISDAIN", new LLUUID("d4416ff1-09d3-300f-4183-1b68a19b9fc1")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_EMBARRASSED", new LLUUID("0b8c8211-d78c-33e8-fa28-c51a9594e424")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_FROWN", new LLUUID("fee3df48-fa3d-1015-1e26-a205810e3001")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_KISS", new LLUUID("1e8d90cc-a84e-e135-884c-7c82c8b03a14")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_LAUGH", new LLUUID("62570842-0950-96f8-341c-809e65110823")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_OPEN_MOUTH", new LLUUID("d63bc1f9-fc81-9625-a0c6-007176d82eb7")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_REPULSED", new LLUUID("f76cda94-41d4-a229-2872-e0296e58afe1")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_SAD", new LLUUID("eb6ebfb2-a4b3-a19c-d388-4dd5c03823f7")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_SHRUG", new LLUUID("a351b1bc-cc94-aac2-7bea-a7e6ebad15ef")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_SMILE", new LLUUID("b7c7c833-e3d3-c4e3-9fc0-131237446312")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_SURPRISE", new LLUUID("728646d9-cc79-08b2-32d6-937f0a835c24")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_TONGUE_OUT", new LLUUID("835965c6-7f2f-bda2-5deb-2478737f91bf")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_TOOTHSMILE", new LLUUID("b92ec1a5-e7ce-a76b-2b05-bcdb9311417e")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_WINK", new LLUUID("da020525-4d94-59d6-23d7-81fdebf33148")); + AnimsLLUUID.Add("ANIM_AGENT_EXPRESS_WORRY", new LLUUID("9c05e5c7-6f07-6ca4-ed5a-b230390c3950")); + AnimsLLUUID.Add("ANIM_AGENT_FALLDOWN", new LLUUID("666307d9-a860-572d-6fd4-c3ab8865c094")); + AnimsLLUUID.Add("ANIM_AGENT_FEMALE_WALK", new LLUUID("f5fc7433-043d-e819-8298-f519a119b688")); + AnimsLLUUID.Add("ANIM_AGENT_FINGER_WAG", new LLUUID("c1bc7f36-3ba0-d844-f93c-93be945d644f")); + AnimsLLUUID.Add("ANIM_AGENT_FIST_PUMP", new LLUUID("7db00ccd-f380-f3ee-439d-61968ec69c8a")); + AnimsLLUUID.Add("ANIM_AGENT_FLY", new LLUUID("aec4610c-757f-bc4e-c092-c6e9caf18daf")); + AnimsLLUUID.Add("ANIM_AGENT_FLYSLOW", new LLUUID("2b5a38b2-5e00-3a97-a495-4c826bc443e6")); + AnimsLLUUID.Add("ANIM_AGENT_HELLO", new LLUUID("9b29cd61-c45b-5689-ded2-91756b8d76a9")); + AnimsLLUUID.Add("ANIM_AGENT_HOLD_BAZOOKA_R", new LLUUID("ef62d355-c815-4816-2474-b1acc21094a6")); + AnimsLLUUID.Add("ANIM_AGENT_HOLD_BOW_L", new LLUUID("8b102617-bcba-037b-86c1-b76219f90c88")); + AnimsLLUUID.Add("ANIM_AGENT_HOLD_HANDGUN_R", new LLUUID("efdc1727-8b8a-c800-4077-975fc27ee2f2")); + AnimsLLUUID.Add("ANIM_AGENT_HOLD_RIFLE_R", new LLUUID("3d94bad0-c55b-7dcc-8763-033c59405d33")); + AnimsLLUUID.Add("ANIM_AGENT_HOLD_THROW_R", new LLUUID("7570c7b5-1f22-56dd-56ef-a9168241bbb6")); + AnimsLLUUID.Add("ANIM_AGENT_HOVER", new LLUUID("4ae8016b-31b9-03bb-c401-b1ea941db41d")); + AnimsLLUUID.Add("ANIM_AGENT_HOVER_DOWN", new LLUUID("20f063ea-8306-2562-0b07-5c853b37b31e")); + AnimsLLUUID.Add("ANIM_AGENT_HOVER_UP", new LLUUID("62c5de58-cb33-5743-3d07-9e4cd4352864")); + AnimsLLUUID.Add("ANIM_AGENT_IMPATIENT", new LLUUID("5ea3991f-c293-392e-6860-91dfa01278a3")); + AnimsLLUUID.Add("ANIM_AGENT_JUMP", new LLUUID("2305bd75-1ca9-b03b-1faa-b176b8a8c49e")); + AnimsLLUUID.Add("ANIM_AGENT_JUMP_FOR_JOY", new LLUUID("709ea28e-1573-c023-8bf8-520c8bc637fa")); + AnimsLLUUID.Add("ANIM_AGENT_KISS_MY_BUTT", new LLUUID("19999406-3a3a-d58c-a2ac-d72e555dcf51")); + AnimsLLUUID.Add("ANIM_AGENT_LAND", new LLUUID("7a17b059-12b2-41b1-570a-186368b6aa6f")); + AnimsLLUUID.Add("ANIM_AGENT_LAUGH_SHORT", new LLUUID("ca5b3f14-3194-7a2b-c894-aa699b718d1f")); + AnimsLLUUID.Add("ANIM_AGENT_MEDIUM_LAND", new LLUUID("f4f00d6e-b9fe-9292-f4cb-0ae06ea58d57")); + AnimsLLUUID.Add("ANIM_AGENT_MOTORCYCLE_SIT", new LLUUID("08464f78-3a8e-2944-cba5-0c94aff3af29")); + AnimsLLUUID.Add("ANIM_AGENT_MUSCLE_BEACH", new LLUUID("315c3a41-a5f3-0ba4-27da-f893f769e69b")); + AnimsLLUUID.Add("ANIM_AGENT_NO", new LLUUID("5a977ed9-7f72-44e9-4c4c-6e913df8ae74")); + AnimsLLUUID.Add("ANIM_AGENT_NO_UNHAPPY", new LLUUID("d83fa0e5-97ed-7eb2-e798-7bd006215cb4")); + AnimsLLUUID.Add("ANIM_AGENT_NYAH_NYAH", new LLUUID("f061723d-0a18-754f-66ee-29a44795a32f")); + AnimsLLUUID.Add("ANIM_AGENT_ONETWO_PUNCH", new LLUUID("eefc79be-daae-a239-8c04-890f5d23654a")); + AnimsLLUUID.Add("ANIM_AGENT_PEACE", new LLUUID("b312b10e-65ab-a0a4-8b3c-1326ea8e3ed9")); + AnimsLLUUID.Add("ANIM_AGENT_POINT_ME", new LLUUID("17c024cc-eef2-f6a0-3527-9869876d7752")); + AnimsLLUUID.Add("ANIM_AGENT_POINT_YOU", new LLUUID("ec952cca-61ef-aa3b-2789-4d1344f016de")); + AnimsLLUUID.Add("ANIM_AGENT_PRE_JUMP", new LLUUID("7a4e87fe-de39-6fcb-6223-024b00893244")); + AnimsLLUUID.Add("ANIM_AGENT_PUNCH_LEFT", new LLUUID("f3300ad9-3462-1d07-2044-0fef80062da0")); + AnimsLLUUID.Add("ANIM_AGENT_PUNCH_RIGHT", new LLUUID("c8e42d32-7310-6906-c903-cab5d4a34656")); + AnimsLLUUID.Add("ANIM_AGENT_REPULSED", new LLUUID("36f81a92-f076-5893-dc4b-7c3795e487cf")); + AnimsLLUUID.Add("ANIM_AGENT_ROUNDHOUSE_KICK", new LLUUID("49aea43b-5ac3-8a44-b595-96100af0beda")); + AnimsLLUUID.Add("ANIM_AGENT_RPS_COUNTDOWN", new LLUUID("35db4f7e-28c2-6679-cea9-3ee108f7fc7f")); + AnimsLLUUID.Add("ANIM_AGENT_RPS_PAPER", new LLUUID("0836b67f-7f7b-f37b-c00a-460dc1521f5a")); + AnimsLLUUID.Add("ANIM_AGENT_RPS_ROCK", new LLUUID("42dd95d5-0bc6-6392-f650-777304946c0f")); + AnimsLLUUID.Add("ANIM_AGENT_RPS_SCISSORS", new LLUUID("16803a9f-5140-e042-4d7b-d28ba247c325")); + AnimsLLUUID.Add("ANIM_AGENT_RUN", new LLUUID("05ddbff8-aaa9-92a1-2b74-8fe77a29b445")); + AnimsLLUUID.Add("ANIM_AGENT_SAD", new LLUUID("0eb702e2-cc5a-9a88-56a5-661a55c0676a")); + AnimsLLUUID.Add("ANIM_AGENT_SALUTE", new LLUUID("cd7668a6-7011-d7e2-ead8-fc69eff1a104")); + AnimsLLUUID.Add("ANIM_AGENT_SHOOT_BOW_L", new LLUUID("e04d450d-fdb5-0432-fd68-818aaf5935f8")); + AnimsLLUUID.Add("ANIM_AGENT_SHOUT", new LLUUID("6bd01860-4ebd-127a-bb3d-d1427e8e0c42")); + AnimsLLUUID.Add("ANIM_AGENT_SHRUG", new LLUUID("70ea714f-3a97-d742-1b01-590a8fcd1db5")); + AnimsLLUUID.Add("ANIM_AGENT_SIT", new LLUUID("1a5fe8ac-a804-8a5d-7cbd-56bd83184568")); + AnimsLLUUID.Add("ANIM_AGENT_SIT_FEMALE", new LLUUID("b1709c8d-ecd3-54a1-4f28-d55ac0840782")); + AnimsLLUUID.Add("ANIM_AGENT_SIT_GENERIC", new LLUUID("245f3c54-f1c0-bf2e-811f-46d8eeb386e7")); + AnimsLLUUID.Add("ANIM_AGENT_SIT_GROUND", new LLUUID("1c7600d6-661f-b87b-efe2-d7421eb93c86")); + AnimsLLUUID.Add("ANIM_AGENT_SIT_GROUND_CONSTRAINED", new LLUUID("1a2bd58e-87ff-0df8-0b4c-53e047b0bb6e")); + AnimsLLUUID.Add("ANIM_AGENT_SIT_TO_STAND", new LLUUID("a8dee56f-2eae-9e7a-05a2-6fb92b97e21e")); + AnimsLLUUID.Add("ANIM_AGENT_SLEEP", new LLUUID("f2bed5f9-9d44-39af-b0cd-257b2a17fe40")); + AnimsLLUUID.Add("ANIM_AGENT_SMOKE_IDLE", new LLUUID("d2f2ee58-8ad1-06c9-d8d3-3827ba31567a")); + AnimsLLUUID.Add("ANIM_AGENT_SMOKE_INHALE", new LLUUID("6802d553-49da-0778-9f85-1599a2266526")); + AnimsLLUUID.Add("ANIM_AGENT_SMOKE_THROW_DOWN", new LLUUID("0a9fb970-8b44-9114-d3a9-bf69cfe804d6")); + AnimsLLUUID.Add("ANIM_AGENT_SNAPSHOT", new LLUUID("eae8905b-271a-99e2-4c0e-31106afd100c")); + AnimsLLUUID.Add("ANIM_AGENT_STAND", new LLUUID("2408fe9e-df1d-1d7d-f4ff-1384fa7b350f")); + AnimsLLUUID.Add("ANIM_AGENT_STANDUP", new LLUUID("3da1d753-028a-5446-24f3-9c9b856d9422")); + AnimsLLUUID.Add("ANIM_AGENT_STAND_1", new LLUUID("15468e00-3400-bb66-cecc-646d7c14458e")); + AnimsLLUUID.Add("ANIM_AGENT_STAND_2", new LLUUID("370f3a20-6ca6-9971-848c-9a01bc42ae3c")); + AnimsLLUUID.Add("ANIM_AGENT_STAND_3", new LLUUID("42b46214-4b44-79ae-deb8-0df61424ff4b")); + AnimsLLUUID.Add("ANIM_AGENT_STAND_4", new LLUUID("f22fed8b-a5ed-2c93-64d5-bdd8b93c889f")); + AnimsLLUUID.Add("ANIM_AGENT_STRETCH", new LLUUID("80700431-74ec-a008-14f8-77575e73693f")); + AnimsLLUUID.Add("ANIM_AGENT_STRIDE", new LLUUID("1cb562b0-ba21-2202-efb3-30f82cdf9595")); + AnimsLLUUID.Add("ANIM_AGENT_SURF", new LLUUID("41426836-7437-7e89-025d-0aa4d10f1d69")); + AnimsLLUUID.Add("ANIM_AGENT_SURPRISE", new LLUUID("313b9881-4302-73c0-c7d0-0e7a36b6c224")); + AnimsLLUUID.Add("ANIM_AGENT_SWORD_STRIKE", new LLUUID("85428680-6bf9-3e64-b489-6f81087c24bd")); + AnimsLLUUID.Add("ANIM_AGENT_TALK", new LLUUID("5c682a95-6da4-a463-0bf6-0f5b7be129d1")); + AnimsLLUUID.Add("ANIM_AGENT_TANTRUM", new LLUUID("11000694-3f41-adc2-606b-eee1d66f3724")); + AnimsLLUUID.Add("ANIM_AGENT_THROW_R", new LLUUID("aa134404-7dac-7aca-2cba-435f9db875ca")); + AnimsLLUUID.Add("ANIM_AGENT_TRYON_SHIRT", new LLUUID("83ff59fe-2346-f236-9009-4e3608af64c1")); + AnimsLLUUID.Add("ANIM_AGENT_TURNLEFT", new LLUUID("56e0ba0d-4a9f-7f27-6117-32f2ebbf6135")); + AnimsLLUUID.Add("ANIM_AGENT_TURNRIGHT", new LLUUID("2d6daa51-3192-6794-8e2e-a15f8338ec30")); + AnimsLLUUID.Add("ANIM_AGENT_TYPE", new LLUUID("c541c47f-e0c0-058b-ad1a-d6ae3a4584d9")); + AnimsLLUUID.Add("ANIM_AGENT_WALK", new LLUUID("6ed24bd8-91aa-4b12-ccc7-c97c857ab4e0")); + AnimsLLUUID.Add("ANIM_AGENT_WHISPER", new LLUUID("7693f268-06c7-ea71-fa21-2b30d6533f8f")); + AnimsLLUUID.Add("ANIM_AGENT_WHISTLE", new LLUUID("b1ed7982-c68e-a982-7561-52a88a5298c0")); + AnimsLLUUID.Add("ANIM_AGENT_WINK", new LLUUID("869ecdad-a44b-671e-3266-56aef2e3ac2e")); + AnimsLLUUID.Add("ANIM_AGENT_WINK_HOLLYWOOD", new LLUUID("c0c4030f-c02b-49de-24ba-2331f43fe41c")); + AnimsLLUUID.Add("ANIM_AGENT_WORRY", new LLUUID("9f496bd2-589a-709f-16cc-69bf7df1d36c")); + AnimsLLUUID.Add("ANIM_AGENT_YES", new LLUUID("15dd911d-be82-2856-26db-27659b142875")); + AnimsLLUUID.Add("ANIM_AGENT_YES_HAPPY", new LLUUID("b8c8b2a3-9008-1771-3bfc-90924955ab2d")); + AnimsLLUUID.Add("ANIM_AGENT_YOGA_FLOAT", new LLUUID("42ecd00b-9947-a97c-400a-bbc9174c7aeb")); + + foreach (KeyValuePair kp in OpenSim.world.Avatar.Animations.AnimsLLUUID) + { + AnimsNames.Add(kp.Value, kp.Key); + } + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Entity.cs b/OpenSim/OpenSim.RegionServer/world/Entity.cs new file mode 100644 index 0000000..96e039a --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Entity.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Axiom.MathLib; +using OpenSim.Physics.Manager; +using OpenSim.types; +using libsecondlife; +using OpenSim.RegionServer.world.scripting; + +namespace OpenSim.world +{ + public abstract class Entity : IScriptReadonlyEntity + { + public libsecondlife.LLUUID uuid; + public uint localid; + public LLVector3 velocity; + public Quaternion rotation; + protected List children; + + protected string m_name; + public virtual string Name + { + get { return m_name; } + } + + protected LLVector3 m_pos; + protected PhysicsActor _physActor; + protected World m_world; + + public virtual LLVector3 Pos + { + get + { + if (this._physActor != null) + { + m_pos.X = _physActor.Position.X; + m_pos.Y = _physActor.Position.Y; + m_pos.Z = _physActor.Position.Z; + } + + return m_pos; + } + set + { + if (this._physActor != null) + { + try + { + lock (this.m_world.LockPhysicsEngine) + { + + this._physActor.Position = new PhysicsVector(value.X, value.Y, value.Z); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + + m_pos = value; + } + } + + /// + /// Creates a new Entity (should not occur on it's own) + /// + public Entity() + { + uuid = new libsecondlife.LLUUID(); + localid = 0; + m_pos = new LLVector3(); + velocity = new LLVector3(); + rotation = new Quaternion(); + m_name = "(basic entity)"; + children = new List(); + } + + public virtual void addForces() + { + foreach (Entity child in children) + { + child.addForces(); + } + } + + /// + /// Performs any updates that need to be done at each frame. This function is overridable from it's children. + /// + public virtual void update() { + // Do any per-frame updates needed that are applicable to every type of entity + foreach (Entity child in children) + { + child.update(); + } + } + + /// + /// Returns a mesh for this object and any dependents + /// + /// The mesh of this entity tree + public virtual Mesh getMesh() + { + Mesh mesh = new Mesh(); + + foreach (Entity child in children) + { + mesh += child.getMesh(); + } + + return mesh; + } + + public virtual void BackUp() + { + + } + + public virtual void LandRenegerated() + { + + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Primitive.cs b/OpenSim/OpenSim.RegionServer/world/Primitive.cs new file mode 100644 index 0000000..e048a9e --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Primitive.cs @@ -0,0 +1,570 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.types; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Types; + +namespace OpenSim.world +{ + public class Primitive : Entity + { + protected float mesh_cutbegin; + protected float mesh_cutend; + protected PrimData primData; + protected bool newPrimFlag = false; + protected bool updateFlag = false; + protected bool dirtyFlag = false; + private ObjectUpdatePacket OurPacket; + private bool physicsEnabled = false; + private bool physicstest = false; + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + private Dictionary m_clientThreads; + private ulong m_regionHandle; + private const uint FULL_MASK_PERMISSIONS = 2147483647; + + public bool PhysicsEnabled + { + get + { + return physicsEnabled; + } + set + { + physicsEnabled = value; + } + } + public bool UpdateFlag + { + get + { + return updateFlag; + } + set + { + updateFlag = value; + } + } + public LLVector3 Scale + { + set + { + LLVector3 offset = (value - primData.Scale); + offset.X /= 2; + offset.Y /= 2; + offset.Z /= 2; + + this.primData.Position += offset; + this.primData.Scale = value; + + this.dirtyFlag = true; + } + get + { + return this.primData.Scale; + } + } + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + } + + public Primitive(Dictionary clientThreads, ulong regionHandle, World world) + { + mesh_cutbegin = 0.0f; + mesh_cutend = 1.0f; + + m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + } + + public override Mesh getMesh() + { + Mesh mesh = new Mesh(); + Triangle tri = new Triangle( + new Axiom.MathLib.Vector3(0.0f, 1.0f, 1.0f), + new Axiom.MathLib.Vector3(1.0f, 0.0f, 1.0f), + new Axiom.MathLib.Vector3(1.0f, 1.0f, 0.0f)); + + mesh.AddTri(tri); + mesh += base.getMesh(); + + return mesh; + } + + public byte[] GetByteArray() + { + return this.primData.ToBytes(); + } + + public void GetProperites(ClientView client) + { + ObjectPropertiesPacket proper = new ObjectPropertiesPacket(); + proper.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[1]; + proper.ObjectData[0] = new ObjectPropertiesPacket.ObjectDataBlock(); + proper.ObjectData[0].ItemID = LLUUID.Zero; // this.uuid; + proper.ObjectData[0].CreationDate = (ulong) this.primData.CreationDate; + proper.ObjectData[0].CreatorID = this.primData.OwnerID; + proper.ObjectData[0].FolderID = LLUUID.Zero; + proper.ObjectData[0].FromTaskID = LLUUID.Zero; + proper.ObjectData[0].GroupID = LLUUID.Zero; + proper.ObjectData[0].InventorySerial = 0; + proper.ObjectData[0].LastOwnerID = LLUUID.Zero; + proper.ObjectData[0].ObjectID = this.uuid; + proper.ObjectData[0].OwnerID = primData.OwnerID; + proper.ObjectData[0].TouchName = new byte[0]; + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = new byte[0]; + proper.ObjectData[0].Name = new byte[0]; + proper.ObjectData[0].Description = new byte[0]; + proper.ObjectData[0].OwnerMask = this.primData.OwnerMask; + proper.ObjectData[0].NextOwnerMask = this.primData.NextOwnerMask; + proper.ObjectData[0].GroupMask = this.primData.GroupMask; + proper.ObjectData[0].EveryoneMask = this.primData.EveryoneMask; + proper.ObjectData[0].BaseMask = this.primData.BaseMask; + + client.OutPacket(proper); + } + + public void UpdatePosition(LLVector3 pos) + { + this.Pos = pos; + if (this._physActor != null) // && this.physicsEnabled) + { + try + { + lock (m_world.LockPhysicsEngine) + { + this._physActor.Position = new PhysicsVector(pos.X, pos.Y, pos.Z); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + this.updateFlag = true; + } + + public override void update() + { + LLVector3 pos2 = new LLVector3(0, 0, 0); + if (this._physActor != null && this.physicsEnabled) + { + + PhysicsVector pPos = this._physActor.Position; + pos2 = new LLVector3(pPos.X, pPos.Y, pPos.Z); + } + if (this.newPrimFlag) + { + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(OurPacket); + } + this.newPrimFlag = false; + } + else if (this.updateFlag) + { + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = m_regionHandle; // FIXME + terse.RegionData.TimeDilation = 64096; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = this.CreateImprovedBlock(); + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(terse); + } + this.updateFlag = false; + } + else if (this.dirtyFlag) + { + foreach (ClientView client in m_clientThreads.Values) + { + UpdateClient(client); + } + this.dirtyFlag = false; + } + else + { + if (this._physActor != null && this.physicsEnabled) + { + if (pos2 != this.positionLastFrame) + { + ImprovedTerseObjectUpdatePacket terse = new ImprovedTerseObjectUpdatePacket(); + terse.RegionData.RegionHandle = m_regionHandle; // FIXME + terse.RegionData.TimeDilation = 64096; + terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1]; + terse.ObjectData[0] = this.CreateImprovedBlock(); + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(terse); + } + } + this.positionLastFrame = pos2; + } + } + + if (this.physicstest) + { + LLVector3 pos = this.Pos; + pos.Z += 0.0001f; + this.UpdatePosition(pos); + this.physicstest = false; + } + } + + public void UpdateClient(ClientView RemoteClient) + { + + LLVector3 lPos; + if (this._physActor != null && this.physicsEnabled) + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + } + else + { + lPos = this.Pos; + } + byte[] pb = lPos.GetBytes(); + Array.Copy(pb, 0, OurPacket.ObjectData[0].ObjectData, 0, pb.Length); + + // OurPacket should be update with the follwing in updateShape() rather than having to do it here + OurPacket.ObjectData[0].OwnerID = this.primData.OwnerID; + OurPacket.ObjectData[0].PCode = this.primData.PCode; + OurPacket.ObjectData[0].PathBegin = this.primData.PathBegin; + OurPacket.ObjectData[0].PathEnd = this.primData.PathEnd; + OurPacket.ObjectData[0].PathScaleX = this.primData.PathScaleX; + OurPacket.ObjectData[0].PathScaleY = this.primData.PathScaleY; + OurPacket.ObjectData[0].PathShearX = this.primData.PathShearX; + OurPacket.ObjectData[0].PathShearY = this.primData.PathShearY; + OurPacket.ObjectData[0].PathSkew = this.primData.PathSkew; + OurPacket.ObjectData[0].ProfileBegin = this.primData.ProfileBegin; + OurPacket.ObjectData[0].ProfileEnd = this.primData.ProfileEnd; + OurPacket.ObjectData[0].Scale = this.primData.Scale; + OurPacket.ObjectData[0].PathCurve = this.primData.PathCurve; + OurPacket.ObjectData[0].ProfileCurve = this.primData.ProfileCurve; + OurPacket.ObjectData[0].ParentID = this.primData.ParentID ; + OurPacket.ObjectData[0].ProfileHollow = this.primData.ProfileHollow; + //finish off copying rest of shape data + OurPacket.ObjectData[0].PathRadiusOffset = this.primData.PathRadiusOffset; + OurPacket.ObjectData[0].PathRevolutions = this.primData.PathRevolutions; + OurPacket.ObjectData[0].PathTaperX = this.primData.PathTaperX; + OurPacket.ObjectData[0].PathTaperY = this.primData.PathTaperY; + OurPacket.ObjectData[0].PathTwist = this.primData.PathTwist; + OurPacket.ObjectData[0].PathTwistBegin = this.primData.PathTwistBegin; + + RemoteClient.OutPacket(OurPacket); + } + + public void UpdateShape(ObjectShapePacket.ObjectDataBlock addPacket) + { + this.primData.PathBegin = addPacket.PathBegin; + this.primData.PathEnd = addPacket.PathEnd; + this.primData.PathScaleX = addPacket.PathScaleX; + this.primData.PathScaleY = addPacket.PathScaleY; + this.primData.PathShearX = addPacket.PathShearX; + this.primData.PathShearY = addPacket.PathShearY; + this.primData.PathSkew = addPacket.PathSkew; + this.primData.ProfileBegin = addPacket.ProfileBegin; + this.primData.ProfileEnd = addPacket.ProfileEnd; + this.primData.PathCurve = addPacket.PathCurve; + this.primData.ProfileCurve = addPacket.ProfileCurve; + this.primData.ProfileHollow = addPacket.ProfileHollow; + this.primData.PathRadiusOffset = addPacket.PathRadiusOffset; + this.primData.PathRevolutions = addPacket.PathRevolutions; + this.primData.PathTaperX = addPacket.PathTaperX; + this.primData.PathTaperY = addPacket.PathTaperY; + this.primData.PathTwist = addPacket.PathTwist; + this.primData.PathTwistBegin = addPacket.PathTwistBegin; + this.dirtyFlag = true; + } + + public void UpdateTexture(byte[] tex) + { + this.OurPacket.ObjectData[0].TextureEntry = tex; + this.primData.Texture = tex; + this.dirtyFlag = true; + } + + public void UpdateObjectFlags(ObjectFlagUpdatePacket pack) + { + if (this._physActor != null) + { + if (this._physActor.Kinematic == pack.AgentData.UsePhysics) + { + this._physActor.Kinematic = !pack.AgentData.UsePhysics; //if Usephysics = true, then Kinematic should = false + } + this.physicsEnabled = pack.AgentData.UsePhysics; + if (this._physActor.Kinematic == false) + { + LLVector3 pos = this.Pos; + this.UpdatePosition(pos); + pos.Z += 0.000001f; + this.UpdatePosition(pos); + this.physicstest = true; + } + else + { + PhysicsVector vec = this._physActor.Position; + LLVector3 pos = new LLVector3(vec.X, vec.Y, vec.Z); + this.Pos = pos; + this.updateFlag = true; + } + } + } + + public void MakeParent(Primitive prim) + { + this.primData.ParentID = prim.localid; + this.Pos -= prim.Pos; + this.dirtyFlag = true; + } + + public void CreateFromPacket(ObjectAddPacket addPacket, LLUUID ownerID, uint localID) + { + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = m_regionHandle; + objupdate.RegionData.TimeDilation = 64096; + + objupdate.ObjectData = new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock[1]; + PrimData PData = new PrimData(); + this.primData = PData; + this.primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + + objupdate.ObjectData[0] = new ObjectUpdatePacket.ObjectDataBlock(); + objupdate.ObjectData[0].PSBlock = new byte[0]; + objupdate.ObjectData[0].ExtraParams = new byte[1]; + objupdate.ObjectData[0].MediaURL = new byte[0]; + objupdate.ObjectData[0].NameValue = new byte[0]; + objupdate.ObjectData[0].Text = new byte[0]; + objupdate.ObjectData[0].TextColor = new byte[4]; + objupdate.ObjectData[0].JointAxisOrAnchor = new LLVector3(0, 0, 0); + objupdate.ObjectData[0].JointPivot = new LLVector3(0, 0, 0); + objupdate.ObjectData[0].Material = 3; + objupdate.ObjectData[0].UpdateFlags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456; + objupdate.ObjectData[0].TextureAnim = new byte[0]; + objupdate.ObjectData[0].Sound = LLUUID.Zero; + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + this.primData.Texture = objupdate.ObjectData[0].TextureEntry = ntex.ToBytes(); + objupdate.ObjectData[0].State = 0; + objupdate.ObjectData[0].Data = new byte[0]; + PData.OwnerID = objupdate.ObjectData[0].OwnerID = ownerID; + PData.PCode = objupdate.ObjectData[0].PCode = addPacket.ObjectData.PCode; + PData.PathBegin = objupdate.ObjectData[0].PathBegin = addPacket.ObjectData.PathBegin; + PData.PathEnd = objupdate.ObjectData[0].PathEnd = addPacket.ObjectData.PathEnd; + PData.PathScaleX = objupdate.ObjectData[0].PathScaleX = addPacket.ObjectData.PathScaleX; + PData.PathScaleY = objupdate.ObjectData[0].PathScaleY = addPacket.ObjectData.PathScaleY; + PData.PathShearX = objupdate.ObjectData[0].PathShearX = addPacket.ObjectData.PathShearX; + PData.PathShearY = objupdate.ObjectData[0].PathShearY = addPacket.ObjectData.PathShearY; + PData.PathSkew = objupdate.ObjectData[0].PathSkew = addPacket.ObjectData.PathSkew; + PData.ProfileBegin = objupdate.ObjectData[0].ProfileBegin = addPacket.ObjectData.ProfileBegin; + PData.ProfileEnd = objupdate.ObjectData[0].ProfileEnd = addPacket.ObjectData.ProfileEnd; + PData.Scale = objupdate.ObjectData[0].Scale = addPacket.ObjectData.Scale; + PData.PathCurve = objupdate.ObjectData[0].PathCurve = addPacket.ObjectData.PathCurve; + PData.ProfileCurve = objupdate.ObjectData[0].ProfileCurve = addPacket.ObjectData.ProfileCurve; + PData.ParentID = objupdate.ObjectData[0].ParentID = 0; + PData.ProfileHollow = objupdate.ObjectData[0].ProfileHollow = addPacket.ObjectData.ProfileHollow; + PData.PathRadiusOffset = objupdate.ObjectData[0].PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; + PData.PathRevolutions = objupdate.ObjectData[0].PathRevolutions = addPacket.ObjectData.PathRevolutions; + PData.PathTaperX = objupdate.ObjectData[0].PathTaperX = addPacket.ObjectData.PathTaperX; + PData.PathTaperY = objupdate.ObjectData[0].PathTaperY = addPacket.ObjectData.PathTaperY; + PData.PathTwist = objupdate.ObjectData[0].PathTwist = addPacket.ObjectData.PathTwist; + PData.PathTwistBegin = objupdate.ObjectData[0].PathTwistBegin = addPacket.ObjectData.PathTwistBegin; + objupdate.ObjectData[0].ID = (uint)(localID); + objupdate.ObjectData[0].FullID = new LLUUID("edba7151-5857-acc5-b30b-f01efef" + (localID - 702000).ToString("00000")); + objupdate.ObjectData[0].ObjectData = new byte[60]; + objupdate.ObjectData[0].ObjectData[46] = 128; + objupdate.ObjectData[0].ObjectData[47] = 63; + LLVector3 pos1 = addPacket.ObjectData.RayEnd; + //update position + byte[] pb = pos1.GetBytes(); + Array.Copy(pb, 0, objupdate.ObjectData[0].ObjectData, 0, pb.Length); + this.newPrimFlag = true; + this.primData.FullID = this.uuid = objupdate.ObjectData[0].FullID; + this.localid = objupdate.ObjectData[0].ID; + this.primData.Position = this.Pos = pos1; + this.OurPacket = objupdate; + } + + public void CreateFromStorage(PrimData store) + { + this.CreateFromStorage(store, store.Position, store.LocalID, false); + } + + public void CreateFromStorage(PrimData store, LLVector3 posi, uint localID, bool newprim) + { + //need to clean this up as it shares a lot of code with CreateFromPacket() + ObjectUpdatePacket objupdate = new ObjectUpdatePacket(); + objupdate.RegionData.RegionHandle = m_regionHandle; + objupdate.RegionData.TimeDilation = 64096; + objupdate.ObjectData = new libsecondlife.Packets.ObjectUpdatePacket.ObjectDataBlock[1]; + + this.primData = store; + objupdate.ObjectData[0] = new ObjectUpdatePacket.ObjectDataBlock(); + objupdate.ObjectData[0].PSBlock = new byte[0]; + objupdate.ObjectData[0].ExtraParams = new byte[1]; + objupdate.ObjectData[0].MediaURL = new byte[0]; + objupdate.ObjectData[0].NameValue = new byte[0]; + objupdate.ObjectData[0].Text = new byte[0]; + objupdate.ObjectData[0].TextColor = new byte[4]; + objupdate.ObjectData[0].JointAxisOrAnchor = new LLVector3(0, 0, 0); + objupdate.ObjectData[0].JointPivot = new LLVector3(0, 0, 0); + objupdate.ObjectData[0].Material = 3; + objupdate.ObjectData[0].UpdateFlags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456; + objupdate.ObjectData[0].TextureAnim = new byte[0]; + objupdate.ObjectData[0].Sound = LLUUID.Zero; + + if (store.Texture == null) + { + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + objupdate.ObjectData[0].TextureEntry = ntex.ToBytes(); + } + else + { + objupdate.ObjectData[0].TextureEntry = store.Texture; + } + + objupdate.ObjectData[0].State = 0; + objupdate.ObjectData[0].Data = new byte[0]; + objupdate.ObjectData[0].OwnerID = this.primData.OwnerID; + objupdate.ObjectData[0].PCode = this.primData.PCode; + objupdate.ObjectData[0].PathBegin = this.primData.PathBegin; + objupdate.ObjectData[0].PathEnd = this.primData.PathEnd; + objupdate.ObjectData[0].PathScaleX = this.primData.PathScaleX; + objupdate.ObjectData[0].PathScaleY = this.primData.PathScaleY; + objupdate.ObjectData[0].PathShearX = this.primData.PathShearX; + objupdate.ObjectData[0].PathShearY = this.primData.PathShearY; + objupdate.ObjectData[0].PathSkew = this.primData.PathSkew; + objupdate.ObjectData[0].ProfileBegin = this.primData.ProfileBegin; + objupdate.ObjectData[0].ProfileEnd = this.primData.ProfileEnd; + objupdate.ObjectData[0].Scale = this.primData.Scale; + objupdate.ObjectData[0].PathCurve = this.primData.PathCurve; + objupdate.ObjectData[0].ProfileCurve = this.primData.ProfileCurve; + objupdate.ObjectData[0].ParentID = 0; + objupdate.ObjectData[0].ProfileHollow = this.primData.ProfileHollow; + //finish off copying rest of shape data + objupdate.ObjectData[0].PathRadiusOffset = this.primData.PathRadiusOffset; + objupdate.ObjectData[0].PathRevolutions = this.primData.PathRevolutions; + objupdate.ObjectData[0].PathTaperX = this.primData.PathTaperX; + objupdate.ObjectData[0].PathTaperY = this.primData.PathTaperY; + objupdate.ObjectData[0].PathTwist = this.primData.PathTwist; + objupdate.ObjectData[0].PathTwistBegin = this.primData.PathTwistBegin; + + objupdate.ObjectData[0].ID = localID; // (uint)store.LocalID; + objupdate.ObjectData[0].FullID = store.FullID; + + objupdate.ObjectData[0].ObjectData = new byte[60]; + objupdate.ObjectData[0].ObjectData[46] = 128; + objupdate.ObjectData[0].ObjectData[47] = 63; + LLVector3 pos1 = posi; // store.Position; + //update position + byte[] pb = pos1.GetBytes(); + Array.Copy(pb, 0, objupdate.ObjectData[0].ObjectData, 0, pb.Length); + + this.uuid = objupdate.ObjectData[0].FullID; + this.localid = objupdate.ObjectData[0].ID; + this.Pos = pos1; + this.OurPacket = objupdate; + if (newprim) + { + this.newPrimFlag = true; + } + } + + public ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedBlock() + { + uint ID = this.localid; + byte[] bytes = new byte[60]; + + int i = 0; + ImprovedTerseObjectUpdatePacket.ObjectDataBlock dat = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock(); + //dat.TextureEntry = this.OurPacket.ObjectData[0].TextureEntry; + dat.TextureEntry = new byte[0]; + //Console.WriteLine("texture-entry length in improvedterse block is " + this.OurPacket.ObjectData[0].TextureEntry.Length); + 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; + + LLVector3 lPos; + Axiom.MathLib.Quaternion lRot; + if (this._physActor != null && this.physicsEnabled) + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + lRot = this._physActor.Orientation; + } + else + { + lPos = this.Pos; + lRot = this.rotation; + } + byte[] pb = lPos.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 * (lRot.w + 1)); + rx = (ushort)(32768 * (lRot.x + 1)); + ry = (ushort)(32768 * (lRot.y + 1)); + rz = (ushort)(32768 * (lRot.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; + } + + public override void BackUp() + { + this.primData.FullID = this.uuid; + this.primData.LocalID = this.localid; + this.primData.Position = this.Pos; + this.primData.Rotation = new LLQuaternion(this.rotation.x, this.rotation.y, this.rotation.z, this.rotation.w); + this.m_world.localStorage.StorePrim(this.primData); + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/Primitive2.cs b/OpenSim/OpenSim.RegionServer/world/Primitive2.cs new file mode 100644 index 0000000..6d071d4 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/Primitive2.cs @@ -0,0 +1,491 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.types; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; + +namespace OpenSim.world +{ + public class Primitive2 : Entity + { + protected PrimData primData; + //private ObjectUpdatePacket OurPacket; + private LLVector3 positionLastFrame = new LLVector3(0, 0, 0); + private Dictionary m_clientThreads; + private ulong m_regionHandle; + private const uint FULL_MASK_PERMISSIONS = 2147483647; + private bool physicsEnabled = false; + + private Dictionary inventoryItems; + + #region Properties + + public LLVector3 Scale + { + set + { + this.primData.Scale = value; + //this.dirtyFlag = true; + } + get + { + return this.primData.Scale; + } + } + + public PhysicsActor PhysActor + { + set + { + this._physActor = value; + } + } + public override LLVector3 Pos + { + get + { + return base.Pos; + } + set + { + base.Pos = value; + } + } + #endregion + + public Primitive2(Dictionary clientThreads, ulong regionHandle, World world) + { + m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + } + + public Primitive2(Dictionary clientThreads, ulong regionHandle, World world, LLUUID owner) + { + m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_world = world; + inventoryItems = new Dictionary(); + this.primData = new PrimData(); + this.primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + this.primData.OwnerID = owner; + } + + public byte[] GetByteArray() + { + byte[] result = null; + List dataArrays = new List(); + dataArrays.Add(primData.ToBytes()); + foreach (Entity child in children) + { + if (child is OpenSim.world.Primitive2) + { + dataArrays.Add(((OpenSim.world.Primitive2)child).GetByteArray()); + } + } + byte[] primstart = Helpers.StringToField(""); + byte[] primend = Helpers.StringToField(""); + int totalLength = primstart.Length + primend.Length; + for (int i = 0; i < dataArrays.Count; i++) + { + totalLength += dataArrays[i].Length; + } + + result = new byte[totalLength]; + int arraypos = 0; + Array.Copy(primstart, 0, result, 0, primstart.Length); + arraypos += primstart.Length; + for (int i = 0; i < dataArrays.Count; i++) + { + Array.Copy(dataArrays[i], 0, result, arraypos, dataArrays[i].Length); + arraypos += dataArrays[i].Length; + } + Array.Copy(primend, 0, result, arraypos, primend.Length); + + return result; + } + + #region Overridden Methods + + public override void update() + { + LLVector3 pos2 = new LLVector3(0, 0, 0); + } + + public override void BackUp() + { + + } + + #endregion + + #region Packet handlers + + public void UpdatePosition(LLVector3 pos) + { + + } + + public void UpdateShape(ObjectShapePacket.ObjectDataBlock addPacket) + { + this.primData.PathBegin = addPacket.PathBegin; + this.primData.PathEnd = addPacket.PathEnd; + this.primData.PathScaleX = addPacket.PathScaleX; + this.primData.PathScaleY = addPacket.PathScaleY; + this.primData.PathShearX = addPacket.PathShearX; + this.primData.PathShearY = addPacket.PathShearY; + this.primData.PathSkew = addPacket.PathSkew; + this.primData.ProfileBegin = addPacket.ProfileBegin; + this.primData.ProfileEnd = addPacket.ProfileEnd; + this.primData.PathCurve = addPacket.PathCurve; + this.primData.ProfileCurve = addPacket.ProfileCurve; + this.primData.ProfileHollow = addPacket.ProfileHollow; + this.primData.PathRadiusOffset = addPacket.PathRadiusOffset; + this.primData.PathRevolutions = addPacket.PathRevolutions; + this.primData.PathTaperX = addPacket.PathTaperX; + this.primData.PathTaperY = addPacket.PathTaperY; + this.primData.PathTwist = addPacket.PathTwist; + this.primData.PathTwistBegin = addPacket.PathTwistBegin; + } + + public void UpdateTexture(byte[] tex) + { + this.primData.Texture = tex; + //this.dirtyFlag = true; + } + + public void UpdateObjectFlags(ObjectFlagUpdatePacket pack) + { + + } + + public void AssignToParent(Primitive prim) + { + + } + + public void GetProperites(ClientView 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.primData.CreationDate; + proper.ObjectData[0].CreatorID = this.primData.OwnerID; + proper.ObjectData[0].FolderID = LLUUID.Zero; + proper.ObjectData[0].FromTaskID = LLUUID.Zero; + proper.ObjectData[0].GroupID = LLUUID.Zero; + proper.ObjectData[0].InventorySerial = 0; + proper.ObjectData[0].LastOwnerID = LLUUID.Zero; + proper.ObjectData[0].ObjectID = this.uuid; + proper.ObjectData[0].OwnerID = primData.OwnerID; + proper.ObjectData[0].TouchName = new byte[0]; + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = new byte[0]; + proper.ObjectData[0].Name = new byte[0]; + proper.ObjectData[0].Description = new byte[0]; + proper.ObjectData[0].OwnerMask = this.primData.OwnerMask; + proper.ObjectData[0].NextOwnerMask = this.primData.NextOwnerMask; + proper.ObjectData[0].GroupMask = this.primData.GroupMask; + proper.ObjectData[0].EveryoneMask = this.primData.EveryoneMask; + proper.ObjectData[0].BaseMask = this.primData.BaseMask; + + client.OutPacket(proper); + } + + #endregion + + # region Inventory Methods + + public bool AddToInventory(InventoryItem item) + { + return false; + } + + public InventoryItem RemoveFromInventory(LLUUID itemID) + { + return null; + } + + public void RequestInventoryInfo(ClientView simClient, RequestTaskInventoryPacket packet) + { + + } + + public void RequestXferInventory(ClientView simClient, ulong xferID) + { + //will only currently work if the total size of the inventory data array is under about 1000 bytes + SendXferPacketPacket send = new SendXferPacketPacket(); + + send.XferID.ID = xferID; + send.XferID.Packet = 1 + 2147483648; + send.DataPacket.Data = this.ConvertInventoryToBytes(); + + simClient.OutPacket(send); + } + + public byte[] ConvertInventoryToBytes() + { + System.Text.Encoding enc = System.Text.Encoding.ASCII; + byte[] result = new byte[0]; + List inventoryData = new List(); + int totallength = 0; + foreach (InventoryItem invItem in inventoryItems.Values) + { + byte[] data = enc.GetBytes(invItem.ExportString()); + inventoryData.Add(data); + totallength += data.Length; + } + //TODO: copy arrays into the single result array + + return result; + } + + public void CreateInventoryFromBytes(byte[] data) + { + + } + + #endregion + + #region Update viewers Methods + + //should change these mehtods, so that outgoing packets are sent through the avatar class + public void SendFullUpdateToClient(ClientView remoteClient) + { + LLVector3 lPos; + if (this._physActor != null && this.physicsEnabled) + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + } + else + { + lPos = this.Pos; + } + + ObjectUpdatePacket outPacket = new ObjectUpdatePacket(); + outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; + outPacket.ObjectData[0] = this.CreateUpdateBlock(); + byte[] pb = lPos.GetBytes(); + Array.Copy(pb, 0, outPacket.ObjectData[0].ObjectData, 0, pb.Length); + + remoteClient.OutPacket(outPacket); + } + + public void SendFullUpdateToAllClients() + { + + } + + public void SendTerseUpdateToClient(ClientView RemoteClient) + { + + } + + public void SendTerseUpdateToALLClients() + { + + } + + #endregion + + #region Create Methods + + public void CreateFromPacket(ObjectAddPacket addPacket, LLUUID ownerID, uint localID) + { + PrimData PData = new PrimData(); + this.primData = PData; + this.primData.CreationDate = (Int32)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + + PData.OwnerID = ownerID; + PData.PCode = addPacket.ObjectData.PCode; + PData.PathBegin = addPacket.ObjectData.PathBegin; + PData.PathEnd = addPacket.ObjectData.PathEnd; + PData.PathScaleX = addPacket.ObjectData.PathScaleX; + PData.PathScaleY = addPacket.ObjectData.PathScaleY; + PData.PathShearX = addPacket.ObjectData.PathShearX; + PData.PathShearY = addPacket.ObjectData.PathShearY; + PData.PathSkew = addPacket.ObjectData.PathSkew; + PData.ProfileBegin = addPacket.ObjectData.ProfileBegin; + PData.ProfileEnd = addPacket.ObjectData.ProfileEnd; + PData.Scale = addPacket.ObjectData.Scale; + PData.PathCurve = addPacket.ObjectData.PathCurve; + PData.ProfileCurve = addPacket.ObjectData.ProfileCurve; + PData.ParentID = 0; + PData.ProfileHollow = addPacket.ObjectData.ProfileHollow; + PData.PathRadiusOffset = addPacket.ObjectData.PathRadiusOffset; + PData.PathRevolutions = addPacket.ObjectData.PathRevolutions; + PData.PathTaperX = addPacket.ObjectData.PathTaperX; + PData.PathTaperY = addPacket.ObjectData.PathTaperY; + PData.PathTwist = addPacket.ObjectData.PathTwist; + PData.PathTwistBegin = addPacket.ObjectData.PathTwistBegin; + LLVector3 pos1 = addPacket.ObjectData.RayEnd; + this.primData.FullID = this.uuid = LLUUID.Random(); + this.localid = (uint)(localID); + this.primData.Position = this.Pos = pos1; + } + + public void CreateFromBytes(byte[] data) + { + + } + + public void CreateFromPrimData(PrimData primData) + { + this.CreateFromPrimData(primData, primData.Position, primData.LocalID, false); + } + + public void CreateFromPrimData(PrimData primData, LLVector3 posi, uint localID, bool newprim) + { + + } + + #endregion + + #region Packet Update Methods + protected void SetDefaultPacketValues(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; + LLObject.TextureEntry ntex = new LLObject.TextureEntry(new LLUUID("00000000-0000-0000-5005-000000000005")); + this.primData.Texture = objdata.TextureEntry = ntex.ToBytes(); + objdata.State = 0; + objdata.Data = new byte[0]; + + objdata.ObjectData = new byte[60]; + objdata.ObjectData[46] = 128; + objdata.ObjectData[47] = 63; + } + + protected void SetPacketShapeData(ObjectUpdatePacket.ObjectDataBlock objectData) + { + objectData.OwnerID = this.primData.OwnerID; + objectData.PCode = this.primData.PCode; + objectData.PathBegin = this.primData.PathBegin; + objectData.PathEnd = this.primData.PathEnd; + objectData.PathScaleX = this.primData.PathScaleX; + objectData.PathScaleY = this.primData.PathScaleY; + objectData.PathShearX = this.primData.PathShearX; + objectData.PathShearY = this.primData.PathShearY; + objectData.PathSkew = this.primData.PathSkew; + objectData.ProfileBegin = this.primData.ProfileBegin; + objectData.ProfileEnd = this.primData.ProfileEnd; + objectData.Scale = this.primData.Scale; + objectData.PathCurve = this.primData.PathCurve; + objectData.ProfileCurve = this.primData.ProfileCurve; + objectData.ParentID = this.primData.ParentID; + objectData.ProfileHollow = this.primData.ProfileHollow; + objectData.PathRadiusOffset = this.primData.PathRadiusOffset; + objectData.PathRevolutions = this.primData.PathRevolutions; + objectData.PathTaperX = this.primData.PathTaperX; + objectData.PathTaperY = this.primData.PathTaperY; + objectData.PathTwist = this.primData.PathTwist; + objectData.PathTwistBegin = this.primData.PathTwistBegin; + } + + #endregion + protected ObjectUpdatePacket.ObjectDataBlock CreateUpdateBlock() + { + ObjectUpdatePacket.ObjectDataBlock objupdate = new ObjectUpdatePacket.ObjectDataBlock(); + this.SetDefaultPacketValues(objupdate); + objupdate.UpdateFlags = 32 + 65536 + 131072 + 256 + 4 + 8 + 2048 + 524288 + 268435456; + this.SetPacketShapeData(objupdate); + byte[] pb = this.Pos.GetBytes(); + Array.Copy(pb, 0, objupdate.ObjectData, 0, pb.Length); + return objupdate; + } + + protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedBlock() + { + uint ID = this.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; + + LLVector3 lPos; + Axiom.MathLib.Quaternion lRot; + if (this._physActor != null && this.physicsEnabled) + { + PhysicsVector pPos = this._physActor.Position; + lPos = new LLVector3(pPos.X, pPos.Y, pPos.Z); + lRot = this._physActor.Orientation; + } + else + { + lPos = this.Pos; + lRot = this.rotation; + } + byte[] pb = lPos.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 * (lRot.w + 1)); + rx = (ushort)(32768 * (lRot.x + 1)); + ry = (ushort)(32768 * (lRot.y + 1)); + rz = (ushort)(32768 * (lRot.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; + } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/SceneObject.cs b/OpenSim/OpenSim.RegionServer/world/SceneObject.cs new file mode 100644 index 0000000..a846fb5 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/SceneObject.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.types; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Framework.Interfaces; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Types; +using OpenSim.Framework.Inventory; + +namespace OpenSim.world +{ + public class SceneObject : Entity + { + private LLUUID rootUUID; + private Dictionary ChildPrimitives = new Dictionary(); + private Dictionary m_clientThreads; + private World m_world; + + public SceneObject() + { + + } + + public void CreateFromPacket(ObjectAddPacket addPacket, LLUUID agentID, uint localID) + { + } + + public void CreateFromBytes(byte[] data) + { + + } + + public override void update() + { + + } + + public override void BackUp() + { + + } + + public void GetProperites(ClientView 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.primData.CreationDate; + proper.ObjectData[0].CreatorID = this.primData.OwnerID; + proper.ObjectData[0].FolderID = LLUUID.Zero; + proper.ObjectData[0].FromTaskID = LLUUID.Zero; + proper.ObjectData[0].GroupID = LLUUID.Zero; + proper.ObjectData[0].InventorySerial = 0; + proper.ObjectData[0].LastOwnerID = LLUUID.Zero; + proper.ObjectData[0].ObjectID = this.uuid; + proper.ObjectData[0].OwnerID = primData.OwnerID; + proper.ObjectData[0].TouchName = new byte[0]; + proper.ObjectData[0].TextureID = new byte[0]; + proper.ObjectData[0].SitName = new byte[0]; + proper.ObjectData[0].Name = new byte[0]; + proper.ObjectData[0].Description = new byte[0]; + proper.ObjectData[0].OwnerMask = this.primData.OwnerMask; + proper.ObjectData[0].NextOwnerMask = this.primData.NextOwnerMask; + proper.ObjectData[0].GroupMask = this.primData.GroupMask; + proper.ObjectData[0].EveryoneMask = this.primData.EveryoneMask; + proper.ObjectData[0].BaseMask = this.primData.BaseMask; + + client.OutPacket(proper); + * */ + } + + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/World.PacketHandlers.cs b/OpenSim/OpenSim.RegionServer/world/World.PacketHandlers.cs new file mode 100644 index 0000000..348cd30 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/World.PacketHandlers.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; +using OpenSim.Framework.Inventory; +using OpenSim.Framework.Utilities; +using OpenSim.Assets; + +namespace OpenSim.world +{ + public partial class World + { + public void ModifyTerrain(byte action, float north, float west) + { + switch (action) + { + case 1: + // raise terrain + Terrain.raise(north, west, 10.0, 0.1); + RegenerateTerrain(true, (int)north, (int)west); + break; + case 2: + //lower terrain + Terrain.lower(north, west, 10.0, 0.1); + RegenerateTerrain(true, (int)north, (int)west); + break; + } + return; + } + + public void SimChat(byte[] message, byte type, LLVector3 fromPos, string fromName, LLUUID fromAgentID) + { + foreach (ClientView client in m_clientThreads.Values) + { + // int dis = Util.fast_distance2d((int)(client.ClientAvatar.Pos.X - simClient.ClientAvatar.Pos.X), (int)(client.ClientAvatar.Pos.Y - simClient.ClientAvatar.Pos.Y)); + int dis = (int)client.ClientAvatar.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 + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + case 1: // Say + if ((dis < 30) && (dis > -30)) + { + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + case 2: // Shout + if ((dis < 100) && (dis > -100)) + { + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + } + break; + + case 0xff: // Broadcast + client.SendChatMessage(message, type, fromPos, fromName, fromAgentID); + break; + } + + } + } + + public void RezObject(AssetBase primAsset, LLVector3 pos) + { + PrimData primd = new PrimData(primAsset.Data); + Primitive nPrim = new Primitive(m_clientThreads, m_regionHandle, this); + nPrim.CreateFromStorage(primd, pos, this._primCount, true); + this.Entities.Add(nPrim.uuid, nPrim); + this._primCount++; + } + + public void DeRezObject(Packet packet, ClientView simClient) + { + DeRezObjectPacket DeRezPacket = (DeRezObjectPacket)packet; + + //Needs to delete object from physics at a later date + if (DeRezPacket.AgentBlock.DestinationID == LLUUID.Zero) + { + //currently following code not used (or don't know of any case of destination being zero + libsecondlife.LLUUID[] DeRezEnts; + DeRezEnts = new libsecondlife.LLUUID[DeRezPacket.ObjectData.Length]; + int i = 0; + foreach (DeRezObjectPacket.ObjectDataBlock Data in DeRezPacket.ObjectData) + { + + //OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LocalID:" + Data.ObjectLocalID.ToString()); + foreach (Entity ent in this.Entities.Values) + { + if (ent.localid == Data.ObjectLocalID) + { + DeRezEnts[i++] = ent.uuid; + this.localStorage.RemovePrim(ent.uuid); + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + kill.ObjectData[0].ID = ent.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + //Uncommenting this means an old UUID will be re-used, thus crashing the asset server + //Uncomment when prim/object UUIDs are random or such + //2007-03-22 - Randomskk + //this._primCount--; + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.VERBOSE, "Deleted UUID " + ent.uuid); + } + } + } + foreach (libsecondlife.LLUUID uuid in DeRezEnts) + { + lock (Entities) + { + Entities.Remove(uuid); + } + } + } + else + { + foreach (DeRezObjectPacket.ObjectDataBlock Data in DeRezPacket.ObjectData) + { + Entity selectedEnt = null; + //OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LocalID:" + Data.ObjectLocalID.ToString()); + foreach (Entity ent in this.Entities.Values) + { + if (ent.localid == Data.ObjectLocalID) + { + AssetBase primAsset = new AssetBase(); + primAsset.FullID = LLUUID.Random();//DeRezPacket.AgentBlock.TransactionID.Combine(LLUUID.Zero); //should be combining with securesessionid + primAsset.InvType = 6; + primAsset.Type = 6; + primAsset.Name = "Prim"; + primAsset.Description = ""; + primAsset.Data = ((Primitive)ent).GetByteArray(); + this._assetCache.AddAsset(primAsset); + this._inventoryCache.AddNewInventoryItem(simClient, DeRezPacket.AgentBlock.DestinationID, primAsset); + selectedEnt = ent; + break; + } + } + if (selectedEnt != null) + { + this.localStorage.RemovePrim(selectedEnt.uuid); + KillObjectPacket kill = new KillObjectPacket(); + kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; + kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); + kill.ObjectData[0].ID = selectedEnt.localid; + foreach (ClientView client in m_clientThreads.Values) + { + client.OutPacket(kill); + } + lock (Entities) + { + Entities.Remove(selectedEnt.uuid); + } + } + } + } + + } + + public void SendAvatarsToClient(ClientView remoteClient) + { + foreach (ClientView client in m_clientThreads.Values) + { + if (client.AgentID != remoteClient.AgentID) + { + // ObjectUpdatePacket objupdate = client.ClientAvatar.CreateUpdatePacket(); + // RemoteClient.OutPacket(objupdate); + client.ClientAvatar.SendUpdateToOtherClient(remoteClient.ClientAvatar); + client.ClientAvatar.SendAppearanceToOtherAgent(remoteClient.ClientAvatar); + } + } + } + + public void LinkObjects(uint parentPrim, List childPrims) + { + Primitive parentprim = null; + foreach (Entity ent in Entities.Values) + { + if (ent.localid == parentPrim) + { + parentprim = (OpenSim.world.Primitive)ent; + + } + } + + for (int i = 0; i < childPrims.Count; i++) + { + uint childId = childPrims[i]; + foreach (Entity ent in Entities.Values) + { + if (ent.localid == childId) + { + ((OpenSim.world.Primitive)ent).MakeParent(parentprim); + } + } + } + + } + + public void UpdatePrimShape(uint primLocalID, ObjectShapePacket.ObjectDataBlock shapeBlock) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == primLocalID) + { + ((OpenSim.world.Primitive)ent).UpdateShape(shapeBlock); + break; + } + } + } + + public void SelectPrim(uint primLocalID, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == primLocalID) + { + ((OpenSim.world.Primitive)ent).GetProperites(remoteClient); + break; + } + } + } + + public void UpdatePrimFlags(uint localID, Packet packet, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == localID) + { + ((OpenSim.world.Primitive)ent).UpdateObjectFlags((ObjectFlagUpdatePacket) packet); + break; + } + } + } + + public void UpdatePrimTexture(uint localID, byte[] texture, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == localID) + { + ((OpenSim.world.Primitive)ent).UpdateTexture(texture); + break; + } + } + } + + public void UpdatePrimPosition(uint localID, LLVector3 pos, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == localID) + { + ((OpenSim.world.Primitive)ent).UpdatePosition(pos); + break; + } + } + } + + public void UpdatePrimRotation(uint localID, LLQuaternion rot, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == localID) + { + ent.rotation = new Axiom.MathLib.Quaternion(rot.W, rot.X, rot.Y, rot.Z); + ((OpenSim.world.Primitive)ent).UpdateFlag = true; + break; + } + } + } + + public void UpdatePrimScale(uint localID, LLVector3 scale, ClientView remoteClient) + { + foreach (Entity ent in Entities.Values) + { + if (ent.localid == localID) + { + ((OpenSim.world.Primitive)ent).Scale = scale; + break; + } + } + } + + /* + public void RequestMapBlock(ClientView simClient, int minX, int minY, int maxX, int maxY) + { + System.Text.Encoding _enc = System.Text.Encoding.ASCII; + if (((m_regInfo.RegionLocX > minX) && (m_regInfo.RegionLocX < maxX)) && ((m_regInfo.RegionLocY > minY) && (m_regInfo.RegionLocY < maxY))) + { + MapBlockReplyPacket mapReply = new MapBlockReplyPacket(); + mapReply.AgentData.AgentID = simClient.AgentID; + mapReply.AgentData.Flags = 0; + mapReply.Data = new MapBlockReplyPacket.DataBlock[1]; + mapReply.Data[0] = new MapBlockReplyPacket.DataBlock(); + mapReply.Data[0].MapImageID = new LLUUID("00000000-0000-0000-9999-000000000007"); + mapReply.Data[0].X = (ushort)m_regInfo.RegionLocX; + mapReply.Data[0].Y = (ushort)m_regInfo.RegionLocY; + mapReply.Data[0].WaterHeight = (byte)m_regInfo.RegionWaterHeight; + mapReply.Data[0].Name = _enc.GetBytes(this.m_regionName); + mapReply.Data[0].RegionFlags = 72458694; + mapReply.Data[0].Access = 13; + mapReply.Data[0].Agents = 1; //should send number of clients connected + simClient.OutPacket(mapReply); + } + } + public bool RezObjectHandler(ClientView simClient, Packet packet) + { + RezObjectPacket rezPacket = (RezObjectPacket)packet; + AgentInventory inven = this._inventoryCache.GetAgentsInventory(simClient.AgentID); + if (inven != null) + { + if (inven.InventoryItems.ContainsKey(rezPacket.InventoryData.ItemID)) + { + AssetBase asset = this._assetCache.GetAsset(inven.InventoryItems[rezPacket.InventoryData.ItemID].AssetID); + if (asset != null) + { + PrimData primd = new PrimData(asset.Data); + Primitive nPrim = new Primitive(m_clientThreads, m_regionHandle, this); + nPrim.CreateFromStorage(primd, rezPacket.RezData.RayEnd, this._primCount, true); + this.Entities.Add(nPrim.uuid, nPrim); + this._primCount++; + this._inventoryCache.DeleteInventoryItem(simClient, rezPacket.InventoryData.ItemID); + } + } + } + return true; + } + public bool ModifyTerrain(ClientView simClient, Packet packet) + { + ModifyLandPacket modify = (ModifyLandPacket)packet; + + switch (modify.ModifyBlock.Action) + { + case 1: + // raise terrain + if (modify.ParcelData.Length > 0) + { + Terrain.raise(modify.ParcelData[0].North, modify.ParcelData[0].West, 10.0, 0.1); + RegenerateTerrain(true, (int)modify.ParcelData[0].North, (int)modify.ParcelData[0].West); + } + break; + case 2: + //lower terrain + if (modify.ParcelData.Length > 0) + { + Terrain.lower(modify.ParcelData[0].North, modify.ParcelData[0].West, 10.0, 0.1); + RegenerateTerrain(true, (int)modify.ParcelData[0].North, (int)modify.ParcelData[0].West); + } + break; + } + return true; + } + */ + + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/World.Scripting.cs b/OpenSim/OpenSim.RegionServer/world/World.Scripting.cs new file mode 100644 index 0000000..44ef05a --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/World.Scripting.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Reflection; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using libsecondlife; + +namespace OpenSim.world +{ + public partial class World + { + private Dictionary scriptEngines = new Dictionary(); + + private void LoadScriptEngines() + { + this.LoadScriptPlugins(); + } + + public void LoadScriptPlugins() + { + string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ScriptEngines"); + string[] pluginFiles = Directory.GetFiles(path, "*.dll"); + + + for (int i = 0; i < pluginFiles.Length; i++) + { + this.AddPlugin(pluginFiles[i]); + } + } + + private void AddPlugin(string FileName) + { + Assembly pluginAssembly = Assembly.LoadFrom(FileName); + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("IScriptEngine", true); + + if (typeInterface != null) + { + IScriptEngine plug = (IScriptEngine)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + plug.Init(this); + this.scriptEngines.Add(plug.GetName(), plug); + + } + + typeInterface = null; + } + } + } + + pluginAssembly = null; + } + + public void LoadScript(string scriptType, string scriptName, string script, Entity ent) + { + if(this.scriptEngines.ContainsKey(scriptType)) + { + this.scriptEngines[scriptType].LoadScript(script, scriptName, ent.localid); + } + } + + #region IScriptAPI Methods + + public OSVector3 GetEntityPosition(uint localID) + { + OSVector3 res = new OSVector3(); + // Console.WriteLine("script- getting entity " + localID + " position"); + foreach (Entity entity in this.Entities.Values) + { + if (entity.localid == localID) + { + res.X = entity.Pos.X; + res.Y = entity.Pos.Y; + res.Z = entity.Pos.Z; + } + } + return res; + } + + public void SetEntityPosition(uint localID, float x , float y, float z) + { + foreach (Entity entity in this.Entities.Values) + { + if (entity.localid == localID && entity is Primitive) + { + LLVector3 pos = entity.Pos; + pos.X = x; + pos.Y = y; + Primitive prim = entity as Primitive; + // Of course, we really should have asked the physEngine if this is possible, and if not, returned false. + prim.UpdatePosition(pos); + // Console.WriteLine("script- setting entity " + localID + " positon"); + } + } + + } + + public uint GetRandomAvatarID() + { + //Console.WriteLine("script- getting random avatar id"); + uint res = 0; + foreach (Entity entity in this.Entities.Values) + { + if (entity is Avatar) + { + res = entity.localid; + } + } + return res; + } + + #endregion + + + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/World.cs b/OpenSim/OpenSim.RegionServer/world/World.cs new file mode 100644 index 0000000..921da3c --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/World.cs @@ -0,0 +1,656 @@ +using System; +using libsecondlife; +using libsecondlife.Packets; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Threading; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; +using OpenSim.Framework.Inventory; +using OpenSim.Assets; +//using OpenSim.world.scripting; +using OpenSim.RegionServer.world.scripting; +using OpenSim.Terrain; + +namespace OpenSim.world +{ + public partial class World : WorldBase, ILocalStorageReceiver, IScriptAPI + { + public object LockPhysicsEngine = new object(); + public Dictionary Avatars; + public Dictionary Prims; + //public ScriptEngine Scripts; + public uint _localNumber = 0; + private PhysicsScene phyScene; + private float timeStep = 0.1f; + public ILocalStorage localStorage; + private Random Rand = new Random(); + private uint _primCount = 702000; + private int storageCount; + private Dictionary m_scriptHandlers; + private Dictionary m_scripts; + private Mutex updateLock; + public string m_datastore; + + #region Properties + public PhysicsScene PhysScene + { + set + { + this.phyScene = value; + } + get + { + return (this.phyScene); + } + } + #endregion + + #region Constructors + /// + /// Creates a new World class, and a region to go with it. + /// + /// Dictionary to contain client threads + /// Region Handle for this region + /// Region Name for this region + public World(Dictionary clientThreads, RegionInfo regInfo, ulong regionHandle, string regionName) + { + try + { + updateLock = new Mutex(false); + m_clientThreads = clientThreads; + m_regionHandle = regionHandle; + m_regionName = regionName; + m_regInfo = regInfo; + + m_scriptHandlers = new Dictionary(); + m_scripts = new Dictionary(); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs - creating new entitities instance"); + Entities = new Dictionary(); + Avatars = new Dictionary(); + Prims = new Dictionary(); + + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs - creating LandMap"); + TerrainManager = new TerrainManager(new SecondLife()); + Terrain = new TerrainEngine(); + Avatar.SetupTemplate("avatar-texture.dat"); + // MainConsole.Instance.WriteLine("World.cs - Creating script engine instance"); + // Initialise this only after the world has loaded + // Scripts = new ScriptEngine(this); + Avatar.LoadAnims(); + this.SetDefaultScripts(); + this.LoadScriptEngines(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.CRITICAL, "World.cs: Constructor failed with exception " + e.ToString()); + } + } + #endregion + + #region Script Methods + /// + /// Loads a new script into the specified entity + /// + /// Entity to be scripted + /// The script to load + public void AddScript(Entity entity, Script script) + { + try + { + ScriptHandler scriptHandler = new ScriptHandler(script, entity, this); + m_scriptHandlers.Add(scriptHandler.ScriptId, scriptHandler); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: AddScript() - Failed with exception " + e.ToString()); + } + } + + /// + /// Loads a new script into the specified entity, using a script loaded from a string. + /// + /// The entity to be scripted + /// The string containing the script + public void AddScript(Entity entity, string scriptData) + { + try + { + int scriptstart = 0; + int scriptend = 0; + string substring; + scriptstart = scriptData.LastIndexOf(""); + substring = scriptData.Substring(scriptstart + 8, scriptend - scriptstart - 8); + substring = substring.Trim(); + //Console.WriteLine("searching for script to add: " + substring); + + ScriptFactory scriptFactory; + //Console.WriteLine("script string is " + substring); + if (substring.StartsWith("'); + string sName = substring1.Substring(0, end); + //Console.WriteLine(" script info : " + sEngine + " , " + sName); + int startscript = substring.IndexOf('>'); + script = substring.Remove(0, startscript + 1); + // Console.WriteLine("script data is " + script); + if (this.scriptEngines.ContainsKey(sEngine)) + { + this.scriptEngines[sEngine].LoadScript(script, sName, entity.localid); + } + } + else if (this.m_scripts.TryGetValue(substring, out scriptFactory)) + { + //Console.WriteLine("added script"); + this.AddScript(entity, scriptFactory()); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: AddScript() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Update Methods + /// + /// Performs per-frame updates on the world, this should be the central world loop + /// + public override void Update() + { + updateLock.WaitOne(); + try + { + if (this.phyScene.IsThreaded) + { + this.phyScene.GetResults(); + + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].addForces(); + } + + lock (this.LockPhysicsEngine) + { + this.phyScene.Simulate(timeStep); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].update(); + } + + foreach (ScriptHandler scriptHandler in m_scriptHandlers.Values) + { + scriptHandler.OnFrame(); + } + foreach (IScriptEngine scripteng in this.scriptEngines.Values) + { + scripteng.OnFrame(); + } + //backup world data + this.storageCount++; + if (storageCount > 1200) //set to how often you want to backup + { + this.Backup(); + storageCount = 0; + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: Update() - Failed with exception " + e.ToString()); + } + updateLock.ReleaseMutex(); + } + + public bool Backup() + { + try + { + // Terrain backup routines + if (Terrain.tainted > 0) + { + Terrain.tainted = 0; + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: Backup() - Terrain tainted, saving."); + localStorage.SaveMap(Terrain.getHeights1D()); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: Backup() - Terrain saved, informing Physics."); + phyScene.SetTerrain(Terrain.getHeights1D()); + } + + // Primitive backup routines + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: Backup() - Backing up Primitives"); + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].BackUp(); + } + + // Backup successful + return true; + } + catch (Exception e) + { + // Backup failed + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "World.cs: Backup() - Backup Failed with exception " + e.ToString()); + return false; + } + } + #endregion + + #region Setup Methods + /// + /// Loads a new storage subsystem from a named library + /// + /// Storage Library + /// Successful or not + public bool LoadStorageDLL(string dllName) + { + try + { + Assembly pluginAssembly = Assembly.LoadFrom(dllName); + ILocalStorage store = null; + + foreach (Type pluginType in pluginAssembly.GetTypes()) + { + if (pluginType.IsPublic) + { + if (!pluginType.IsAbstract) + { + Type typeInterface = pluginType.GetInterface("ILocalStorage", true); + + if (typeInterface != null) + { + ILocalStorage plug = (ILocalStorage)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); + store = plug; + + store.Initialise(this.m_datastore); + break; + } + + typeInterface = null; + } + } + } + pluginAssembly = null; + this.localStorage = store; + return (store == null); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: LoadStorageDLL() - Failed with exception " + e.ToString()); + return false; + } + } + + public void SetDefaultScripts() + { + this.m_scripts.Add("FollowRandomAvatar", delegate() + { + return new OpenSim.RegionServer.world.scripting.FollowRandomAvatar(); + }); + } + + #endregion + + #region Regenerate Terrain + + /// + /// Rebuilds the terrain using a procedural algorithm + /// + public void RegenerateTerrain() + { + try + { + Terrain.hills(); + + lock (this.LockPhysicsEngine) + { + this.phyScene.SetTerrain(Terrain.getHeights1D()); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + + foreach (ClientView client in m_clientThreads.Values) + { + this.SendLayerData(client); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "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.LockPhysicsEngine) + { + this.phyScene.SetTerrain(this.Terrain.getHeights1D()); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + + foreach (ClientView client in m_clientThreads.Values) + { + this.SendLayerData(client); + } + + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + Entities[UUID].LandRenegerated(); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "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) + { + lock (this.LockPhysicsEngine) + { + this.phyScene.SetTerrain(this.Terrain.getHeights1D()); + } + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + + foreach (ClientView client in m_clientThreads.Values) + { + this.SendLayerData(pointx, pointy, client); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: RegenerateTerrain() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Load Terrain + /// + /// Loads the World heightmap + /// + public override void LoadWorldMap() + { + try + { + float[] map = this.localStorage.LoadWorld(); + if (map == null) + { + Console.WriteLine("creating new terrain"); + this.Terrain.hills(); + + this.localStorage.SaveMap(this.Terrain.getHeights1D()); + } + else + { + this.Terrain.setHeights1D(map); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: LoadWorldMap() - Failed with exception " + e.ToString()); + } + } + #endregion + + #region Primitives Methods + + /// + /// Sends prims to a client + /// + /// Client to send to + public void GetInitialPrims(ClientView RemoteClient) + { + try + { + foreach (libsecondlife.LLUUID UUID in Entities.Keys) + { + if (Entities[UUID] is Primitive) + { + Primitive primitive = Entities[UUID] as Primitive; + primitive.UpdateClient(RemoteClient); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: GetInitialPrims() - Failed with exception " + e.ToString()); + } + } + + /// + /// Loads the World's objects + /// + public void LoadPrimsFromStorage() + { + try + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: LoadPrimsFromStorage() - Loading primitives"); + this.localStorage.LoadPrimitives(this); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: LoadPrimsFromStorage() - Failed with exception " + e.ToString()); + } + } + + /// + /// Loads a specific object from storage + /// + /// The object to load + public void PrimFromStorage(PrimData prim) + { + try + { + if (prim.LocalID >= this._primCount) + { + _primCount = prim.LocalID + 1; + } + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: PrimFromStorage() - Reloading prim (localId " + prim.LocalID + " ) from storage"); + Primitive nPrim = new Primitive(m_clientThreads, m_regionHandle, this); + nPrim.CreateFromStorage(prim); + this.Entities.Add(nPrim.uuid, nPrim); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: PrimFromStorage() - Failed with exception " + e.ToString()); + } + } + + public void AddNewPrim(Packet addPacket, ClientView agentClient) + { + AddNewPrim((ObjectAddPacket)addPacket, agentClient.AgentID); + } + + public void AddNewPrim(ObjectAddPacket addPacket, LLUUID ownerID) + { + try + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs: AddNewPrim() - Creating new prim"); + Primitive prim = new Primitive(m_clientThreads, m_regionHandle, this); + prim.CreateFromPacket(addPacket, ownerID, this._primCount); + PhysicsVector pVec = new PhysicsVector(prim.Pos.X, prim.Pos.Y, prim.Pos.Z); + PhysicsVector pSize = new PhysicsVector(0.255f, 0.255f, 0.255f); + if (OpenSim.world.Avatar.PhysicsEngineFlying) + { + lock (this.LockPhysicsEngine) + { + prim.PhysActor = this.phyScene.AddPrim(pVec, pSize); + } + } + + this.Entities.Add(prim.uuid, prim); + this._primCount++; + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: AddNewPrim() - Failed with exception " + e.ToString()); + } + } + + #endregion + + #region Add/Remove Avatar Methods + + public override void AddViewerAgent(ClientView agentClient) + { + //register for events + agentClient.OnChatFromViewer += new ChatFromViewer(this.SimChat); + agentClient.OnRezObject += new RezObject(this.RezObject); + agentClient.OnModifyTerrain += new ModifyTerrain(this.ModifyTerrain); + agentClient.OnRegionHandShakeReply += new ClientView.GenericCall(this.SendLayerData); + agentClient.OnRequestWearables += new ClientView.GenericCall(this.GetInitialPrims); + agentClient.OnRequestAvatarsData += new ClientView.GenericCall(this.SendAvatarsToClient); + agentClient.OnLinkObjects += new LinkObjects(this.LinkObjects); + agentClient.OnAddPrim += new ClientView.GenericCall4(this.AddNewPrim); + agentClient.OnUpdatePrimShape += new ClientView.UpdateShape(this.UpdatePrimShape); + agentClient.OnObjectSelect += new ClientView.ObjectSelect(this.SelectPrim); + agentClient.OnUpdatePrimFlags += new ClientView.UpdatePrimFlags(this.UpdatePrimFlags); + agentClient.OnUpdatePrimTexture += new ClientView.UpdatePrimTexture(this.UpdatePrimTexture); + agentClient.OnUpdatePrimPosition += new ClientView.UpdatePrimVector(this.UpdatePrimPosition); + agentClient.OnUpdatePrimRotation += new ClientView.UpdatePrimRotation(this.UpdatePrimRotation); + agentClient.OnUpdatePrimScale += new ClientView.UpdatePrimVector(this.UpdatePrimScale); + agentClient.OnDeRezObject += new ClientView.GenericCall4(this.DeRezObject); + + try + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs:AddViewerAgent() - Creating new avatar for remote viewer agent"); + Avatar newAvatar = new Avatar(agentClient, this, m_regionName, m_clientThreads, m_regionHandle, true, 20); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs:AddViewerAgent() - Adding new avatar to world"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "World.cs:AddViewerAgent() - Starting RegionHandshake "); + newAvatar.SendRegionHandshake(this); + if (!agentClient.m_child) + { + PhysicsVector pVec = new PhysicsVector(newAvatar.Pos.X, newAvatar.Pos.Y, newAvatar.Pos.Z); + lock (this.LockPhysicsEngine) + { + newAvatar.PhysActor = this.phyScene.AddAvatar(pVec); + } + } + lock (Entities) + { + if (!Entities.ContainsKey(agentClient.AgentID)) + { + this.Entities.Add(agentClient.AgentID, newAvatar); + } + else + { + Entities[agentClient.AgentID] = newAvatar; + } + } + lock (Avatars) + { + if (Avatars.ContainsKey(agentClient.AgentID)) + { + Avatars[agentClient.AgentID] = newAvatar; + } + else + { + this.Avatars.Add(agentClient.AgentID, newAvatar); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: AddViewerAgent() - Failed with exception " + e.ToString()); + } + } + + public override void RemoveViewerAgent(ClientView agentClient) + { + try + { + lock (Entities) + { + Entities.Remove(agentClient.AgentID); + } + lock (Avatars) + { + Avatars.Remove(agentClient.AgentID); + } + if (agentClient.ClientAvatar.PhysActor != null) + { + //this.phyScene.RemoveAvatar(agentClient.ClientAvatar.PhysActor); + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: RemoveViewerAgent() - Failed with exception " + e.ToString()); + } + } + #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. + + public List RequestAvatarList() + { + List result = new List(); + + foreach (Avatar avatar in Avatars.Values) + { + result.Add(avatar); + } + + return result; + } + #endregion + + #region ShutDown + /// + /// Tidy before shutdown + /// + public override void Close() + { + try + { + this.localStorage.ShutDown(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "World.cs: Close() - Failed with exception " + e.ToString()); + } + } + #endregion + + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/WorldBase.cs b/OpenSim/OpenSim.RegionServer/world/WorldBase.cs new file mode 100644 index 0000000..edc5518 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/WorldBase.cs @@ -0,0 +1,176 @@ +using System; +using libsecondlife; +using libsecondlife.Packets; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Threading; +using OpenSim.Physics.Manager; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; +using OpenSim.Framework.Inventory; +using OpenSim.Assets; +using OpenSim.RegionServer.world.scripting; +using OpenSim.Terrain; + +namespace OpenSim.world +{ + public class WorldBase + { + public Dictionary Entities; + protected Dictionary m_clientThreads; + protected ulong m_regionHandle; + protected string m_regionName; + protected InventoryCache _inventoryCache; + protected AssetCache _assetCache; + protected RegionInfo m_regInfo; + + public TerrainEngine Terrain; //TODO: Replace TerrainManager with this. + protected libsecondlife.TerrainManager TerrainManager; // To be referenced via TerrainEngine + + #region Properties + public InventoryCache InventoryCache + { + set + { + this._inventoryCache = value; + } + } + + public AssetCache AssetCache + { + set + { + this._assetCache = value; + } + } + #endregion + + #region Constructors + public WorldBase() + { + + } + #endregion + + #region Setup Methods + /// + /// Register Packet handler Methods with the packet server (which will register them with the SimClient) + /// + /// + public virtual void RegisterPacketHandlers(PacketServer packetServer) + { + + } + #endregion + + #region Update Methods + /// + /// Normally called once every frame/tick to let the world preform anything required (like running the physics simulation) + /// + public virtual void Update() + { + + } + #endregion + + #region Terrain Methods + + /// + /// Loads the World heightmap + /// + public virtual void LoadWorldMap() + { + + } + + /// + /// Send the region heightmap to the client + /// + /// Client to send to + public virtual void SendLayerData(ClientView RemoteClient) + { + 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(Terrain.getHeights1D(), patches); + RemoteClient.OutPacket(layerpack); + } + } + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: SendLayerData() - Failed with exception " + e.ToString()); + } + } + + /// + /// Sends a specified patch to a client + /// + /// Patch coordinate (x) 0..16 + /// Patch coordinate (y) 0..16 + /// The client to send to + public void SendLayerData(int px, int py, ClientView RemoteClient) + { + 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(Terrain.getHeights1D(), patches); + RemoteClient.OutPacket(layerpack); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "World.cs: SendLayerData() - Failed with exception " + e.ToString()); + } + } + #endregion + + #region Add/Remove Agent/Avatar + /// + /// Add a new Agent's avatar + /// + /// + public virtual void AddViewerAgent(ClientView agentClient) + { + + } + + /// + /// Remove a Agent's avatar + /// + /// + public virtual void RemoveViewerAgent(ClientView agentClient) + { + + } + #endregion + + #region Shutdown + /// + /// Tidy before shutdown + /// + public virtual void Close() + { + + } + #endregion + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/IScriptContext.cs b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptContext.cs new file mode 100644 index 0000000..465c23b --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptContext.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.RegionServer.world.scripting +{ + public interface IScriptContext + { + IScriptEntity Entity { get; } + bool TryGetRandomAvatar(out IScriptReadonlyEntity avatar); + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/IScriptEntity.cs b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptEntity.cs new file mode 100644 index 0000000..2ef16a4 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptEntity.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.RegionServer.world.scripting +{ + public interface IScriptReadonlyEntity + { + LLVector3 Pos { get; } + string Name { get; } + } + + public interface IScriptEntity + { + LLVector3 Pos { get; set; } + string Name { get; } + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/IScriptHandler.cs b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptHandler.cs new file mode 100644 index 0000000..15efc49 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/IScriptHandler.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; +using OpenSim.Physics.Manager; +using OpenSim.world; +using Avatar=OpenSim.world.Avatar; +using Primitive = OpenSim.world.Primitive; + +namespace OpenSim.RegionServer.world.scripting +{ + public delegate void ScriptEventHandler(IScriptContext context); + + public class ScriptHandler : IScriptContext, IScriptEntity, IScriptReadonlyEntity + { + private World m_world; + private Script m_script; + private Entity m_entity; + + public LLUUID ScriptId + { + get + { + return m_script.ScriptId; + } + } + + public void OnFrame() + { + m_script.OnFrame(this); + } + + public ScriptHandler(Script script, Entity entity, World world) + { + m_script = script; + m_entity = entity; + m_world = world; + } + + #region IScriptContext Members + + IScriptEntity IScriptContext.Entity + { + get + { + return this; + } + } + + bool IScriptContext.TryGetRandomAvatar(out IScriptReadonlyEntity avatar) + { + foreach (Entity entity in m_world.Entities.Values ) + { + if( entity is Avatar ) + { + avatar = entity; + return true; + } + } + + avatar = null; + return false; + } + + #endregion + + #region IScriptEntity and IScriptReadonlyEntity Members + + public string Name + { + get + { + return m_entity.Name; + } + } + + public LLVector3 Pos + { + get + { + return m_entity.Pos; + } + + set + { + if (m_entity is Primitive) + { + Primitive prim = m_entity as Primitive; + // Of course, we really should have asked the physEngine if this is possible, and if not, returned false. + prim.UpdatePosition( value ); + } + } + } + + #endregion + } + +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/Script.cs b/OpenSim/OpenSim.RegionServer/world/scripting/Script.cs new file mode 100644 index 0000000..48c18ff --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/Script.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.RegionServer.world.scripting +{ + public class Script + { + private LLUUID m_scriptId; + public virtual LLUUID ScriptId + { + get + { + return m_scriptId; + } + } + + public Script( LLUUID scriptId ) + { + m_scriptId = scriptId; + } + + public ScriptEventHandler OnFrame; + } +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/ScriptFactory.cs b/OpenSim/OpenSim.RegionServer/world/scripting/ScriptFactory.cs new file mode 100644 index 0000000..4c6d373 --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/ScriptFactory.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.RegionServer.world.scripting +{ + public delegate Script ScriptFactory(); +} diff --git a/OpenSim/OpenSim.RegionServer/world/scripting/Scripts/FollowRandomAvatar.cs b/OpenSim/OpenSim.RegionServer/world/scripting/Scripts/FollowRandomAvatar.cs new file mode 100644 index 0000000..6a689ab --- /dev/null +++ b/OpenSim/OpenSim.RegionServer/world/scripting/Scripts/FollowRandomAvatar.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Text; +using libsecondlife; + +namespace OpenSim.RegionServer.world.scripting +{ + public class FollowRandomAvatar : Script + { + public FollowRandomAvatar() + : base(LLUUID.Random()) + { + OnFrame += MyOnFrame; + } + + private void MyOnFrame(IScriptContext context) + { + LLVector3 pos = context.Entity.Pos; + + IScriptReadonlyEntity avatar; + + if (context.TryGetRandomAvatar(out avatar)) + { + LLVector3 avatarPos = avatar.Pos; + + float x = pos.X + ((float)avatarPos.X.CompareTo(pos.X)) / 2; + float y = pos.Y + ((float)avatarPos.Y.CompareTo(pos.Y)) / 2; + + LLVector3 newPos = new LLVector3(x, y, pos.Z); + + context.Entity.Pos = newPos; + } + } + } + + +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassInstance.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassInstance.cs new file mode 100644 index 0000000..15ef814 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassInstance.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class ClassInstance : Object + { + public int size; + public Dictionary Fields = new Dictionary(); + + public ClassInstance() + { + + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassRecord.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassRecord.cs new file mode 100644 index 0000000..f2f0da5 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/ClassRecord.cs @@ -0,0 +1,476 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.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/OpenSim.Scripting/EmbeddedJVM/Heap.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Heap.cs new file mode 100644 index 0000000..138e85e --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Heap.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class Heap + { + public List ClassObjects = new List(); + + public Heap() + { + + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Interpreter.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Interpreter.cs new file mode 100644 index 0000000..b94248c --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Interpreter.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; +using OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes; + +namespace OpenSim.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/OpenSim.Scripting/EmbeddedJVM/InterpreterLogic.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterLogic.cs new file mode 100644 index 0000000..3b7da35 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterLogic.cs @@ -0,0 +1,400 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; +using OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes; + +namespace OpenSim.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/OpenSim.Scripting/EmbeddedJVM/InterpreterMethods.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterMethods.cs new file mode 100644 index 0000000..c66c148 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterMethods.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; +using OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.Types; + +namespace OpenSim.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]); + //Console.WriteLine("call to method : "+refIndex); + if (this._mThread.currentClass._constantsPool[refIndex - 1] is ClassRecord.PoolMethodRef) + { + // Console.WriteLine("which is " + ((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value + "." + ((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value); + // Console.WriteLine("of type " + ((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Type.Value); + 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); + //Console.WriteLine("split is " + typeparam + " which is length " + typeparam.Length + " , " + typereturn); + 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 + + //for now we will have a built in OpenSimAPI class, but this should be a java class that then calls native methods + if (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mClass.Name.Value == "OpenSimAPI") + { + switch (((ClassRecord.PoolMethodRef)this._mThread.currentClass._constantsPool[refIndex - 1]).mNameType.Name.Value) + { + case "GetEntityID": + Int entityID = new Int(); + entityID.mValue =(int) this._mThread.EntityId; + this._mThread.currentFrame.OpStack.Push(entityID); + this._mThread.PC += 2; + break; + case "GetRandomAvatarID": + entityID = new Int(); + entityID.mValue = (int)Thread.OpenSimScriptAPI.GetRandomAvatarID(); + this._mThread.currentFrame.OpStack.Push(entityID); + this._mThread.PC += 2; + break; + case "GetEntityPositionX": + BaseType bs1 = this._mThread.currentFrame.OpStack.Pop(); + if (bs1 is Int) + { + //Console.WriteLine("get entity pos for " + ((Int)bs1).mValue); + //should get the position of the entity from the IScriptAPI + OSVector3 vec3 = Thread.OpenSimScriptAPI.GetEntityPosition((uint)((Int)bs1).mValue); + Float pos = new Float(); + pos.mValue = vec3.X; + // Console.WriteLine("returned x value " + vec3.X.ToString()); + this._mThread.currentFrame.OpStack.Push(pos); + } + this._mThread.PC += 2; + break; + case "GetEntityPositionY": + bs1 = this._mThread.currentFrame.OpStack.Pop(); + if (bs1 is Int) + { + //should get the position of the entity from the IScriptAPI + OSVector3 vec3 = Thread.OpenSimScriptAPI.GetEntityPosition((uint)((Int)bs1).mValue); + Float pos = new Float(); + pos.mValue = vec3.Y; + this._mThread.currentFrame.OpStack.Push(pos); + } + this._mThread.PC += 2; + break; + case "GetEntityPositionZ": + bs1 = this._mThread.currentFrame.OpStack.Pop(); + if (bs1 is Int) + { + //should get the position of the entity from the IScriptAPI + OSVector3 vec3 = Thread.OpenSimScriptAPI.GetEntityPosition((uint)((Int)bs1).mValue); + Float pos = new Float(); + pos.mValue = vec3.Z; + this._mThread.currentFrame.OpStack.Push(pos); + } + this._mThread.PC += 2; + break; + case "SetEntityPosition": + //pop the three float values and the entity id + BaseType ft3 = this._mThread.currentFrame.OpStack.Pop(); + BaseType ft2 = this._mThread.currentFrame.OpStack.Pop(); + BaseType ft1 = this._mThread.currentFrame.OpStack.Pop(); + BaseType in1 = this._mThread.currentFrame.OpStack.Pop(); + if (ft1 is Float && ft2 is Float && ft3 is Float) + { + if(in1 is Int) + { + //Console.WriteLine("set: " + ((Int)in1).mValue + " , " + ((Float)ft1).mValue + " , " + ((Float)ft2).mValue + " , " + ((Float)ft3).mValue); + Thread.OpenSimScriptAPI.SetEntityPosition((uint)((Int) in1).mValue, ((Float)ft1).mValue, ((Float)ft2).mValue, ((Float)ft3).mValue); + } + } + this._mThread.PC += 2; + break; + } + } + } + } + else + { + this._mThread.PC += 2; + } + result = true; + break; + } + + return result; + } + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterReturn.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterReturn.cs new file mode 100644 index 0000000..6704e31 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/InterpreterReturn.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + partial class Thread + { + private partial class Interpreter + { + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/MainMemory.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/MainMemory.cs new file mode 100644 index 0000000..ff18f90 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/MainMemory.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class MainMemory + { + public Heap HeapArea; + public MethodMemory MethodArea; + + public MainMemory() + { + MethodArea = new MethodMemory(); + HeapArea = new Heap(); + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/MethodMemory.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/MethodMemory.cs new file mode 100644 index 0000000..2541991 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/MethodMemory.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.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/OpenSim.Scripting/EmbeddedJVM/Object.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Object.cs new file mode 100644 index 0000000..e6e392c --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Object.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class Object + { + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj new file mode 100644 index 0000000..a1e95f4 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj @@ -0,0 +1,153 @@ + + + Local + 8.0.50727 + 2.0 + {97A82740-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Scripting.EmbeddedJVM + JScript + Grid + IE50 + false + Library + + OpenSim.Scripting.EmbeddedJVM + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ScriptEngines\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ScriptEngines\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj.user b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.dll.build b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.dll.build new file mode 100644 index 0000000..ae79c83 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSim.Scripting.EmbeddedJVM.dll.build @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSimJVM.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSimJVM.cs new file mode 100644 index 0000000..b47bb50 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/OpenSimJVM.cs @@ -0,0 +1,134 @@ +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; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class OpenSimJVM : IScriptEngine + { + private List _threads = new List(); + private BlockingQueue CompileScripts = new BlockingQueue(); + private MainMemory _mainMemory; + private System.Threading.Thread compileThread; + + public OpenSimJVM() + { + + } + + public bool Init(IScriptAPI api) + { + Console.WriteLine("Creating OpenSim JVM scripting engine"); + _mainMemory = new MainMemory(); + Thread.GlobalMemory = this._mainMemory; + Thread.OpenSimScriptAPI = api; + compileThread = new System.Threading.Thread(new ThreadStart(CompileScript)); + compileThread.IsBackground = true; + compileThread.Start(); + return true; + } + + public string GetName() + { + return "OpenSimJVM"; + } + + public void LoadScript(string script, string scriptName, uint entityID) + { + Console.WriteLine("OpenSimJVM - loading new script: " + scriptName); + CompileInfo comp = new CompileInfo(); + comp.entityId = entityID; + comp.script = script; + comp.scriptName = scriptName; + this.CompileScripts.Enqueue(comp); + } + + public void CompileScript() + { + while (true) + { + CompileInfo comp = this.CompileScripts.Dequeue(); + string script = comp.script; + string scriptName = comp.scriptName; + uint entityID = comp.entityId; + 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.EntityId = entityID; + newThread.currentClass = class1; + + //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); + } + } + } + + public void 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(); + } + } + } + } + + private class CompileInfo + { + public string script; + public string scriptName; + public uint entityId; + + public CompileInfo() + { + + } + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Properties/AssemblyInfo.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..53a0f08 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Scripting.EmbeddedJVM")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Scripting.EmbeddedJVM")] +[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("087c0917-5a6a-4b47-a4dd-0928dd85bd4b")] + +// 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/OpenSim.Scripting/EmbeddedJVM/Stack.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Stack.cs new file mode 100644 index 0000000..d77d82e --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Stack.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public class Stack + { + public Stack StackFrames = new Stack(); + + public Stack() + { + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/StackFrame.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/StackFrame.cs new file mode 100644 index 0000000..afca7a9 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/StackFrame.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; + +namespace OpenSim.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/OpenSim.Scripting/EmbeddedJVM/Thread.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Thread.cs new file mode 100644 index 0000000..436949c --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Thread.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.Scripting.EmbeddedJVM.Types; +using OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes; +using OpenSim.Framework; +using OpenSim.Framework.Interfaces; + +namespace OpenSim.Scripting.EmbeddedJVM +{ + public partial class Thread + { + public static MainMemory GlobalMemory; + public static IScriptAPI OpenSimScriptAPI; + 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 uint EntityId = 0; + + 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/OpenSim.Scripting/EmbeddedJVM/Types/ArrayReference.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ArrayReference.cs new file mode 100644 index 0000000..2854eab --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ArrayReference.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types +{ + public class ArrayReference :BaseType + { + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/BaseType.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/BaseType.cs new file mode 100644 index 0000000..270aa7b --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/BaseType.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types +{ + public class BaseType : Object + { + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ObjectReference.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ObjectReference.cs new file mode 100644 index 0000000..da28eaa --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/ObjectReference.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types +{ + public class ObjectReference : BaseType + { + public ushort Reference; + + public ObjectReference() + { + + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Byte.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Byte.cs new file mode 100644 index 0000000..1a3ecff --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Byte.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Byte : BaseType + { + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Char.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Char.cs new file mode 100644 index 0000000..19002d4 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Char.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Char : BaseType + { + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Float.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Float.cs new file mode 100644 index 0000000..91f1679 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Float.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Float : BaseType + { + public float mValue = 0; + + public Float() + { + + } + } +} diff --git a/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Int.cs b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Int.cs new file mode 100644 index 0000000..4ecd325 --- /dev/null +++ b/OpenSim/OpenSim.Scripting/EmbeddedJVM/Types/PrimitiveTypes/Int.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Scripting.EmbeddedJVM.Types.PrimitiveTypes +{ + public class Int : BaseType + { + public int mValue = 0; + + public Int() + { + + } + } +} diff --git a/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs new file mode 100644 index 0000000..d4db8c0 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/BDBLocalStorage.cs @@ -0,0 +1,95 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +// BDB Support +// Apparently broken on Mono + +using System; +using System.Collections.Generic; +using System.Data; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; +using BerkeleyDb; +using Kds.Serialization; +using Kds.Serialization.Buffer; + +namespace OpenSim.Storage.LocalStorageBDB +{ + public class BDBLocalStorage : ILocalStorage + { + const string simDbName = "localsim.db"; + + DbHash sim; + Db DB; + //BEFormatter formatter; + + public BDBLocalStorage() + { + DB = new Db(DbCreateFlags.None); + sim = (DbHash)DB.Open(null, simDbName, null, BerkeleyDb.DbType.Hash, Db.OpenFlags.Create, 0); + //vendorDb = (DbBTree)db.Open(null, VendorDbName, null, DbType.BTree, Db.OpenFlags.Create, 0); + } + + public void Initialise(string file) + { + // Blank + } + + public void StorePrim(PrimData prim) + { + DbEntry key = new DbEntry(); + DbEntry data = new DbEntry(); + lock (sim) + { + sim.PutUnique(null, ref key, ref data, DbFile.WriteFlags.AutoCommit); + } + } + public void RemovePrim(LLUUID primID) + { + + } + public void LoadPrimitives(ILocalStorageReceiver receiver) + { + + } + public float[] LoadWorld() + { + return new float[65536]; + } + public void SaveMap(float[] heightmap) + { + + } + public void ShutDown() + { + sim.GetDb().Close(); + DB.Close(); + } + } +} \ No newline at end of file diff --git a/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj new file mode 100644 index 0000000..12c5016 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj @@ -0,0 +1,112 @@ + + + Local + 8.0.50727 + 2.0 + {EE9E5D96-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Storage.LocalStorageBerkeleyDB + JScript + Grid + IE50 + false + Library + + OpenSim.Storage.LocalStorageBerkeleyDB + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + System.Data.dll + False + + + ..\..\bin\Kds.Serialization.dll + False + + + ..\..\bin\libdb_dotNET43.dll + False + + + ..\..\bin\libsecondlife.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj.user b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build new file mode 100644 index 0000000..885b088 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageBerkeleyDB/OpenSim.Storage.LocalStorageBerkeleyDB.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/AssemblyInfo.cs b/OpenSim/OpenSim.Storage/LocalStorageDb4o/AssemblyInfo.cs new file mode 100644 index 0000000..6610606 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("Db4LocalStorage")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Db4LocalStorage")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("1.0.*")] diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/Db4LocalStorage.cs b/OpenSim/OpenSim.Storage/LocalStorageDb4o/Db4LocalStorage.cs new file mode 100644 index 0000000..5dceb7f --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/Db4LocalStorage.cs @@ -0,0 +1,182 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ +using System; +using System.Collections.Generic; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + /// + /// + /// + public class Db4LocalStorage : ILocalStorage + { + private IObjectContainer db; + private string datastore; + + public Db4LocalStorage() + { + + } + + public void Initialise(string dfile) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"Db4LocalStorage Opening " + dfile); + datastore = dfile; + try + { + db = Db4oFactory.OpenFile(datastore); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"Db4LocalStorage creation"); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"Db4LocalStorage :Constructor - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,e.ToString()); + } + } + + public void StorePrim(PrimData prim) + { + IObjectSet result = db.Query(new UUIDQuery(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.Texture = prim.Texture; + db.Set(found); + db.Commit(); + } + else + { + //not in storage + db.Set(prim); + db.Commit(); + } + } + + public void RemovePrim(LLUUID primID) + { + IObjectSet result = db.Query(new UUIDQuery(primID)); + if(result.Count>0) + { + PrimData found = (PrimData) result.Next(); + db.Delete(found); + } + } + + + public void LoadPrimitives(ILocalStorageReceiver receiver) + { + IObjectSet result = db.Get(typeof(PrimData)); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"Db4LocalStorage.cs: LoadPrimitives() - number of prims in storages is "+result.Count); + foreach (PrimData prim in result) { + receiver.PrimFromStorage(prim); + } + } + + public float[] LoadWorld() + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"LoadWorld() - Loading world...."); + //World blank = new World(); + float[] heightmap = null; + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"LoadWorld() - Looking for a heightmap in local DB"); + IObjectSet world_result = db.Get(typeof(MapStorage)); + if (world_result.Count > 0) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"LoadWorld() - Found a heightmap in local database, loading"); + MapStorage map = (MapStorage)world_result.Next(); + //blank.LandMap = map.Map; + heightmap = map.Map; + } + else + { + /* + OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LoadWorld() - No heightmap found, generating new one"); + HeightmapGenHills hills = new HeightmapGenHills(); + // blank.LandMap = hills.GenerateHeightmap(200, 4.0f, 80.0f, false); + // heightmap = hills.GenerateHeightmap(200, 4.0f, 80.0f, false); + heightmap = new float[256, 256]; + OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LoadWorld() - Saving heightmap to local database"); + MapStorage map = new MapStorage(); + map.Map = heightmap; //blank.LandMap; + db.Set(map); + db.Commit(); + */ + } + return heightmap; + } + + public void SaveMap(float[] heightmap) + { + IObjectSet world_result = db.Get(typeof(MapStorage)); + if (world_result.Count > 0) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.LOW,"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 ShutDown() + { + db.Commit(); + db.Close(); + } + } +} diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/MapStorage.cs b/OpenSim/OpenSim.Storage/LocalStorageDb4o/MapStorage.cs new file mode 100644 index 0000000..db590ff --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/MapStorage.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + public class MapStorage + { + public float[] Map; + + public MapStorage() + { + + } + } +} \ No newline at end of file diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj new file mode 100644 index 0000000..6504b77 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj @@ -0,0 +1,113 @@ + + + Local + 8.0.50727 + 2.0 + {E1B79ECF-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Storage.LocalStorageDb4o + JScript + Grid + IE50 + false + Library + + OpenSim.Storage.LocalStorageDb4o + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\..\bin\Db4objects.Db4o.dll + False + + + ..\..\bin\libsecondlife.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj.user b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.dll.build b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.dll.build new file mode 100644 index 0000000..8be321d --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/OpenSim.Storage.LocalStorageDb4o.dll.build @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageDb4o/UUIDQuery.cs b/OpenSim/OpenSim.Storage/LocalStorageDb4o/UUIDQuery.cs new file mode 100644 index 0000000..ba9e139 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageDb4o/UUIDQuery.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Db4objects.Db4o; +using Db4objects.Db4o.Query; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; + +namespace OpenSim.Storage.LocalStorageDb4o +{ + public class UUIDQuery : Predicate + { + private LLUUID _findID; + + public UUIDQuery(LLUUID find) + { + _findID = find; + } + public bool Match(PrimData prim) + { + return (prim.FullID == _findID); + } + } +} diff --git a/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj new file mode 100644 index 0000000..8039721 --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj @@ -0,0 +1,111 @@ + + + Local + 8.0.50727 + 2.0 + {6B20B603-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Storage.LocalStorageSQLite + JScript + Grid + IE50 + false + Library + + OpenSim.Storage.LocalStorageSQLite + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + System.Data.dll + False + + + ..\..\bin\System.Data.SQLite.dll + False + + + ..\..\bin\libsecondlife.dll + False + + + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj.user b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build new file mode 100644 index 0000000..79c27fc --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageSQLite/OpenSim.Storage.LocalStorageSQLite.dll.build @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs b/OpenSim/OpenSim.Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fe81f8a --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageSQLite/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Storage.LocalStorageSQLite")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Storage.LocalStorageSQLite")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ecd6e0c1-7909-413e-9e3f-659678ac3bc3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.*")] +[assembly: AssemblyFileVersion("1.0.0.*")] diff --git a/OpenSim/OpenSim.Storage/LocalStorageSQLite/SQLiteLocalStorage.cs b/OpenSim/OpenSim.Storage/LocalStorageSQLite/SQLiteLocalStorage.cs new file mode 100644 index 0000000..368405b --- /dev/null +++ b/OpenSim/OpenSim.Storage/LocalStorageSQLite/SQLiteLocalStorage.cs @@ -0,0 +1,176 @@ +/* +* Copyright (c) OpenSim project, http://sim.opensecondlife.org/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +// SQLite Support +// A bad idea, but the IRC people told me to! + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SQLite; +using libsecondlife; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.Framework.Terrain; + +namespace OpenSim.Storage.LocalStorageSQLite +{ + public class SQLiteLocalStorage : ILocalStorage + { + IDbConnection db; + + public SQLiteLocalStorage() + { + try + { + string connectionstring = "URI=file:localsim.sdb"; + db = (IDbConnection)new SQLiteConnection(connectionstring); + db.Open(); + } + catch (Exception e) + { + db.Close(); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"SQLiteLocalStorage :Constructor - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,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.Texture.ToString() + "\","; + sql += "\"" + prim.CreationDate.ToString() + "\","; + sql += "\"" + prim.OwnerMask.ToString() + "\","; + sql += "\"" + prim.NextOwnerMask.ToString() + "\","; + sql += "\"" + prim.GroupMask.ToString() + "\","; + sql += "\"" + prim.EveryoneMask.ToString() + "\","; + sql += "\"" + prim.BaseMask.ToString() + "\","; + sql += "\"" + prim.Position.ToString() + "\","; + sql += "\"" + prim.Rotation.ToString() + "\","; + sql += "\"" + prim.LocalID.ToString() + "\","; + sql += "\"" + prim.FullID.ToString() + "\")"; + + cmd.CommandText = sql; + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"SQLiteLocalStorage :StorePrim - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,e.ToString()); + } + + cmd.Dispose(); + cmd = null; + } + + public void RemovePrim(LLUUID primID) + { + IDbCommand cmd = db.CreateCommand(); + + //SECURITY WARNING: + // These parameters wont produce SQL injections since they are all integer based, however. + // if inserting strings such as name or description, you will need to use appropriate + // measures to prevent SQL injection (although the value of SQL injection in this is limited). + + string sql = "DELETE FROM prim WHERE FullID = \"" + primID.ToStringHyphenated() + "\""; + + cmd.CommandText = sql; + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,"SQLiteLocalStorage :RemovePrim - Exception occured"); + OpenSim.Framework.Console.MainConsole.Instance.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM,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 ShutDown() + { + db.Close(); + db = null; + } + } +} \ No newline at end of file diff --git a/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj new file mode 100644 index 0000000..1cdfaf6 --- /dev/null +++ b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj @@ -0,0 +1,95 @@ + + + Local + 8.0.50727 + 2.0 + {2270B8FE-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim.Terrain.BasicTerrain + JScript + Grid + IE50 + false + Library + + OpenSim.Terrain.BasicTerrain + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\bin\ + False + False + False + 4 + + + + + ..\bin\libTerrain-BSD.dll + False + + + System.dll + False + + + System.Data.dll + False + + + System.Xml.dll + False + + + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj.user b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj.user new file mode 100644 index 0000000..d47d65d --- /dev/null +++ b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.csproj.user @@ -0,0 +1,12 @@ + + + Debug + AnyCPU + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.dll.build b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.dll.build new file mode 100644 index 0000000..e1a3d2d --- /dev/null +++ b/OpenSim/OpenSim.Terrain.BasicTerrain/OpenSim.Terrain.BasicTerrain.dll.build @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim.Terrain.BasicTerrain/Properties/AssemblyInfo.cs b/OpenSim/OpenSim.Terrain.BasicTerrain/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bd74993 --- /dev/null +++ b/OpenSim/OpenSim.Terrain.BasicTerrain/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Terrain.BasicTerrain")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OpenSim.Terrain.BasicTerrain")] +[assembly: AssemblyCopyright("Copyright © 2007")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3263f5b5-0a41-4ed5-91a2-9baaaeecc849")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/OpenSim.Terrain.BasicTerrain/TerrainEngine.cs b/OpenSim/OpenSim.Terrain.BasicTerrain/TerrainEngine.cs new file mode 100644 index 0000000..a0f37f9 --- /dev/null +++ b/OpenSim/OpenSim.Terrain.BasicTerrain/TerrainEngine.cs @@ -0,0 +1,453 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using libTerrain; + +namespace OpenSim.Terrain +{ + public class TerrainEngine + { + /// + /// A [normally] 256x256 heightmap + /// + public Channel heightmap; + + /// + /// Whether or not the terrain has been modified since it was last saved and sent to the Physics engine. + /// Counts the number of modifications since the last save. (0 = Untainted) + /// + public int tainted; + + int w, h; + + /// + /// Generate a new TerrainEngine instance and creates a new heightmap + /// + public TerrainEngine() + { + w = 256; + h = 256; + heightmap = new Channel(w, h); + + tainted++; + } + + /// + /// Converts the heightmap to a 65536 value 1D floating point array + /// + /// A float[65536] array containing the heightmap + public float[] getHeights1D() + { + float[] heights = new float[w * h]; + int i; + + for (i = 0; i < w * h; i++) + { + heights[i] = (float)heightmap.map[i / w, i % w]; + } + + return heights; + } + + /// + /// Converts the heightmap to a 256x256 value 2D floating point array. + /// + /// An array of 256,256 values containing the heightmap + public float[,] getHeights2D() + { + float[,] heights = new float[w, h]; + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heights[x, y] = (float)heightmap.map[x, y]; + } + } + return heights; + } + + /// + /// Imports a 1D floating point array into the 2D heightmap array + /// + /// The array to import (must have 65536 members) + public void setHeights1D(float[] heights) + { + int i; + for (i = 0; i < w * h; i++) + { + heightmap.map[i / w, i % w] = heights[i]; + } + + tainted++; + } + + /// + /// Loads a 2D array of values into the heightmap + /// + /// An array of 256,256 float values + public void setHeights2D(float[,] heights) + { + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.set(x,y,(double)heights[x,y]); + } + } + tainted++; + } + + /// + /// Processes a terrain-specific command + /// + /// Commandline arguments (space seperated) + /// Reference that returns error or help text if returning false + /// If the operation was successful (if not, the error is placed into resultText) + public bool RunTerrainCmd(string[] args, ref string resultText) + { + string command = args[0]; + + try + { + + switch (command) + { + case "help": + resultText += "terrain regenerate - rebuilds the sims terrain using a default algorithm\n"; + resultText += "terrain seed - sets the random seed value to \n"; + resultText += "terrain load - loads a terrain from disk, type can be 'F32', 'F64' or 'IMG'\n"; + resultText += "terrain save - saves a terrain to disk, type can be 'F32' or 'F64'\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"; + return false; + + case "seed": + setSeed(Convert.ToInt32(args[1])); + break; + + case "erode": + 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; + } + break; + + case "regenerate": + hills(); + break; + + case "rescale": + setRange(Convert.ToSingle(args[1]), Convert.ToSingle(args[2])); + break; + + case "multiply": + heightmap *= Convert.ToDouble(args[1]); + break; + + case "load": + switch (args[1].ToLower()) + { + case "f32": + loadFromFileF32(args[2]); + break; + + case "f64": + loadFromFileF64(args[2]); + break; + + case "img": + resultText = "Error - IMG mode is presently unsupported."; + return false; + + default: + resultText = "Unknown image or data format"; + return false; + } + break; + + case "save": + switch (args[1].ToLower()) + { + case "f32": + writeToFileF32(args[2]); + break; + + case "f64": + writeToFileF64(args[2]); + break; + + case "grdmap": + exportImage(args[2], args[3]); + break; + + default: + resultText = "Unknown image or data format"; + return false; + } + break; + + default: + resultText = "Unknown terrain command"; + return false; + } + return true; + } + catch (Exception e) + { + resultText = "Error running terrain command: " + e.ToString(); + return false; + } + } + + /// + /// Renormalises the array between min and max + /// + /// Minimum value of the new array + /// Maximum value of the new array + public void setRange(float min, float max) + { + heightmap.normalise((double)min, (double)max); + tainted++; + } + + /// + /// Loads a file consisting of 256x256 doubles and imports it as an array into the map. + /// + /// TODO: Move this to libTerrain itself + /// The filename of the double array to import + public void loadFromFileF64(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); + System.IO.BinaryReader bs = new System.IO.BinaryReader(s); + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.map[x, y] = bs.ReadDouble(); + } + } + + bs.Close(); + s.Close(); + + tainted++; + } + + /// + /// Loads a file consisting of 256x256 floats and imports it as an array into the map. + /// + /// TODO: Move this to libTerrain itself + /// The filename of the float array to import + public void loadFromFileF32(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); + System.IO.BinaryReader bs = new System.IO.BinaryReader(s); + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + heightmap.map[x, y] = (double)bs.ReadSingle(); + } + } + + bs.Close(); + s.Close(); + + tainted++; + } + + /// + /// Writes the current terrain heightmap to disk, in the format of a 65536 entry double[] array. + /// + /// The desired output filename + public void writeToFileF64(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); + System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s); + + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + bs.Write(heightmap.get(x,y)); + } + } + + bs.Close(); + s.Close(); + } + + /// + /// Writes the current terrain heightmap to disk, in the format of a 65536 entry float[] array + /// + /// The desired output filename + public void writeToFileF32(string filename) + { + System.IO.FileInfo file = new System.IO.FileInfo(filename); + System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); + System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s); + + int x, y; + for (x = 0; x < w; x++) + { + for (y = 0; y < h; y++) + { + bs.Write((float)heightmap.get(x, y)); + } + } + + bs.Close(); + s.Close(); + } + + /// + /// Sets the random seed to be used by procedural functions which involve random numbers. + /// + /// The desired seed + public void setSeed(int val) + { + heightmap.seed = val; + } + + /// + /// Raises land in a sphere around the specified coordinates + /// + /// Center of the sphere on the X axis + /// Center of the sphere on the Y axis + /// The radius of the sphere + /// Scale the height of the sphere by this amount (recommended 0..2) + public void raise(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + heightmap.raise(rx, ry, size, amount); + } + + tainted++; + } + + /// + /// Lowers the land in a sphere around the specified coordinates + /// + /// The center of the sphere at the X axis + /// The center of the sphere at the Y axis + /// The radius of the sphere in meters + /// Scale the height of the sphere by this amount (recommended 0..2) + public void lower(double rx, double ry, double size, double amount) + { + lock (heightmap) + { + heightmap.lower(rx, ry, size, amount); + } + + tainted++; + } + + /// + /// Generates a simple set of hills in the shape of an island + /// + public void hills() + { + lock (heightmap) + { + heightmap.hillsSpheres(200, 20, 40, true, true, false); + heightmap.normalise(); + heightmap *= 60.0; // Raise to 60m + } + + tainted++; + } + + /// + /// Multiplies the heightfield by val + /// + /// The heightfield + /// The multiplier + /// + public static TerrainEngine operator *(TerrainEngine meep, Double val) { + meep.heightmap *= val; + meep.tainted++; + return meep; + } + + /// + /// Returns the height at the coordinates x,y + /// + /// X Coordinate + /// Y Coordinate + /// + public float this[int x, int y] + { + get + { + return (float)heightmap.get(x,y); + } + set + { + tainted++; + heightmap.set(x,y,(double)value); + } + } + + /// + /// Exports the current heightmap to a PNG file + /// + /// The destination filename for the image + /// A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal. + public void exportImage(string filename, string gradientmap) + { + try + { + Bitmap gradientmapLd = new Bitmap(gradientmap); + + int pallete = gradientmapLd.Width; + + Bitmap bmp = new Bitmap(heightmap.w, heightmap.h); + Color[] colours = new Color[pallete]; + + for (int i = 0; i < pallete; i++) + { + colours[i] = gradientmapLd.GetPixel(1, i); + } + + Channel copy = heightmap.copy(); + for (int x = 0; x < copy.w; x++) + { + for (int y = 0; y < copy.h; y++) + { + // 512 is the largest possible height before colours clamp + int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(x, y) / 512.0), 0.0) * pallete); + bmp.SetPixel(x, y, colours[colorindex]); + } + } + + bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png); + } + catch (Exception e) + { + Console.WriteLine("Failed generating terrain map: " + e.ToString()); + } + } + } +} diff --git a/OpenSim/OpenSim/Application.cs b/OpenSim/OpenSim/Application.cs new file mode 100644 index 0000000..3f9c0ec --- /dev/null +++ b/OpenSim/OpenSim/Application.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenSim.UserServer; +using OpenSim.Framework.Console; + +namespace OpenSim +{ + public class Application + { + //could move our main function into OpenSimMain and kill this class + [STAThread] + public static void Main(string[] args) + { + Console.WriteLine("OpenSim " + VersionInfo.Version + "\n"); + Console.WriteLine("Starting...\n"); + + bool sandBoxMode = false; + bool startLoginServer = false; + string physicsEngine = "basicphysics"; + bool allowFlying = false; + bool userAccounts = false; + bool gridLocalAsset = false; + bool useConfigFile = false; + bool silent = false; + string configFile = "simconfig.xml"; + + for (int i = 0; i < args.Length; i++) + { + if (args[i] == "-sandbox") + { + sandBoxMode = true; + startLoginServer = true; + } + /* + if (args[i] == "-loginserver") + { + startLoginServer = true; + }*/ + if (args[i] == "-accounts") + { + userAccounts = true; + } + if (args[i] == "-realphysx") + { + physicsEngine = "RealPhysX"; + allowFlying = true; + } + if (args[i] == "-ode") + { + physicsEngine = "OpenDynamicsEngine"; + allowFlying = true; + } + if (args[i] == "-localasset") + { + gridLocalAsset = true; + } + if (args[i] == "-configfile") + { + useConfigFile = true; + } + if (args[i] == "-noverbose") + { + silent = true; + } + if (args[i] == "-config") + { + try + { + i++; + configFile = args[i]; + } + catch (Exception e) + { + Console.WriteLine("-config: Please specify a config file. (" + e.ToString() + ")"); + } + } + } + + OpenSimMain sim = new OpenSimMain(sandBoxMode, startLoginServer, physicsEngine, useConfigFile, silent, configFile); + // OpenSimRoot.Instance.Application = sim; + sim.m_sandbox = sandBoxMode; + sim.user_accounts = userAccounts; + sim.gridLocalAsset = gridLocalAsset; + OpenSim.world.Avatar.PhysicsEngineFlying = allowFlying; + + sim.StartUp(); + + while (true) + { + OpenSim.Framework.Console.MainConsole.Instance.MainConsolePrompt(); + } + } + } +} diff --git a/OpenSim/OpenSim/OpenSim.csproj b/OpenSim/OpenSim/OpenSim.csproj new file mode 100644 index 0000000..4456fc7 --- /dev/null +++ b/OpenSim/OpenSim/OpenSim.csproj @@ -0,0 +1,147 @@ + + + Local + 8.0.50727 + 2.0 + {438A9556-0000-0000-0000-000000000000} + Debug + AnyCPU + + + + OpenSim + JScript + Grid + IE50 + false + Exe + + OpenSim + + + + + + False + 285212672 + False + + + TRACE;DEBUG + + True + 4096 + False + ..\bin\ + False + False + False + 4 + + + + False + 285212672 + False + + + TRACE + + False + 4096 + True + ..\bin\ + False + False + False + 4 + + + + + System.dll + False + + + System.Xml.dll + False + + + ..\bin\libsecondlife.dll + False + + + ..\bin\Axiom.MathLib.dll + False + + + ..\bin\Db4objects.Db4o.dll + False + + + + + OpenSim.Terrain.BasicTerrain + {2270B8FE-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework + {8ACA2445-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Framework.Console + {A7CD0630-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Physics.Manager + {8BE16150-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.Servers + {8BB20F0A-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.RegionServer + {632E1BFD-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + OpenSim.GenericConfig.Xml + {E88EF749-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + XMLRPC + {8E81D43C-0000-0000-0000-000000000000} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + False + + + + + Code + + + Code + + + + + + + + + + diff --git a/OpenSim/OpenSim/OpenSim.csproj.user b/OpenSim/OpenSim/OpenSim.csproj.user new file mode 100644 index 0000000..1422ebf --- /dev/null +++ b/OpenSim/OpenSim/OpenSim.csproj.user @@ -0,0 +1,13 @@ + + + Debug + AnyCPU + -loginserver -sandbox -accounts + C:\New Folder\second-life-viewer\opensim-dailys2\opensim15-07\bin\ + 8.0.50727 + ProjectFiles + 0 + + + + diff --git a/OpenSim/OpenSim/OpenSim.exe.build b/OpenSim/OpenSim/OpenSim.exe.build new file mode 100644 index 0000000..19d0b28 --- /dev/null +++ b/OpenSim/OpenSim/OpenSim.exe.build @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/OpenSim/OpenSimMain.cs b/OpenSim/OpenSim/OpenSimMain.cs new file mode 100644 index 0000000..9025316 --- /dev/null +++ b/OpenSim/OpenSim/OpenSimMain.cs @@ -0,0 +1,533 @@ +/* +Copyright (c) OpenSim project, http://osgrid.org/ + +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +using System; +using System.Text; +using System.IO; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Timers; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using libsecondlife; +using libsecondlife.Packets; +using OpenSim.world; +using OpenSim.Terrain; +using OpenSim.Framework.Interfaces; +using OpenSim.Framework.Types; +using OpenSim.UserServer; +using OpenSim.Assets; +using OpenSim.CAPS; +using OpenSim.Framework.Console; +using OpenSim.Physics.Manager; +using Nwc.XmlRpc; +using OpenSim.Servers; +using OpenSim.GenericConfig; + +namespace OpenSim +{ + + public class OpenSimMain : RegionServerBase, conscmd_callback + { + private CheckSumServer checkServer; + + 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_console = new ConsoleBase("region-console-" + Guid.NewGuid().ToString() + ".log", "Region", this, silent); + OpenSim.Framework.Console.MainConsole.Instance = m_console; + } + + /// + /// Performs initialisation of the world, such as loading configuration from disk. + /// + public override void StartUp() + { + this.regionData = new RegionInfo(); + try + { + this.localConfig = new XmlConfig(m_config); + this.localConfig.LoadData(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + if (this.configFileSetup) + { + this.SetupFromConfigFile(this.localConfig); + } + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Loading configuration"); + this.regionData.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 + + GridServers = new Grid(); + if (m_sandbox) + { + this.SetupLocalGridServers(); + //Authenticate Session Handler + AuthenticateSessionsLocal authen = new AuthenticateSessionsLocal(); + this.AuthenticateSessionsHandler = authen; + this.checkServer = new CheckSumServer(12036); + this.checkServer.ServerListener(); + } + else + { + this.SetupRemoteGridServers(); + //Authenticate Session Handler + AuthenticateSessionsRemote authen = new AuthenticateSessionsRemote(); + this.AuthenticateSessionsHandler = authen; + } + + startuptime = DateTime.Now; + + try + { + AssetCache = new AssetCache(GridServers.AssetServer); + InventoryCache = new InventoryCache(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup local cache"); + Environment.Exit(1); + } + + m_udpServer = new UDPServer(this.regionData.IPListenPort, this.GridServers, this.AssetCache, this.InventoryCache, this.regionData, this.m_sandbox, this.user_accounts, this.m_console, this.AuthenticateSessionsHandler); + + //should be passing a IGenericConfig object to these so they can read the config data they want from it + GridServers.AssetServer.SetServerInfo(regionData.AssetURL, regionData.AssetSendKey); + IGridServer gridServer = GridServers.GridServer; + gridServer.SetServerInfo(regionData.GridURL, regionData.GridSendKey, regionData.GridRecvKey); + + if (!m_sandbox) + { + this.ConnectToRemoteGridServer(); + } + + this.SetupLocalWorld(); + + if (m_sandbox) + { + AssetCache.LoadDefaultTextureSet(); + } + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Initialising HTTP server"); + + this.SetupHttpListener(); + + //Login server setup + LoginServer loginServer = null; + LoginServer adminLoginServer = null; + + bool sandBoxWithLoginServer = m_loginserver && m_sandbox; + if (sandBoxWithLoginServer) + { + loginServer = new LoginServer(regionData.IPListenAddr, regionData.IPListenPort, regionData.RegionLocX, regionData.RegionLocY, this.user_accounts); + loginServer.Startup(); + loginServer.SetSessionHandler(((AuthenticateSessionsLocal)this.AuthenticateSessionsHandler).AddNewSession); + + if (user_accounts) + { + //sandbox mode with loginserver using accounts + this.GridServers.UserServer = loginServer; + adminLoginServer = loginServer; + + httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.LocalUserManager.XmlRpcLoginMethod); + } + else + { + //sandbox mode with loginserver not using accounts + httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.XmlRpcLoginMethod); + } + } + + //Web front end setup + AdminWebFront adminWebFront = new AdminWebFront("Admin", LocalWorld, InventoryCache, adminLoginServer); + adminWebFront.LoadMethods(httpServer); + + //Start http server + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Starting HTTP server"); + httpServer.Start(); + + // Start UDP server + this.m_udpServer.ServerListener(); + + m_heartbeatTimer.Enabled = true; + m_heartbeatTimer.Interval = 100; + m_heartbeatTimer.Elapsed += new ElapsedEventHandler(this.Heartbeat); + } + + # region Setup methods + protected override void SetupLocalGridServers() + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll"; + GridServers.GridDll = "OpenSim.GridInterfaces.Local.dll"; + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Starting in Sandbox mode"); + + try + { + GridServers.Initialise(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup the grid interface"); + Environment.Exit(1); + } + } + + protected override void SetupRemoteGridServers() + { + if (this.gridLocalAsset) + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll"; + } + else + { + GridServers.AssetDll = "OpenSim.GridInterfaces.Remote.dll"; + } + GridServers.GridDll = "OpenSim.GridInterfaces.Remote.dll"; + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Starting in Grid mode"); + + try + { + GridServers.Initialise(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, e.Message + "\nSorry, could not setup the grid interface"); + Environment.Exit(1); + } + } + + protected override void SetupLocalWorld() + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.NORMAL, "Main.cs:Startup() - We are " + regionData.RegionName + " at " + regionData.RegionLocX.ToString() + "," + regionData.RegionLocY.ToString()); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Initialising world"); + m_console.componentname = "Region " + regionData.RegionName; + + m_localWorld = new World(this.m_udpServer.PacketServer.ClientThreads, regionData, regionData.RegionHandle, regionData.RegionName); + LocalWorld.InventoryCache = InventoryCache; + LocalWorld.AssetCache = AssetCache; + + this.m_udpServer.LocalWorld = LocalWorld; + this.m_udpServer.PacketServer.RegisterClientPacketHandlers(); + + this.physManager = new OpenSim.Physics.Manager.PhysicsManager(); + this.physManager.LoadPlugins(); + + LocalWorld.m_datastore = this.regionData.DataStore; + + LocalWorld.LoadStorageDLL("OpenSim.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded. + LocalWorld.LoadWorldMap(); + + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Starting up messaging system"); + LocalWorld.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); + LocalWorld.PhysScene.SetTerrain(LocalWorld.Terrain.getHeights1D()); + LocalWorld.LoadPrimsFromStorage(); + } + + protected override void SetupHttpListener() + { + httpServer = new BaseHttpServer(regionData.IPListenPort); + + if (this.GridServers.GridServer.GetName() == "Remote") + { + + // we are in Grid mode so set a XmlRpc handler to handle "expect_user" calls from the user server + httpServer.AddXmlRPCHandler("expect_user", ((AuthenticateSessionsRemote)this.AuthenticateSessionsHandler).ExpectUser); + + httpServer.AddXmlRPCHandler("agent_crossing", + delegate(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + uint circuitcode = Convert.ToUInt32(requestData["circuit_code"]); + + AgentCircuitData agent_data = new AgentCircuitData(); + agent_data.firstname = (string)requestData["firstname"]; + agent_data.lastname = (string)requestData["lastname"]; + agent_data.circuitcode = circuitcode; + agent_data.startpos = new LLVector3(Single.Parse((string)requestData["pos_x"]), Single.Parse((string)requestData["pos_y"]), Single.Parse((string)requestData["pos_z"])); + + AuthenticateSessionsHandler.UpdateAgentData(agent_data); + + return new XmlRpcResponse(); + }); + + httpServer.AddRestHandler("GET", "/simstatus/", + delegate(string request, string path, string param) + { + return "OK"; + }); + } + } + + protected override void ConnectToRemoteGridServer() + { + if (GridServers.GridServer.RequestConnection(regionData.SimUUID, regionData.IPListenAddr, (uint)regionData.IPListenPort)) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Startup() - Success: Got a grid connection OK!"); + } + else + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.CRITICAL, "Main.cs:Startup() - FAILED: Unable to get connection to grid. Shutting down."); + Shutdown(); + } + + GridServers.AssetServer.SetServerInfo((string)((RemoteGridBase)GridServers.GridServer).GridData["asset_url"], (string)((RemoteGridBase)GridServers.GridServer).GridData["asset_sendkey"]); + + // If we are being told to load a file, load it. + string dataUri = (string)((RemoteGridBase)GridServers.GridServer).GridData["data_uri"]; + + if (!String.IsNullOrEmpty(dataUri)) + { + this.LocalWorld.m_datastore = dataUri; + } + + if (((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString() != "") + { + // The grid server has told us who we are + // We must obey the grid server. + try + { + regionData.RegionLocX = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locx"].ToString()); + regionData.RegionLocY = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locy"].ToString()); + regionData.RegionName = ((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString(); + } + catch (Exception e) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.CRITICAL, e.Message + "\nBAD ERROR! THIS SHOULD NOT HAPPEN! Bad GridData from the grid interface!!!! ZOMG!!!"); + Environment.Exit(1); + } + } + } + + #endregion + + private void SetupFromConfigFile(IGenericConfig configData) + { + try + { + // SandBoxMode + string 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_console.WriteLine(OpenSim.Framework.Console.LogPriority.MEDIUM, "Main.cs: SetupFromConfig() - Invalid value for PhysicsEngine attribute, terminating"); + Environment.Exit(1); + break; + + case "": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.world.Avatar.PhysicsEngineFlying = false; + break; + + case "basicphysics": + this.m_physicsEngine = "basicphysics"; + configData.SetAttribute("PhysicsEngine", "basicphysics"); + OpenSim.world.Avatar.PhysicsEngineFlying = false; + break; + + case "RealPhysX": + this.m_physicsEngine = "RealPhysX"; + OpenSim.world.Avatar.PhysicsEngineFlying = true; + break; + + case "OpenDynamicsEngine": + this.m_physicsEngine = "OpenDynamicsEngine"; + OpenSim.world.Avatar.PhysicsEngineFlying = true; + break; + } + + configData.Commit(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine("\nSorry, a fatal error occurred while trying to initialise the configuration data"); + Console.WriteLine("Can not continue starting up"); + Environment.Exit(1); + } + } + + /// + /// Performs any last-minute sanity checking and shuts down the region server + /// + public virtual void Shutdown() + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Closing all threads"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Killing listener thread"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Killing clients"); + // IMPLEMENT THIS + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.LOW, "Main.cs:Shutdown() - Closing console and terminating"); + LocalWorld.Close(); + GridServers.Close(); + m_console.Close(); + Environment.Exit(0); + } + + /// + /// Performs per-frame updates regularly + /// + /// + /// + void Heartbeat(object sender, System.EventArgs e) + { + LocalWorld.Update(); + } + + #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_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "show users - show info about connected users"); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "shutdown - disconnect all clients and shutdown"); + break; + + case "show": + Show(cmdparams[0]); + break; + + case "terrain": + string result = ""; + if (!LocalWorld.Terrain.RunTerrainCmd(cmdparams, ref result)) + { + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, result); + } + break; + + case "shutdown": + Shutdown(); + break; + + default: + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "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_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "OpenSim has been running since " + startuptime.ToString()); + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, "That is " + (DateTime.Now - startuptime).ToString()); + break; + case "users": + OpenSim.world.Avatar TempAv; + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP")); + foreach (libsecondlife.LLUUID UUID in LocalWorld.Entities.Keys) + { + if (LocalWorld.Entities[UUID].ToString() == "OpenSim.world.Avatar") + { + TempAv = (OpenSim.world.Avatar)LocalWorld.Entities[UUID]; + m_console.WriteLine(OpenSim.Framework.Console.LogPriority.HIGH, String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.SessionID, TempAv.ControllingClient.CircuitCode, TempAv.ControllingClient.userEP.ToString())); + } + } + break; + } + } + #endregion + } + + +} \ No newline at end of file -- cgit v1.1