aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region')
-rw-r--r--OpenSim/Region/Application/Application.cs1
-rw-r--r--OpenSim/Region/Application/ConfigurationLoader.cs53
-rw-r--r--OpenSim/Region/Application/HGCommands.cs60
-rw-r--r--[-rwxr-xr-x]OpenSim/Region/Application/OpenSim.cs150
-rw-r--r--OpenSim/Region/Application/OpenSimBase.cs43
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs1
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs353
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLFileTransfer.cs4
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs35
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs47
-rw-r--r--OpenSim/Region/ClientStack/RegionApplicationBase.cs15
-rw-r--r--OpenSim/Region/Communications/Hypergrid/HGCommunicationsGridMode.cs60
-rw-r--r--OpenSim/Region/Communications/Hypergrid/HGCommunicationsStandalone.cs68
-rw-r--r--OpenSim/Region/Communications/Hypergrid/HGUserDataPlugin.cs72
-rw-r--r--OpenSim/Region/Communications/Hypergrid/HGUserServices.cs337
-rw-r--r--OpenSim/Region/Communications/Local/CommunicationsLocal.cs59
-rw-r--r--OpenSim/Region/Communications/Local/LocalUserServices.cs100
-rw-r--r--OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs65
-rw-r--r--OpenSim/Region/Communications/OGS1/OGS1UserDataPlugin.cs774
-rw-r--r--OpenSim/Region/Communications/OGS1/OGS1UserServices.cs176
-rw-r--r--OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs65
-rw-r--r--OpenSim/Region/CoreModules/Agent/AssetTransaction/AgentAssetsTransactions.cs5
-rw-r--r--OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs4
-rw-r--r--OpenSim/Region/CoreModules/Agent/TextureDownload/TextureDownloadModule.cs6
-rw-r--r--OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs61
-rw-r--r--OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs2
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs13
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs440
-rw-r--r--OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs46
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs77
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs69
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs1376
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs293
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Gestures/GesturesModule.cs2
-rw-r--r--OpenSim/Region/CoreModules/Avatar/InstantMessage/InstantMessageModule.cs60
-rw-r--r--OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs117
-rw-r--r--OpenSim/Region/CoreModules/Avatar/InstantMessage/MuteListModule.cs70
-rw-r--r--OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs81
-rw-r--r--OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs398
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs20
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs24
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs60
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs958
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Inventory/Transfer/InventoryTransferModule.cs60
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Lure/LureModule.cs64
-rw-r--r--OpenSim/Region/CoreModules/Avatar/ObjectCaps/ObjectAdd.cs2
-rw-r--r--OpenSim/Region/CoreModules/Avatar/Profiles/AvatarProfilesModule.cs168
-rw-r--r--OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs1609
-rw-r--r--OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs280
-rw-r--r--OpenSim/Region/CoreModules/Framework/InventoryAccess/HGAssetMapper.cs200
-rw-r--r--OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs (renamed from OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.Inventory.cs)129
-rw-r--r--OpenSim/Region/CoreModules/Framework/InventoryAccess/HGUuidGatherer.cs (renamed from OpenSim/Region/Framework/Scenes/Hypergrid/HGUuidGatherer.cs)3
-rw-r--r--OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs660
-rw-r--r--OpenSim/Region/CoreModules/Framework/Library/LibraryModule.cs77
-rw-r--r--OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs6
-rw-r--r--OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs311
-rw-r--r--OpenSim/Region/CoreModules/InterGrid/OGSRadmin.cs19
-rw-r--r--OpenSim/Region/CoreModules/InterGrid/OpenGridProtocolModule.cs44
-rw-r--r--OpenSim/Region/CoreModules/LightShare/LightShareModule.cs (renamed from OpenSim/Region/CoreModules/World/Meta7Windlight/Meta7WindlightModule.cs)185
-rw-r--r--OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml39
-rw-r--r--OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs23
-rw-r--r--OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs12
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs5
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs119
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs119
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs (renamed from OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/HypergridServiceInConnectorModule.cs)23
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs8
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs128
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs28
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs20
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/RemoteAssetServiceConnector.cs2
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/LocalAuthenticationServiceConnector.cs164
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/RemoteAuthenticationServiceConnector.cs (renamed from OpenSim/Region/CoreModules/ServiceConnectorsOut/User/LocalUserServiceConnector.cs)47
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs6
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/LocalAvatarServiceConnector.cs168
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/RemoteAvatarServiceConnector.cs (renamed from OpenSim/Region/CoreModules/ServiceConnectorsOut/User/RemoteUserServiceConnector.cs)18
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGCommands.cs303
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGGridConnector.cs811
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs16
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs24
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs6
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs116
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs178
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs153
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/RESTInterregionComms.cs842
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/BaseInventoryConnector.cs11
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs623
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs54
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs119
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs26
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs303
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs199
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs103
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs159
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs115
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs (renamed from OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/LocalInterregionComms.cs)185
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs305
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/LocalUserAccountServiceConnector.cs190
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/RemoteUserAccountServiceConnector.cs155
-rw-r--r--OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/UserAccountCache.cs95
-rw-r--r--OpenSim/Region/CoreModules/World/Access/AccessModule.cs1
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs80
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs14
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/ArchiverModule.cs19
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/AssetsDearchiver.cs2
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs23
-rw-r--r--OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs6
-rw-r--r--OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs160
-rw-r--r--OpenSim/Region/CoreModules/World/Estate/EstateTerrainXferHandler.cs2
-rw-r--r--OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs333
-rw-r--r--OpenSim/Region/CoreModules/World/Land/LandObject.cs88
-rw-r--r--OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs222
-rw-r--r--OpenSim/Region/CoreModules/World/Sound/SoundModule.cs34
-rw-r--r--OpenSim/Region/CoreModules/World/Sun/SunModule.cs9
-rw-r--r--OpenSim/Region/CoreModules/World/Wind/WindModule.cs12
-rw-r--r--OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs7
-rw-r--r--OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs27
-rw-r--r--OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs94
-rw-r--r--OpenSim/Region/DataSnapshot/DataSnapshotManager.cs24
-rw-r--r--OpenSim/Region/DataSnapshot/EstateSnapshot.cs15
-rw-r--r--OpenSim/Region/DataSnapshot/LandSnapshot.cs7
-rw-r--r--OpenSim/Region/DataSnapshot/ObjectSnapshot.cs62
-rw-r--r--OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs20
-rw-r--r--OpenSim/Region/Examples/SimpleModule/RegionModule.cs10
-rw-r--r--OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs140
-rw-r--r--OpenSim/Region/Framework/Interfaces/IDialogModule.cs12
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEntityInventory.cs5
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs (renamed from OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs)46
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs8
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEstateModule.cs7
-rw-r--r--OpenSim/Region/Framework/Interfaces/IFriendsModule.cs16
-rw-r--r--OpenSim/Region/Framework/Interfaces/IGroupsMessagingModule.cs73
-rw-r--r--OpenSim/Region/Framework/Interfaces/IGroupsModule.cs39
-rw-r--r--OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs (renamed from OpenSim/Region/Framework/Interfaces/ITeleportModule.cs)16
-rw-r--r--OpenSim/Region/Framework/Interfaces/IInventoryArchiverModule.cs4
-rw-r--r--OpenSim/Region/Framework/Interfaces/IPresenceModule.cs10
-rw-r--r--OpenSim/Region/Framework/Interfaces/IRegionArchiverModule.cs12
-rw-r--r--OpenSim/Region/Framework/Interfaces/IRegionDataStore.cs4
-rw-r--r--OpenSim/Region/Framework/Interfaces/IRegionModule.cs3
-rw-r--r--OpenSim/Region/Framework/Interfaces/IScriptModule.cs8
-rw-r--r--OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs13
-rw-r--r--OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs5
-rw-r--r--OpenSim/Region/Framework/Scenes/EventManager.cs55
-rw-r--r--OpenSim/Region/Framework/Scenes/Hypergrid/HGAssetMapper.cs265
-rw-r--r--OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.cs77
-rw-r--r--OpenSim/Region/Framework/Scenes/Hypergrid/HGSceneCommunicationService.cs391
-rw-r--r--OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.Inventory.cs875
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs77
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.cs1249
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneBase.cs28
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs1243
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneGraph.cs407
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneManager.cs33
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs12
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs93
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs165
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs146
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs330
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneViewer.cs1
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs1
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs5
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs12
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs14
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs8
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs9
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs6
-rw-r--r--OpenSim/Region/Framework/Scenes/UuidGatherer.cs48
-rw-r--r--OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs20
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs6
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Chat/IRCBridgeModule.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs4
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs41
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs274
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs336
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs66
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs1390
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs402
-rw-r--r--OpenSim/Region/OptionalModules/Scripting/Minimodule/Graphics.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs8
-rw-r--r--OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs6
-rw-r--r--OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs24
-rw-r--r--OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs19
-rw-r--r--OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs16
-rw-r--r--OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs4
-rw-r--r--OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETCharacter.cs33
-rw-r--r--OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETPrim.cs102
-rw-r--r--OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs99
-rw-r--r--OpenSim/Region/Physics/Meshing/PrimMesher.cs132
-rw-r--r--OpenSim/Region/Physics/Meshing/SculptMap.cs176
-rw-r--r--OpenSim/Region/Physics/Meshing/SculptMesh.cs146
-rw-r--r--OpenSim/Region/Physics/OdePlugin/ODEPrim.cs4
-rw-r--r--OpenSim/Region/RegionCombinerModule/RegionCombinerModule.cs25
-rw-r--r--OpenSim/Region/ScriptEngine/Interfaces/IScriptInstance.cs3
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs49
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs229
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs56
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs122
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs29
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Constants.cs2
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs2
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs11
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Instance/ScriptInstance.cs249
-rw-r--r--OpenSim/Region/ScriptEngine/XEngine/XEngine.cs18
-rw-r--r--OpenSim/Region/UserStatistics/ActiveConnectionsAJAX.cs14
209 files changed, 14705 insertions, 13227 deletions
diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs
index 555baa4..7721cdf 100644
--- a/OpenSim/Region/Application/Application.cs
+++ b/OpenSim/Region/Application/Application.cs
@@ -129,7 +129,6 @@ namespace OpenSim
129 configSource.AddSwitch("Startup", "inifile"); 129 configSource.AddSwitch("Startup", "inifile");
130 configSource.AddSwitch("Startup", "inimaster"); 130 configSource.AddSwitch("Startup", "inimaster");
131 configSource.AddSwitch("Startup", "inidirectory"); 131 configSource.AddSwitch("Startup", "inidirectory");
132 configSource.AddSwitch("Startup", "gridmode");
133 configSource.AddSwitch("Startup", "physics"); 132 configSource.AddSwitch("Startup", "physics");
134 configSource.AddSwitch("Startup", "gui"); 133 configSource.AddSwitch("Startup", "gui");
135 configSource.AddSwitch("Startup", "console"); 134 configSource.AddSwitch("Startup", "console");
diff --git a/OpenSim/Region/Application/ConfigurationLoader.cs b/OpenSim/Region/Application/ConfigurationLoader.cs
index 21edcc5..cac5fa9 100644
--- a/OpenSim/Region/Application/ConfigurationLoader.cs
+++ b/OpenSim/Region/Application/ConfigurationLoader.cs
@@ -42,6 +42,8 @@ namespace OpenSim
42 /// </summary> 42 /// </summary>
43 public class ConfigurationLoader 43 public class ConfigurationLoader
44 { 44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
45 /// <summary> 47 /// <summary>
46 /// Various Config settings the region needs to start 48 /// Various Config settings the region needs to start
47 /// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor, 49 /// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
@@ -61,17 +63,6 @@ namespace OpenSim
61 protected NetworkServersInfo m_networkServersInfo; 63 protected NetworkServersInfo m_networkServersInfo;
62 64
63 /// <summary> 65 /// <summary>
64 /// Console logger
65 /// </summary>
66 private static readonly ILog m_log =
67 LogManager.GetLogger(
68 MethodBase.GetCurrentMethod().DeclaringType);
69
70 public ConfigurationLoader()
71 {
72 }
73
74 /// <summary>
75 /// Loads the region configuration 66 /// Loads the region configuration
76 /// </summary> 67 /// </summary>
77 /// <param name="argvSource">Parameters passed into the process when started</param> 68 /// <param name="argvSource">Parameters passed into the process when started</param>
@@ -164,12 +155,12 @@ namespace OpenSim
164 m_config.Source = new IniConfigSource(); 155 m_config.Source = new IniConfigSource();
165 m_config.Source.Merge(DefaultConfig()); 156 m_config.Source.Merge(DefaultConfig());
166 157
167 m_log.Info("[CONFIG] Reading configuration settings"); 158 m_log.Info("[CONFIG]: Reading configuration settings");
168 159
169 if (sources.Count == 0) 160 if (sources.Count == 0)
170 { 161 {
171 m_log.FatalFormat("[CONFIG] Could not load any configuration"); 162 m_log.FatalFormat("[CONFIG]: Could not load any configuration");
172 m_log.FatalFormat("[CONFIG] Did you copy the OpenSim.ini.example file to OpenSim.ini?"); 163 m_log.FatalFormat("[CONFIG]: Did you copy the OpenSim.ini.example file to OpenSim.ini?");
173 Environment.Exit(1); 164 Environment.Exit(1);
174 } 165 }
175 166
@@ -182,13 +173,12 @@ namespace OpenSim
182 173
183 if (!iniFileExists) 174 if (!iniFileExists)
184 { 175 {
185 m_log.FatalFormat("[CONFIG] Could not load any configuration"); 176 m_log.FatalFormat("[CONFIG]: Could not load any configuration");
186 m_log.FatalFormat("[CONFIG] Configuration exists, but there was an error loading it!"); 177 m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!");
187 Environment.Exit(1); 178 Environment.Exit(1);
188 } 179 }
189 180
190 // Make sure command line options take precedence 181 // Make sure command line options take precedence
191 //
192 m_config.Source.Merge(argvSource); 182 m_config.Source.Merge(argvSource);
193 183
194 ReadConfigSettings(); 184 ReadConfigSettings();
@@ -257,20 +247,17 @@ namespace OpenSim
257 247
258 if (!IsUri(iniPath)) 248 if (!IsUri(iniPath))
259 { 249 {
260 m_log.InfoFormat("[CONFIG] Reading configuration file {0}", 250 m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath));
261 Path.GetFullPath(iniPath));
262 251
263 m_config.Source.Merge(new IniConfigSource(iniPath)); 252 m_config.Source.Merge(new IniConfigSource(iniPath));
264 success = true; 253 success = true;
265 } 254 }
266 else 255 else
267 { 256 {
268 m_log.InfoFormat("[CONFIG] {0} is a http:// URI, fetching ...", 257 m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath);
269 iniPath);
270 258
271 // The ini file path is a http URI 259 // The ini file path is a http URI
272 // Try to read it 260 // Try to read it
273 //
274 try 261 try
275 { 262 {
276 XmlReader r = XmlReader.Create(iniPath); 263 XmlReader r = XmlReader.Create(iniPath);
@@ -281,7 +268,7 @@ namespace OpenSim
281 } 268 }
282 catch (Exception e) 269 catch (Exception e)
283 { 270 {
284 m_log.FatalFormat("[CONFIG] Exception reading config from URI {0}\n" + e.ToString(), iniPath); 271 m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath);
285 Environment.Exit(1); 272 Environment.Exit(1);
286 } 273 }
287 } 274 }
@@ -304,7 +291,6 @@ namespace OpenSim
304 291
305 config.Set("region_info_source", "filesystem"); 292 config.Set("region_info_source", "filesystem");
306 293
307 config.Set("gridmode", false);
308 config.Set("physics", "OpenDynamicsEngine"); 294 config.Set("physics", "OpenDynamicsEngine");
309 config.Set("meshing", "Meshmerizer"); 295 config.Set("meshing", "Meshmerizer");
310 config.Set("physical_prim", true); 296 config.Set("physical_prim", true);
@@ -342,19 +328,7 @@ namespace OpenSim
342 if (null == config) 328 if (null == config)
343 config = defaultConfig.AddConfig("Network"); 329 config = defaultConfig.AddConfig("Network");
344 330
345 config.Set("default_location_x", 1000);
346 config.Set("default_location_y", 1000);
347 config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort); 331 config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
348 config.Set("remoting_listener_port", ConfigSettings.DefaultRegionRemotingPort);
349 config.Set("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString());
350 config.Set("grid_send_key", "null");
351 config.Set("grid_recv_key", "null");
352 config.Set("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
353 config.Set("user_send_key", "null");
354 config.Set("user_recv_key", "null");
355 config.Set("asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString());
356 config.Set("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString());
357 config.Set("secure_inventory_server", "true");
358 } 332 }
359 333
360 return defaultConfig; 334 return defaultConfig;
@@ -368,7 +342,6 @@ namespace OpenSim
368 IConfig startupConfig = m_config.Source.Configs["Startup"]; 342 IConfig startupConfig = m_config.Source.Configs["Startup"];
369 if (startupConfig != null) 343 if (startupConfig != null)
370 { 344 {
371 m_configSettings.Standalone = !startupConfig.GetBoolean("gridmode", false);
372 m_configSettings.PhysicsEngine = startupConfig.GetString("physics"); 345 m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
373 m_configSettings.MeshEngineName = startupConfig.GetString("meshing"); 346 m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
374 m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true); 347 m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
@@ -376,12 +349,6 @@ namespace OpenSim
376 m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true); 349 m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
377 350
378 m_configSettings.StorageDll = startupConfig.GetString("storage_plugin"); 351 m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
379 if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll")
380 {
381 m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll";
382 m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll.");
383 Thread.Sleep(3000);
384 }
385 352
386 m_configSettings.StorageConnectionString 353 m_configSettings.StorageConnectionString
387 = startupConfig.GetString("storage_connection_string"); 354 = startupConfig.GetString("storage_connection_string");
diff --git a/OpenSim/Region/Application/HGCommands.cs b/OpenSim/Region/Application/HGCommands.cs
deleted file mode 100644
index 7ae161d..0000000
--- a/OpenSim/Region/Application/HGCommands.cs
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using System.Xml;
32using log4net;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Console;
37using OpenSim.Region.Framework;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Region.Framework.Scenes.Hypergrid;
40
41namespace OpenSim
42{
43 public class HGCommands
44 {
45// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 public static Scene CreateScene(RegionInfo regionInfo, AgentCircuitManager circuitManager, CommunicationsManager m_commsManager,
48 StorageManager storageManager, ModuleLoader m_moduleLoader, ConfigSettings m_configSettings, OpenSimConfigSource m_config, string m_version)
49 {
50 HGSceneCommunicationService sceneGridService = new HGSceneCommunicationService(m_commsManager);
51
52 return
53 new HGScene(
54 regionInfo, circuitManager, m_commsManager, sceneGridService, storageManager,
55 m_moduleLoader, false, m_configSettings.PhysicalPrim,
56 m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
57 }
58
59 }
60}
diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs
index 05e283e..1395030 100755..100644
--- a/OpenSim/Region/Application/OpenSim.cs
+++ b/OpenSim/Region/Application/OpenSim.cs
@@ -122,8 +122,7 @@ namespace OpenSim
122 m_log.Info("===================================================================="); 122 m_log.Info("====================================================================");
123 m_log.Info("========================= STARTING OPENSIM ========================="); 123 m_log.Info("========================= STARTING OPENSIM =========================");
124 m_log.Info("===================================================================="); 124 m_log.Info("====================================================================");
125 m_log.InfoFormat("[OPENSIM MAIN]: Running in {0} mode", 125 m_log.InfoFormat("[OPENSIM MAIN]: Running ");
126 (ConfigurationSettings.Standalone ? "sandbox" : "grid"));
127 //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); 126 //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
128 // http://msdn.microsoft.com/en-us/library/bb384202.aspx 127 // http://msdn.microsoft.com/en-us/library/bb384202.aspx
129 //GCSettings.LatencyMode = GCLatencyMode.Batch; 128 //GCSettings.LatencyMode = GCLatencyMode.Batch;
@@ -153,6 +152,11 @@ namespace OpenSim
153 RegisterConsoleCommands(); 152 RegisterConsoleCommands();
154 153
155 base.StartupSpecific(); 154 base.StartupSpecific();
155
156 MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
157 MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
158 if (userStatsURI != String.Empty)
159 MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));
156 160
157 if (m_console is RemoteConsole) 161 if (m_console is RemoteConsole)
158 { 162 {
@@ -247,8 +251,9 @@ namespace OpenSim
247 "Save named prim to XML2", SavePrimsXml2); 251 "Save named prim to XML2", SavePrimsXml2);
248 252
249 m_console.Commands.AddCommand("region", false, "load oar", 253 m_console.Commands.AddCommand("region", false, "load oar",
250 "load oar [--merge] <oar name>", 254 "load oar [--merge] [--skip-assets] <oar name>",
251 "Load a region's data from OAR archive", LoadOar); 255 "Load a region's data from OAR archive. --merge will merge the oar with the existing scene. --skip-assets will load the oar but ignore the assets it contains",
256 LoadOar);
252 257
253 m_console.Commands.AddCommand("region", false, "save oar", 258 m_console.Commands.AddCommand("region", false, "save oar",
254 "save oar <oar name>", 259 "save oar <oar name>",
@@ -350,25 +355,6 @@ namespace OpenSim
350 "kill uuid <UUID>", 355 "kill uuid <UUID>",
351 "Kill an object by UUID", KillUUID); 356 "Kill an object by UUID", KillUUID);
352 357
353 if (ConfigurationSettings.Standalone)
354 {
355 m_console.Commands.AddCommand("region", false, "create user",
356 "create user [<first> [<last> [<pass> [<x> <y> [<email>]]]]]",
357 "Create a new user", HandleCreateUser);
358
359 m_console.Commands.AddCommand("region", false, "reset user password",
360 "reset user password [<first> [<last> [<password>]]]",
361 "Reset a user password", HandleResetUserPassword);
362 }
363
364 m_console.Commands.AddCommand("hypergrid", false, "link-mapping", "link-mapping [<x> <y>] <cr>",
365 "Set local coordinate to map HG regions to", RunCommand);
366 m_console.Commands.AddCommand("hypergrid", false, "link-region",
367 "link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>] <cr>",
368 "Link a hypergrid region", RunCommand);
369 m_console.Commands.AddCommand("hypergrid", false, "unlink-region",
370 "unlink-region <local name> or <HostName>:<HttpPort> <cr>",
371 "Unlink a hypergrid region", RunCommand);
372 } 358 }
373 359
374 public override void ShutdownSpecific() 360 public override void ShutdownSpecific()
@@ -421,7 +407,7 @@ namespace OpenSim
421 407
422 foreach (ScenePresence presence in agents) 408 foreach (ScenePresence presence in agents)
423 { 409 {
424 RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle); 410 RegionInfo regionInfo = presence.Scene.RegionInfo;
425 411
426 if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) && 412 if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) &&
427 presence.Lastname.ToLower().Contains(cmdparams[3].ToLower())) 413 presence.Lastname.ToLower().Contains(cmdparams[3].ToLower()))
@@ -777,38 +763,6 @@ namespace OpenSim
777 } 763 }
778 764
779 /// <summary> 765 /// <summary>
780 /// Execute switch for some of the create commands
781 /// </summary>
782 /// <param name="args"></param>
783 private void HandleCreateUser(string module, string[] cmd)
784 {
785 if (ConfigurationSettings.Standalone)
786 {
787 CreateUser(cmd);
788 }
789 else
790 {
791 MainConsole.Instance.Output("Create user is not available in grid mode, use the user server.");
792 }
793 }
794
795 /// <summary>
796 /// Execute switch for some of the reset commands
797 /// </summary>
798 /// <param name="args"></param>
799 protected void HandleResetUserPassword(string module, string[] cmd)
800 {
801 if (ConfigurationSettings.Standalone)
802 {
803 ResetUserPassword(cmd);
804 }
805 else
806 {
807 MainConsole.Instance.Output("Reset user password is not available in grid mode, use the user-server.");
808 }
809 }
810
811 /// <summary>
812 /// Turn on some debugging values for OpenSim. 766 /// Turn on some debugging values for OpenSim.
813 /// </summary> 767 /// </summary>
814 /// <param name="args"></param> 768 /// <param name="args"></param>
@@ -908,7 +862,7 @@ namespace OpenSim
908 862
909 foreach (ScenePresence presence in agents) 863 foreach (ScenePresence presence in agents)
910 { 864 {
911 RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle); 865 RegionInfo regionInfo = presence.Scene.RegionInfo;
912 string regionName; 866 string regionName;
913 867
914 if (regionInfo == null) 868 if (regionInfo == null)
@@ -944,7 +898,7 @@ namespace OpenSim
944 { 898 {
945 connections.AppendFormat("{0}: {1} ({2}) from {3} on circuit {4}\n", 899 connections.AppendFormat("{0}: {1} ({2}) from {3} on circuit {4}\n",
946 scene.RegionInfo.RegionName, client.Name, client.AgentId, client.RemoteEndPoint, client.CircuitCode); 900 scene.RegionInfo.RegionName, client.Name, client.AgentId, client.RemoteEndPoint, client.CircuitCode);
947 }, false 901 }
948 ); 902 );
949 } 903 }
950 ); 904 );
@@ -1046,86 +1000,6 @@ namespace OpenSim
1046 } 1000 }
1047 1001
1048 /// <summary> 1002 /// <summary>
1049 /// Create a new user
1050 /// </summary>
1051 /// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
1052 protected void CreateUser(string[] cmdparams)
1053 {
1054 string firstName;
1055 string lastName;
1056 string password;
1057 string email;
1058 uint regX = 1000;
1059 uint regY = 1000;
1060
1061 IConfig standalone;
1062 if ((standalone = m_config.Source.Configs["StandAlone"]) != null)
1063 {
1064 regX = (uint)standalone.GetInt("default_location_x", (int)regX);
1065 regY = (uint)standalone.GetInt("default_location_y", (int)regY);
1066 }
1067
1068
1069 if (cmdparams.Length < 3)
1070 firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
1071 else firstName = cmdparams[2];
1072
1073 if (cmdparams.Length < 4)
1074 lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
1075 else lastName = cmdparams[3];
1076
1077 if (cmdparams.Length < 5)
1078 password = MainConsole.Instance.PasswdPrompt("Password");
1079 else password = cmdparams[4];
1080
1081 if (cmdparams.Length < 6)
1082 regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString()));
1083 else regX = Convert.ToUInt32(cmdparams[5]);
1084
1085 if (cmdparams.Length < 7)
1086 regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString()));
1087 else regY = Convert.ToUInt32(cmdparams[6]);
1088
1089 if (cmdparams.Length < 8)
1090 email = MainConsole.Instance.CmdPrompt("Email", "");
1091 else email = cmdparams[7];
1092
1093 if (null == m_commsManager.UserProfileCacheService.GetUserDetails(firstName, lastName))
1094 {
1095 m_commsManager.UserAdminService.AddUser(firstName, lastName, password, email, regX, regY);
1096 }
1097 else
1098 {
1099 MainConsole.Instance.Output(string.Format("A user with the name {0} {1} already exists!", firstName, lastName));
1100 }
1101 }
1102
1103 /// <summary>
1104 /// Reset a user password.
1105 /// </summary>
1106 /// <param name="cmdparams"></param>
1107 private void ResetUserPassword(string[] cmdparams)
1108 {
1109 string firstName;
1110 string lastName;
1111 string newPassword;
1112
1113 if (cmdparams.Length < 4)
1114 firstName = MainConsole.Instance.CmdPrompt("First name");
1115 else firstName = cmdparams[3];
1116
1117 if (cmdparams.Length < 5)
1118 lastName = MainConsole.Instance.CmdPrompt("Last name");
1119 else lastName = cmdparams[4];
1120
1121 if (cmdparams.Length < 6)
1122 newPassword = MainConsole.Instance.PasswdPrompt("New password");
1123 else newPassword = cmdparams[5];
1124
1125 m_commsManager.UserAdminService.ResetUserPassword(firstName, lastName, newPassword);
1126 }
1127
1128 /// <summary>
1129 /// Use XML2 format to serialize data to a file 1003 /// Use XML2 format to serialize data to a file
1130 /// </summary> 1004 /// </summary>
1131 /// <param name="module"></param> 1005 /// <param name="module"></param>
diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs
index 1ec96a0..ba2c2de 100644
--- a/OpenSim/Region/Application/OpenSimBase.cs
+++ b/OpenSim/Region/Application/OpenSimBase.cs
@@ -36,8 +36,7 @@ using Nini.Config;
36using OpenMetaverse; 36using OpenMetaverse;
37using OpenSim.Framework; 37using OpenSim.Framework;
38using OpenSim.Framework.Communications; 38using OpenSim.Framework.Communications;
39using OpenSim.Framework.Communications.Services; 39
40using OpenSim.Framework.Communications.Cache;
41using OpenSim.Framework.Console; 40using OpenSim.Framework.Console;
42using OpenSim.Framework.Servers; 41using OpenSim.Framework.Servers;
43using OpenSim.Framework.Servers.HttpServer; 42using OpenSim.Framework.Servers.HttpServer;
@@ -85,8 +84,6 @@ namespace OpenSim
85 84
86 protected ConfigurationLoader m_configLoader; 85 protected ConfigurationLoader m_configLoader;
87 86
88 protected GridInfoService m_gridInfoService;
89
90 public ConsoleCommand CreateAccount = null; 87 public ConsoleCommand CreateAccount = null;
91 88
92 protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>(); 89 protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
@@ -604,35 +601,6 @@ namespace OpenSim
604 scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); 601 scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
605 scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight); 602 scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
606 603
607 // TODO: Remove this cruft once MasterAvatar is fully deprecated
608 //Master Avatar Setup
609 UserProfileData masterAvatar;
610 if (scene.RegionInfo.MasterAvatarAssignedUUID == UUID.Zero)
611 {
612 masterAvatar =
613 m_commsManager.UserService.SetupMasterUser(scene.RegionInfo.MasterAvatarFirstName,
614 scene.RegionInfo.MasterAvatarLastName,
615 scene.RegionInfo.MasterAvatarSandboxPassword);
616 }
617 else
618 {
619 masterAvatar = m_commsManager.UserService.SetupMasterUser(scene.RegionInfo.MasterAvatarAssignedUUID);
620 scene.RegionInfo.MasterAvatarFirstName = masterAvatar.FirstName;
621 scene.RegionInfo.MasterAvatarLastName = masterAvatar.SurName;
622 }
623
624 if (masterAvatar == null)
625 {
626 m_log.Info("[PARCEL]: No master avatar found, using null.");
627 scene.RegionInfo.MasterAvatarAssignedUUID = UUID.Zero;
628 }
629 else
630 {
631 m_log.InfoFormat("[PARCEL]: Found master avatar {0} {1} [" + masterAvatar.ID.ToString() + "]",
632 scene.RegionInfo.MasterAvatarFirstName, scene.RegionInfo.MasterAvatarLastName);
633 scene.RegionInfo.MasterAvatarAssignedUUID = masterAvatar.ID;
634 }
635
636 return scene; 604 return scene;
637 } 605 }
638 606
@@ -655,15 +623,10 @@ namespace OpenSim
655 protected override Scene CreateScene(RegionInfo regionInfo, StorageManager storageManager, 623 protected override Scene CreateScene(RegionInfo regionInfo, StorageManager storageManager,
656 AgentCircuitManager circuitManager) 624 AgentCircuitManager circuitManager)
657 { 625 {
658 bool hgrid = ConfigSource.Source.Configs["Startup"].GetBoolean("hypergrid", false); 626 SceneCommunicationService sceneGridService = new SceneCommunicationService();
659 if (hgrid)
660 return HGCommands.CreateScene(regionInfo, circuitManager, m_commsManager,
661 storageManager, m_moduleLoader, m_configSettings, m_config, m_version);
662
663 SceneCommunicationService sceneGridService = new SceneCommunicationService(m_commsManager);
664 627
665 return new Scene( 628 return new Scene(
666 regionInfo, circuitManager, m_commsManager, sceneGridService, 629 regionInfo, circuitManager, sceneGridService,
667 storageManager, m_moduleLoader, false, m_configSettings.PhysicalPrim, 630 storageManager, m_moduleLoader, false, m_configSettings.PhysicalPrim,
668 m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version); 631 m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
669 } 632 }
diff --git a/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs b/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
index b53a2fb..9869a99 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
@@ -31,7 +31,6 @@ using OpenMetaverse;
31using OpenMetaverse.Imaging; 31using OpenMetaverse.Imaging;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Region.Framework.Interfaces; 33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes.Hypergrid;
35using OpenSim.Services.Interfaces; 34using OpenSim.Services.Interfaces;
36using log4net; 35using log4net;
37using System.Reflection; 36using System.Reflection;
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
index 5c774b5..d5fda9d 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
@@ -40,11 +40,9 @@ using OpenMetaverse.Packets;
40using OpenMetaverse.StructuredData; 40using OpenMetaverse.StructuredData;
41using OpenSim.Framework; 41using OpenSim.Framework;
42using OpenSim.Framework.Client; 42using OpenSim.Framework.Client;
43using OpenSim.Framework.Communications.Cache;
44using OpenSim.Framework.Statistics; 43using OpenSim.Framework.Statistics;
45using OpenSim.Region.Framework.Interfaces; 44using OpenSim.Region.Framework.Interfaces;
46using OpenSim.Region.Framework.Scenes; 45using OpenSim.Region.Framework.Scenes;
47using OpenSim.Region.Framework.Scenes.Hypergrid;
48using OpenSim.Services.Interfaces; 46using OpenSim.Services.Interfaces;
49using Timer = System.Timers.Timer; 47using Timer = System.Timers.Timer;
50using AssetLandmark = OpenSim.Framework.AssetLandmark; 48using AssetLandmark = OpenSim.Framework.AssetLandmark;
@@ -98,6 +96,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
98 /// </summary> 96 /// </summary>
99 public class LLClientView : IClientAPI, IClientCore, IClientIM, IClientChat, IClientIPEndpoint, IStatsCollector 97 public class LLClientView : IClientAPI, IClientCore, IClientIM, IClientChat, IClientIPEndpoint, IStatsCollector
100 { 98 {
99 /// <value>
100 /// Debug packet level. At the moment, only 255 does anything (prints out all in and out packets).
101 /// </value>
102 protected int m_debugPacketLevel = 0;
103
101 #region Events 104 #region Events
102 105
103 public event GenericMessage OnGenericMessage; 106 public event GenericMessage OnGenericMessage;
@@ -122,7 +125,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
122 public event ObjectAttach OnObjectAttach; 125 public event ObjectAttach OnObjectAttach;
123 public event ObjectDeselect OnObjectDetach; 126 public event ObjectDeselect OnObjectDetach;
124 public event ObjectDrop OnObjectDrop; 127 public event ObjectDrop OnObjectDrop;
125 public event GenericCall2 OnCompleteMovementToRegion; 128 public event GenericCall1 OnCompleteMovementToRegion;
129 public event UpdateAgent OnPreAgentUpdate;
126 public event UpdateAgent OnAgentUpdate; 130 public event UpdateAgent OnAgentUpdate;
127 public event AgentRequestSit OnAgentRequestSit; 131 public event AgentRequestSit OnAgentRequestSit;
128 public event AgentSit OnAgentSit; 132 public event AgentSit OnAgentSit;
@@ -178,6 +182,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
178 public event TeleportLocationRequest OnSetStartLocationRequest; 182 public event TeleportLocationRequest OnSetStartLocationRequest;
179 public event UpdateAvatarProperties OnUpdateAvatarProperties; 183 public event UpdateAvatarProperties OnUpdateAvatarProperties;
180 public event CreateNewInventoryItem OnCreateNewInventoryItem; 184 public event CreateNewInventoryItem OnCreateNewInventoryItem;
185 public event LinkInventoryItem OnLinkInventoryItem;
181 public event CreateInventoryFolder OnCreateNewInventoryFolder; 186 public event CreateInventoryFolder OnCreateNewInventoryFolder;
182 public event UpdateInventoryFolder OnUpdateInventoryFolder; 187 public event UpdateInventoryFolder OnUpdateInventoryFolder;
183 public event MoveInventoryFolder OnMoveInventoryFolder; 188 public event MoveInventoryFolder OnMoveInventoryFolder;
@@ -348,11 +353,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP
348 protected PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_avatarTerseUpdates; 353 protected PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_avatarTerseUpdates;
349 private PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_primTerseUpdates; 354 private PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_primTerseUpdates;
350 private PriorityQueue<double, ObjectUpdatePacket.ObjectDataBlock> m_primFullUpdates; 355 private PriorityQueue<double, ObjectUpdatePacket.ObjectDataBlock> m_primFullUpdates;
356
357 /// <value>
358 /// List used in construction of data blocks for an object update packet. This is to stop us having to
359 /// continually recreate it.
360 /// </value>
361 protected List<ObjectUpdatePacket.ObjectDataBlock> m_fullUpdateDataBlocksBuilder;
362
363 /// <value>
364 /// Maintain a record of all the objects killed. This allows us to stop an update being sent from the
365 /// thread servicing the m_primFullUpdates queue after a kill. If this happens the object persists as an
366 /// ownerless phantom.
367 ///
368 /// All manipulation of this set has to occur under a m_primFullUpdate.SyncRoot lock
369 ///
370 /// </value>
371 protected HashSet<uint> m_killRecord;
372
351 private int m_moneyBalance; 373 private int m_moneyBalance;
352 private int m_animationSequenceNumber = 1; 374 private int m_animationSequenceNumber = 1;
353 private bool m_SendLogoutPacketWhenClosing = true; 375 private bool m_SendLogoutPacketWhenClosing = true;
354 private AgentUpdateArgs lastarg; 376 private AgentUpdateArgs lastarg;
355 private bool m_IsActive = true; 377 private bool m_IsActive = true;
378 private bool m_IsLoggingOut = false;
356 379
357 protected Dictionary<PacketType, PacketProcessor> m_packetHandlers = new Dictionary<PacketType, PacketProcessor>(); 380 protected Dictionary<PacketType, PacketProcessor> m_packetHandlers = new Dictionary<PacketType, PacketProcessor>();
358 protected Dictionary<string, GenericMessage> m_genericPacketHandlers = new Dictionary<string, GenericMessage>(); //PauPaw:Local Generic Message handlers 381 protected Dictionary<string, GenericMessage> m_genericPacketHandlers = new Dictionary<string, GenericMessage>(); //PauPaw:Local Generic Message handlers
@@ -416,6 +439,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
416 get { return m_IsActive; } 439 get { return m_IsActive; }
417 set { m_IsActive = value; } 440 set { m_IsActive = value; }
418 } 441 }
442 public bool IsLoggingOut
443 {
444 get { return m_IsLoggingOut; }
445 set { m_IsLoggingOut = value; }
446 }
447
419 public bool SendLogoutPacketWhenClosing { set { m_SendLogoutPacketWhenClosing = value; } } 448 public bool SendLogoutPacketWhenClosing { set { m_SendLogoutPacketWhenClosing = value; } }
420 449
421 #endregion Properties 450 #endregion Properties
@@ -437,6 +466,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
437 m_avatarTerseUpdates = new PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(); 466 m_avatarTerseUpdates = new PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock>();
438 m_primTerseUpdates = new PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(); 467 m_primTerseUpdates = new PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock>();
439 m_primFullUpdates = new PriorityQueue<double, ObjectUpdatePacket.ObjectDataBlock>(m_scene.Entities.Count); 468 m_primFullUpdates = new PriorityQueue<double, ObjectUpdatePacket.ObjectDataBlock>(m_scene.Entities.Count);
469 m_fullUpdateDataBlocksBuilder = new List<ObjectUpdatePacket.ObjectDataBlock>();
470 m_killRecord = new HashSet<uint>();
440 471
441 m_assetService = m_scene.RequestModuleInterface<IAssetService>(); 472 m_assetService = m_scene.RequestModuleInterface<IAssetService>();
442 m_hyperAssets = m_scene.RequestModuleInterface<IHyperAssetService>(); 473 m_hyperAssets = m_scene.RequestModuleInterface<IHyperAssetService>();
@@ -466,6 +497,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
466 497
467 public void SetDebugPacketLevel(int newDebug) 498 public void SetDebugPacketLevel(int newDebug)
468 { 499 {
500 m_debugPacketLevel = newDebug;
469 } 501 }
470 502
471 #region Client Methods 503 #region Client Methods
@@ -610,7 +642,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
610 if (pprocessor.Async) 642 if (pprocessor.Async)
611 { 643 {
612 object obj = new AsyncPacketProcess(this, pprocessor.method, packet); 644 object obj = new AsyncPacketProcess(this, pprocessor.method, packet);
613 Util.FireAndForget(ProcessSpecificPacketAsync,obj); 645 Util.FireAndForget(ProcessSpecificPacketAsync, obj);
614 result = true; 646 result = true;
615 } 647 }
616 else 648 else
@@ -638,8 +670,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
638 public void ProcessSpecificPacketAsync(object state) 670 public void ProcessSpecificPacketAsync(object state)
639 { 671 {
640 AsyncPacketProcess packetObject = (AsyncPacketProcess)state; 672 AsyncPacketProcess packetObject = (AsyncPacketProcess)state;
641 packetObject.result = packetObject.Method(packetObject.ClientView, packetObject.Pack); 673
642 674 try
675 {
676 packetObject.result = packetObject.Method(packetObject.ClientView, packetObject.Pack);
677 }
678 catch (Exception e)
679 {
680 // Make sure that we see any exception caused by the asynchronous operation.
681 m_log.Error(
682 string.Format("[LLCLIENTVIEW]: Caught exception while processing {0}", packetObject.Pack), e);
683 }
643 } 684 }
644 685
645 #endregion Packet Handling 686 #endregion Packet Handling
@@ -825,6 +866,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
825 gmp.ParamList[i] = new GenericMessagePacket.ParamListBlock(); 866 gmp.ParamList[i] = new GenericMessagePacket.ParamListBlock();
826 gmp.ParamList[i++].Parameter = val; 867 gmp.ParamList[i++].Parameter = val;
827 } 868 }
869
828 OutPacket(gmp, ThrottleOutPacketType.Task); 870 OutPacket(gmp, ThrottleOutPacketType.Task);
829 } 871 }
830 872
@@ -1461,7 +1503,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
1461 kill.ObjectData[0].ID = localID; 1503 kill.ObjectData[0].ID = localID;
1462 kill.Header.Reliable = true; 1504 kill.Header.Reliable = true;
1463 kill.Header.Zerocoded = true; 1505 kill.Header.Zerocoded = true;
1464 OutPacket(kill, ThrottleOutPacketType.State); 1506
1507 lock (m_primFullUpdates.SyncRoot)
1508 {
1509 m_killRecord.Add(localID);
1510 OutPacket(kill, ThrottleOutPacketType.State);
1511 }
1465 } 1512 }
1466 1513
1467 /// <summary> 1514 /// <summary>
@@ -2512,6 +2559,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
2512 2559
2513 public void SendAsset(AssetRequestToClient req) 2560 public void SendAsset(AssetRequestToClient req)
2514 { 2561 {
2562 if (req.AssetInf.Data == null)
2563 {
2564 m_log.ErrorFormat("Cannot send asset {0} ({1}), asset data is null",
2565 req.AssetInf.ID, req.AssetInf.Metadata.ContentType);
2566 return;
2567 }
2568
2515 //m_log.Debug("sending asset " + req.RequestAssetID); 2569 //m_log.Debug("sending asset " + req.RequestAssetID);
2516 TransferInfoPacket Transfer = new TransferInfoPacket(); 2570 TransferInfoPacket Transfer = new TransferInfoPacket();
2517 Transfer.TransferInfo.ChannelType = 2; 2571 Transfer.TransferInfo.ChannelType = 2;
@@ -3501,21 +3555,34 @@ namespace OpenSim.Region.ClientStack.LindenUDP
3501 if (count == 0) 3555 if (count == 0)
3502 return; 3556 return;
3503 3557
3504 outPacket.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[count]; 3558 m_fullUpdateDataBlocksBuilder.Clear();
3559
3505 for (int i = 0; i < count; i++) 3560 for (int i = 0; i < count; i++)
3506 { 3561 {
3507 outPacket.ObjectData[i] = m_primFullUpdates.Dequeue(); 3562 ObjectUpdatePacket.ObjectDataBlock block = m_primFullUpdates.Dequeue();
3508 3563
3564 if (!m_killRecord.Contains(block.ID))
3565 {
3566 m_fullUpdateDataBlocksBuilder.Add(block);
3567
3509// string text = Util.FieldToString(outPacket.ObjectData[i].Text); 3568// string text = Util.FieldToString(outPacket.ObjectData[i].Text);
3510// if (text.IndexOf("\n") >= 0) 3569// if (text.IndexOf("\n") >= 0)
3511// text = text.Remove(text.IndexOf("\n")); 3570// text = text.Remove(text.IndexOf("\n"));
3512// m_log.DebugFormat( 3571// m_log.DebugFormat(
3513// "[CLIENT]: Sending full info about prim {0} text {1} to client {2}", 3572// "[CLIENT]: Sending full info about prim {0} text {1} to client {2}",
3514// outPacket.ObjectData[i].ID, text, Name); 3573// outPacket.ObjectData[i].ID, text, Name);
3574 }
3575// else
3576// {
3577// m_log.WarnFormat(
3578// "[CLIENT]: Preventing full update for {0} after kill to {1}", block.ID, Name);
3579// }
3515 } 3580 }
3516 }
3517 3581
3518 OutPacket(outPacket, ThrottleOutPacketType.State); 3582 outPacket.ObjectData = m_fullUpdateDataBlocksBuilder.ToArray();
3583
3584 OutPacket(outPacket, ThrottleOutPacketType.State);
3585 }
3519 } 3586 }
3520 3587
3521 public void SendPrimTerseUpdate(SendPrimitiveTerseData data) 3588 public void SendPrimTerseUpdate(SendPrimitiveTerseData data)
@@ -4051,10 +4118,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
4051 EstateCovenantReplyPacket.DataBlock edata = new EstateCovenantReplyPacket.DataBlock(); 4118 EstateCovenantReplyPacket.DataBlock edata = new EstateCovenantReplyPacket.DataBlock();
4052 edata.CovenantID = covenant; 4119 edata.CovenantID = covenant;
4053 edata.CovenantTimestamp = 0; 4120 edata.CovenantTimestamp = 0;
4054 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 4121 edata.EstateOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
4055 edata.EstateOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
4056 else
4057 edata.EstateOwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
4058 edata.EstateName = Utils.StringToBytes(m_scene.RegionInfo.EstateSettings.EstateName); 4122 edata.EstateName = Utils.StringToBytes(m_scene.RegionInfo.EstateSettings.EstateName);
4059 einfopack.Data = edata; 4123 einfopack.Data = edata;
4060 OutPacket(einfopack, ThrottleOutPacketType.Task); 4124 OutPacket(einfopack, ThrottleOutPacketType.Task);
@@ -4075,8 +4139,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
4075 4139
4076 //Sending Estate Settings 4140 //Sending Estate Settings
4077 returnblock[0].Parameter = Utils.StringToBytes(estateName); 4141 returnblock[0].Parameter = Utils.StringToBytes(estateName);
4078 // TODO: remove this cruft once MasterAvatar is fully deprecated
4079 //
4080 returnblock[1].Parameter = Utils.StringToBytes(estateOwner.ToString()); 4142 returnblock[1].Parameter = Utils.StringToBytes(estateOwner.ToString());
4081 returnblock[2].Parameter = Utils.StringToBytes(estateID.ToString()); 4143 returnblock[2].Parameter = Utils.StringToBytes(estateID.ToString());
4082 4144
@@ -4674,6 +4736,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
4674 AddLocalPacketHandler(PacketType.UpdateInventoryFolder, HandleUpdateInventoryFolder); 4736 AddLocalPacketHandler(PacketType.UpdateInventoryFolder, HandleUpdateInventoryFolder);
4675 AddLocalPacketHandler(PacketType.MoveInventoryFolder, HandleMoveInventoryFolder); 4737 AddLocalPacketHandler(PacketType.MoveInventoryFolder, HandleMoveInventoryFolder);
4676 AddLocalPacketHandler(PacketType.CreateInventoryItem, HandleCreateInventoryItem); 4738 AddLocalPacketHandler(PacketType.CreateInventoryItem, HandleCreateInventoryItem);
4739 AddLocalPacketHandler(PacketType.LinkInventoryItem, HandleLinkInventoryItem);
4677 AddLocalPacketHandler(PacketType.FetchInventory, HandleFetchInventory); 4740 AddLocalPacketHandler(PacketType.FetchInventory, HandleFetchInventory);
4678 AddLocalPacketHandler(PacketType.FetchInventoryDescendents, HandleFetchInventoryDescendents); 4741 AddLocalPacketHandler(PacketType.FetchInventoryDescendents, HandleFetchInventoryDescendents);
4679 AddLocalPacketHandler(PacketType.PurgeInventoryDescendents, HandlePurgeInventoryDescendents); 4742 AddLocalPacketHandler(PacketType.PurgeInventoryDescendents, HandlePurgeInventoryDescendents);
@@ -4866,7 +4929,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
4866 UpdateAgent handlerAgentUpdate = OnAgentUpdate; 4929 UpdateAgent handlerAgentUpdate = OnAgentUpdate;
4867 lastarg = arg; // save this set of arguments for nexttime 4930 lastarg = arg; // save this set of arguments for nexttime
4868 if (handlerAgentUpdate != null) 4931 if (handlerAgentUpdate != null)
4932 {
4933 OnPreAgentUpdate(this, arg);
4869 OnAgentUpdate(this, arg); 4934 OnAgentUpdate(this, arg);
4935 }
4870 4936
4871 handlerAgentUpdate = null; 4937 handlerAgentUpdate = null;
4872 } 4938 }
@@ -5505,6 +5571,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
5505 // for the client session anyway, in order to protect ourselves against bad code in plugins 5571 // for the client session anyway, in order to protect ourselves against bad code in plugins
5506 try 5572 try
5507 { 5573 {
5574
5508 byte[] visualparams = new byte[appear.VisualParam.Length]; 5575 byte[] visualparams = new byte[appear.VisualParam.Length];
5509 for (int i = 0; i < appear.VisualParam.Length; i++) 5576 for (int i = 0; i < appear.VisualParam.Length; i++)
5510 visualparams[i] = appear.VisualParam[i].ParamValue; 5577 visualparams[i] = appear.VisualParam[i].ParamValue;
@@ -5715,10 +5782,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
5715 5782
5716 private bool HandleCompleteAgentMovement(IClientAPI sender, Packet Pack) 5783 private bool HandleCompleteAgentMovement(IClientAPI sender, Packet Pack)
5717 { 5784 {
5718 GenericCall2 handlerCompleteMovementToRegion = OnCompleteMovementToRegion; 5785 GenericCall1 handlerCompleteMovementToRegion = OnCompleteMovementToRegion;
5719 if (handlerCompleteMovementToRegion != null) 5786 if (handlerCompleteMovementToRegion != null)
5720 { 5787 {
5721 handlerCompleteMovementToRegion(); 5788 handlerCompleteMovementToRegion(sender);
5722 } 5789 }
5723 handlerCompleteMovementToRegion = null; 5790 handlerCompleteMovementToRegion = null;
5724 5791
@@ -5946,7 +6013,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
5946 || avSetStartLocationRequestPacket.StartLocationData.LocationPos.Y == 255.5f) 6013 || avSetStartLocationRequestPacket.StartLocationData.LocationPos.Y == 255.5f)
5947 { 6014 {
5948 ScenePresence avatar = null; 6015 ScenePresence avatar = null;
5949 if (((Scene)m_scene).TryGetAvatar(AgentId, out avatar)) 6016 if (((Scene)m_scene).TryGetScenePresence(AgentId, out avatar))
5950 { 6017 {
5951 if (avSetStartLocationRequestPacket.StartLocationData.LocationPos.X == 255.5f) 6018 if (avSetStartLocationRequestPacket.StartLocationData.LocationPos.X == 255.5f)
5952 { 6019 {
@@ -6989,6 +7056,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
6989 return true; 7056 return true;
6990 } 7057 }
6991 7058
7059 /// <summary>
7060 /// This is the entry point for the UDP route by which the client can retrieve asset data. If the request
7061 /// is successful then a TransferInfo packet will be sent back, followed by one or more TransferPackets
7062 /// </summary>
7063 /// <param name="sender"></param>
7064 /// <param name="Pack"></param>
7065 /// <returns>This parameter may be ignored since we appear to return true whatever happens</returns>
6992 private bool HandleTransferRequest(IClientAPI sender, Packet Pack) 7066 private bool HandleTransferRequest(IClientAPI sender, Packet Pack)
6993 { 7067 {
6994 //m_log.Debug("ClientView.ProcessPackets.cs:ProcessInPacket() - Got transfer request"); 7068 //m_log.Debug("ClientView.ProcessPackets.cs:ProcessInPacket() - Got transfer request");
@@ -6999,37 +7073,95 @@ namespace OpenSim.Region.ClientStack.LindenUDP
6999 // Has to be done here, because AssetCache can't do it 7073 // Has to be done here, because AssetCache can't do it
7000 // 7074 //
7001 UUID taskID = UUID.Zero; 7075 UUID taskID = UUID.Zero;
7002 if (transfer.TransferInfo.SourceType == 3) 7076 if (transfer.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
7003 { 7077 {
7004 taskID = new UUID(transfer.TransferInfo.Params, 48); 7078 taskID = new UUID(transfer.TransferInfo.Params, 48);
7005 UUID itemID = new UUID(transfer.TransferInfo.Params, 64); 7079 UUID itemID = new UUID(transfer.TransferInfo.Params, 64);
7006 UUID requestID = new UUID(transfer.TransferInfo.Params, 80); 7080 UUID requestID = new UUID(transfer.TransferInfo.Params, 80);
7081
7082// m_log.DebugFormat(
7083// "[CLIENT]: Got request for asset {0} from item {1} in prim {2} by {3}",
7084// requestID, itemID, taskID, Name);
7085
7007 if (!(((Scene)m_scene).Permissions.BypassPermissions())) 7086 if (!(((Scene)m_scene).Permissions.BypassPermissions()))
7008 { 7087 {
7009 if (taskID != UUID.Zero) // Prim 7088 if (taskID != UUID.Zero) // Prim
7010 { 7089 {
7011 SceneObjectPart part = ((Scene)m_scene).GetSceneObjectPart(taskID); 7090 SceneObjectPart part = ((Scene)m_scene).GetSceneObjectPart(taskID);
7091
7012 if (part == null) 7092 if (part == null)
7093 {
7094 m_log.WarnFormat(
7095 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but prim does not exist",
7096 Name, requestID, itemID, taskID);
7013 return true; 7097 return true;
7098 }
7014 7099
7015 if (part.OwnerID != AgentId) 7100 TaskInventoryItem tii = part.Inventory.GetInventoryItem(itemID);
7016 return true; 7101 if (tii == null)
7017 7102 {
7018 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0) 7103 m_log.WarnFormat(
7019 return true; 7104 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but item does not exist",
7020 7105 Name, requestID, itemID, taskID);
7021 TaskInventoryItem ti = part.Inventory.GetInventoryItem(itemID);
7022 if (ti == null)
7023 return true;
7024
7025 if (ti.OwnerID != AgentId)
7026 return true;
7027
7028 if ((ti.CurrentPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer)) != ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer))
7029 return true;
7030
7031 if (ti.AssetID != requestID)
7032 return true; 7106 return true;
7107 }
7108
7109 if (tii.Type == (int)AssetType.LSLText)
7110 {
7111 if (!((Scene)m_scene).Permissions.CanEditScript(itemID, taskID, AgentId))
7112 return true;
7113 }
7114 else if (tii.Type == (int)AssetType.Notecard)
7115 {
7116 if (!((Scene)m_scene).Permissions.CanEditNotecard(itemID, taskID, AgentId))
7117 return true;
7118 }
7119 else
7120 {
7121 // TODO: Change this code to allow items other than notecards and scripts to be successfully
7122 // shared with group. In fact, this whole block of permissions checking should move to an IPermissionsModule
7123 if (part.OwnerID != AgentId)
7124 {
7125 m_log.WarnFormat(
7126 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but the prim is owned by {4}",
7127 Name, requestID, itemID, taskID, part.OwnerID);
7128 return true;
7129 }
7130
7131 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
7132 {
7133 m_log.WarnFormat(
7134 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but modify permissions are not set",
7135 Name, requestID, itemID, taskID);
7136 return true;
7137 }
7138
7139 if (tii.OwnerID != AgentId)
7140 {
7141 m_log.WarnFormat(
7142 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but the item is owned by {4}",
7143 Name, requestID, itemID, taskID, tii.OwnerID);
7144 return true;
7145 }
7146
7147 if ((
7148 tii.CurrentPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer))
7149 != ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer))
7150 {
7151 m_log.WarnFormat(
7152 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but item permissions are not modify/copy/transfer",
7153 Name, requestID, itemID, taskID);
7154 return true;
7155 }
7156
7157 if (tii.AssetID != requestID)
7158 {
7159 m_log.WarnFormat(
7160 "[CLIENT]: {0} requested asset {1} from item {2} in prim {3} but this does not match item's asset {4}",
7161 Name, requestID, itemID, taskID, tii.AssetID);
7162 return true;
7163 }
7164 }
7033 } 7165 }
7034 else // Agent 7166 else // Agent
7035 { 7167 {
@@ -7038,7 +7170,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7038 assetRequestItem = invService.GetItem(assetRequestItem); 7170 assetRequestItem = invService.GetItem(assetRequestItem);
7039 if (assetRequestItem == null) 7171 if (assetRequestItem == null)
7040 { 7172 {
7041 assetRequestItem = ((Scene)m_scene).CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID); 7173 ILibraryService lib = m_scene.RequestModuleInterface<ILibraryService>();
7174 if (lib != null)
7175 assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
7042 if (assetRequestItem == null) 7176 if (assetRequestItem == null)
7043 return true; 7177 return true;
7044 } 7178 }
@@ -7047,7 +7181,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7047 // only to notecards and scripts. All 7181 // only to notecards and scripts. All
7048 // other asset types are always available 7182 // other asset types are always available
7049 // 7183 //
7050 if (assetRequestItem.AssetType == 10) 7184 if (assetRequestItem.AssetType == (int)AssetType.LSLText)
7051 { 7185 {
7052 if (!((Scene)m_scene).Permissions.CanViewScript(itemID, UUID.Zero, AgentId)) 7186 if (!((Scene)m_scene).Permissions.CanViewScript(itemID, UUID.Zero, AgentId))
7053 { 7187 {
@@ -7055,7 +7189,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7055 return true; 7189 return true;
7056 } 7190 }
7057 } 7191 }
7058 else if (assetRequestItem.AssetType == 7) 7192 else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
7059 { 7193 {
7060 if (!((Scene)m_scene).Permissions.CanViewNotecard(itemID, UUID.Zero, AgentId)) 7194 if (!((Scene)m_scene).Permissions.CanViewNotecard(itemID, UUID.Zero, AgentId))
7061 { 7195 {
@@ -7065,7 +7199,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7065 } 7199 }
7066 7200
7067 if (assetRequestItem.AssetID != requestID) 7201 if (assetRequestItem.AssetID != requestID)
7202 {
7203 m_log.WarnFormat(
7204 "[CLIENT]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
7205 Name, requestID, itemID, assetRequestItem.AssetID);
7068 return true; 7206 return true;
7207 }
7069 } 7208 }
7070 } 7209 }
7071 } 7210 }
@@ -7268,6 +7407,38 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7268 return true; 7407 return true;
7269 } 7408 }
7270 7409
7410 private bool HandleLinkInventoryItem(IClientAPI sender, Packet Pack)
7411 {
7412 LinkInventoryItemPacket createLink = (LinkInventoryItemPacket)Pack;
7413
7414 #region Packet Session and User Check
7415 if (m_checkPackets)
7416 {
7417 if (createLink.AgentData.SessionID != SessionId ||
7418 createLink.AgentData.AgentID != AgentId)
7419 return true;
7420 }
7421 #endregion
7422
7423 LinkInventoryItem linkInventoryItem = OnLinkInventoryItem;
7424
7425 if (linkInventoryItem != null)
7426 {
7427 linkInventoryItem(
7428 this,
7429 createLink.InventoryBlock.TransactionID,
7430 createLink.InventoryBlock.FolderID,
7431 createLink.InventoryBlock.CallbackID,
7432 Util.FieldToString(createLink.InventoryBlock.Description),
7433 Util.FieldToString(createLink.InventoryBlock.Name),
7434 createLink.InventoryBlock.InvType,
7435 createLink.InventoryBlock.Type,
7436 createLink.InventoryBlock.OldItemID);
7437 }
7438
7439 return true;
7440 }
7441
7271 private bool HandleFetchInventory(IClientAPI sender, Packet Pack) 7442 private bool HandleFetchInventory(IClientAPI sender, Packet Pack)
7272 { 7443 {
7273 if (OnFetchInventory != null) 7444 if (OnFetchInventory != null)
@@ -7612,12 +7783,15 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7612 newTaskItem.GroupPermissions = updatetask.InventoryData.GroupMask; 7783 newTaskItem.GroupPermissions = updatetask.InventoryData.GroupMask;
7613 newTaskItem.EveryonePermissions = updatetask.InventoryData.EveryoneMask; 7784 newTaskItem.EveryonePermissions = updatetask.InventoryData.EveryoneMask;
7614 newTaskItem.NextPermissions = updatetask.InventoryData.NextOwnerMask; 7785 newTaskItem.NextPermissions = updatetask.InventoryData.NextOwnerMask;
7786
7787 // Unused? Clicking share with group sets GroupPermissions instead, so perhaps this is something
7788 // different
7615 //newTaskItem.GroupOwned=updatetask.InventoryData.GroupOwned; 7789 //newTaskItem.GroupOwned=updatetask.InventoryData.GroupOwned;
7616 newTaskItem.Type = updatetask.InventoryData.Type; 7790 newTaskItem.Type = updatetask.InventoryData.Type;
7617 newTaskItem.InvType = updatetask.InventoryData.InvType; 7791 newTaskItem.InvType = updatetask.InventoryData.InvType;
7618 newTaskItem.Flags = updatetask.InventoryData.Flags; 7792 newTaskItem.Flags = updatetask.InventoryData.Flags;
7619 //newTaskItem.SaleType=updatetask.InventoryData.SaleType; 7793 //newTaskItem.SaleType=updatetask.InventoryData.SaleType;
7620 //newTaskItem.SalePrice=updatetask.InventoryData.SalePrice;; 7794 //newTaskItem.SalePrice=updatetask.InventoryData.SalePrice;
7621 newTaskItem.Name = Util.FieldToString(updatetask.InventoryData.Name); 7795 newTaskItem.Name = Util.FieldToString(updatetask.InventoryData.Name);
7622 newTaskItem.Description = Util.FieldToString(updatetask.InventoryData.Description); 7796 newTaskItem.Description = Util.FieldToString(updatetask.InventoryData.Description);
7623 newTaskItem.CreationDate = (uint)updatetask.InventoryData.CreationDate; 7797 newTaskItem.CreationDate = (uint)updatetask.InventoryData.CreationDate;
@@ -7625,7 +7799,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7625 newTaskItem, updatetask.UpdateData.LocalID); 7799 newTaskItem, updatetask.UpdateData.LocalID);
7626 } 7800 }
7627 } 7801 }
7628 } 7802 }
7629 7803
7630 return true; 7804 return true;
7631 } 7805 }
@@ -10928,7 +11102,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
10928 LLUDPServer.LogPacketHeader(false, m_circuitCode, 0, packet.Type, (ushort)packet.Length); 11102 LLUDPServer.LogPacketHeader(false, m_circuitCode, 0, packet.Type, (ushort)packet.Length);
10929 #endregion BinaryStats 11103 #endregion BinaryStats
10930 11104
10931 m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, true); 11105 OutPacket(packet, throttlePacketType, true);
10932 } 11106 }
10933 11107
10934 /// <summary> 11108 /// <summary>
@@ -10941,6 +11115,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
10941 /// handles splitting manually</param> 11115 /// handles splitting manually</param>
10942 protected void OutPacket(Packet packet, ThrottleOutPacketType throttlePacketType, bool doAutomaticSplitting) 11116 protected void OutPacket(Packet packet, ThrottleOutPacketType throttlePacketType, bool doAutomaticSplitting)
10943 { 11117 {
11118 if (m_debugPacketLevel >= 255)
11119 m_log.DebugFormat("[CLIENT]: Packet OUT {0}", packet.Type);
11120
10944 m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, doAutomaticSplitting); 11121 m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, doAutomaticSplitting);
10945 } 11122 }
10946 11123
@@ -11012,10 +11189,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11012 /// <param name="Pack">OpenMetaverse.packet</param> 11189 /// <param name="Pack">OpenMetaverse.packet</param>
11013 public void ProcessInPacket(Packet Pack) 11190 public void ProcessInPacket(Packet Pack)
11014 { 11191 {
11015// m_log.DebugFormat("[CLIENT]: Packet IN {0}", Pack); 11192 if (m_debugPacketLevel >= 255)
11016 11193 m_log.DebugFormat("[CLIENT]: Packet IN {0}", Pack.Type);
11194
11017 if (!ProcessPacketMethod(Pack)) 11195 if (!ProcessPacketMethod(Pack))
11018 m_log.Warn("[CLIENT]: unhandled packet " + Pack); 11196 m_log.Warn("[CLIENT]: unhandled packet " + Pack.Type);
11019 11197
11020 PacketPool.Instance.ReturnPacket(Pack); 11198 PacketPool.Instance.ReturnPacket(Pack);
11021 } 11199 }
@@ -11235,17 +11413,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11235 return String.Empty; 11413 return String.Empty;
11236 } 11414 }
11237 11415
11238 public void MakeAssetRequest(TransferRequestPacket transferRequest, UUID taskID) 11416 /// <summary>
11417 /// Make an asset request to the asset service in response to a client request.
11418 /// </summary>
11419 /// <param name="transferRequest"></param>
11420 /// <param name="taskID"></param>
11421 protected void MakeAssetRequest(TransferRequestPacket transferRequest, UUID taskID)
11239 { 11422 {
11240 UUID requestID = UUID.Zero; 11423 UUID requestID = UUID.Zero;
11241 if (transferRequest.TransferInfo.SourceType == 2) 11424 if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
11242 { 11425 {
11243 //direct asset request
11244 requestID = new UUID(transferRequest.TransferInfo.Params, 0); 11426 requestID = new UUID(transferRequest.TransferInfo.Params, 0);
11245 } 11427 }
11246 else if (transferRequest.TransferInfo.SourceType == 3) 11428 else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
11247 { 11429 {
11248 //inventory asset request
11249 requestID = new UUID(transferRequest.TransferInfo.Params, 80); 11430 requestID = new UUID(transferRequest.TransferInfo.Params, 80);
11250 //m_log.Debug("[XXX] inventory asset request " + requestID); 11431 //m_log.Debug("[XXX] inventory asset request " + requestID);
11251 //if (taskID == UUID.Zero) // Agent 11432 //if (taskID == UUID.Zero) // Agent
@@ -11258,29 +11439,34 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11258 // } 11439 // }
11259 } 11440 }
11260 11441
11261 //check to see if asset is in local cache, if not we need to request it from asset server. 11442// m_log.DebugFormat("[CLIENT]: {0} requesting asset {1}", Name, requestID);
11262 //m_log.Debug("asset request " + requestID);
11263 11443
11264 m_assetService.Get(requestID.ToString(), transferRequest, AssetReceived); 11444 m_assetService.Get(requestID.ToString(), transferRequest, AssetReceived);
11265
11266 } 11445 }
11267 11446
11447 /// <summary>
11448 /// When we get a reply back from the asset service in response to a client request, send back the data.
11449 /// </summary>
11450 /// <param name="id"></param>
11451 /// <param name="sender"></param>
11452 /// <param name="asset"></param>
11268 protected void AssetReceived(string id, Object sender, AssetBase asset) 11453 protected void AssetReceived(string id, Object sender, AssetBase asset)
11269 { 11454 {
11270 TransferRequestPacket transferRequest = (TransferRequestPacket)sender; 11455 TransferRequestPacket transferRequest = (TransferRequestPacket)sender;
11271 11456
11272 UUID requestID = UUID.Zero; 11457 UUID requestID = UUID.Zero;
11273 byte source = 2; 11458 byte source = (byte)SourceType.Asset;
11274 if ((transferRequest.TransferInfo.SourceType == 2) || (transferRequest.TransferInfo.SourceType == 2222)) 11459
11460 if ((transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
11461 || (transferRequest.TransferInfo.SourceType == 2222))
11275 { 11462 {
11276 //direct asset request
11277 requestID = new UUID(transferRequest.TransferInfo.Params, 0); 11463 requestID = new UUID(transferRequest.TransferInfo.Params, 0);
11278 } 11464 }
11279 else if ((transferRequest.TransferInfo.SourceType == 3) || (transferRequest.TransferInfo.SourceType == 3333)) 11465 else if ((transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
11466 || (transferRequest.TransferInfo.SourceType == 3333))
11280 { 11467 {
11281 //inventory asset request
11282 requestID = new UUID(transferRequest.TransferInfo.Params, 80); 11468 requestID = new UUID(transferRequest.TransferInfo.Params, 80);
11283 source = 3; 11469 source = (byte)SourceType.SimInventoryItem;
11284 //m_log.Debug("asset request " + requestID); 11470 //m_log.Debug("asset request " + requestID);
11285 } 11471 }
11286 11472
@@ -11293,9 +11479,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11293 if ((userAssets != string.Empty) && (userAssets != m_hyperAssets.GetSimAssetServer())) 11479 if ((userAssets != string.Empty) && (userAssets != m_hyperAssets.GetSimAssetServer()))
11294 { 11480 {
11295 m_log.DebugFormat("[CLIENT]: asset {0} not found in local asset storage. Trying user's storage.", id); 11481 m_log.DebugFormat("[CLIENT]: asset {0} not found in local asset storage. Trying user's storage.", id);
11296 if (transferRequest.TransferInfo.SourceType == 2) 11482 if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
11297 transferRequest.TransferInfo.SourceType = 2222; // marker 11483 transferRequest.TransferInfo.SourceType = 2222; // marker
11298 else if (transferRequest.TransferInfo.SourceType == 3) 11484 else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
11299 transferRequest.TransferInfo.SourceType = 3333; // marker 11485 transferRequest.TransferInfo.SourceType = 3333; // marker
11300 11486
11301 m_assetService.Get(userAssets + "/" + id, transferRequest, AssetReceived); 11487 m_assetService.Get(userAssets + "/" + id, transferRequest, AssetReceived);
@@ -11310,7 +11496,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11310 } 11496 }
11311 11497
11312 // Scripts cannot be retrieved by direct request 11498 // Scripts cannot be retrieved by direct request
11313 if (transferRequest.TransferInfo.SourceType == 2 && asset.Type == 10) 11499 if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset && asset.Type == 10)
11314 return; 11500 return;
11315 11501
11316 // The asset is known to exist and is in our cache, so add it to the AssetRequests list 11502 // The asset is known to exist and is in our cache, so add it to the AssetRequests list
@@ -11336,6 +11522,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11336 const uint m_maxPacketSize = 600; 11522 const uint m_maxPacketSize = 600;
11337 int numPackets = 1; 11523 int numPackets = 1;
11338 11524
11525 if (data == null)
11526 return 0;
11527
11339 if (data.LongLength > m_maxPacketSize) 11528 if (data.LongLength > m_maxPacketSize)
11340 { 11529 {
11341 // over max number of bytes so split up file 11530 // over max number of bytes so split up file
@@ -11540,6 +11729,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11540 public PacketMethod method; 11729 public PacketMethod method;
11541 public bool Async; 11730 public bool Async;
11542 } 11731 }
11732
11543 public class AsyncPacketProcess 11733 public class AsyncPacketProcess
11544 { 11734 {
11545 public bool result = false; 11735 public bool result = false;
@@ -11581,5 +11771,40 @@ namespace OpenSim.Region.ClientStack.LindenUDP
11581 packet.PropertiesData.LanguagesText = Utils.StringToBytes(languages); 11771 packet.PropertiesData.LanguagesText = Utils.StringToBytes(languages);
11582 OutPacket(packet, ThrottleOutPacketType.Task); 11772 OutPacket(packet, ThrottleOutPacketType.Task);
11583 } 11773 }
11774
11775 public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
11776 {
11777 ChangeUserRightsPacket packet = (ChangeUserRightsPacket)PacketPool.Instance.GetPacket(PacketType.ChangeUserRights);
11778
11779 packet.AgentData = new ChangeUserRightsPacket.AgentDataBlock();
11780 packet.AgentData.AgentID = agentID;
11781
11782 packet.Rights = new ChangeUserRightsPacket.RightsBlock[1];
11783 packet.Rights[0] = new ChangeUserRightsPacket.RightsBlock();
11784 packet.Rights[0].AgentRelated = friendID;
11785 packet.Rights[0].RelatedRights = rights;
11786
11787 OutPacket(packet, ThrottleOutPacketType.Task);
11788 }
11789
11790 public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
11791 {
11792 ScriptDialogPacket dialog = (ScriptDialogPacket)PacketPool.Instance.GetPacket(PacketType.ScriptDialog);
11793 dialog.Data.ObjectID = objectId;
11794 dialog.Data.ChatChannel = chatChannel;
11795 dialog.Data.ImageID = UUID.Zero;
11796 dialog.Data.ObjectName = Util.StringToBytes256(objectname);
11797 // this is the username of the *owner*
11798 dialog.Data.FirstName = Util.StringToBytes256(ownerFirstName);
11799 dialog.Data.LastName = Util.StringToBytes256(ownerLastName);
11800 dialog.Data.Message = Util.StringToBytes256(message);
11801
11802
11803 ScriptDialogPacket.ButtonsBlock[] buttons = new ScriptDialogPacket.ButtonsBlock[1];
11804 buttons[0] = new ScriptDialogPacket.ButtonsBlock();
11805 buttons[0].ButtonLabel = Util.StringToBytes256("!!llTextBox!!");
11806 dialog.Buttons = buttons;
11807 OutPacket(dialog, ThrottleOutPacketType.Task);
11808 }
11584 } 11809 }
11585} 11810}
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLFileTransfer.cs b/OpenSim/Region/ClientStack/LindenUDP/LLFileTransfer.cs
index adf171e..10e5a95 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLFileTransfer.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLFileTransfer.cs
@@ -197,7 +197,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
197 197
198 private void Initialise(UUID fileID, string fileName) 198 private void Initialise(UUID fileID, string fileName)
199 { 199 {
200 m_asset = new AssetBase(fileID, fileName, type); 200 m_asset = new AssetBase(fileID, fileName, type, UUID.Zero.ToString());
201 m_asset.Data = new byte[0]; 201 m_asset.Data = new byte[0];
202 m_asset.Description = "empty"; 202 m_asset.Description = "empty";
203 m_asset.Local = true; 203 m_asset.Local = true;
@@ -212,6 +212,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
212 212
213 public void RequestStartXfer(IClientAPI pRemoteClient) 213 public void RequestStartXfer(IClientAPI pRemoteClient)
214 { 214 {
215 m_asset.Metadata.CreatorID = pRemoteClient.AgentId.ToString();
216
215 if (!String.IsNullOrEmpty(m_asset.Name)) 217 if (!String.IsNullOrEmpty(m_asset.Name))
216 { 218 {
217 pRemoteClient.SendXferRequest(mXferID, m_asset.Type, m_asset.FullID, 0, Utils.StringToBytes(m_asset.Name)); 219 pRemoteClient.SendXferRequest(mXferID, m_asset.Type, m_asset.FullID, 0, Utils.StringToBytes(m_asset.Name));
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs
index 55d9c9c..6232c48 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs
@@ -144,6 +144,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
144 /// <summary>A reference to the LLUDPServer that is managing this client</summary> 144 /// <summary>A reference to the LLUDPServer that is managing this client</summary>
145 private readonly LLUDPServer m_udpServer; 145 private readonly LLUDPServer m_udpServer;
146 146
147 /// <summary>Caches packed throttle information</summary>
148 private byte[] m_packedThrottles;
149
147 private int m_defaultRTO = 3000; 150 private int m_defaultRTO = 3000;
148 private int m_maxRTO = 60000; 151 private int m_maxRTO = 60000;
149 152
@@ -350,21 +353,31 @@ namespace OpenSim.Region.ClientStack.LindenUDP
350 bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture]; 353 bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture];
351 bucket.DripRate = texture; 354 bucket.DripRate = texture;
352 bucket.MaxBurst = texture; 355 bucket.MaxBurst = texture;
356
357 // Reset the packed throttles cached data
358 m_packedThrottles = null;
353 } 359 }
354 360
355 public byte[] GetThrottlesPacked() 361 public byte[] GetThrottlesPacked()
356 { 362 {
357 byte[] data = new byte[7 * 4]; 363 byte[] data = m_packedThrottles;
358 int i = 0; 364
359 365 if (data == null)
360 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate), 0, data, i, 4); i += 4; 366 {
361 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate), 0, data, i, 4); i += 4; 367 data = new byte[7 * 4];
362 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate), 0, data, i, 4); i += 4; 368 int i = 0;
363 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate), 0, data, i, 4); i += 4; 369
364 Buffer.BlockCopy(Utils.FloatToBytes((float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate) + 370 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate), 0, data, i, 4); i += 4;
365 m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate), 0, data, i, 4); i += 4; 371 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate), 0, data, i, 4); i += 4;
366 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate), 0, data, i, 4); i += 4; 372 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate), 0, data, i, 4); i += 4;
367 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate), 0, data, i, 4); i += 4; 373 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate), 0, data, i, 4); i += 4;
374 Buffer.BlockCopy(Utils.FloatToBytes((float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate) +
375 m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate), 0, data, i, 4); i += 4;
376 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate), 0, data, i, 4); i += 4;
377 Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate), 0, data, i, 4); i += 4;
378
379 m_packedThrottles = data;
380 }
368 381
369 return data; 382 return data;
370 } 383 }
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs
index 3c4fa72..41e41e4 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs
@@ -513,6 +513,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
513 byte flags = buffer.Data[0]; 513 byte flags = buffer.Data[0];
514 bool isResend = (flags & Helpers.MSG_RESENT) != 0; 514 bool isResend = (flags & Helpers.MSG_RESENT) != 0;
515 bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0; 515 bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
516 bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
516 LLUDPClient udpClient = outgoingPacket.Client; 517 LLUDPClient udpClient = outgoingPacket.Client;
517 518
518 if (!udpClient.IsConnected) 519 if (!udpClient.IsConnected)
@@ -522,23 +523,27 @@ namespace OpenSim.Region.ClientStack.LindenUDP
522 523
523 int dataLength = buffer.DataLength; 524 int dataLength = buffer.DataLength;
524 525
525 // Keep appending ACKs until there is no room left in the buffer or there are 526 // NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
526 // no more ACKs to append 527 if (!isZerocoded)
527 uint ackCount = 0;
528 uint ack;
529 while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
530 { 528 {
531 Utils.UIntToBytesBig(ack, buffer.Data, dataLength); 529 // Keep appending ACKs until there is no room left in the buffer or there are
532 dataLength += 4; 530 // no more ACKs to append
533 ++ackCount; 531 uint ackCount = 0;
534 } 532 uint ack;
533 while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
534 {
535 Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
536 dataLength += 4;
537 ++ackCount;
538 }
535 539
536 if (ackCount > 0) 540 if (ackCount > 0)
537 { 541 {
538 // Set the last byte of the packet equal to the number of appended ACKs 542 // Set the last byte of the packet equal to the number of appended ACKs
539 buffer.Data[dataLength++] = (byte)ackCount; 543 buffer.Data[dataLength++] = (byte)ackCount;
540 // Set the appended ACKs flag on this packet 544 // Set the appended ACKs flag on this packet
541 buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS); 545 buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
546 }
542 } 547 }
543 548
544 buffer.DataLength = dataLength; 549 buffer.DataLength = dataLength;
@@ -596,15 +601,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP
596 } 601 }
597 catch (MalformedDataException) 602 catch (MalformedDataException)
598 { 603 {
599 m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse packet from {0}:\n{1}",
600 buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
601 } 604 }
602 605
603 // Fail-safe check 606 // Fail-safe check
604 if (packet == null) 607 if (packet == null)
605 { 608 {
606 m_log.Warn("[LLUDPSERVER]: Couldn't build a message from incoming data " + buffer.DataLength + 609 m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}:",
607 " bytes long from " + buffer.RemoteEndPoint); 610 buffer.DataLength, buffer.RemoteEndPoint);
611 m_log.Error(Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
608 return; 612 return;
609 } 613 }
610 614
@@ -919,7 +923,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
919 // Remove this client from the scene 923 // Remove this client from the scene
920 IClientAPI client; 924 IClientAPI client;
921 if (m_scene.TryGetClient(udpClient.AgentID, out client)) 925 if (m_scene.TryGetClient(udpClient.AgentID, out client))
926 {
927 client.IsLoggingOut = true;
922 client.Close(); 928 client.Close();
929 }
923 } 930 }
924 931
925 private void IncomingPacketHandler() 932 private void IncomingPacketHandler()
@@ -1018,7 +1025,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
1018 1025
1019 // Handle outgoing packets, resends, acknowledgements, and pings for each 1026 // Handle outgoing packets, resends, acknowledgements, and pings for each
1020 // client. m_packetSent will be set to true if a packet is sent 1027 // client. m_packetSent will be set to true if a packet is sent
1021 m_scene.ForEachClient(clientPacketHandler, false); 1028 m_scene.ForEachClient(clientPacketHandler);
1022 1029
1023 // If nothing was sent, sleep for the minimum amount of time before a 1030 // If nothing was sent, sleep for the minimum amount of time before a
1024 // token bucket could get more tokens 1031 // token bucket could get more tokens
diff --git a/OpenSim/Region/ClientStack/RegionApplicationBase.cs b/OpenSim/Region/ClientStack/RegionApplicationBase.cs
index c7aeca14..e683821 100644
--- a/OpenSim/Region/ClientStack/RegionApplicationBase.cs
+++ b/OpenSim/Region/ClientStack/RegionApplicationBase.cs
@@ -56,13 +56,6 @@ namespace OpenSim.Region.ClientStack
56 56
57 protected uint m_httpServerPort; 57 protected uint m_httpServerPort;
58 58
59 public CommunicationsManager CommunicationsManager
60 {
61 get { return m_commsManager; }
62 set { m_commsManager = value; }
63 }
64 protected CommunicationsManager m_commsManager;
65
66 protected StorageManager m_storageManager; 59 protected StorageManager m_storageManager;
67 60
68 protected ClientStackManager m_clientStackManager; 61 protected ClientStackManager m_clientStackManager;
@@ -105,12 +98,14 @@ namespace OpenSim.Region.ClientStack
105 98
106 if (m_networkServersInfo.HttpUsesSSL && (m_networkServersInfo.HttpListenerPort == m_networkServersInfo.httpSSLPort)) 99 if (m_networkServersInfo.HttpUsesSSL && (m_networkServersInfo.HttpListenerPort == m_networkServersInfo.httpSSLPort))
107 { 100 {
108 m_log.Error("[HTTP]: HTTP Server config failed. HTTP Server and HTTPS server must be on different ports"); 101 m_log.Error("[REGION SERVER]: HTTP Server config failed. HTTP Server and HTTPS server must be on different ports");
109 } 102 }
110 103
111 m_log.Info("[REGION]: Starting HTTP server"); 104 m_log.InfoFormat("[REGION SERVER]: Starting HTTP server on port {0}", m_httpServerPort);
112 m_httpServer.Start(); 105 m_httpServer.Start();
113 106
107 MainServer.Instance = m_httpServer;
108
114 base.StartupSpecific(); 109 base.StartupSpecific();
115 } 110 }
116 111
@@ -134,4 +129,4 @@ namespace OpenSim.Region.ClientStack
134 return physicsPluginManager.GetPhysicsScene(engine, meshEngine, config, osSceneIdentifier); 129 return physicsPluginManager.GetPhysicsScene(engine, meshEngine, config, osSceneIdentifier);
135 } 130 }
136 } 131 }
137} 132} \ No newline at end of file
diff --git a/OpenSim/Region/Communications/Hypergrid/HGCommunicationsGridMode.cs b/OpenSim/Region/Communications/Hypergrid/HGCommunicationsGridMode.cs
deleted file mode 100644
index e80f6ab..0000000
--- a/OpenSim/Region/Communications/Hypergrid/HGCommunicationsGridMode.cs
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Reflection;
29using log4net;
30using OpenSim.Data;
31using OpenSim.Framework;
32using OpenSim.Framework.Communications;
33using OpenSim.Framework.Communications.Cache;
34using OpenSim.Framework.Servers;
35using OpenSim.Framework.Servers.HttpServer;
36using OpenSim.Region.Communications.OGS1;
37using OpenSim.Region.Framework.Scenes;
38
39namespace OpenSim.Region.Communications.Hypergrid
40{
41 public class HGCommunicationsGridMode : CommunicationsManager // CommunicationsOGS1
42 {
43
44 public HGCommunicationsGridMode(
45 NetworkServersInfo serversInfo,
46 SceneManager sman, LibraryRootFolder libraryRootFolder)
47 : base(serversInfo, libraryRootFolder)
48 {
49
50 HGUserServices userServices = new HGUserServices(this);
51 // This plugin arrangement could eventually be configurable rather than hardcoded here.
52 userServices.AddPlugin(new TemporaryUserProfilePlugin());
53 userServices.AddPlugin(new HGUserDataPlugin(this, userServices));
54
55 m_userService = userServices;
56 m_messageService = userServices;
57 m_avatarService = userServices;
58 }
59 }
60}
diff --git a/OpenSim/Region/Communications/Hypergrid/HGCommunicationsStandalone.cs b/OpenSim/Region/Communications/Hypergrid/HGCommunicationsStandalone.cs
deleted file mode 100644
index 4e3f5a1..0000000
--- a/OpenSim/Region/Communications/Hypergrid/HGCommunicationsStandalone.cs
+++ /dev/null
@@ -1,68 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using OpenSim.Data;
30using OpenSim.Framework;
31using OpenSim.Framework.Communications;
32using OpenSim.Framework.Communications.Cache;
33using OpenSim.Framework.Communications.Osp;
34using OpenSim.Framework.Servers;
35using OpenSim.Framework.Servers.HttpServer;
36using OpenSim.Region.Communications.Local;
37using OpenSim.Region.Communications.OGS1;
38
39namespace OpenSim.Region.Communications.Hypergrid
40{
41 public class HGCommunicationsStandalone : CommunicationsManager
42 {
43 public HGCommunicationsStandalone(
44 ConfigSettings configSettings,
45 NetworkServersInfo serversInfo,
46 BaseHttpServer httpServer,
47 LibraryRootFolder libraryRootFolder,
48 bool dumpAssetsToFile)
49 : base(serversInfo, libraryRootFolder)
50 {
51 LocalUserServices localUserService =
52 new LocalUserServices(
53 serversInfo.DefaultHomeLocX, serversInfo.DefaultHomeLocY, this);
54 localUserService.AddPlugin(configSettings.StandaloneUserPlugin, configSettings.StandaloneUserSource);
55
56 HGUserServices hgUserService = new HGUserServices(this, localUserService);
57 // This plugin arrangement could eventually be configurable rather than hardcoded here.
58 hgUserService.AddPlugin(new TemporaryUserProfilePlugin());
59 hgUserService.AddPlugin(new HGUserDataPlugin(this, hgUserService));
60
61 m_userService = hgUserService;
62 m_userAdminService = hgUserService;
63 m_avatarService = hgUserService;
64 m_messageService = hgUserService;
65
66 }
67 }
68}
diff --git a/OpenSim/Region/Communications/Hypergrid/HGUserDataPlugin.cs b/OpenSim/Region/Communications/Hypergrid/HGUserDataPlugin.cs
deleted file mode 100644
index 4b8fc26..0000000
--- a/OpenSim/Region/Communications/Hypergrid/HGUserDataPlugin.cs
+++ /dev/null
@@ -1,72 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Net;
32using System.Reflection;
33using System.Text.RegularExpressions;
34using System.Xml.Serialization;
35using log4net;
36using Nwc.XmlRpc;
37using OpenMetaverse;
38using OpenSim.Data;
39using OpenSim.Framework;
40using OpenSim.Framework.Communications;
41using OpenSim.Framework.Communications.Clients;
42using OpenSim.Region.Communications.OGS1;
43
44namespace OpenSim.Region.Communications.Hypergrid
45{
46 public class HGUserDataPlugin : OGS1UserDataPlugin
47 {
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49
50 HGUserServices m_UserServices;
51
52 public HGUserDataPlugin()
53 {
54 }
55
56 public HGUserDataPlugin(CommunicationsManager commsManager, HGUserServices userServices)
57 {
58 m_log.DebugFormat("[HG USER SERVICES]: {0} initialized", Name);
59 m_commsManager = commsManager;
60 m_UserServices = userServices;
61 }
62
63 protected override string GetUserServerURL(UUID userID)
64 {
65 string url = string.Empty;
66 if (m_UserServices.IsForeignUser(userID, out url))
67 return url;
68 return m_commsManager.NetworkServersInfo.UserURL;
69 }
70
71 }
72}
diff --git a/OpenSim/Region/Communications/Hypergrid/HGUserServices.cs b/OpenSim/Region/Communications/Hypergrid/HGUserServices.cs
deleted file mode 100644
index 09d8285..0000000
--- a/OpenSim/Region/Communications/Hypergrid/HGUserServices.cs
+++ /dev/null
@@ -1,337 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using OpenMetaverse;
32using OpenSim.Framework;
33using OpenSim.Framework.Communications;
34using OpenSim.Framework.Communications.Cache;
35using OpenSim.Framework.Communications.Clients;
36using OpenSim.Region.Communications.OGS1;
37using OpenSim.Region.Communications.Local;
38using OpenSim.Services.Interfaces;
39
40namespace OpenSim.Region.Communications.Hypergrid
41{
42 /// <summary>
43 /// For the time being, this class is just an identity wrapper around OGS1UserServices,
44 /// so it always fails for foreign users.
45 /// Later it needs to talk with the foreign users' user servers.
46 /// </summary>
47 public class HGUserServices : OGS1UserServices
48 {
49 //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 //private OGS1UserServices m_remoteUserServices;
52 private LocalUserServices m_localUserServices;
53
54 // Constructor called when running in grid mode
55 public HGUserServices(CommunicationsManager commsManager)
56 : base(commsManager)
57 {
58 }
59
60 // Constructor called when running in standalone
61 public HGUserServices(CommunicationsManager commsManager, LocalUserServices local)
62 : base(commsManager)
63 {
64 m_localUserServices = local;
65 }
66
67 public override void SetInventoryService(IInventoryService invService)
68 {
69 base.SetInventoryService(invService);
70 if (m_localUserServices != null)
71 m_localUserServices.SetInventoryService(invService);
72 }
73
74 public override UUID AddUser(
75 string firstName, string lastName, string password, string email, uint regX, uint regY, UUID uuid)
76 {
77 // Only valid to create users locally
78 if (m_localUserServices != null)
79 return m_localUserServices.AddUser(firstName, lastName, password, email, regX, regY, uuid);
80
81 return UUID.Zero;
82 }
83
84 public override bool AddUserAgent(UserAgentData agentdata)
85 {
86 if (m_localUserServices != null)
87 return m_localUserServices.AddUserAgent(agentdata);
88
89 return base.AddUserAgent(agentdata);
90 }
91
92 public override UserAgentData GetAgentByUUID(UUID userId)
93 {
94 string url = string.Empty;
95 if ((m_localUserServices != null) && !IsForeignUser(userId, out url))
96 return m_localUserServices.GetAgentByUUID(userId);
97
98 return base.GetAgentByUUID(userId);
99 }
100
101 public override void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
102 {
103 string url = string.Empty;
104 if ((m_localUserServices != null) && !IsForeignUser(userid, out url))
105 m_localUserServices.LogOffUser(userid, regionid, regionhandle, position, lookat);
106 else
107 base.LogOffUser(userid, regionid, regionhandle, position, lookat);
108 }
109
110 public override UserProfileData GetUserProfile(string firstName, string lastName)
111 {
112 if (m_localUserServices != null)
113 return m_localUserServices.GetUserProfile(firstName, lastName);
114
115 return base.GetUserProfile(firstName, lastName);
116 }
117
118 public override List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
119 {
120 if (m_localUserServices != null)
121 return m_localUserServices.GenerateAgentPickerRequestResponse(queryID, query);
122
123 return base.GenerateAgentPickerRequestResponse(queryID, query);
124 }
125
126 /// <summary>
127 /// Get a user profile from the user server
128 /// </summary>
129 /// <param name="avatarID"></param>
130 /// <returns>null if the request fails</returns>
131 public override UserProfileData GetUserProfile(UUID avatarID)
132 {
133 //string url = string.Empty;
134 // Unfortunately we can't query for foreigners here,
135 // because we'll end up in an infinite loop...
136 //if ((m_localUserServices != null) && (!IsForeignUser(avatarID, out url)))
137 if (m_localUserServices != null)
138 return m_localUserServices.GetUserProfile(avatarID);
139
140 return base.GetUserProfile(avatarID);
141 }
142
143 public override void ClearUserAgent(UUID avatarID)
144 {
145 if (m_localUserServices != null)
146 m_localUserServices.ClearUserAgent(avatarID);
147 else
148 base.ClearUserAgent(avatarID);
149 }
150
151 /// <summary>
152 /// Retrieve the user information for the given master uuid.
153 /// </summary>
154 /// <param name="uuid"></param>
155 /// <returns></returns>
156 public override UserProfileData SetupMasterUser(string firstName, string lastName)
157 {
158 if (m_localUserServices != null)
159 return m_localUserServices.SetupMasterUser(firstName, lastName);
160
161 return base.SetupMasterUser(firstName, lastName);
162 }
163
164 /// <summary>
165 /// Retrieve the user information for the given master uuid.
166 /// </summary>
167 /// <param name="uuid"></param>
168 /// <returns></returns>
169 public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
170 {
171 if (m_localUserServices != null)
172 return m_localUserServices.SetupMasterUser(firstName, lastName, password);
173
174 return base.SetupMasterUser(firstName, lastName, password);
175 }
176
177 /// <summary>
178 /// Retrieve the user information for the given master uuid.
179 /// </summary>
180 /// <param name="uuid"></param>
181 /// <returns></returns>
182 public override UserProfileData SetupMasterUser(UUID uuid)
183 {
184 if (m_localUserServices != null)
185 return m_localUserServices.SetupMasterUser(uuid);
186
187 return base.SetupMasterUser(uuid);
188 }
189
190 public override bool ResetUserPassword(string firstName, string lastName, string newPassword)
191 {
192 if (m_localUserServices != null)
193 return m_localUserServices.ResetUserPassword(firstName, lastName, newPassword);
194 else
195 return base.ResetUserPassword(firstName, lastName, newPassword);
196 }
197
198 public override bool UpdateUserProfile(UserProfileData userProfile)
199 {
200 string url = string.Empty;
201 if ((m_localUserServices != null) && (!IsForeignUser(userProfile.ID, out url)))
202 return m_localUserServices.UpdateUserProfile(userProfile);
203
204 return base.UpdateUserProfile(userProfile);
205 }
206
207 public override bool AuthenticateUserByPassword(UUID userID, string password)
208 {
209 if (m_localUserServices != null)
210 return m_localUserServices.AuthenticateUserByPassword(userID, password);
211 else
212 return base.AuthenticateUserByPassword(userID, password);
213 }
214
215 #region IUserServices Friend Methods
216
217 // NOTE: We're still not dealing with foreign user friends
218
219 /// <summary>
220 /// Adds a new friend to the database for XUser
221 /// </summary>
222 /// <param name="friendlistowner">The agent that who's friends list is being added to</param>
223 /// <param name="friend">The agent that being added to the friends list of the friends list owner</param>
224 /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
225 public override void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
226 {
227 if (m_localUserServices != null)
228 m_localUserServices.AddNewUserFriend(friendlistowner, friend, perms);
229 else
230 base.AddNewUserFriend(friendlistowner, friend, perms);
231 }
232
233 /// <summary>
234 /// Delete friend on friendlistowner's friendlist.
235 /// </summary>
236 /// <param name="friendlistowner">The agent that who's friends list is being updated</param>
237 /// <param name="friend">The Ex-friend agent</param>
238 public override void RemoveUserFriend(UUID friendlistowner, UUID friend)
239 {
240 if (m_localUserServices != null)
241 m_localUserServices.RemoveUserFriend(friendlistowner, friend);
242 else
243 base.RemoveUserFriend(friend, friend);
244 }
245
246 /// <summary>
247 /// Update permissions for friend on friendlistowner's friendlist.
248 /// </summary>
249 /// <param name="friendlistowner">The agent that who's friends list is being updated</param>
250 /// <param name="friend">The agent that is getting or loosing permissions</param>
251 /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
252 public override void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
253 {
254 if (m_localUserServices != null)
255 m_localUserServices.UpdateUserFriendPerms(friendlistowner, friend, perms);
256 else
257 base.UpdateUserFriendPerms(friendlistowner, friend, perms);
258 }
259 /// <summary>
260 /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner
261 /// </summary>
262 /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param>
263 public override List<FriendListItem> GetUserFriendList(UUID friendlistowner)
264 {
265 if (m_localUserServices != null)
266 return m_localUserServices.GetUserFriendList(friendlistowner);
267
268 return base.GetUserFriendList(friendlistowner);
269 }
270
271 #endregion
272
273 /// Appearance
274 public override AvatarAppearance GetUserAppearance(UUID user)
275 {
276 string url = string.Empty;
277 if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
278 return m_localUserServices.GetUserAppearance(user);
279 else
280 return base.GetUserAppearance(user);
281 }
282
283 public override void UpdateUserAppearance(UUID user, AvatarAppearance appearance)
284 {
285 string url = string.Empty;
286 if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
287 m_localUserServices.UpdateUserAppearance(user, appearance);
288 else
289 base.UpdateUserAppearance(user, appearance);
290 }
291
292 #region IMessagingService
293
294 public override Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
295 {
296 if (m_localUserServices != null)
297 return m_localUserServices.GetFriendRegionInfos(uuids);
298
299 return base.GetFriendRegionInfos(uuids);
300 }
301 #endregion
302
303 public override bool VerifySession(UUID userID, UUID sessionID)
304 {
305 string url = string.Empty;
306 if ((m_localUserServices != null) && (!IsForeignUser(userID, out url)))
307 return m_localUserServices.VerifySession(userID, sessionID);
308 else
309 return base.VerifySession(userID, sessionID);
310 }
311
312
313 protected override string GetUserServerURL(UUID userID)
314 {
315 string serverURL = string.Empty;
316 if (IsForeignUser(userID, out serverURL))
317 return serverURL;
318
319 return m_commsManager.NetworkServersInfo.UserURL;
320 }
321
322 public bool IsForeignUser(UUID userID, out string userServerURL)
323 {
324 userServerURL = m_commsManager.NetworkServersInfo.UserURL;
325 CachedUserInfo uinfo = m_commsManager.UserProfileCacheService.GetUserDetails(userID);
326 if (uinfo != null)
327 {
328 if (!HGNetworkServersInfo.Singleton.IsLocalUser(uinfo.UserProfile))
329 {
330 userServerURL = ((ForeignUserProfileData)(uinfo.UserProfile)).UserServerURI;
331 return true;
332 }
333 }
334 return false;
335 }
336 }
337}
diff --git a/OpenSim/Region/Communications/Local/CommunicationsLocal.cs b/OpenSim/Region/Communications/Local/CommunicationsLocal.cs
deleted file mode 100644
index eaf996d..0000000
--- a/OpenSim/Region/Communications/Local/CommunicationsLocal.cs
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using OpenSim.Data;
30using OpenSim.Framework;
31using OpenSim.Framework.Communications;
32using OpenSim.Framework.Communications.Cache;
33using OpenSim.Framework.Communications.Osp;
34
35namespace OpenSim.Region.Communications.Local
36{
37 public class CommunicationsLocal : CommunicationsManager
38 {
39 public CommunicationsLocal(
40 ConfigSettings configSettings,
41 NetworkServersInfo serversInfo,
42 LibraryRootFolder libraryRootFolder)
43 : base(serversInfo, libraryRootFolder)
44 {
45
46 LocalUserServices lus
47 = new LocalUserServices(
48 serversInfo.DefaultHomeLocX, serversInfo.DefaultHomeLocY, this);
49 lus.AddPlugin(new TemporaryUserProfilePlugin());
50 lus.AddPlugin(configSettings.StandaloneUserPlugin, configSettings.StandaloneUserSource);
51 m_userService = lus;
52 m_userAdminService = lus;
53 m_avatarService = lus;
54 m_messageService = lus;
55
56 //LocalLoginService loginService = CreateLoginService(libraryRootFolder, inventoryService, userService, backendService);
57 }
58 }
59}
diff --git a/OpenSim/Region/Communications/Local/LocalUserServices.cs b/OpenSim/Region/Communications/Local/LocalUserServices.cs
deleted file mode 100644
index 89b55c4..0000000
--- a/OpenSim/Region/Communications/Local/LocalUserServices.cs
+++ /dev/null
@@ -1,100 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using OpenMetaverse;
30using OpenSim.Framework;
31using OpenSim.Framework.Communications;
32using log4net;
33using System.Reflection;
34
35namespace OpenSim.Region.Communications.Local
36{
37 public class LocalUserServices : UserManagerBase
38 {
39 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
40 private readonly uint m_defaultHomeX;
41 private readonly uint m_defaultHomeY;
42
43 /// <summary>
44 /// User services used when OpenSim is running in standalone mode.
45 /// </summary>
46 /// <param name="defaultHomeLocX"></param>
47 /// <param name="defaultHomeLocY"></param>
48 /// <param name="commsManager"></param>
49 public LocalUserServices(
50 uint defaultHomeLocX, uint defaultHomeLocY, CommunicationsManager commsManager)
51 : base(commsManager)
52 {
53 m_defaultHomeX = defaultHomeLocX;
54 m_defaultHomeY = defaultHomeLocY;
55 }
56
57 public override UserProfileData SetupMasterUser(string firstName, string lastName)
58 {
59 return SetupMasterUser(firstName, lastName, String.Empty);
60 }
61
62 public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
63 {
64 UserProfileData profile = GetUserProfile(firstName, lastName);
65 if (profile != null)
66 {
67 return profile;
68 }
69
70 m_log.Debug("Unknown Master User. Sandbox Mode: Creating Account");
71 AddUser(firstName, lastName, password, "", m_defaultHomeX, m_defaultHomeY);
72 return GetUserProfile(firstName, lastName);
73 }
74
75 public override UserProfileData SetupMasterUser(UUID uuid)
76 {
77 UserProfileData data = GetUserProfile(uuid);
78 if (data == null)
79 {
80 throw new Exception("[LOCAL USER SERVICES]: Unknown master user UUID. Possible reason: UserServer is not running.");
81 }
82 return data;
83 }
84
85 public override bool AuthenticateUserByPassword(UUID userID, string password)
86 {
87 UserProfileData userProfile = GetUserProfile(userID);
88
89 if (null == userProfile)
90 return false;
91
92 string md5PasswordHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + userProfile.PasswordSalt);
93
94 if (md5PasswordHash == userProfile.PasswordHash)
95 return true;
96 else
97 return false;
98 }
99 }
100} \ No newline at end of file
diff --git a/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs b/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs
deleted file mode 100644
index c631bf7..0000000
--- a/OpenSim/Region/Communications/Local/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,65 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Reflection;
29using System.Runtime.InteropServices;
30
31// General information about an assembly is controlled through the following
32// set of attributes. Change these attribute values to modify the information
33// associated with an assembly.
34
35[assembly : AssemblyTitle("OpenSim.Region.Communications.Local")]
36[assembly : AssemblyDescription("")]
37[assembly : AssemblyConfiguration("")]
38[assembly : AssemblyCompany("http://opensimulator.org")]
39[assembly : AssemblyProduct("OpenSim.Region.Communications.Local")]
40[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")]
41[assembly : AssemblyTrademark("")]
42[assembly : AssemblyCulture("")]
43
44// Setting ComVisible to false makes the types in this assembly not visible
45// to COM components. If you need to access a type in this assembly from
46// COM, set the ComVisible attribute to true on that type.
47
48[assembly : ComVisible(false)]
49
50// The following GUID is for the ID of the typelib if this project is exposed to COM
51
52[assembly : Guid("fb173926-bd0a-4cd0-bb45-185b2f72ddfb")]
53
54// Version information for an assembly consists of the following four values:
55//
56// Major Version
57// Minor Version
58// Build Number
59// Revision
60//
61// You can specify all the values or you can default the Revision and Build Numbers
62// by using the '*' as shown below:
63
64[assembly : AssemblyVersion("0.6.5.*")]
65[assembly : AssemblyFileVersion("0.6.5.0")]
diff --git a/OpenSim/Region/Communications/OGS1/OGS1UserDataPlugin.cs b/OpenSim/Region/Communications/OGS1/OGS1UserDataPlugin.cs
deleted file mode 100644
index cb1766a..0000000
--- a/OpenSim/Region/Communications/OGS1/OGS1UserDataPlugin.cs
+++ /dev/null
@@ -1,774 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Net;
32using System.Reflection;
33using System.Text.RegularExpressions;
34using System.Xml.Serialization;
35using log4net;
36using Nwc.XmlRpc;
37using OpenMetaverse;
38using OpenSim.Data;
39using OpenSim.Framework;
40using OpenSim.Framework.Communications;
41using OpenSim.Framework.Communications.Clients;
42
43namespace OpenSim.Region.Communications.OGS1
44{
45 public class OGS1UserDataPlugin : IUserDataPlugin
46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48
49 protected CommunicationsManager m_commsManager;
50
51 public OGS1UserDataPlugin()
52 {
53 }
54
55 public OGS1UserDataPlugin(CommunicationsManager commsManager)
56 {
57 m_log.DebugFormat("[OGS1 USER SERVICES]: {0} initialized", Name);
58 m_commsManager = commsManager;
59 }
60
61 public string Version { get { return "0.1"; } }
62 public string Name { get { return "Open Grid Services 1 (OGS1) User Data Plugin"; } }
63 public void Initialise() {}
64
65 public void Initialise(string connect) {}
66
67 public void Dispose() {}
68
69 // Arguably the presence of these means that IUserDataPlugin could be fissioned
70 public UserAgentData GetUserAgent(string name) { return null; }
71 public UserAgentData GetAgentByName(string name) { return null; }
72 public UserAgentData GetAgentByName(string fname, string lname) { return null; }
73 public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {}
74 public void AddNewUserProfile(UserProfileData user) {}
75 public void AddNewUserAgent(UserAgentData agent) {}
76 public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; }
77 public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; }
78 public void ResetAttachments(UUID userID) {}
79 public void LogoutUsers(UUID regionID) {}
80
81 public virtual void AddTemporaryUserProfile(UserProfileData userProfile)
82 {
83 // Not interested
84 }
85
86 public UserProfileData GetUserByUri(Uri uri)
87 {
88 WebRequest request = WebRequest.Create(uri);
89
90 WebResponse webResponse = request.GetResponse();
91
92 XmlSerializer deserializer = new XmlSerializer(typeof(XmlRpcResponse));
93 XmlRpcResponse xmlRpcResponse = (XmlRpcResponse)deserializer.Deserialize(webResponse.GetResponseStream());
94
95 Hashtable respData = (Hashtable)xmlRpcResponse.Value;
96
97 return ConvertXMLRPCDataToUserProfile(respData);
98 }
99
100// public Uri GetUserUri(UserProfileData userProfile)
101// {
102// throw new NotImplementedException();
103// }
104
105 public virtual UserAgentData GetAgentByUUID(UUID userId)
106 {
107 try
108 {
109 Hashtable param = new Hashtable();
110 param["avatar_uuid"] = userId.ToString();
111 IList parameters = new ArrayList();
112 parameters.Add(param);
113 XmlRpcRequest req = new XmlRpcRequest("get_agent_by_uuid", parameters);
114
115 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 6000);
116 Hashtable respData = (Hashtable)resp.Value;
117 if (respData.Contains("error_type"))
118 {
119 //m_log.Warn("[GRID]: " +
120 // "Error sent by user server when trying to get agent: (" +
121 // (string) respData["error_type"] +
122 // "): " + (string)respData["error_desc"]);
123 return null;
124 }
125 UUID sessionid = UUID.Zero;
126
127 UserAgentData userAgent = new UserAgentData();
128 userAgent.Handle = Convert.ToUInt64((string)respData["handle"]);
129 UUID.TryParse((string)respData["sessionid"], out sessionid);
130 userAgent.SessionID = sessionid;
131
132 if ((string)respData["agent_online"] == "TRUE")
133 {
134 userAgent.AgentOnline = true;
135 }
136 else
137 {
138 userAgent.AgentOnline = false;
139 }
140
141 return userAgent;
142 }
143 catch (Exception e)
144 {
145 m_log.ErrorFormat(
146 "[OGS1 USER SERVICES]: Error when trying to fetch agent data by uuid from remote user server: {0}",
147 e);
148 }
149
150 return null;
151 }
152
153 public virtual UserProfileData GetUserByName(string firstName, string lastName)
154 {
155 return GetUserProfile(firstName + " " + lastName);
156 }
157
158 public virtual List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query)
159 {
160 List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>();
161 Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9 ]");
162 try
163 {
164 Hashtable param = new Hashtable();
165 param["queryid"] = (string)queryID.ToString();
166 param["avquery"] = objAlphaNumericPattern.Replace(query, String.Empty);
167 IList parameters = new ArrayList();
168 parameters.Add(param);
169 XmlRpcRequest req = new XmlRpcRequest("get_avatar_picker_avatar", parameters);
170 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000);
171 Hashtable respData = (Hashtable)resp.Value;
172 pickerlist = ConvertXMLRPCDataToAvatarPickerList(queryID, respData);
173 }
174 catch (WebException e)
175 {
176 m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar Picker Response: " +
177 e.Message);
178 // Return Empty picker list (no results)
179 }
180 return pickerlist;
181 }
182
183 /// <summary>
184 /// Get a user profile from the user server
185 /// </summary>
186 /// <param name="avatarID"></param>
187 /// <returns>null if the request fails</returns>
188 protected virtual UserProfileData GetUserProfile(string name)
189 {
190 try
191 {
192 Hashtable param = new Hashtable();
193 param["avatar_name"] = name;
194 IList parameters = new ArrayList();
195 parameters.Add(param);
196 XmlRpcRequest req = new XmlRpcRequest("get_user_by_name", parameters);
197 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000);
198 Hashtable respData = (Hashtable)resp.Value;
199
200 return ConvertXMLRPCDataToUserProfile(respData);
201 }
202 catch (WebException e)
203 {
204 m_log.ErrorFormat(
205 "[OGS1 USER SERVICES]: Error when trying to fetch profile data by name from remote user server: {0}",
206 e);
207 }
208
209 return null;
210 }
211
212 /// <summary>
213 /// Get a user profile from the user server
214 /// </summary>
215 /// <param name="avatarID"></param>
216 /// <returns>null if the request fails</returns>
217 public virtual UserProfileData GetUserByUUID(UUID avatarID)
218 {
219 try
220 {
221 Hashtable param = new Hashtable();
222 param["avatar_uuid"] = avatarID.ToString();
223 IList parameters = new ArrayList();
224 parameters.Add(param);
225 XmlRpcRequest req = new XmlRpcRequest("get_user_by_uuid", parameters);
226 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000);
227 Hashtable respData = (Hashtable)resp.Value;
228
229 return ConvertXMLRPCDataToUserProfile(respData);
230 }
231 catch (Exception e)
232 {
233 m_log.ErrorFormat(
234 "[OGS1 USER SERVICES]: Error when trying to fetch profile data by uuid from remote user server: {0}",
235 e);
236 }
237
238 return null;
239 }
240
241 public virtual bool UpdateUserProfile(UserProfileData userProfile)
242 {
243 m_log.Debug("[OGS1 USER SERVICES]: Asking UserServer to update profile.");
244
245 Hashtable param = new Hashtable();
246 param["avatar_uuid"] = userProfile.ID.ToString();
247 //param["AllowPublish"] = userProfile.ToString();
248 param["FLImageID"] = userProfile.FirstLifeImage.ToString();
249 param["ImageID"] = userProfile.Image.ToString();
250 //param["MaturePublish"] = MaturePublish.ToString();
251 param["AboutText"] = userProfile.AboutText;
252 param["FLAboutText"] = userProfile.FirstLifeAboutText;
253 //param["ProfileURL"] = userProfile.ProfileURL.ToString();
254
255 param["home_region"] = userProfile.HomeRegion.ToString();
256 param["home_region_id"] = userProfile.HomeRegionID.ToString();
257
258 param["home_pos_x"] = userProfile.HomeLocationX.ToString();
259 param["home_pos_y"] = userProfile.HomeLocationY.ToString();
260 param["home_pos_z"] = userProfile.HomeLocationZ.ToString();
261 param["home_look_x"] = userProfile.HomeLookAtX.ToString();
262 param["home_look_y"] = userProfile.HomeLookAtY.ToString();
263 param["home_look_z"] = userProfile.HomeLookAtZ.ToString();
264 param["user_flags"] = userProfile.UserFlags.ToString();
265 param["god_level"] = userProfile.GodLevel.ToString();
266 param["custom_type"] = userProfile.CustomType.ToString();
267 param["partner"] = userProfile.Partner.ToString();
268
269 IList parameters = new ArrayList();
270 parameters.Add(param);
271
272 XmlRpcRequest req = new XmlRpcRequest("update_user_profile", parameters);
273 XmlRpcResponse resp = req.Send(GetUserServerURL(userProfile.ID), 3000);
274 Hashtable respData = (Hashtable)resp.Value;
275 if (respData != null)
276 {
277 if (respData.Contains("returnString"))
278 {
279 if (((string)respData["returnString"]).ToUpper() != "TRUE")
280 {
281 m_log.Warn("[GRID]: Unable to update user profile, User Server Reported an issue");
282 return false;
283 }
284 }
285 else
286 {
287 m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!");
288 return false;
289 }
290 }
291 else
292 {
293 m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!");
294 return false;
295 }
296
297 return true;
298 }
299
300 /// <summary>
301 /// Adds a new friend to the database for XUser
302 /// </summary>
303 /// <param name="friendlistowner">The agent that who's friends list is being added to</param>
304 /// <param name="friend">The agent that being added to the friends list of the friends list owner</param>
305 /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
306 public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
307 {
308 try
309 {
310 Hashtable param = new Hashtable();
311 param["ownerID"] = friendlistowner.Guid.ToString();
312 param["friendID"] = friend.Guid.ToString();
313 param["friendPerms"] = perms.ToString();
314 IList parameters = new ArrayList();
315 parameters.Add(param);
316
317 XmlRpcRequest req = new XmlRpcRequest("add_new_user_friend", parameters);
318 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000);
319 Hashtable respData = (Hashtable)resp.Value;
320 if (respData != null)
321 {
322 if (respData.Contains("returnString"))
323 {
324 if ((string)respData["returnString"] == "TRUE")
325 {
326
327 }
328 else
329 {
330 m_log.Warn("[GRID]: Unable to add new friend, User Server Reported an issue");
331 }
332 }
333 else
334 {
335 m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!");
336 }
337 }
338 else
339 {
340 m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!");
341
342 }
343 }
344 catch (WebException e)
345 {
346 m_log.Warn("[GRID]: Error when trying to AddNewUserFriend: " +
347 e.Message);
348
349 }
350 }
351
352 /// <summary>
353 /// Delete friend on friendlistowner's friendlist.
354 /// </summary>
355 /// <param name="friendlistowner">The agent that who's friends list is being updated</param>
356 /// <param name="friend">The Ex-friend agent</param>
357 public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend)
358 {
359 try
360 {
361 Hashtable param = new Hashtable();
362 param["ownerID"] = friendlistowner.Guid.ToString();
363 param["friendID"] = friend.Guid.ToString();
364
365 IList parameters = new ArrayList();
366 parameters.Add(param);
367
368 XmlRpcRequest req = new XmlRpcRequest("remove_user_friend", parameters);
369 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000);
370 Hashtable respData = (Hashtable)resp.Value;
371 if (respData != null)
372 {
373 if (respData.Contains("returnString"))
374 {
375 if ((string)respData["returnString"] == "TRUE")
376 {
377
378 }
379 else
380 {
381 m_log.Warn("[GRID]: Unable to remove friend, User Server Reported an issue");
382 }
383 }
384 else
385 {
386 m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!");
387 }
388 }
389 else
390 {
391 m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!");
392
393 }
394 }
395 catch (WebException e)
396 {
397 m_log.Warn("[GRID]: Error when trying to RemoveUserFriend: " +
398 e.Message);
399
400 }
401 }
402
403 /// <summary>
404 /// Update permissions for friend on friendlistowner's friendlist.
405 /// </summary>
406 /// <param name="friendlistowner">The agent that who's friends list is being updated</param>
407 /// <param name="friend">The agent that is getting or loosing permissions</param>
408 /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
409 public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
410 {
411 try
412 {
413 Hashtable param = new Hashtable();
414 param["ownerID"] = friendlistowner.Guid.ToString();
415 param["friendID"] = friend.Guid.ToString();
416 param["friendPerms"] = perms.ToString();
417 IList parameters = new ArrayList();
418 parameters.Add(param);
419
420 XmlRpcRequest req = new XmlRpcRequest("update_user_friend_perms", parameters);
421 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000);
422 Hashtable respData = (Hashtable)resp.Value;
423 if (respData != null)
424 {
425 if (respData.Contains("returnString"))
426 {
427 if ((string)respData["returnString"] == "TRUE")
428 {
429
430 }
431 else
432 {
433 m_log.Warn("[GRID]: Unable to update_user_friend_perms, User Server Reported an issue");
434 }
435 }
436 else
437 {
438 m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!");
439 }
440 }
441 else
442 {
443 m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!");
444
445 }
446 }
447 catch (WebException e)
448 {
449 m_log.Warn("[GRID]: Error when trying to update_user_friend_perms: " +
450 e.Message);
451 }
452 }
453 /// <summary>
454 /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner
455 /// </summary>
456 /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param>
457 public virtual List<FriendListItem> GetUserFriendList(UUID friendlistowner)
458 {
459 List<FriendListItem> buddylist = new List<FriendListItem>();
460
461 try
462 {
463 Hashtable param = new Hashtable();
464 param["ownerID"] = friendlistowner.Guid.ToString();
465
466 IList parameters = new ArrayList();
467 parameters.Add(param);
468 XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters);
469 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 8000);
470 Hashtable respData = (Hashtable)resp.Value;
471
472 if (respData != null && respData.Contains("avcount"))
473 {
474 buddylist = ConvertXMLRPCDataToFriendListItemList(respData);
475 }
476
477 }
478 catch (WebException e)
479 {
480 m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar's friends list: " +
481 e.Message);
482 // Return Empty list (no friends)
483 }
484 return buddylist;
485 }
486
487 public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
488 {
489 Dictionary<UUID, FriendRegionInfo> result = new Dictionary<UUID, FriendRegionInfo>();
490
491 // ask MessageServer about the current on-/offline status and regions the friends are in
492 ArrayList parameters = new ArrayList();
493 Hashtable map = new Hashtable();
494
495 ArrayList list = new ArrayList();
496 foreach (UUID uuid in uuids)
497 {
498 list.Add(uuid.ToString());
499 list.Add(uuid.ToString());
500 }
501 map["uuids"] = list;
502
503 map["recv_key"] = m_commsManager.NetworkServersInfo.UserRecvKey;
504 map["send_key"] = m_commsManager.NetworkServersInfo.UserSendKey;
505
506 parameters.Add(map);
507
508 try
509 {
510 XmlRpcRequest req = new XmlRpcRequest("get_presence_info_bulk", parameters);
511 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.MessagingURL, 8000);
512 Hashtable respData = resp != null ? (Hashtable)resp.Value : null;
513
514 if (respData == null || respData.ContainsKey("faultMessage"))
515 {
516 m_log.WarnFormat("[OGS1 USER SERVICES]: Contacting MessagingServer about user-regions resulted in error: {0}",
517 respData == null ? "<unknown error>" : respData["faultMessage"]);
518 }
519 else if (!respData.ContainsKey("count"))
520 {
521 m_log.WarnFormat("[OGS1 USER SERVICES]: Wrong format in response for MessagingServer request get_presence_info_bulk: missing 'count' field");
522 }
523 else
524 {
525 int count = (int)respData["count"];
526 m_log.DebugFormat("[OGS1 USER SERVICES]: Request returned {0} results.", count);
527 for (int i = 0; i < count; ++i)
528 {
529 if (respData.ContainsKey("uuid_" + i) && respData.ContainsKey("isOnline_" + i) && respData.ContainsKey("regionHandle_" + i))
530 {
531 UUID uuid;
532 if (UUID.TryParse((string)respData["uuid_" + i], out uuid))
533 {
534 FriendRegionInfo info = new FriendRegionInfo();
535 info.isOnline = (bool)respData["isOnline_" + i];
536 if (info.isOnline)
537 {
538 // TODO remove this after the next protocol update (say, r7800?)
539 info.regionHandle = Convert.ToUInt64(respData["regionHandle_" + i]);
540
541 // accept missing id
542 if (respData.ContainsKey("regionID_" + i))
543 UUID.TryParse((string)respData["regionID_" + i], out info.regionID);
544 }
545
546 result.Add(uuid, info);
547 }
548 }
549 else
550 {
551 m_log.WarnFormat("[OGS1 USER SERVICES]: Response to get_presence_info_bulk contained an error in entry {0}", i);
552 }
553 }
554 }
555 }
556 catch (WebException e)
557 {
558 m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch friend infos: {0}", e.Message);
559 }
560
561 m_log.DebugFormat("[OGS1 USER SERVICES]: Returning {0} entries", result.Count);
562
563 return result;
564 }
565
566 public virtual AvatarAppearance GetUserAppearance(UUID user)
567 {
568 AvatarAppearance appearance = null;
569
570 try
571 {
572 Hashtable param = new Hashtable();
573 param["owner"] = user.ToString();
574
575 IList parameters = new ArrayList();
576 parameters.Add(param);
577 XmlRpcRequest req = new XmlRpcRequest("get_avatar_appearance", parameters);
578 XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000);
579 Hashtable respData = (Hashtable)resp.Value;
580
581 return ConvertXMLRPCDataToAvatarAppearance(respData);
582 }
583 catch (WebException e)
584 {
585 m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch appearance for avatar {0}, {1}", user, e.Message);
586 }
587
588 return appearance;
589 }
590
591 public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance)
592 {
593 try
594 {
595 Hashtable param = appearance.ToHashTable();
596 param["owner"] = user.ToString();
597
598 IList parameters = new ArrayList();
599 parameters.Add(param);
600 XmlRpcRequest req = new XmlRpcRequest("update_avatar_appearance", parameters);
601 XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000);
602 Hashtable respData = (Hashtable)resp.Value;
603
604 if (respData != null)
605 {
606 if (respData.Contains("returnString"))
607 {
608 if ((string)respData["returnString"] == "TRUE")
609 {
610 m_log.DebugFormat("[OGS1 USER SERVICES]: Updated user appearance in {0}", GetUserServerURL(user));
611 }
612 else
613 {
614 m_log.Warn("[GRID]: Unable to update_user_appearance, User Server Reported an issue");
615 }
616 }
617 else
618 {
619 m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!");
620 }
621 }
622 else
623 {
624 m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!");
625 }
626 }
627 catch (WebException e)
628 {
629 m_log.WarnFormat("[OGS1 USER SERVICES]: Error when trying to update Avatar's appearance in {0}: {1}",
630 GetUserServerURL(user), e.Message);
631 // Return Empty list (no friends)
632 }
633 }
634
635 protected virtual string GetUserServerURL(UUID userID)
636 {
637 return m_commsManager.NetworkServersInfo.UserURL;
638 }
639
640 protected UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data)
641 {
642 if (data.Contains("error_type"))
643 {
644 //m_log.Warn("[GRID]: " +
645 // "Error sent by user server when trying to get user profile: (" +
646 // data["error_type"] +
647 // "): " + data["error_desc"]);
648 return null;
649 }
650
651 UserProfileData userData = new UserProfileData();
652 userData.FirstName = (string)data["firstname"];
653 userData.SurName = (string)data["lastname"];
654 if (data["email"] != null)
655 userData.Email = (string)data["email"];
656 userData.ID = new UUID((string)data["uuid"]);
657 userData.Created = Convert.ToInt32(data["profile_created"]);
658 if (data.Contains("server_inventory") && data["server_inventory"] != null)
659 userData.UserInventoryURI = (string)data["server_inventory"];
660 if (data.Contains("server_asset") && data["server_asset"] != null)
661 userData.UserAssetURI = (string)data["server_asset"];
662 if (data.Contains("profile_firstlife_about") && data["profile_firstlife_about"] != null)
663 userData.FirstLifeAboutText = (string)data["profile_firstlife_about"];
664 userData.FirstLifeImage = new UUID((string)data["profile_firstlife_image"]);
665 userData.CanDoMask = Convert.ToUInt32((string)data["profile_can_do"]);
666 userData.WantDoMask = Convert.ToUInt32(data["profile_want_do"]);
667 userData.AboutText = (string)data["profile_about"];
668 userData.Image = new UUID((string)data["profile_image"]);
669 userData.LastLogin = Convert.ToInt32((string)data["profile_lastlogin"]);
670 userData.HomeRegion = Convert.ToUInt64((string)data["home_region"]);
671 if (data.Contains("home_region_id"))
672 userData.HomeRegionID = new UUID((string)data["home_region_id"]);
673 else
674 userData.HomeRegionID = UUID.Zero;
675 userData.HomeLocation =
676 new Vector3((float)Convert.ToDecimal((string)data["home_coordinates_x"], Culture.NumberFormatInfo),
677 (float)Convert.ToDecimal((string)data["home_coordinates_y"], Culture.NumberFormatInfo),
678 (float)Convert.ToDecimal((string)data["home_coordinates_z"], Culture.NumberFormatInfo));
679 userData.HomeLookAt =
680 new Vector3((float)Convert.ToDecimal((string)data["home_look_x"], Culture.NumberFormatInfo),
681 (float)Convert.ToDecimal((string)data["home_look_y"], Culture.NumberFormatInfo),
682 (float)Convert.ToDecimal((string)data["home_look_z"], Culture.NumberFormatInfo));
683 if (data.Contains("user_flags"))
684 userData.UserFlags = Convert.ToInt32((string)data["user_flags"]);
685 if (data.Contains("god_level"))
686 userData.GodLevel = Convert.ToInt32((string)data["god_level"]);
687
688 if (data.Contains("custom_type"))
689 userData.CustomType = (string)data["custom_type"];
690 else
691 userData.CustomType = "";
692 if (userData.CustomType == null)
693 userData.CustomType = "";
694
695 if (data.Contains("partner"))
696 userData.Partner = new UUID((string)data["partner"]);
697 else
698 userData.Partner = UUID.Zero;
699
700 return userData;
701 }
702
703 protected AvatarAppearance ConvertXMLRPCDataToAvatarAppearance(Hashtable data)
704 {
705 if (data != null)
706 {
707 if (data.Contains("error_type"))
708 {
709 m_log.Warn("[GRID]: " +
710 "Error sent by user server when trying to get user appearance: (" +
711 data["error_type"] +
712 "): " + data["error_desc"]);
713 return null;
714 }
715 else
716 {
717 return new AvatarAppearance(data);
718 }
719 }
720 else
721 {
722 m_log.Error("[GRID]: The avatar appearance is null, something bad happenend");
723 return null;
724 }
725 }
726
727 protected List<AvatarPickerAvatar> ConvertXMLRPCDataToAvatarPickerList(UUID queryID, Hashtable data)
728 {
729 List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>();
730 int pickercount = Convert.ToInt32((string)data["avcount"]);
731 UUID respqueryID = new UUID((string)data["queryid"]);
732 if (queryID == respqueryID)
733 {
734 for (int i = 0; i < pickercount; i++)
735 {
736 AvatarPickerAvatar apicker = new AvatarPickerAvatar();
737 UUID avatarID = new UUID((string)data["avatarid" + i.ToString()]);
738 string firstname = (string)data["firstname" + i.ToString()];
739 string lastname = (string)data["lastname" + i.ToString()];
740 apicker.AvatarID = avatarID;
741 apicker.firstName = firstname;
742 apicker.lastName = lastname;
743 pickerlist.Add(apicker);
744 }
745 }
746 else
747 {
748 m_log.Warn("[OGS1 USER SERVICES]: Got invalid queryID from userServer");
749 }
750 return pickerlist;
751 }
752
753 protected List<FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
754 {
755 List<FriendListItem> buddylist = new List<FriendListItem>();
756 int buddycount = Convert.ToInt32((string)data["avcount"]);
757
758
759 for (int i = 0; i < buddycount; i++)
760 {
761 FriendListItem buddylistitem = new FriendListItem();
762
763 buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
764 buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
765 buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
766 buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
767
768 buddylist.Add(buddylistitem);
769 }
770
771 return buddylist;
772 }
773 }
774}
diff --git a/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs b/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs
deleted file mode 100644
index ed3526d..0000000
--- a/OpenSim/Region/Communications/OGS1/OGS1UserServices.cs
+++ /dev/null
@@ -1,176 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Net;
32using System.Reflection;
33using System.Text.RegularExpressions;
34using System.Xml.Serialization;
35using log4net;
36using Nwc.XmlRpc;
37using OpenMetaverse;
38using OpenSim.Data;
39using OpenSim.Framework;
40using OpenSim.Framework.Communications;
41using OpenSim.Framework.Communications.Clients;
42
43namespace OpenSim.Region.Communications.OGS1
44{
45 public class OGS1UserServices : UserManagerBase
46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48
49 public OGS1UserServices(CommunicationsManager commsManager)
50 : base(commsManager)
51 {
52 }
53
54 public override void ClearUserAgent(UUID avatarID)
55 {
56 // TODO: implement
57 // It may be possible to use the UserManagerBase implementation.
58 }
59
60 protected virtual string GetUserServerURL(UUID userID)
61 {
62 return m_commsManager.NetworkServersInfo.UserURL;
63 }
64
65 /// <summary>
66 /// Logs off a user on the user server
67 /// </summary>
68 /// <param name="UserID">UUID of the user</param>
69 /// <param name="regionID">UUID of the Region</param>
70 /// <param name="regionhandle">regionhandle</param>
71 /// <param name="position">final position</param>
72 /// <param name="lookat">final lookat</param>
73 public override void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
74 {
75 Hashtable param = new Hashtable();
76 param["avatar_uuid"] = userid.Guid.ToString();
77 param["region_uuid"] = regionid.Guid.ToString();
78 param["region_handle"] = regionhandle.ToString();
79 param["region_pos_x"] = position.X.ToString();
80 param["region_pos_y"] = position.Y.ToString();
81 param["region_pos_z"] = position.Z.ToString();
82 param["lookat_x"] = lookat.X.ToString();
83 param["lookat_y"] = lookat.Y.ToString();
84 param["lookat_z"] = lookat.Z.ToString();
85
86 IList parameters = new ArrayList();
87 parameters.Add(param);
88 XmlRpcRequest req = new XmlRpcRequest("logout_of_simulator", parameters);
89
90 try
91 {
92 req.Send(GetUserServerURL(userid), 3000);
93 }
94 catch (WebException)
95 {
96 m_log.Warn("[LOGOFF]: Unable to notify grid server of user logoff");
97 }
98 }
99
100 /// <summary>
101 /// Retrieve the user information for the given master uuid.
102 /// </summary>
103 /// <param name="uuid"></param>
104 /// <returns></returns>
105 public override UserProfileData SetupMasterUser(string firstName, string lastName)
106 {
107 return SetupMasterUser(firstName, lastName, String.Empty);
108 }
109
110 /// <summary>
111 /// Retrieve the user information for the given master uuid.
112 /// </summary>
113 /// <param name="uuid"></param>
114 /// <returns></returns>
115 public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
116 {
117 UserProfileData profile = GetUserProfile(firstName, lastName);
118 return profile;
119 }
120
121 /// <summary>
122 /// Retrieve the user information for the given master uuid.
123 /// </summary>
124 /// <param name="uuid"></param>
125 /// <returns></returns>
126 public override UserProfileData SetupMasterUser(UUID uuid)
127 {
128 UserProfileData data = GetUserProfile(uuid);
129
130 if (data == null)
131 {
132 throw new Exception(
133 "Could not retrieve profile for master user " + uuid + ". User server did not respond to the request.");
134 }
135
136 return data;
137 }
138
139 public override bool VerifySession(UUID userID, UUID sessionID)
140 {
141 m_log.DebugFormat("[OGS1 USER SERVICES]: Verifying user session for " + userID);
142 return AuthClient.VerifySession(GetUserServerURL(userID), userID, sessionID);
143 }
144
145 public override bool AuthenticateUserByPassword(UUID userID, string password)
146 {
147 Hashtable param = new Hashtable();
148 param["user_uuid"] = userID.ToString();
149 param["password"] = password;
150 IList parameters = new ArrayList();
151 parameters.Add(param);
152 XmlRpcRequest req = new XmlRpcRequest("authenticate_user_by_password", parameters);
153 XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000);
154
155 // Temporary measure to deal with older services
156 if (resp.IsFault && resp.FaultCode == XmlRpcErrorCodes.SERVER_ERROR_METHOD)
157 {
158 throw new Exception(
159 String.Format(
160 "XMLRPC method 'authenticate_user_by_password' not yet implemented by user service at {0}",
161 m_commsManager.NetworkServersInfo.UserURL));
162 }
163
164 Hashtable respData = (Hashtable)resp.Value;
165
166 if ((string)respData["auth_user"] == "TRUE")
167 {
168 return true;
169 }
170 else
171 {
172 return false;
173 }
174 }
175 }
176} \ No newline at end of file
diff --git a/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs b/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs
deleted file mode 100644
index 2b54f2e..0000000
--- a/OpenSim/Region/Communications/OGS1/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,65 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Reflection;
29using System.Runtime.InteropServices;
30
31// General information about an assembly is controlled through the following
32// set of attributes. Change these attribute values to modify the information
33// associated with an assembly.
34
35[assembly : AssemblyTitle("OpenGrid.Framework.Communications.OGS1")]
36[assembly : AssemblyDescription("")]
37[assembly : AssemblyConfiguration("")]
38[assembly : AssemblyCompany("http://opensimulator.org")]
39[assembly : AssemblyProduct("OpenGrid.Framework.Communications.OGS1")]
40[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")]
41[assembly : AssemblyTrademark("")]
42[assembly : AssemblyCulture("")]
43
44// Setting ComVisible to false makes the types in this assembly not visible
45// to COM components. If you need to access a type in this assembly from
46// COM, set the ComVisible attribute to true on that type.
47
48[assembly : ComVisible(false)]
49
50// The following GUID is for the ID of the typelib if this project is exposed to COM
51
52[assembly : Guid("a8b2b39b-c83b-41e2-b0b5-7ccfc1fddae7")]
53
54// Version information for an assembly consists of the following four values:
55//
56// Major Version
57// Minor Version
58// Build Number
59// Revision
60//
61// You can specify all the values or you can default the Revision and Build Numbers
62// by using the '*' as shown below:
63
64[assembly : AssemblyVersion("0.6.5.*")]
65[assembly : AssemblyFileVersion("0.6.5.0")]
diff --git a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AgentAssetsTransactions.cs b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AgentAssetsTransactions.cs
index c9ee54f..d30e954 100644
--- a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AgentAssetsTransactions.cs
+++ b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AgentAssetsTransactions.cs
@@ -30,7 +30,7 @@ using System.Reflection;
30using log4net; 30using log4net;
31using OpenMetaverse; 31using OpenMetaverse;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Framework.Communications.Cache; 33
34using OpenSim.Region.Framework.Scenes; 34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Services.Interfaces; 35using OpenSim.Services.Interfaces;
36 36
@@ -181,7 +181,10 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
181 Manager.MyScene.AssetService.Store(asset); 181 Manager.MyScene.AssetService.Store(asset);
182 182
183 if (part.Inventory.UpdateInventoryItem(item)) 183 if (part.Inventory.UpdateInventoryItem(item))
184 {
185 remoteClient.SendAgentAlertMessage("Notecard saved", false);
184 part.GetProperties(remoteClient); 186 part.GetProperties(remoteClient);
187 }
185 } 188 }
186 } 189 }
187 } 190 }
diff --git a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
index fa92fe8..c791cb4 100644
--- a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
+++ b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
@@ -31,7 +31,7 @@ using System.Reflection;
31using log4net; 31using log4net;
32using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications.Cache; 34
35using OpenSim.Services.Interfaces; 35using OpenSim.Services.Interfaces;
36 36
37namespace OpenSim.Region.CoreModules.Agent.AssetTransaction 37namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
@@ -112,7 +112,7 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
112 bool storeLocal, bool tempFile) 112 bool storeLocal, bool tempFile)
113 { 113 {
114 ourClient = remoteClient; 114 ourClient = remoteClient;
115 m_asset = new AssetBase(assetID, "blank", type); 115 m_asset = new AssetBase(assetID, "blank", type, remoteClient.AgentId.ToString());
116 m_asset.Data = data; 116 m_asset.Data = data;
117 m_asset.Description = "empty"; 117 m_asset.Description = "empty";
118 m_asset.Local = storeLocal; 118 m_asset.Local = storeLocal;
diff --git a/OpenSim/Region/CoreModules/Agent/TextureDownload/TextureDownloadModule.cs b/OpenSim/Region/CoreModules/Agent/TextureDownload/TextureDownloadModule.cs
index 71ff28c..c7bf6c8 100644
--- a/OpenSim/Region/CoreModules/Agent/TextureDownload/TextureDownloadModule.cs
+++ b/OpenSim/Region/CoreModules/Agent/TextureDownload/TextureDownloadModule.cs
@@ -33,7 +33,7 @@ using log4net;
33using Nini.Config; 33using Nini.Config;
34using OpenMetaverse; 34using OpenMetaverse;
35using OpenSim.Framework; 35using OpenSim.Framework;
36using OpenSim.Framework.Communications.Cache; 36
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
39using BlockingQueue = OpenSim.Framework.BlockingQueue<OpenSim.Region.Framework.Interfaces.ITextureSender>; 39using BlockingQueue = OpenSim.Framework.BlockingQueue<OpenSim.Region.Framework.Interfaces.ITextureSender>;
@@ -214,8 +214,8 @@ namespace OpenSim.Region.CoreModules.Agent.TextureDownload
214 { 214 {
215 Scene scene = (Scene)client.Scene; 215 Scene scene = (Scene)client.Scene;
216 216
217 CachedUserInfo profile = scene.CommsManager.UserProfileCacheService.GetUserDetails(client.AgentId); 217 ScenePresence sp = scene.GetScenePresence(client.AgentId);
218 if (profile == null) // Deny unknown user 218 if (sp == null) // Deny unknown user
219 return; 219 return;
220 220
221 IInventoryService invService = scene.InventoryService; 221 IInventoryService invService = scene.InventoryService;
diff --git a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
index 7ac8bed..1386e86 100644
--- a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
+++ b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
@@ -60,6 +60,8 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
60 60
61 #region IRegionModule 61 #region IRegionModule
62 62
63 private bool m_useCSJ2K = true;
64
63 public string Name { get { return "J2KDecoderModule"; } } 65 public string Name { get { return "J2KDecoderModule"; } }
64 public bool IsSharedModule { get { return true; } } 66 public bool IsSharedModule { get { return true; } }
65 67
@@ -73,6 +75,12 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
73 m_scene = scene; 75 m_scene = scene;
74 76
75 scene.RegisterModuleInterface<IJ2KDecoder>(this); 77 scene.RegisterModuleInterface<IJ2KDecoder>(this);
78
79 IConfig startupConfig = source.Configs["Startup"];
80 if (startupConfig != null)
81 {
82 m_useCSJ2K = startupConfig.GetBoolean("UseCSJ2K", m_useCSJ2K);
83 }
76 } 84 }
77 85
78 public void PostInitialise() 86 public void PostInitialise()
@@ -144,41 +152,52 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
144 /// <param name="j2kData">JPEG2000 data</param> 152 /// <param name="j2kData">JPEG2000 data</param>
145 private void DoJ2KDecode(UUID assetID, byte[] j2kData) 153 private void DoJ2KDecode(UUID assetID, byte[] j2kData)
146 { 154 {
147// int DecodeTime = 0; 155 //int DecodeTime = 0;
148// DecodeTime = Environment.TickCount; 156 //DecodeTime = Environment.TickCount;
149 OpenJPEG.J2KLayerInfo[] layers; 157 OpenJPEG.J2KLayerInfo[] layers;
150 158
151 if (!TryLoadCacheForAsset(assetID, out layers)) 159 if (!TryLoadCacheForAsset(assetID, out layers))
152 { 160 {
153 try 161 if (m_useCSJ2K)
154 { 162 {
155 List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData)); 163 try
156
157 if (layerStarts != null && layerStarts.Count > 0)
158 { 164 {
159 layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; 165 List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
160 166
161 for (int i = 0; i < layerStarts.Count; i++) 167 if (layerStarts != null && layerStarts.Count > 0)
162 { 168 {
163 OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); 169 layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
170
171 for (int i = 0; i < layerStarts.Count; i++)
172 {
173 OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
164 174
165 if (i == 0) 175 if (i == 0)
166 layer.Start = 0; 176 layer.Start = 0;
167 else 177 else
168 layer.Start = layerStarts[i]; 178 layer.Start = layerStarts[i];
169 179
170 if (i == layerStarts.Count - 1) 180 if (i == layerStarts.Count - 1)
171 layer.End = j2kData.Length; 181 layer.End = j2kData.Length;
172 else 182 else
173 layer.End = layerStarts[i + 1] - 1; 183 layer.End = layerStarts[i + 1] - 1;
174 184
175 layers[i] = layer; 185 layers[i] = layer;
186 }
176 } 187 }
177 } 188 }
189 catch (Exception ex)
190 {
191 m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
192 }
178 } 193 }
179 catch (Exception ex) 194 else
180 { 195 {
181 m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); 196 int components;
197 if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components))
198 {
199 m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID);
200 }
182 } 201 }
183 202
184 if (layers == null || layers.Length == 0) 203 if (layers == null || layers.Length == 0)
@@ -240,7 +259,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
240 { 259 {
241 string assetID = "j2kCache_" + AssetId.ToString(); 260 string assetID = "j2kCache_" + AssetId.ToString();
242 261
243 AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard); 262 AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_scene.RegionInfo.RegionID.ToString());
244 layerDecodeAsset.Local = true; 263 layerDecodeAsset.Local = true;
245 layerDecodeAsset.Temporary = true; 264 layerDecodeAsset.Temporary = true;
246 265
diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
index dd796da..9eaa758 100644
--- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
@@ -647,7 +647,7 @@ namespace Flotsam.RegionModules.AssetCache
647 { 647 {
648 UuidGatherer gatherer = new UuidGatherer(m_AssetService); 648 UuidGatherer gatherer = new UuidGatherer(m_AssetService);
649 649
650 Dictionary<UUID, int> assets = new Dictionary<UUID, int>(); 650 Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
651 foreach (Scene s in m_Scenes) 651 foreach (Scene s in m_Scenes)
652 { 652 {
653 StampRegionStatusFile(s.RegionInfo.RegionID); 653 StampRegionStatusFile(s.RegionInfo.RegionID);
diff --git a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs
index 3b66859..53d2cef 100644
--- a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs
@@ -109,7 +109,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
109 109
110 // Try to parse the texture ID from the request URL 110 // Try to parse the texture ID from the request URL
111 NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); 111 NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
112 string textureStr = GetOne(query, "texture_id"); 112 string textureStr = query.GetOne("texture_id");
113 113
114 if (m_assetService == null) 114 if (m_assetService == null)
115 { 115 {
@@ -166,7 +166,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
166 166
167 private void SendTexture(OSHttpRequest request, OSHttpResponse response, AssetBase texture) 167 private void SendTexture(OSHttpRequest request, OSHttpResponse response, AssetBase texture)
168 { 168 {
169 string range = GetOne(request.Headers, "Range"); 169 string range = request.Headers.GetOne("Range");
170 if (!String.IsNullOrEmpty(range)) 170 if (!String.IsNullOrEmpty(range))
171 { 171 {
172 // Range request 172 // Range request
@@ -216,14 +216,5 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
216 start = end = 0; 216 start = end = 0;
217 return false; 217 return false;
218 } 218 }
219
220 private static string GetOne(NameValueCollection collection, string key)
221 {
222 string[] values = collection.GetValues(key);
223 if (values != null && values.Length > 0)
224 return values[0];
225
226 return null;
227 }
228 } 219 }
229} 220}
diff --git a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs
new file mode 100644
index 0000000..4fac01f
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs
@@ -0,0 +1,440 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using System.Reflection;
30using System.Xml;
31using log4net;
32using Nini.Config;
33using OpenMetaverse;
34using OpenMetaverse.Packets;
35using OpenSim.Framework;
36using OpenSim.Region.Framework;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Region.Framework.Scenes.Serialization;
40
41namespace OpenSim.Region.CoreModules.Avatar.Attachments
42{
43 public class AttachmentsModule : IAttachmentsModule, IRegionModule
44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 protected Scene m_scene = null;
48
49 public void Initialise(Scene scene, IConfigSource source)
50 {
51 scene.RegisterModuleInterface<IAttachmentsModule>(this);
52 m_scene = scene;
53 }
54
55 public void PostInitialise()
56 {
57 }
58
59 public void Close()
60 {
61 }
62
63 public string Name
64 {
65 get { return "Attachments Module"; }
66 }
67
68 public bool IsSharedModule
69 {
70 get { return false; }
71 }
72
73 public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent)
74 {
75 m_log.Debug("[ATTACHMENTS MODULE]: Invoking AttachObject");
76
77 // If we can't take it, we can't attach it!
78 SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
79 if (part == null)
80 return;
81
82 if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
83 return;
84
85 // Calls attach with a Zero position
86 if (AttachObject(remoteClient, objectLocalID, AttachmentPt, rot, Vector3.Zero, false))
87 {
88 m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.GetFromItemID(), remoteClient.AgentId);
89
90 // Save avatar attachment information
91 ScenePresence presence;
92 if (m_scene.AvatarFactory != null && m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
93 {
94 m_log.Info(
95 "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
96 + ", AttachmentPoint: " + AttachmentPt);
97
98 m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
99 }
100 }
101 }
102
103 public bool AttachObject(
104 IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent)
105 {
106 SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
107 if (group != null)
108 {
109 if (m_scene.Permissions.CanTakeObject(group.UUID, remoteClient.AgentId))
110 {
111 // If the attachment point isn't the same as the one previously used
112 // set it's offset position = 0 so that it appears on the attachment point
113 // and not in a weird location somewhere unknown.
114 if (AttachmentPt != 0 && AttachmentPt != (uint)group.GetAttachmentPoint())
115 {
116 attachPos = Vector3.Zero;
117 }
118
119 // AttachmentPt 0 means the client chose to 'wear' the attachment.
120 if (AttachmentPt == 0)
121 {
122 // Check object for stored attachment point
123 AttachmentPt = (uint)group.GetAttachmentPoint();
124 }
125
126 // if we still didn't find a suitable attachment point.......
127 if (AttachmentPt == 0)
128 {
129 // Stick it on left hand with Zero Offset from the attachment point.
130 AttachmentPt = (uint)AttachmentPoint.LeftHand;
131 attachPos = Vector3.Zero;
132 }
133
134 group.SetAttachmentPoint((byte)AttachmentPt);
135 group.AbsolutePosition = attachPos;
136
137 // Saves and gets itemID
138 UUID itemId;
139
140 if (group.GetFromItemID() == UUID.Zero)
141 {
142 m_scene.attachObjectAssetStore(remoteClient, group, remoteClient.AgentId, out itemId);
143 }
144 else
145 {
146 itemId = group.GetFromItemID();
147 }
148
149 SetAttachmentInventoryStatus(remoteClient, AttachmentPt, itemId, group);
150
151 group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos, silent);
152
153 // In case it is later dropped again, don't let
154 // it get cleaned up
155 group.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
156 group.HasGroupChanged = false;
157 }
158 else
159 {
160 remoteClient.SendAgentAlertMessage(
161 "You don't have sufficient permissions to attach this object", false);
162
163 return false;
164 }
165 }
166 else
167 {
168 m_log.DebugFormat("[ATTACHMENTS MODULE]: AttachObject found no such scene object {0}", objectLocalID);
169 return false;
170 }
171
172 return true;
173 }
174
175 public void RezMultipleAttachmentsFromInventory(
176 IClientAPI remoteClient,
177 RezMultipleAttachmentsFromInvPacket.HeaderDataBlock header,
178 RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects)
179 {
180 foreach (RezMultipleAttachmentsFromInvPacket.ObjectDataBlock obj in objects)
181 {
182 RezSingleAttachmentFromInventory(remoteClient, obj.ItemID, obj.AttachmentPt);
183 }
184 }
185
186 public UUID RezSingleAttachmentFromInventory(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
187 {
188 m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing single attachment from item {0} for {1}", itemID, remoteClient.Name);
189
190 return RezSingleAttachmentFromInventory(remoteClient, itemID, AttachmentPt, true);
191 }
192
193 public UUID RezSingleAttachmentFromInventory(
194 IClientAPI remoteClient, UUID itemID, uint AttachmentPt, bool updateInventoryStatus)
195 {
196 return RezSingleAttachmentFromInventory(remoteClient, itemID, AttachmentPt, true, null);
197 }
198
199 public UUID RezSingleAttachmentFromInventory(
200 IClientAPI remoteClient, UUID itemID, uint AttachmentPt, bool updateInventoryStatus, XmlDocument doc)
201 {
202 SceneObjectGroup att = RezSingleAttachmentFromInventoryInternal(remoteClient, itemID, AttachmentPt, doc);
203
204 if (updateInventoryStatus)
205 {
206 if (att == null)
207 {
208 ShowDetachInUserInventory(itemID, remoteClient);
209 }
210
211 SetAttachmentInventoryStatus(att, remoteClient, itemID, AttachmentPt);
212 }
213
214 if (null == att)
215 return UUID.Zero;
216 else
217 return att.UUID;
218 }
219
220 protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
221 IClientAPI remoteClient, UUID itemID, uint AttachmentPt, XmlDocument doc)
222 {
223 IInventoryAccessModule invAccess = m_scene.RequestModuleInterface<IInventoryAccessModule>();
224 if (invAccess != null)
225 {
226 SceneObjectGroup objatt = invAccess.RezObject(remoteClient,
227 itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
228 false, false, remoteClient.AgentId, true);
229
230// m_log.DebugFormat(
231// "[ATTACHMENTS MODULE]: Retrieved single object {0} for attachment to {1} on point {2}",
232// objatt.Name, remoteClient.Name, AttachmentPt);
233
234 if (objatt != null)
235 {
236 bool tainted = false;
237 if (AttachmentPt != 0 && AttachmentPt != objatt.GetAttachmentPoint())
238 tainted = true;
239
240 AttachObject(
241 remoteClient, objatt.LocalId, AttachmentPt, Quaternion.Identity, objatt.AbsolutePosition, false);
242 //objatt.ScheduleGroupForFullUpdate();
243
244 if (tainted)
245 objatt.HasGroupChanged = true;
246
247 if (doc != null)
248 {
249 objatt.LoadScriptState(doc);
250 objatt.ResetOwnerChangeFlag();
251 }
252
253 // Fire after attach, so we don't get messy perms dialogs
254 // 3 == AttachedRez
255 objatt.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3);
256 objatt.ResumeScripts();
257
258 // Do this last so that event listeners have access to all the effects of the attachment
259 //m_scene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, remoteClient.AgentId);
260 }
261 else
262 {
263 m_log.WarnFormat(
264 "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
265 itemID, remoteClient.Name, AttachmentPt);
266 }
267
268 return objatt;
269 }
270
271 return null;
272 }
273
274 public UUID SetAttachmentInventoryStatus(
275 SceneObjectGroup att, IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
276 {
277 m_log.DebugFormat(
278 "[ATTACHMENTS MODULE]: Updating inventory of {0} to show attachment of {1} (item ID {2})",
279 remoteClient.Name, att.Name, itemID);
280
281 if (!att.IsDeleted)
282 AttachmentPt = att.RootPart.AttachmentPoint;
283
284 ScenePresence presence;
285 if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
286 {
287 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
288 if (m_scene.InventoryService != null)
289 item = m_scene.InventoryService.GetItem(item);
290
291 presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/);
292 }
293
294 return att.UUID;
295 }
296
297 /// <summary>
298 /// Update the user inventory to reflect an attachment
299 /// </summary>
300 /// <param name="remoteClient"></param>
301 /// <param name="AttachmentPt"></param>
302 /// <param name="itemID"></param>
303 /// <param name="att"></param>
304 public void SetAttachmentInventoryStatus(
305 IClientAPI remoteClient, uint AttachmentPt, UUID itemID, SceneObjectGroup att)
306 {
307// m_log.DebugFormat(
308// "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
309// att.Name, remoteClient.Name, AttachmentPt, itemID);
310
311 if (UUID.Zero == itemID)
312 {
313 m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
314 return;
315 }
316
317 if (0 == AttachmentPt)
318 {
319 m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
320 return;
321 }
322
323 if (null == att.RootPart)
324 {
325 m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment for a prim without the rootpart!");
326 return;
327 }
328
329 ScenePresence presence;
330 if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
331 {
332 // XXYY!!
333 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
334 if (item == null)
335 m_log.Error("[ATTACHMENT]: item == null");
336 if (m_scene == null)
337 m_log.Error("[ATTACHMENT]: m_scene == null");
338 if (m_scene.InventoryService == null)
339 m_log.Error("[ATTACHMENT]: m_scene.InventoryService == null");
340 item = m_scene.InventoryService.GetItem(item);
341 presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /* att.UUID */);
342
343 if (m_scene.AvatarFactory != null)
344 m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
345 }
346 }
347
348 public void DetachObject(uint objectLocalID, IClientAPI remoteClient)
349 {
350 SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
351 if (group != null)
352 {
353 //group.DetachToGround();
354 ShowDetachInUserInventory(group.GetFromItemID(), remoteClient);
355 }
356 }
357
358 public void ShowDetachInUserInventory(UUID itemID, IClientAPI remoteClient)
359 {
360 ScenePresence presence;
361 if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
362 {
363 presence.Appearance.DetachAttachment(itemID);
364
365 // Save avatar attachment information
366 if (m_scene.AvatarFactory != null)
367 {
368 m_log.Debug("[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId + ", ItemID: " + itemID);
369 m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
370 }
371 }
372
373 DetachSingleAttachmentToInv(itemID, remoteClient);
374 }
375
376 public void DetachSingleAttachmentToGround(UUID itemID, IClientAPI remoteClient)
377 {
378 SceneObjectPart part = m_scene.GetSceneObjectPart(itemID);
379 if (part == null || part.ParentGroup == null)
380 return;
381
382 UUID inventoryID = part.ParentGroup.GetFromItemID();
383
384 ScenePresence presence;
385 if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
386 {
387 if (!m_scene.Permissions.CanRezObject(
388 part.ParentGroup.Children.Count, remoteClient.AgentId, presence.AbsolutePosition))
389 return;
390
391 presence.Appearance.DetachAttachment(itemID);
392
393 if (m_scene.AvatarFactory != null)
394 {
395 m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
396 }
397 part.ParentGroup.DetachToGround();
398
399 List<UUID> uuids = new List<UUID>();
400 uuids.Add(inventoryID);
401 m_scene.InventoryService.DeleteItems(remoteClient.AgentId, uuids);
402 remoteClient.SendRemoveInventoryItem(inventoryID);
403 }
404
405 m_scene.EventManager.TriggerOnAttach(part.ParentGroup.LocalId, itemID, UUID.Zero);
406 }
407
408 // What makes this method odd and unique is it tries to detach using an UUID.... Yay for standards.
409 // To LocalId or UUID, *THAT* is the question. How now Brown UUID??
410 protected void DetachSingleAttachmentToInv(UUID itemID, IClientAPI remoteClient)
411 {
412 if (itemID == UUID.Zero) // If this happened, someone made a mistake....
413 return;
414
415 // We can NOT use the dictionries here, as we are looking
416 // for an entity by the fromAssetID, which is NOT the prim UUID
417 List<EntityBase> detachEntities = m_scene.GetEntities();
418 SceneObjectGroup group;
419
420 foreach (EntityBase entity in detachEntities)
421 {
422 if (entity is SceneObjectGroup)
423 {
424 group = (SceneObjectGroup)entity;
425 if (group.GetFromItemID() == itemID)
426 {
427 m_scene.EventManager.TriggerOnAttach(group.LocalId, itemID, UUID.Zero);
428 // CM / XMREngine!!!! Needed to conclude attach event
429 SceneObjectSerializer.ToOriginalXmlFormat(group);
430 group.DetachToInventoryPrep();
431 m_log.Debug("[ATTACHMENTS MODULE]: Saving attachpoint: " + ((uint)group.GetAttachmentPoint()).ToString());
432 m_scene.UpdateKnownItem(remoteClient, group,group.GetFromItemID(), group.OwnerID);
433 m_scene.DeleteSceneObject(group, false);
434 return;
435 }
436 }
437 }
438 }
439 }
440}
diff --git a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
index 144c8d1..22c8937 100644
--- a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
@@ -31,7 +31,7 @@ using log4net;
31using Nini.Config; 31using Nini.Config;
32using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications.Cache; 34
35using OpenSim.Region.Framework.Interfaces; 35using OpenSim.Region.Framework.Interfaces;
36using OpenSim.Region.Framework.Scenes; 36using OpenSim.Region.Framework.Scenes;
37using OpenSim.Services.Interfaces; 37using OpenSim.Services.Interfaces;
@@ -46,21 +46,16 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
46 46
47 public bool TryGetAvatarAppearance(UUID avatarId, out AvatarAppearance appearance) 47 public bool TryGetAvatarAppearance(UUID avatarId, out AvatarAppearance appearance)
48 { 48 {
49 CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(avatarId); 49 AvatarData avatar = m_scene.AvatarService.GetAvatar(avatarId);
50 //if ((profile != null) && (profile.RootFolder != null)) 50 //if ((profile != null) && (profile.RootFolder != null))
51 if (profile != null) 51 if (avatar != null)
52 { 52 {
53 appearance = m_scene.CommsManager.AvatarService.GetUserAppearance(avatarId); 53 appearance = avatar.ToAvatarAppearance(avatarId);
54 if (appearance != null) 54 return true;
55 {
56 //SetAppearanceAssets(profile, ref appearance);
57 //m_log.DebugFormat("[APPEARANCE]: Found : {0}", appearance.ToString());
58 return true;
59 }
60 } 55 }
61 56
62 appearance = CreateDefault(avatarId);
63 m_log.ErrorFormat("[APPEARANCE]: Appearance not found for {0}, creating default", avatarId); 57 m_log.ErrorFormat("[APPEARANCE]: Appearance not found for {0}, creating default", avatarId);
58 appearance = CreateDefault(avatarId);
64 return false; 59 return false;
65 } 60 }
66 61
@@ -160,21 +155,23 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
160 /// <param name="e"></param> 155 /// <param name="e"></param>
161 public void AvatarIsWearing(Object sender, AvatarWearingArgs e) 156 public void AvatarIsWearing(Object sender, AvatarWearingArgs e)
162 { 157 {
158 m_log.DebugFormat("[APPEARANCE]: AvatarIsWearing");
159
163 IClientAPI clientView = (IClientAPI)sender; 160 IClientAPI clientView = (IClientAPI)sender;
164 ScenePresence avatar = m_scene.GetScenePresence(clientView.AgentId); 161 ScenePresence sp = m_scene.GetScenePresence(clientView.AgentId);
165 162
166 if (avatar == null) 163 if (sp == null)
167 { 164 {
168 m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event"); 165 m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event");
169 return; 166 return;
170 } 167 }
171 168
172 AvatarAppearance avatAppearance = null; 169 AvatarAppearance avatAppearance = sp.Appearance;
173 if (!TryGetAvatarAppearance(clientView.AgentId, out avatAppearance)) 170 //if (!TryGetAvatarAppearance(clientView.AgentId, out avatAppearance))
174 { 171 //{
175 m_log.Warn("[APPEARANCE]: We didn't seem to find the appearance, falling back to ScenePresence"); 172 // m_log.Warn("[APPEARANCE]: We didn't seem to find the appearance, falling back to ScenePresence");
176 avatAppearance = avatar.Appearance; 173 // avatAppearance = sp.Appearance;
177 } 174 //}
178 175
179 //m_log.DebugFormat("[APPEARANCE]: Received wearables for {0}", clientView.Name); 176 //m_log.DebugFormat("[APPEARANCE]: Received wearables for {0}", clientView.Name);
180 177
@@ -186,10 +183,11 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
186 } 183 }
187 } 184 }
188 185
189 SetAppearanceAssets(avatar.UUID, ref avatAppearance); 186 SetAppearanceAssets(sp.UUID, ref avatAppearance);
187 AvatarData adata = new AvatarData(avatAppearance);
188 m_scene.AvatarService.SetAvatar(clientView.AgentId, adata);
190 189
191 m_scene.CommsManager.AvatarService.UpdateUserAppearance(clientView.AgentId, avatAppearance); 190 sp.Appearance = avatAppearance;
192 avatar.Appearance = avatAppearance;
193 } 191 }
194 192
195 public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams) 193 public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
@@ -200,7 +198,9 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
200 198
201 public void UpdateDatabase(UUID user, AvatarAppearance appearance) 199 public void UpdateDatabase(UUID user, AvatarAppearance appearance)
202 { 200 {
203 m_scene.CommsManager.AvatarService.UpdateUserAppearance(user, appearance); 201 //m_log.DebugFormat("[APPEARANCE]: UpdateDatabase");
202 AvatarData adata = new AvatarData(appearance);
203 m_scene.AvatarService.SetAvatar(user, adata);
204 } 204 }
205 205
206 private static byte[] GetDefaultVisualParams() 206 private static byte[] GetDefaultVisualParams()
diff --git a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs
index 1a6cd6c..9df6074 100644
--- a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs
@@ -89,60 +89,57 @@ namespace OpenSim.Region.CoreModules.Avatar.Combat.CombatModule
89 get { return true; } 89 get { return true; }
90 } 90 }
91 91
92 private void KillAvatar(uint killerObjectLocalID, ScenePresence DeadAvatar) 92 private void KillAvatar(uint killerObjectLocalID, ScenePresence deadAvatar)
93 { 93 {
94 string deadAvatarMessage;
95 ScenePresence killingAvatar = null;
96 string killingAvatarMessage;
97
94 if (killerObjectLocalID == 0) 98 if (killerObjectLocalID == 0)
95 DeadAvatar.ControllingClient.SendAgentAlertMessage("You committed suicide!", true); 99 deadAvatarMessage = "You committed suicide!";
96 else 100 else
97 { 101 {
98 bool foundResult = false; 102 // Try to get the avatar responsible for the killing
99 string resultstring = String.Empty; 103 killingAvatar = deadAvatar.Scene.GetScenePresence(killerObjectLocalID);
100 ScenePresence[] allav = DeadAvatar.Scene.GetScenePresences(); 104 if (killingAvatar == null)
101 try
102 { 105 {
103 for (int i = 0; i < allav.Length; i++) 106 // Try to get the object which was responsible for the killing
107 SceneObjectPart part = deadAvatar.Scene.GetSceneObjectPart(killerObjectLocalID);
108 if (part == null)
104 { 109 {
105 ScenePresence av = allav[i]; 110 // Cause of death: Unknown
106 111 deadAvatarMessage = "You died!";
107 if (av.LocalId == killerObjectLocalID)
108 {
109 av.ControllingClient.SendAlertMessage("You fragged " + DeadAvatar.Firstname + " " + DeadAvatar.Lastname);
110 resultstring = av.Firstname + " " + av.Lastname;
111 foundResult = true;
112 }
113 } 112 }
114 } catch (InvalidOperationException) 113 else
115 {
116
117 }
118
119 if (!foundResult)
120 {
121 SceneObjectPart part = DeadAvatar.Scene.GetSceneObjectPart(killerObjectLocalID);
122 if (part != null)
123 { 114 {
124 ScenePresence av = DeadAvatar.Scene.GetScenePresence(part.OwnerID); 115 // Try to find the avatar wielding the killing object
125 if (av != null) 116 killingAvatar = deadAvatar.Scene.GetScenePresence(part.OwnerID);
126 { 117 if (killingAvatar == null)
127 av.ControllingClient.SendAlertMessage("You fragged " + DeadAvatar.Firstname + " " + DeadAvatar.Lastname); 118 deadAvatarMessage = String.Format("You impaled yourself on {0} owned by {1}!", part.Name, deadAvatar.Scene.GetUserName(part.OwnerID));
128 resultstring = av.Firstname + " " + av.Lastname;
129 DeadAvatar.ControllingClient.SendAgentAlertMessage("You got killed by " + resultstring + "!", true);
130 }
131 else 119 else
132 { 120 {
133 string killer = DeadAvatar.Scene.CommsManager.UUIDNameRequestString(part.OwnerID); 121 killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name);
134 DeadAvatar.ControllingClient.SendAgentAlertMessage("You impaled yourself on " + part.Name + " owned by " + killer +"!", true); 122 deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name);
135 } 123 }
136 //DeadAvatar.Scene. part.ObjectOwner
137 }
138 else
139 {
140 DeadAvatar.ControllingClient.SendAgentAlertMessage("You died!", true);
141 } 124 }
142 } 125 }
126 else
127 {
128 killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name);
129 deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name);
130 }
143 } 131 }
144 DeadAvatar.Health = 100; 132 try
145 DeadAvatar.Scene.TeleportClientHome(DeadAvatar.UUID, DeadAvatar.ControllingClient); 133 {
134 deadAvatar.ControllingClient.SendAgentAlertMessage(deadAvatarMessage, true);
135 if(killingAvatar != null)
136 killingAvatar.ControllingClient.SendAlertMessage("You fragged " + deadAvatar.Firstname + " " + deadAvatar.Lastname);
137 }
138 catch (InvalidOperationException)
139 { }
140
141 deadAvatar.Health = 100;
142 deadAvatar.Scene.TeleportClientHome(deadAvatar.UUID, deadAvatar.ControllingClient);
146 } 143 }
147 144
148 private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) 145 private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
diff --git a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs
index 72ec869..da38ede 100644
--- a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs
@@ -25,15 +25,17 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System;
28using System.Collections.Generic; 29using System.Collections.Generic;
29using System.Reflection; 30using System.Reflection;
30using log4net; 31using log4net;
31using Nini.Config; 32using Nini.Config;
32using OpenMetaverse; 33using OpenMetaverse;
33using OpenSim.Framework; 34using OpenSim.Framework;
34using OpenSim.Framework.Communications.Cache; 35
35using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
36using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
38using OpenSim.Services.Interfaces;
37 39
38namespace OpenSim.Region.CoreModules.Avatar.Dialog 40namespace OpenSim.Region.CoreModules.Avatar.Dialog
39{ 41{
@@ -85,43 +87,30 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
85 87
86 public void SendAlertToUser(string firstName, string lastName, string message, bool modal) 88 public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
87 { 89 {
88 ScenePresence[] presenceList = m_scene.GetScenePresences(); 90 ScenePresence presence = m_scene.GetScenePresence(firstName, lastName);
89 91 if(presence != null)
90 for (int i = 0; i < presenceList.Length; i++) 92 presence.ControllingClient.SendAgentAlertMessage(message, modal);
91 {
92 ScenePresence presence = presenceList[i];
93
94 if (presence.Firstname == firstName && presence.Lastname == lastName)
95 {
96 presence.ControllingClient.SendAgentAlertMessage(message, modal);
97 break;
98 }
99 }
100 } 93 }
101 94
102 public void SendGeneralAlert(string message) 95 public void SendGeneralAlert(string message)
103 { 96 {
104 ScenePresence[] presenceList = m_scene.GetScenePresences(); 97 m_scene.ForEachScenePresence(delegate(ScenePresence presence)
105
106 for (int i = 0; i < presenceList.Length; i++)
107 { 98 {
108 ScenePresence presence = presenceList[i];
109
110 if (!presence.IsChildAgent) 99 if (!presence.IsChildAgent)
111 presence.ControllingClient.SendAlertMessage(message); 100 presence.ControllingClient.SendAlertMessage(message);
112 } 101 });
113 } 102 }
114 103
115 public void SendDialogToUser( 104 public void SendDialogToUser(
116 UUID avatarID, string objectName, UUID objectID, UUID ownerID, 105 UUID avatarID, string objectName, UUID objectID, UUID ownerID,
117 string message, UUID textureID, int ch, string[] buttonlabels) 106 string message, UUID textureID, int ch, string[] buttonlabels)
118 { 107 {
119 CachedUserInfo info = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(ownerID); 108 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerID);
120 string ownerFirstName, ownerLastName; 109 string ownerFirstName, ownerLastName;
121 if (info != null) 110 if (account != null)
122 { 111 {
123 ownerFirstName = info.UserProfile.FirstName; 112 ownerFirstName = account.FirstName;
124 ownerLastName = info.UserProfile.SurName; 113 ownerLastName = account.LastName;
125 } 114 }
126 else 115 else
127 { 116 {
@@ -143,25 +132,37 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
143 sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); 132 sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url);
144 } 133 }
145 134
146 public void SendNotificationToUsersInEstate( 135 public void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid)
147 UUID fromAvatarID, string fromAvatarName, string message)
148 { 136 {
149 // TODO: This does not yet do what it says on the tin - it only sends the message to users in the same 137 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid);
150 // region as the sending avatar. 138 string ownerFirstName, ownerLastName;
151 SendNotificationToUsersInRegion(fromAvatarID, fromAvatarName, message); 139 if (account != null)
140 {
141 ownerFirstName = account.FirstName;
142 ownerLastName = account.LastName;
143 }
144 else
145 {
146 ownerFirstName = "(unknown";
147 ownerLastName = "user)";
148 }
149
150
151 ScenePresence sp = m_scene.GetScenePresence(avatarid);
152
153 if (sp != null) {
154 sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid);
155 }
152 } 156 }
153 157
154 public void SendNotificationToUsersInRegion( 158 public void SendNotificationToUsersInRegion(
155 UUID fromAvatarID, string fromAvatarName, string message) 159 UUID fromAvatarID, string fromAvatarName, string message)
156 { 160 {
157 ScenePresence[] presences = m_scene.GetScenePresences(); 161 m_scene.ForEachScenePresence(delegate(ScenePresence presence)
158
159 for (int i = 0; i < presences.Length; i++)
160 { 162 {
161 ScenePresence presence = presences[i];
162 if (!presence.IsChildAgent) 163 if (!presence.IsChildAgent)
163 presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); 164 presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message);
164 } 165 });
165 } 166 }
166 167
167 /// <summary> 168 /// <summary>
diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
index 086d4fe..febd4ca 100644
--- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
@@ -28,7 +28,6 @@
28using System; 28using System;
29using System.Collections; 29using System.Collections;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Net;
32using System.Reflection; 31using System.Reflection;
33using log4net; 32using log4net;
34using Nini.Config; 33using Nini.Config;
@@ -36,1119 +35,724 @@ using Nwc.XmlRpc;
36using OpenMetaverse; 35using OpenMetaverse;
37using OpenSim.Framework; 36using OpenSim.Framework;
38using OpenSim.Framework.Communications; 37using OpenSim.Framework.Communications;
39using OpenSim.Framework.Communications.Cache;
40using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
41using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
42using OpenSim.Services.Interfaces; 40using OpenSim.Services.Interfaces;
41using OpenSim.Services.Connectors.Friends;
42using OpenSim.Server.Base;
43using OpenSim.Framework.Servers.HttpServer;
44using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
45using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
43using GridRegion = OpenSim.Services.Interfaces.GridRegion; 46using GridRegion = OpenSim.Services.Interfaces.GridRegion;
44 47
45namespace OpenSim.Region.CoreModules.Avatar.Friends 48namespace OpenSim.Region.CoreModules.Avatar.Friends
46{ 49{
47 /* 50 public class FriendsModule : ISharedRegionModule, IFriendsModule
48 This module handles adding/removing friends, and the the presence
49 notification process for login/logoff of friends.
50
51 The presence notification works as follows:
52 - After the user initially connects to a region (so we now have a UDP
53 connection to work with), this module fetches the friends of user
54 (those are cached), their on-/offline status, and info about the
55 region they are in from the MessageServer.
56 - (*) It then informs the user about the on-/offline status of her friends.
57 - It then informs all online friends currently on this region-server about
58 user's new online status (this will save some network traffic, as local
59 messages don't have to be transferred inter-region, and it will be all
60 that has to be done in Standalone Mode).
61 - For the rest of the online friends (those not on this region-server),
62 this module uses the provided region-information to map users to
63 regions, and sends one notification to every region containing the
64 friends to inform on that server.
65 - The region-server will handle that in the following way:
66 - If it finds the friend, it informs her about the user being online.
67 - If it doesn't find the friend (maybe she TPed away in the meantime),
68 it stores that information.
69 - After it processed all friends, it returns the list of friends it
70 couldn't find.
71 - If this list isn't empty, the FriendsModule re-requests information
72 about those online friends that have been missed and starts at (*)
73 again until all friends have been found, or until it tried 3 times
74 (to prevent endless loops due to some uncaught error).
75
76 NOTE: Online/Offline notifications don't need to be sent on region change.
77
78 We implement two XMLRpc handlers here, handling all the inter-region things
79 we have to handle:
80 - On-/Offline-Notifications (bulk)
81 - Terminate Friendship messages (single)
82 */
83
84 public class FriendsModule : IRegionModule, IFriendsModule
85 { 51 {
86 private class Transaction 52 protected class UserFriendData
87 { 53 {
88 public UUID agentID; 54 public UUID PrincipalID;
89 public string agentName; 55 public FriendInfo[] Friends;
90 public uint count; 56 public int Refcount;
57 public UUID RegionID;
91 58
92 public Transaction(UUID agentID, string agentName) 59 public bool IsFriend(string friend)
93 { 60 {
94 this.agentID = agentID; 61 foreach (FriendInfo fi in Friends)
95 this.agentName = agentName; 62 {
96 this.count = 1; 63 if (fi.Friend == friend)
64 return true;
65 }
66
67 return false;
97 } 68 }
98 } 69 }
99 70
100 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 71 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
101 72
102 private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate); 73 protected List<Scene> m_Scenes = new List<Scene>();
103 74
104 private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>(); 75 protected IPresenceService m_PresenceService = null;
76 protected IFriendsService m_FriendsService = null;
77 protected FriendsSimConnector m_FriendsSimConnector;
105 78
106 private Dictionary<UUID, UUID> m_pendingCallingcardRequests = new Dictionary<UUID,UUID>(); 79 protected Dictionary<UUID, UserFriendData> m_Friends =
80 new Dictionary<UUID, UserFriendData>();
107 81
108 private Scene m_initialScene; // saves a lookup if we don't have a specific scene 82 protected List<UUID> m_NeedsListOfFriends = new List<UUID>();
109 private Dictionary<ulong, Scene> m_scenes = new Dictionary<ulong,Scene>();
110 private IMessageTransferModule m_TransferModule = null;
111 83
112 private IGridService m_gridServices = null; 84 protected IPresenceService PresenceService
113
114 #region IRegionModule Members
115
116 public void Initialise(Scene scene, IConfigSource config)
117 { 85 {
118 lock (m_scenes) 86 get
119 { 87 {
120 if (m_scenes.Count == 0) 88 if (m_PresenceService == null)
121 { 89 {
122 MainServer.Instance.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk); 90 if (m_Scenes.Count > 0)
123 MainServer.Instance.AddXmlRPCHandler("terminate_friend", processTerminateFriend); 91 m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
124 m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max
125 m_initialScene = scene;
126 } 92 }
127 93
128 if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle)) 94 return m_PresenceService;
129 m_scenes[scene.RegionInfo.RegionHandle] = scene;
130 } 95 }
131
132 scene.RegisterModuleInterface<IFriendsModule>(this);
133
134 scene.EventManager.OnNewClient += OnNewClient;
135 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
136 scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
137 scene.EventManager.OnMakeChildAgent += MakeChildAgent;
138 scene.EventManager.OnClientClosed += ClientClosed;
139 } 96 }
140 97
141 public void PostInitialise() 98 protected IFriendsService FriendsService
142 { 99 {
143 if (m_scenes.Count > 0) 100 get
144 { 101 {
145 m_TransferModule = m_initialScene.RequestModuleInterface<IMessageTransferModule>(); 102 if (m_FriendsService == null)
146 m_gridServices = m_initialScene.GridService; 103 {
147 } 104 if (m_Scenes.Count > 0)
148 if (m_TransferModule == null) 105 m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
149 m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work"); 106 }
150 }
151
152 public void Close()
153 {
154 }
155 107
156 public string Name 108 return m_FriendsService;
157 { 109 }
158 get { return "FriendsModule"; }
159 } 110 }
160 111
161 public bool IsSharedModule 112 protected IGridService GridService
162 { 113 {
163 get { return true; } 114 get
115 {
116 return m_Scenes[0].GridService;
117 }
164 } 118 }
165 119
166 #endregion 120 public IScene Scene
167
168 #region IInterregionFriendsComms
169
170 public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online)
171 { 121 {
172 List<UUID> tpdAway = new List<UUID>(); 122 get
173
174 // destRegionHandle is a region on another server
175 uint x = 0, y = 0;
176 Utils.LongToUInts(destRegionHandle, out x, out y);
177 GridRegion info = m_gridServices.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID, (int)x, (int)y);
178 if (info != null)
179 { 123 {
180 string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; 124 if (m_Scenes.Count > 0)
181 125 return m_Scenes[0];
182 Hashtable reqParams = new Hashtable(); 126 else
183 reqParams["agentID"] = agentId.ToString(); 127 return null;
184 reqParams["agentOnline"] = online;
185 int count = 0;
186 foreach (UUID uuid in friends)
187 {
188 reqParams["friendID_" + count++] = uuid.ToString();
189 }
190 reqParams["friendCount"] = count;
191
192 IList parameters = new ArrayList();
193 parameters.Add(reqParams);
194 try
195 {
196 XmlRpcRequest request = new XmlRpcRequest("presence_update_bulk", parameters);
197 XmlRpcResponse response = request.Send(httpServer, 5000);
198 Hashtable respData = (Hashtable)response.Value;
199
200 count = (int)respData["friendCount"];
201 for (int i = 0; i < count; ++i)
202 {
203 UUID uuid;
204 if (UUID.TryParse((string)respData["friendID_" + i], out uuid)) tpdAway.Add(uuid);
205 }
206 }
207 catch (WebException e)
208 {
209 // Ignore connect failures, simulators come and go
210 //
211 if (!e.Message.Contains("ConnectFailure"))
212 {
213 m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e);
214 }
215 }
216 catch (Exception e)
217 {
218 m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e);
219 }
220 } 128 }
221 else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}???", destRegionHandle);
222
223 return tpdAway;
224 } 129 }
225 130
226 public bool TriggerTerminateFriend(ulong destRegionHandle, UUID agentID, UUID exFriendID) 131 public void Initialise(IConfigSource config)
227 { 132 {
228 // destRegionHandle is a region on another server 133 IConfig friendsConfig = config.Configs["Friends"];
229 uint x = 0, y = 0; 134 if (friendsConfig != null)
230 Utils.LongToUInts(destRegionHandle, out x, out y);
231 GridRegion info = m_gridServices.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID, (int)x, (int)y);
232 if (info == null)
233 { 135 {
234 m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}", destRegionHandle); 136 int mPort = friendsConfig.GetInt("Port", 0);
235 return false; // region not found???
236 }
237 137
238 string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; 138 string connector = friendsConfig.GetString("Connector", String.Empty);
139 Object[] args = new Object[] { config };
239 140
240 Hashtable reqParams = new Hashtable(); 141 m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
241 reqParams["agentID"] = agentID.ToString(); 142 m_FriendsSimConnector = new FriendsSimConnector();
242 reqParams["friendID"] = exFriendID.ToString();
243 143
244 IList parameters = new ArrayList(); 144 // Instantiate the request handler
245 parameters.Add(reqParams); 145 IHttpServer server = MainServer.GetHttpServer((uint)mPort);
246 try 146 server.AddStreamHandler(new FriendsRequestHandler(this));
247 {
248 XmlRpcRequest request = new XmlRpcRequest("terminate_friend", parameters);
249 XmlRpcResponse response = request.Send(httpServer, 5000);
250 Hashtable respData = (Hashtable)response.Value;
251 147
252 return (bool)respData["success"];
253 } 148 }
254 catch (Exception e) 149
150 if (m_FriendsService == null)
255 { 151 {
256 m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); 152 m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
257 return false; 153 throw new Exception("Connector load error");
258 } 154 }
155
259 } 156 }
260 157
261 #endregion 158 public void PostInitialise()
159 {
160 }
262 161
263 #region Incoming XMLRPC messages 162 public void Close()
264 /// <summary>
265 /// Receive presence information changes about clients in other regions.
266 /// </summary>
267 /// <param name="req"></param>
268 /// <returns></returns>
269 public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req, IPEndPoint remoteClient)
270 { 163 {
271 Hashtable requestData = (Hashtable)req.Params[0]; 164 }
272 165
273 List<UUID> friendsNotHere = new List<UUID>(); 166 public void AddRegion(Scene scene)
167 {
168 m_Scenes.Add(scene);
169 scene.RegisterModuleInterface<IFriendsModule>(this);
274 170
275 // this is called with the expectation that all the friends in the request are on this region-server. 171 scene.EventManager.OnNewClient += OnNewClient;
276 // But as some time passed since we checked (on the other region-server, via the MessagingServer), 172 scene.EventManager.OnClientClosed += OnClientClosed;
277 // some of the friends might have teleported away. 173 scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
278 // Actually, even now, between this line and the sending below, some people could TP away. So, 174 scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
279 // we'll have to lock the m_rootAgents list for the duration to prevent/delay that. 175 scene.EventManager.OnClientLogin += OnClientLogin;
280 lock (m_rootAgents) 176 }
281 {
282 List<ScenePresence> friendsHere = new List<ScenePresence>();
283
284 try
285 {
286 UUID agentID = new UUID((string)requestData["agentID"]);
287 bool agentOnline = (bool)requestData["agentOnline"];
288 int count = (int)requestData["friendCount"];
289 for (int i = 0; i < count; ++i)
290 {
291 UUID uuid;
292 if (UUID.TryParse((string)requestData["friendID_" + i], out uuid))
293 {
294 if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid));
295 else friendsNotHere.Add(uuid);
296 }
297 }
298 177
299 // now send, as long as they are still here... 178 public void RegionLoaded(Scene scene)
300 UUID[] agentUUID = new UUID[] { agentID }; 179 {
301 if (agentOnline) 180 }
302 {
303 foreach (ScenePresence agent in friendsHere)
304 {
305 agent.ControllingClient.SendAgentOnline(agentUUID);
306 }
307 }
308 else
309 {
310 foreach (ScenePresence agent in friendsHere)
311 {
312 agent.ControllingClient.SendAgentOffline(agentUUID);
313 }
314 }
315 }
316 catch(Exception e)
317 {
318 m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e);
319 }
320 }
321 181
322 // no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region, 182 public void RemoveRegion(Scene scene)
323 // which should be caught on the next iteration... 183 {
324 Hashtable result = new Hashtable(); 184 m_Scenes.Remove(scene);
325 int idx = 0; 185 }
326 foreach (UUID uuid in friendsNotHere)
327 {
328 result["friendID_" + idx++] = uuid.ToString();
329 }
330 result["friendCount"] = idx;
331 186
332 XmlRpcResponse response = new XmlRpcResponse(); 187 public string Name
333 response.Value = result; 188 {
189 get { return "FriendsModule"; }
190 }
334 191
335 return response; 192 public Type ReplaceableInterface
193 {
194 get { return null; }
336 } 195 }
337 196
338 public XmlRpcResponse processTerminateFriend(XmlRpcRequest req, IPEndPoint remoteClient) 197 public uint GetFriendPerms(UUID principalID, UUID friendID)
339 { 198 {
340 Hashtable requestData = (Hashtable)req.Params[0]; 199 if (!m_Friends.ContainsKey(principalID))
200 return 0;
341 201
342 bool success = false; 202 UserFriendData data = m_Friends[principalID];
343 203
344 UUID agentID; 204 foreach (FriendInfo fi in data.Friends)
345 UUID friendID;
346 if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) &&
347 requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID))
348 { 205 {
349 // try to find it and if it is there, prevent it to vanish before we sent the message 206 if (fi.Friend == friendID.ToString())
350 lock (m_rootAgents) 207 return (uint)fi.TheirFlags;
351 {
352 if (m_rootAgents.ContainsKey(agentID))
353 {
354 m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID);
355 GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID);
356 success = true;
357 }
358 }
359 } 208 }
360 209 return 0;
361 // return whether we were successful
362 Hashtable result = new Hashtable();
363 result["success"] = success;
364
365 XmlRpcResponse response = new XmlRpcResponse();
366 response.Value = result;
367 return response;
368 } 210 }
369 211
370 #endregion
371
372 #region Scene events
373
374 private void OnNewClient(IClientAPI client) 212 private void OnNewClient(IClientAPI client)
375 { 213 {
376 // All friends establishment protocol goes over instant message
377 // There's no way to send a message from the sim
378 // to a user to 'add a friend' without causing dialog box spam
379
380 // Subscribe to instant messages
381 client.OnInstantMessage += OnInstantMessage; 214 client.OnInstantMessage += OnInstantMessage;
382
383 // Friend list management
384 client.OnApproveFriendRequest += OnApproveFriendRequest; 215 client.OnApproveFriendRequest += OnApproveFriendRequest;
385 client.OnDenyFriendRequest += OnDenyFriendRequest; 216 client.OnDenyFriendRequest += OnDenyFriendRequest;
386 client.OnTerminateFriendship += OnTerminateFriendship; 217 client.OnTerminateFriendship += OnTerminateFriendship;
387 218
388 // ... calling card handling... 219 client.OnGrantUserRights += OnGrantUserRights;
389 client.OnOfferCallingCard += OnOfferCallingCard;
390 client.OnAcceptCallingCard += OnAcceptCallingCard;
391 client.OnDeclineCallingCard += OnDeclineCallingCard;
392 220
393 // we need this one exactly once per agent session (see comments in the handler below)
394 client.OnEconomyDataRequest += OnEconomyDataRequest;
395
396 // if it leaves, we want to know, too
397 client.OnLogout += OnLogout; 221 client.OnLogout += OnLogout;
398
399 client.OnGrantUserRights += GrantUserFriendRights;
400 client.OnTrackAgent += FindAgent;
401 client.OnFindAgent += FindAgent;
402 222
223 if (m_Friends.ContainsKey(client.AgentId))
224 {
225 m_Friends[client.AgentId].Refcount++;
226 return;
227 }
228
229 UserFriendData newFriends = new UserFriendData();
230
231 newFriends.PrincipalID = client.AgentId;
232 newFriends.Friends = m_FriendsService.GetFriends(client.AgentId);
233 newFriends.Refcount = 1;
234 newFriends.RegionID = UUID.Zero;
235
236 m_Friends.Add(client.AgentId, newFriends);
237
238 //StatusChange(client.AgentId, true);
403 } 239 }
404 240
405 private void ClientClosed(UUID AgentId, Scene scene) 241 private void OnClientClosed(UUID agentID, Scene scene)
406 { 242 {
407 // agent's client was closed. As we handle logout in OnLogout, this here has only to handle 243 if (m_Friends.ContainsKey(agentID))
408 // TPing away (root agent is closed) or TPing/crossing in a region far enough away (client
409 // agent is closed).
410 // NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around
411 // in one of the regions here anymore.
412 lock (m_rootAgents)
413 { 244 {
414 if (m_rootAgents.ContainsKey(AgentId)) 245 if (m_Friends[agentID].Refcount == 1)
415 { 246 m_Friends.Remove(agentID);
416 m_rootAgents.Remove(AgentId); 247 else
417 } 248 m_Friends[agentID].Refcount--;
418 } 249 }
419 } 250 }
420 251
421 private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) 252 private void OnLogout(IClientAPI client)
422 { 253 {
423 lock (m_rootAgents) 254 StatusChange(client.AgentId, false);
424 { 255 m_Friends.Remove(client.AgentId);
425 m_rootAgents[avatar.UUID] = avatar.RegionHandle;
426 // Claim User! my user! Mine mine mine!
427 }
428 } 256 }
429 257
430 private void MakeChildAgent(ScenePresence avatar) 258 private void OnMakeRootAgent(ScenePresence sp)
431 { 259 {
432 lock (m_rootAgents) 260 UUID agentID = sp.ControllingClient.AgentId;
261
262 if (m_Friends.ContainsKey(agentID))
433 { 263 {
434 if (m_rootAgents.ContainsKey(avatar.UUID)) 264 if (m_Friends[agentID].RegionID == UUID.Zero && m_Friends[agentID].Friends == null)
435 { 265 {
436 // only delete if the region matches. As this is a shared module, the avatar could be 266 m_Friends[agentID].Friends =
437 // root agent in another region on this server. 267 m_FriendsService.GetFriends(agentID);
438 if (m_rootAgents[avatar.UUID] == avatar.RegionHandle)
439 {
440 m_rootAgents.Remove(avatar.UUID);
441// m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent");
442 }
443 } 268 }
269 m_Friends[agentID].RegionID =
270 sp.ControllingClient.Scene.RegionInfo.RegionID;
444 } 271 }
445 } 272 }
446 #endregion
447 273
448 private ScenePresence GetRootPresenceFromAgentID(UUID AgentID) 274
275 private void OnMakeChildAgent(ScenePresence sp)
449 { 276 {
450 ScenePresence returnAgent = null; 277 UUID agentID = sp.ControllingClient.AgentId;
451 lock (m_scenes) 278
279 if (m_Friends.ContainsKey(agentID))
452 { 280 {
453 ScenePresence queryagent = null; 281 if (m_Friends[agentID].RegionID == sp.ControllingClient.Scene.RegionInfo.RegionID)
454 foreach (Scene scene in m_scenes.Values) 282 m_Friends[agentID].RegionID = UUID.Zero;
455 {
456 queryagent = scene.GetScenePresence(AgentID);
457 if (queryagent != null)
458 {
459 if (!queryagent.IsChildAgent)
460 {
461 returnAgent = queryagent;
462 break;
463 }
464 }
465 }
466 } 283 }
467 return returnAgent;
468 } 284 }
469 285
470 private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID) 286 private void OnClientLogin(IClientAPI client)
471 { 287 {
472 ScenePresence returnAgent = null; 288 UUID agentID = client.AgentId;
473 lock (m_scenes) 289
474 { 290 // Inform the friends that this user is online
475 ScenePresence queryagent = null; 291 StatusChange(agentID, true);
476 foreach (Scene scene in m_scenes.Values) 292
293 // Register that we need to send the list of online friends to this user
294 lock (m_NeedsListOfFriends)
295 if (!m_NeedsListOfFriends.Contains(agentID))
477 { 296 {
478 queryagent = scene.GetScenePresence(AgentID); 297 m_NeedsListOfFriends.Add(agentID);
479 if (queryagent != null)
480 {
481 returnAgent = queryagent;
482 break;
483 }
484 } 298 }
485 }
486 return returnAgent;
487 } 299 }
488 300
489 public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage) 301 public void SendFriendsOnlineIfNeeded(IClientAPI client)
490 { 302 {
491 CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId); 303 UUID agentID = client.AgentId;
492 304 if (m_NeedsListOfFriends.Contains(agentID))
493 if (userInfo != null)
494 { 305 {
495 GridInstantMessage msg = new GridInstantMessage( 306 if (!m_Friends.ContainsKey(agentID))
496 toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId, 307 {
497 (byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero); 308 m_log.DebugFormat("[FRIENDS MODULE]: agent {0} not found in local cache", agentID);
498 309 return;
499 FriendshipOffered(msg); 310 }
500 }
501 else
502 {
503 m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId);
504 }
505 }
506 311
507 #region FriendRequestHandling 312 //
313 // Send the friends online
314 //
315 List<UUID> online = GetOnlineFriends(agentID);
316 if (online.Count > 0)
317 {
318 m_log.DebugFormat("[FRIENDS MODULE]: User {0} in region {1} has {2} friends online", client.AgentId, client.Scene.RegionInfo.RegionName, online.Count);
319 client.SendAgentOnline(online.ToArray());
320 }
508 321
509 private void OnInstantMessage(IClientAPI client, GridInstantMessage im) 322 //
510 { 323 // Send outstanding friendship offers
511 // Friend Requests go by Instant Message.. using the dialog param 324 //
512 // https://wiki.secondlife.com/wiki/ImprovedInstantMessage 325 if (m_Friends.ContainsKey(agentID))
326 {
327 List<string> outstanding = new List<string>();
513 328
514 if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38 329 foreach (FriendInfo fi in m_Friends[agentID].Friends)
515 { 330 if (fi.TheirFlags == -1)
516 // fromAgentName is the *destination* name (the friend we offer friendship to) 331 outstanding.Add(fi.Friend);
517 ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID)); 332
518 im.fromAgentName = initiator != null ? initiator.Name : "(hippo)"; 333 GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, "", agentID, (byte)InstantMessageDialog.FriendshipOffered, "Will you be my friend?", true, Vector3.Zero);
519 334 foreach (string fid in outstanding)
520 FriendshipOffered(im); 335 {
521 } 336 try
522 else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39 337 {
523 { 338 im.fromAgentID = new Guid(fid);
524 FriendshipAccepted(client, im); 339 }
525 } 340 catch
526 else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40 341 {
527 { 342 continue;
528 FriendshipDeclined(client, im); 343 }
529 }
530 }
531
532 /// <summary>
533 /// Invoked when a user offers a friendship.
534 /// </summary>
535 ///
536 /// <param name="im"></param>
537 /// <param name="client"></param>
538 private void FriendshipOffered(GridInstantMessage im)
539 {
540 // this is triggered by the initiating agent:
541 // A local agent offers friendship to some possibly remote friend.
542 // A IM is triggered, processed here and sent to the friend (possibly in a remote region).
543 344
544 m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}", 345 UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, new UUID(im.fromAgentID));
545 im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline); 346 im.fromAgentName = account.FirstName + " " + account.LastName;
546 347
547 // 1.20 protocol sends an UUID in the message field, instead of the friendship offer text. 348 PresenceInfo[] presences = PresenceService.GetAgents(new string[] { fid });
548 // For interoperability, we have to clear that 349 PresenceInfo presence = PresenceInfo.GetOnlinePresence(presences);
549 if (Util.isUUID(im.message)) im.message = ""; 350 if (presence != null)
351 im.offline = 0;
550 352
551 // be sneeky and use the initiator-UUID as transactionID. This means we can be stateless. 353 im.imSessionID = im.fromAgentID;
552 // we have to look up the agent name on friendship-approval, though.
553 im.imSessionID = im.fromAgentID;
554 354
555 if (m_TransferModule != null) 355 // Finally
556 { 356 LocalFriendshipOffered(agentID, im);
557 // Send it to whoever is the destination.
558 // If new friend is local, it will send an IM to the viewer.
559 // If new friend is remote, it will cause a OnGridInstantMessage on the remote server
560 m_TransferModule.SendInstantMessage(
561 im,
562 delegate(bool success)
563 {
564 m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
565 } 357 }
566 );
567 }
568 }
569
570 /// <summary>
571 /// Invoked when a user accepts a friendship offer.
572 /// </summary>
573 /// <param name="im"></param>
574 /// <param name="client"></param>
575 private void FriendshipAccepted(IClientAPI client, GridInstantMessage im)
576 {
577 m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})",
578 client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
579 }
580
581 /// <summary>
582 /// Invoked when a user declines a friendship offer.
583 /// </summary>
584 /// May not currently be used - see OnDenyFriendRequest() instead
585 /// <param name="im"></param>
586 /// <param name="client"></param>
587 private void FriendshipDeclined(IClientAPI client, GridInstantMessage im)
588 {
589 UUID fromAgentID = new UUID(im.fromAgentID);
590 UUID toAgentID = new UUID(im.toAgentID);
591
592 // declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator
593 // toAgentID is initiator, fromAgentID declined friendship
594 m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})",
595 client != null ? client.AgentId.ToString() : "<null>",
596 fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
597
598 // Send the decline to whoever is the destination.
599 GridInstantMessage msg
600 = new GridInstantMessage(
601 client.Scene, fromAgentID, client.Name, toAgentID,
602 im.dialog, im.message, im.offline != 0, im.Position);
603
604 // If new friend is local, it will send an IM to the viewer.
605 // If new friend is remote, it will cause a OnGridInstantMessage on the remote server
606 m_TransferModule.SendInstantMessage(msg,
607 delegate(bool success) {
608 m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
609 } 358 }
610 );
611 }
612
613 private void OnGridInstantMessage(GridInstantMessage msg)
614 {
615 // This event won't be raised unless we have that agent,
616 // so we can depend on the above not trying to send
617 // via grid again
618 //m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}",
619 // msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog);
620
621 if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered ||
622 msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted ||
623 msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined)
624 {
625 // this should succeed as we *know* the root agent is here.
626 m_TransferModule.SendInstantMessage(msg,
627 delegate(bool success) {
628 //m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
629 }
630 );
631 }
632 359
633 if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted) 360 lock (m_NeedsListOfFriends)
634 { 361 m_NeedsListOfFriends.Remove(agentID);
635 // for accept friendship, we have to do a bit more
636 ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName);
637 } 362 }
638 } 363 }
639 364
640 private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName) 365 List<UUID> GetOnlineFriends(UUID userID)
641 { 366 {
642 m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}", 367 List<string> friendList = new List<string>();
643 fromAgentID, fromName, toAgentID); 368 List<UUID> online = new List<UUID>();
644 369
645 // a new friend was added in the initiator's and friend's data, so the cache entries are wrong now. 370 foreach (FriendInfo fi in m_Friends[userID].Friends)
646 lock (m_friendLists)
647 { 371 {
648 m_friendLists.Invalidate(fromAgentID.ToString()); 372 if (((fi.TheirFlags & 1) != 0) && (fi.TheirFlags != -1))
649 m_friendLists.Invalidate(toAgentID.ToString()); 373 friendList.Add(fi.Friend);
650 } 374 }
651 375
652 // now send presence update and add a calling card for the new friend 376 if (friendList.Count == 0)
377 // no friends whatsoever
378 return online;
653 379
654 ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID); 380 PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
655 if (initiator == null)
656 {
657 // quite wrong. Shouldn't happen.
658 m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID);
659 return;
660 }
661 381
662 m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online", 382 foreach (PresenceInfo pi in presence)
663 initiator.Name, fromName);
664 // tell initiator that friend is online
665 initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID });
666
667 // find the folder for the friend...
668 //InventoryFolderImpl folder =
669 // initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard);
670 IInventoryService invService = initiator.Scene.InventoryService;
671 InventoryFolderBase folder = invService.GetFolderForType(toAgentID, AssetType.CallingCard);
672 if (folder != null)
673 { 383 {
674 // ... and add the calling card 384 if (pi.Online)
675 CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName); 385 {
386 online.Add(new UUID(pi.UserID));
387 //m_log.DebugFormat("[XXX] {0} friend online {1}", userID, pi.UserID);
388 }
676 } 389 }
390
391 return online;
677 } 392 }
678 393
679 private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) 394 //
395 // Find the client for a ID
396 //
397 public IClientAPI LocateClientObject(UUID agentID)
680 { 398 {
681 m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}", 399 Scene scene = GetClientScene(agentID);
682 client.Name, client.AgentId, agentID, friendID); 400 if (scene == null)
683 401 return null;
684 // store the new friend persistently for both avatars
685 m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline);
686 402
687 // The cache entries aren't valid anymore either, as we just added a friend to both sides. 403 ScenePresence presence = scene.GetScenePresence(agentID);
688 lock (m_friendLists) 404 if (presence == null)
689 { 405 return null;
690 m_friendLists.Invalidate(agentID.ToString());
691 m_friendLists.Invalidate(friendID.ToString());
692 }
693 406
694 // if it's a local friend, we don't have to do the lookup 407 return presence.ControllingClient;
695 ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID); 408 }
696 409
697 if (friendPresence != null) 410 //
411 // Find the scene for an agent
412 //
413 private Scene GetClientScene(UUID agentId)
414 {
415 lock (m_Scenes)
698 { 416 {
699 m_log.Debug("[FRIEND]: Local agent detected."); 417 foreach (Scene scene in m_Scenes)
700 418 {
701 // create calling card 419 ScenePresence presence = scene.GetScenePresence(agentId);
702 CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name); 420 if (presence != null)
703 421 {
704 // local message means OnGridInstantMessage won't be triggered, so do the work here. 422 if (!presence.IsChildAgent)
705 friendPresence.ControllingClient.SendInstantMessage( 423 return scene;
706 new GridInstantMessage(client.Scene, agentID, 424 }
707 client.Name, friendID, 425 }
708 (byte)InstantMessageDialog.FriendshipAccepted,
709 agentID.ToString(), false, Vector3.Zero));
710 ApproveFriendship(agentID, friendID, client.Name);
711 } 426 }
712 else 427 return null;
713 { 428 }
714 m_log.Debug("[FRIEND]: Remote agent detected.");
715
716 // fetch the friend's name for the calling card.
717 CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID);
718
719 // create calling card
720 CreateCallingCard(client, friendID, callingCardFolders[0],
721 info.UserProfile.FirstName + " " + info.UserProfile.SurName);
722 429
723 // Compose (remote) response to friend. 430 /// <summary>
724 GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, 431 /// Caller beware! Call this only for root agents.
725 (byte)InstantMessageDialog.FriendshipAccepted, 432 /// </summary>
726 agentID.ToString(), false, Vector3.Zero); 433 /// <param name="agentID"></param>
727 if (m_TransferModule != null) 434 /// <param name="online"></param>
435 private void StatusChange(UUID agentID, bool online)
436 {
437 if (m_Friends.ContainsKey(agentID))
438 {
439 List<FriendInfo> friendList = new List<FriendInfo>();
440 foreach (FriendInfo fi in m_Friends[agentID].Friends)
728 { 441 {
729 m_TransferModule.SendInstantMessage(msg, 442 if (((fi.MyFlags & 1) != 0) && (fi.TheirFlags != -1))
730 delegate(bool success) { 443 friendList.Add(fi);
731 m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); 444 }
732 } 445 foreach (FriendInfo fi in friendList)
733 ); 446 {
447 // Notify about this user status
448 StatusNotify(fi, agentID, online);
734 } 449 }
735 } 450 }
736
737 // tell client that new friend is online
738 client.SendAgentOnline(new UUID[] { friendID });
739 } 451 }
740 452
741 private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) 453 private void StatusNotify(FriendInfo friend, UUID userID, bool online)
742 { 454 {
743 m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}", 455 UUID friendID = UUID.Zero;
744 client.Name, client.AgentId, agentID, friendID); 456
745 457 if (UUID.TryParse(friend.Friend, out friendID))
746 // Compose response to other agent.
747 GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID,
748 (byte)InstantMessageDialog.FriendshipDeclined,
749 agentID.ToString(), false, Vector3.Zero);
750 // send decline to initiator
751 if (m_TransferModule != null)
752 { 458 {
753 m_TransferModule.SendInstantMessage(msg, 459 // Try local
754 delegate(bool success) { 460 if (LocalStatusNotification(userID, friendID, online))
755 m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); 461 return;
756 } 462
757 ); 463 // The friend is not here [as root]. Let's forward.
464 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
465 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
466 if (friendSession != null)
467 {
468 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
469 m_FriendsSimConnector.StatusNotify(region, userID, friendID, online);
470 }
471
472 // Friend is not online. Ignore.
758 } 473 }
759 } 474 }
760 475
761 private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID) 476 private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
762 { 477 {
763 // client.AgentId == agentID! 478 if (im.dialog == (byte)OpenMetaverse.InstantMessageDialog.FriendshipOffered)
479 {
480 // we got a friendship offer
481 UUID principalID = new UUID(im.fromAgentID);
482 UUID friendID = new UUID(im.toAgentID);
764 483
765 // this removes the friends from the stored friendlists. After the next login, they will be gone... 484 m_log.DebugFormat("[FRIENDS]: {0} offered friendship to {1}", principalID, friendID);
766 m_initialScene.StoreRemoveFriendship(agentID, exfriendID);
767 485
768 // ... now tell the two involved clients that they aren't friends anymore. 486 // This user wants to be friends with the other user.
487 // Let's add the relation backwards, in case the other is not online
488 FriendsService.StoreFriend(friendID, principalID.ToString(), 0);
769 489
770 // I don't know why we have to tell <agent>, as this was caused by her, but that's how it works in SL... 490 // Now let's ask the other user to be friends with this user
771 client.SendTerminateFriend(exfriendID); 491 ForwardFriendshipOffer(principalID, friendID, im);
772
773 // now send the friend, if online
774 ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID);
775 if (presence != null)
776 {
777 m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID);
778 presence.ControllingClient.SendTerminateFriend(agentID);
779 } 492 }
780 else 493 }
781 {
782 // retry 3 times, in case the agent TPed from the last known region...
783 for (int retry = 0; retry < 3; ++retry)
784 {
785 // wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send
786 UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID);
787
788 if (null == data)
789 break;
790
791 if (!data.AgentOnline)
792 {
793 m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID);
794 break; // if ex-friend isn't online, we don't need to send
795 }
796 494
797 m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}", 495 private void ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
798 agentID, exfriendID, data.Handle); 496 {
497 // !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
498 // We stick this agent's ID as imSession, so that it's directly available on the receiving end
499 im.imSessionID = im.fromAgentID;
799 500
800 // try to send to foreign region, retry if it fails (friend TPed away, for example) 501 // Try the local sim
801 if (TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break; 502 if (LocalFriendshipOffered(friendID, im))
802 } 503 return;
803 }
804 504
805 // clean up cache: FriendList is wrong now... 505 // The prospective friend is not here [as root]. Let's forward.
806 lock (m_friendLists) 506 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
507 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
508 if (friendSession != null)
807 { 509 {
808 m_friendLists.Invalidate(agentID.ToString()); 510 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
809 m_friendLists.Invalidate(exfriendID.ToString()); 511 m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
810 } 512 }
513
514 // If the prospective friend is not online, he'll get the message upon login.
811 } 515 }
812 516
813 #endregion 517 private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
518 {
519 FriendsService.StoreFriend(agentID, friendID.ToString(), 1);
520 FriendsService.StoreFriend(friendID, agentID.ToString(), 1);
521 // update the local cache
522 m_Friends[agentID].Friends = FriendsService.GetFriends(agentID);
814 523
815 #region CallingCards 524 m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID);
816 525
817 private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID) 526 //
818 { 527 // Notify the friend
819 m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}", 528 //
820 client.AgentId, destID, transactionID); 529
821 // This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent 530 // Try Local
822 // (or the root instead of the child) 531 if (LocalFriendshipApproved(agentID, client.Name, friendID))
823 ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
824 if (destAgent == null)
825 { 532 {
826 client.SendAlertMessage("The person you have offered a card to can't be found anymore."); 533 client.SendAgentOnline(new UUID[] { friendID });
827 return; 534 return;
828 } 535 }
829 536
830 lock (m_pendingCallingcardRequests) 537 // The friend is not here
538 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
539 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
540 if (friendSession != null)
831 { 541 {
832 m_pendingCallingcardRequests[transactionID] = client.AgentId; 542 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
543 m_FriendsSimConnector.FriendshipApproved(region, agentID, client.Name, friendID);
544 client.SendAgentOnline(new UUID[] { friendID });
833 } 545 }
834 // inform the destination agent about the offer
835 destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID);
836 }
837 546
838 private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name)
839 {
840 InventoryItemBase item = new InventoryItemBase();
841 item.AssetID = UUID.Zero;
842 item.AssetType = (int)AssetType.CallingCard;
843 item.BasePermissions = (uint)PermissionMask.Copy;
844 item.CreationDate = Util.UnixTimeSinceEpoch();
845 item.CreatorId = creator.ToString();
846 item.CurrentPermissions = item.BasePermissions;
847 item.Description = "";
848 item.EveryOnePermissions = (uint)PermissionMask.None;
849 item.Flags = 0;
850 item.Folder = folder;
851 item.GroupID = UUID.Zero;
852 item.GroupOwned = false;
853 item.ID = UUID.Random();
854 item.InvType = (int)InventoryType.CallingCard;
855 item.Name = name;
856 item.NextPermissions = item.EveryOnePermissions;
857 item.Owner = client.AgentId;
858 item.SalePrice = 10;
859 item.SaleType = (byte)SaleType.Not;
860 ((Scene)client.Scene).AddInventoryItem(client, item);
861 } 547 }
862 548
863 private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID) 549 private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
864 { 550 {
865 m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}", 551 m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", agentID, friendID);
866 client.AgentId,
867 client.FirstName, client.LastName,
868 transactionID, folderID);
869 UUID destID;
870 lock (m_pendingCallingcardRequests)
871 {
872 if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID))
873 {
874 m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
875 client.Name);
876 return;
877 }
878 // else found pending calling card request with that transaction.
879 m_pendingCallingcardRequests.Remove(transactionID);
880 }
881 552
553 FriendsService.Delete(agentID, friendID.ToString());
554 FriendsService.Delete(friendID, agentID.ToString());
882 555
883 ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); 556 //
884 // inform sender of the card that destination declined the offer 557 // Notify the friend
885 if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID); 558 //
886 559
887 // put a calling card into the inventory of receiver 560 // Try local
888 CreateCallingCard(client, destID, folderID, destAgent.Name); 561 if (LocalFriendshipDenied(agentID, client.Name, friendID))
889 } 562 return;
890 563
891 private void OnDeclineCallingCard(IClientAPI client, UUID transactionID) 564 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
892 { 565 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
893 m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}", 566 if (friendSession != null)
894 client.Name, client.AgentId, transactionID);
895 UUID destID;
896 lock (m_pendingCallingcardRequests)
897 { 567 {
898 if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) 568 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
899 { 569 m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID);
900 m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
901 client.Name);
902 return;
903 }
904 // else found pending calling card request with that transaction.
905 m_pendingCallingcardRequests.Remove(transactionID);
906 } 570 }
907
908 ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
909 // inform sender of the card that destination declined the offer
910 if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID);
911 } 571 }
912 572
913 /// <summary> 573 private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID)
914 /// Send presence information about a client to other clients in both this region and others.
915 /// </summary>
916 /// <param name="client"></param>
917 /// <param name="friendList"></param>
918 /// <param name="iAmOnline"></param>
919 private void SendPresenceState(IClientAPI client, List<FriendListItem> friendList, bool iAmOnline)
920 { 574 {
921 //m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out"); 575 FriendsService.Delete(agentID, exfriendID.ToString());
576 FriendsService.Delete(exfriendID, agentID.ToString());
922 577
923 if (friendList == null || friendList.Count == 0) 578 // Update local cache
924 { 579 m_Friends[agentID].Friends = FriendsService.GetFriends(agentID);
925 //m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name);
926 return; // nothing we can do if she doesn't have friends...
927 }
928 580
929 // collect sets of friendIDs; to send to (online and offline), and to receive from 581 client.SendTerminateFriend(exfriendID);
930 // TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets.
931 // I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago...
932 List<UUID> friendIDsToSendTo = new List<UUID>();
933 List<UUID> candidateFriendIDsToReceive = new List<UUID>();
934
935 foreach (FriendListItem item in friendList)
936 {
937 if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0)
938 {
939 // friend is allowed to see my presence => add
940 if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
941 friendIDsToSendTo.Add(item.Friend);
942 582
943 if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) 583 //
944 candidateFriendIDsToReceive.Add(item.Friend); 584 // Notify the friend
945 } 585 //
946 }
947 586
948 // we now have a list of "interesting" friends (which we have to find out on-/offline state for), 587 // Try local
949 // friends we want to send our online state to (if *they* are online, too), and 588 if (LocalFriendshipTerminated(exfriendID))
950 // friends we want to receive online state for (currently unknown whether online or not) 589 return;
951 590
952 // as this processing might take some time and friends might TP away, we try up to three times to 591 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
953 // reach them. Most of the time, we *will* reach them, and this loop won't loop 592 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
954 int retry = 0; 593 if (friendSession != null)
955 do
956 { 594 {
957 // build a list of friends to look up region-information and on-/offline-state for 595 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
958 List<UUID> friendIDsToLookup = new List<UUID>(friendIDsToSendTo); 596 m_FriendsSimConnector.FriendshipTerminated(region, agentID, exfriendID);
959 foreach (UUID uuid in candidateFriendIDsToReceive) 597 }
960 { 598 }
961 if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid);
962 }
963
964 m_log.DebugFormat(
965 "[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}",
966 friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name);
967
968 // we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't
969 // necessarily contain the correct online state...
970 Dictionary<UUID, FriendRegionInfo> friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup);
971 m_log.DebugFormat(
972 "[FRIEND]: Found {0} regionInfos for {1} friends of {2}",
973 friendRegions.Count, friendIDsToLookup.Count, client.Name);
974 599
975 // argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops. 600 private void OnGrantUserRights(IClientAPI remoteClient, UUID requester, UUID target, int rights)
976 UUID[] agentArr = new UUID[] { client.AgentId }; 601 {
602 if (!m_Friends.ContainsKey(remoteClient.AgentId))
603 return;
977 604
978 // first, send to friend presence state to me, if I'm online... 605 m_log.DebugFormat("[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}", requester, rights, target);
979 if (iAmOnline) 606 // Let's find the friend in this user's friend list
980 { 607 UserFriendData fd = m_Friends[remoteClient.AgentId];
981 List<UUID> friendIDsToReceive = new List<UUID>(); 608 FriendInfo friend = null;
982 609 foreach (FriendInfo fi in fd.Friends)
983 for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i) 610 if (fi.Friend == target.ToString())
984 { 611 friend = fi;
985 UUID uuid = candidateFriendIDsToReceive[i];
986 FriendRegionInfo info;
987 if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
988 {
989 friendIDsToReceive.Add(uuid);
990 }
991 }
992
993 m_log.DebugFormat(
994 "[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name);
995
996 if (friendIDsToReceive.Count > 0)
997 client.SendAgentOnline(friendIDsToReceive.ToArray());
998
999 // clear them for a possible second iteration; we don't have to repeat this
1000 candidateFriendIDsToReceive.Clear();
1001 }
1002 612
1003 // now, send my presence state to my friends 613 if (friend != null) // Found it
1004 for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i) 614 {
1005 { 615 // Store it on the DB
1006 UUID uuid = friendIDsToSendTo[i]; 616 FriendsService.StoreFriend(requester, target.ToString(), rights);
1007 FriendRegionInfo info;
1008 if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
1009 {
1010 // any client is good enough, root or child...
1011 ScenePresence agent = GetAnyPresenceFromAgentID(uuid);
1012 if (agent != null)
1013 {
1014 //m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name);
1015 617
1016 // friend is online and on this server... 618 // Store it in the local cache
1017 if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr); 619 int myFlags = friend.MyFlags;
1018 else agent.ControllingClient.SendAgentOffline(agentArr); 620 friend.MyFlags = rights;
1019 621
1020 // done, remove it 622 // Always send this back to the original client
1021 friendIDsToSendTo.RemoveAt(i); 623 remoteClient.SendChangeUserRights(requester, target, rights);
1022 }
1023 }
1024 else
1025 {
1026 //m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i);
1027 624
1028 // friend is offline => no need to try sending 625 //
1029 friendIDsToSendTo.RemoveAt(i); 626 // Notify the friend
1030 } 627 //
1031 }
1032 628
1033 m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count); 629 // Try local
630 if (LocalGrantRights(requester, target, myFlags, rights))
631 return;
1034 632
1035 // we now have all the friends left that are online (we think), but not on this region-server 633 PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { target.ToString() });
1036 if (friendIDsToSendTo.Count > 0) 634 PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions);
635 if (friendSession != null)
1037 { 636 {
1038 // sort them into regions 637 GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
1039 Dictionary<ulong, List<UUID>> friendsInRegion = new Dictionary<ulong,List<UUID>>(); 638 // TODO: You might want to send the delta to save the lookup
1040 foreach (UUID uuid in friendIDsToSendTo) 639 // on the other end!!
1041 { 640 m_FriendsSimConnector.GrantRights(region, requester, target, myFlags, rights);
1042 ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already
1043 List<UUID> friends;
1044 if (!friendsInRegion.TryGetValue(handle, out friends))
1045 {
1046 friends = new List<UUID>();
1047 friendsInRegion[handle] = friends;
1048 }
1049 friends.Add(uuid);
1050 }
1051 m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count);
1052
1053 // clear uuids list and collect missed friends in it for the next retry
1054 friendIDsToSendTo.Clear();
1055
1056 // send bulk updates to the region
1057 foreach (KeyValuePair<ulong, List<UUID>> pair in friendsInRegion)
1058 {
1059 //m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line",
1060 // pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off");
1061
1062 friendIDsToSendTo.AddRange(InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline));
1063 }
1064 } 641 }
1065 // now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them.
1066 // In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again...
1067 } 642 }
1068 while (++retry < 3 && friendIDsToSendTo.Count > 0);
1069 } 643 }
1070 644
1071 private void OnEconomyDataRequest(UUID agentID) 645 #region Local
646
647 public bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
1072 { 648 {
1073 // KLUDGE: This is the only way I found to get a message (only) after login was completed and the 649 IClientAPI friendClient = LocateClientObject(toID);
1074 // client is connected enough to receive UDP packets). 650 if (friendClient != null)
1075 // This packet seems to be sent only once, just after connection was established to the first
1076 // region after login.
1077 // We use it here to trigger a presence update; the old update-on-login was never be heard by
1078 // the freshly logged in viewer, as it wasn't connected to the region at that time.
1079 // TODO: Feel free to replace this by a better solution if you find one.
1080
1081 // get the agent. This should work every time, as we just got a packet from it
1082 //ScenePresence agent = GetRootPresenceFromAgentID(agentID);
1083 // KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit
1084 ScenePresence agent = GetAnyPresenceFromAgentID(agentID);
1085
1086 // just to be paranoid...
1087 if (agent == null)
1088 { 651 {
1089 m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID); 652 // the prospective friend in this sim as root agent
1090 return; 653 friendClient.SendInstantMessage(im);
654 // we're done
655 return true;
1091 } 656 }
657 return false;
658 }
1092 659
1093 List<FriendListItem> fl; 660 public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
1094 lock (m_friendLists) 661 {
662 IClientAPI friendClient = LocateClientObject(friendID);
663 if (friendClient != null)
1095 { 664 {
1096 fl = (List<FriendListItem>)m_friendLists.Get(agent.ControllingClient.AgentId.ToString(), 665 // the prospective friend in this sim as root agent
1097 m_initialScene.GetFriendList); 666 GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
667 (byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
668 friendClient.SendInstantMessage(im);
669 // update the local cache
670 m_Friends[friendID].Friends = FriendsService.GetFriends(friendID);
671 // we're done
672 return true;
1098 } 673 }
1099 674
1100 // tell everyone that we are online 675 return false;
1101 SendPresenceState(agent.ControllingClient, fl, true);
1102 } 676 }
1103 677
1104 private void OnLogout(IClientAPI remoteClient) 678 public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
1105 { 679 {
1106 List<FriendListItem> fl; 680 IClientAPI friendClient = LocateClientObject(friendID);
1107 lock (m_friendLists) 681 if (friendClient != null)
1108 { 682 {
1109 fl = (List<FriendListItem>)m_friendLists.Get(remoteClient.AgentId.ToString(), 683 // the prospective friend in this sim as root agent
1110 m_initialScene.GetFriendList);
1111 }
1112 684
1113 // tell everyone that we are offline 685 GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
1114 SendPresenceState(remoteClient, fl, false); 686 (byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
687 friendClient.SendInstantMessage(im);
688 // we're done
689 return true;
690 }
691
692 return false;
1115 } 693 }
1116 private void GrantUserFriendRights(IClientAPI remoteClient, UUID requester, UUID target, int rights) 694
695 public bool LocalFriendshipTerminated(UUID exfriendID)
1117 { 696 {
1118 ((Scene)remoteClient.Scene).CommsManager.UpdateUserFriendPerms(requester, target, (uint)rights); 697 IClientAPI friendClient = LocateClientObject(exfriendID);
698 if (friendClient != null)
699 {
700 // the friend in this sim as root agent
701 friendClient.SendTerminateFriend(exfriendID);
702 // update local cache
703 m_Friends[exfriendID].Friends = FriendsService.GetFriends(exfriendID);
704 // we're done
705 return true;
706 }
707
708 return false;
1119 } 709 }
1120 public void FindAgent(IClientAPI remoteClient, UUID hunter, UUID target) 710
711 public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights)
1121 { 712 {
1122 List<FriendListItem> friendList = GetUserFriends(hunter); 713 IClientAPI friendClient = LocateClientObject(friendID);
1123 foreach (FriendListItem item in friendList) 714 if (friendClient != null)
1124 { 715 {
1125 if (item.onlinestatus == true) 716 bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0;
717 if (onlineBitChanged)
1126 { 718 {
1127 if (item.Friend == target && (item.FriendPerms & (uint)FriendRights.CanSeeOnMap) != 0) 719 if ((rights & (int)FriendRights.CanSeeOnline) == 1)
1128 { 720 friendClient.SendAgentOnline(new UUID[] { new UUID(userID) });
1129 ScenePresence SPTarget = ((Scene)remoteClient.Scene).GetScenePresence(target); 721 else
1130 string regionname = SPTarget.Scene.RegionInfo.RegionName; 722 friendClient.SendAgentOffline(new UUID[] { new UUID(userID) });
1131 remoteClient.SendScriptTeleportRequest("FindAgent", regionname,new Vector3(SPTarget.AbsolutePosition),new Vector3(SPTarget.Lookat));
1132 }
1133 } 723 }
1134 else 724 else
1135 { 725 {
1136 remoteClient.SendAgentAlertMessage("The agent you are looking for is not online.", false); 726 bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0;
727 if (canEditObjectsChanged)
728 friendClient.SendChangeUserRights(userID, friendID, rights);
1137 } 729 }
730
731 return true;
1138 } 732 }
733
734 return false;
735
1139 } 736 }
1140 737
1141 public List<FriendListItem> GetUserFriends(UUID agentID) 738 public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
1142 { 739 {
1143 List<FriendListItem> fl; 740 IClientAPI friendClient = LocateClientObject(friendID);
1144 lock (m_friendLists) 741 if (friendClient != null)
1145 { 742 {
1146 fl = (List<FriendListItem>)m_friendLists.Get(agentID.ToString(), 743 //m_log.DebugFormat("[FRIENDS]: Notify {0} that user {1} is {2}", friend.Friend, userID, online);
1147 m_initialScene.GetFriendList); 744 // the friend in this sim as root agent
745 if (online)
746 friendClient.SendAgentOnline(new UUID[] { userID });
747 else
748 friendClient.SendAgentOffline(new UUID[] { userID });
749 // we're done
750 return true;
1148 } 751 }
1149 752
1150 return fl; 753 return false;
1151 } 754 }
755 #endregion
756
1152 } 757 }
1153 #endregion
1154} 758}
diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs
new file mode 100644
index 0000000..0883c5b
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs
@@ -0,0 +1,293 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Reflection;
32using System.Xml;
33
34using OpenSim.Framework;
35using OpenSim.Server.Base;
36using OpenSim.Framework.Servers.HttpServer;
37using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
38
39using OpenMetaverse;
40using log4net;
41
42namespace OpenSim.Region.CoreModules.Avatar.Friends
43{
44 public class FriendsRequestHandler : BaseStreamHandler
45 {
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47
48 private FriendsModule m_FriendsModule;
49
50 public FriendsRequestHandler(FriendsModule fmodule)
51 : base("POST", "/friends")
52 {
53 m_FriendsModule = fmodule;
54 }
55
56 public override byte[] Handle(string path, Stream requestData,
57 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
58 {
59 StreamReader sr = new StreamReader(requestData);
60 string body = sr.ReadToEnd();
61 sr.Close();
62 body = body.Trim();
63
64 m_log.DebugFormat("[XXX]: query String: {0}", body);
65
66 try
67 {
68 Dictionary<string, object> request =
69 ServerUtils.ParseQueryString(body);
70
71 if (!request.ContainsKey("METHOD"))
72 return FailureResult();
73
74 string method = request["METHOD"].ToString();
75 request.Remove("METHOD");
76
77 switch (method)
78 {
79 case "friendship_offered":
80 return FriendshipOffered(request);
81 case "friendship_approved":
82 return FriendshipApproved(request);
83 case "friendship_denied":
84 return FriendshipDenied(request);
85 case "friendship_terminated":
86 return FriendshipTerminated(request);
87 case "grant_rights":
88 return GrantRights(request);
89 case "status":
90 return StatusNotification(request);
91 }
92 }
93 catch (Exception e)
94 {
95 m_log.Debug("[FRIENDS]: Exception {0}" + e.ToString());
96 }
97
98 return FailureResult();
99 }
100
101 byte[] FriendshipOffered(Dictionary<string, object> request)
102 {
103 UUID fromID = UUID.Zero;
104 UUID toID = UUID.Zero;
105 string message = string.Empty;
106
107 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
108 return FailureResult();
109
110 message = request["Message"].ToString();
111
112 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
113 return FailureResult();
114
115 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
116 return FailureResult();
117
118 GridInstantMessage im = new GridInstantMessage(m_FriendsModule.Scene, fromID, "", toID,
119 (byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero);
120
121 if (m_FriendsModule.LocalFriendshipOffered(toID, im))
122 return SuccessResult();
123
124 return FailureResult();
125 }
126
127 byte[] FriendshipApproved(Dictionary<string, object> request)
128 {
129 UUID fromID = UUID.Zero;
130 UUID toID = UUID.Zero;
131 string fromName = string.Empty;
132
133 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
134 return FailureResult();
135
136 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
137 return FailureResult();
138
139 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
140 return FailureResult();
141
142 if (request.ContainsKey("FromName"))
143 fromName = request["FromName"].ToString();
144
145 if (m_FriendsModule.LocalFriendshipApproved(fromID, fromName, toID))
146 return SuccessResult();
147
148 return FailureResult();
149 }
150
151 byte[] FriendshipDenied(Dictionary<string, object> request)
152 {
153 UUID fromID = UUID.Zero;
154 UUID toID = UUID.Zero;
155 string fromName = string.Empty;
156
157 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
158 return FailureResult();
159
160 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
161 return FailureResult();
162
163 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
164 return FailureResult();
165
166 if (request.ContainsKey("FromName"))
167 fromName = request["FromName"].ToString();
168
169 if (m_FriendsModule.LocalFriendshipDenied(fromID, fromName, toID))
170 return SuccessResult();
171
172 return FailureResult();
173 }
174
175 byte[] FriendshipTerminated(Dictionary<string, object> request)
176 {
177 UUID fromID = UUID.Zero;
178 UUID toID = UUID.Zero;
179
180 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
181 return FailureResult();
182
183 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
184 return FailureResult();
185
186 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
187 return FailureResult();
188
189 if (m_FriendsModule.LocalFriendshipTerminated(toID))
190 return SuccessResult();
191
192 return FailureResult();
193 }
194
195 byte[] GrantRights(Dictionary<string, object> request)
196 {
197 UUID fromID = UUID.Zero;
198 UUID toID = UUID.Zero;
199 int rights = 0, userFlags = 0;
200
201 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
202 return FailureResult();
203
204 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
205 return FailureResult();
206
207 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
208 return FailureResult();
209
210 if (!Int32.TryParse(request["UserFlags"].ToString(), out userFlags))
211 return FailureResult();
212
213 if (!Int32.TryParse(request["Rights"].ToString(), out rights))
214 return FailureResult();
215
216 if (m_FriendsModule.LocalGrantRights(UUID.Zero, UUID.Zero, userFlags, rights))
217 return SuccessResult();
218
219 return FailureResult();
220 }
221
222 byte[] StatusNotification(Dictionary<string, object> request)
223 {
224 UUID fromID = UUID.Zero;
225 UUID toID = UUID.Zero;
226 bool online = false;
227
228 if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID") || !request.ContainsKey("Online"))
229 return FailureResult();
230
231 if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
232 return FailureResult();
233
234 if (!UUID.TryParse(request["ToID"].ToString(), out toID))
235 return FailureResult();
236
237 if (!Boolean.TryParse(request["Online"].ToString(), out online))
238 return FailureResult();
239
240 if (m_FriendsModule.LocalStatusNotification(fromID, toID, online))
241 return SuccessResult();
242
243 return FailureResult();
244 }
245
246 #region Misc
247
248 private byte[] FailureResult()
249 {
250 return BoolResult(false);
251 }
252
253 private byte[] SuccessResult()
254 {
255 return BoolResult(true);
256 }
257
258 private byte[] BoolResult(bool value)
259 {
260 XmlDocument doc = new XmlDocument();
261
262 XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
263 "", "");
264
265 doc.AppendChild(xmlnode);
266
267 XmlElement rootElement = doc.CreateElement("", "ServerResponse",
268 "");
269
270 doc.AppendChild(rootElement);
271
272 XmlElement result = doc.CreateElement("", "RESULT", "");
273 result.AppendChild(doc.CreateTextNode(value.ToString()));
274
275 rootElement.AppendChild(result);
276
277 return DocToBytes(doc);
278 }
279
280 private byte[] DocToBytes(XmlDocument doc)
281 {
282 MemoryStream ms = new MemoryStream();
283 XmlTextWriter xw = new XmlTextWriter(ms, null);
284 xw.Formatting = Formatting.Indented;
285 doc.WriteTo(xw);
286 xw.Flush();
287
288 return ms.ToArray();
289 }
290
291 #endregion
292 }
293}
diff --git a/OpenSim/Region/CoreModules/Avatar/Gestures/GesturesModule.cs b/OpenSim/Region/CoreModules/Avatar/Gestures/GesturesModule.cs
index 8ce5092..7303fe7 100644
--- a/OpenSim/Region/CoreModules/Avatar/Gestures/GesturesModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Gestures/GesturesModule.cs
@@ -30,7 +30,7 @@ using log4net;
30using Nini.Config; 30using Nini.Config;
31using OpenMetaverse; 31using OpenMetaverse;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Framework.Communications.Cache; 33
34using OpenSim.Region.Framework.Interfaces; 34using OpenSim.Region.Framework.Interfaces;
35using OpenSim.Region.Framework.Scenes; 35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Services.Interfaces; 36using OpenSim.Services.Interfaces;
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/InstantMessageModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/InstantMessageModule.cs
index 9a68749..ab141eb 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/InstantMessageModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/InstantMessageModule.cs
@@ -24,6 +24,7 @@
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27using System;
27using System.Collections.Generic; 28using System.Collections.Generic;
28using System.Reflection; 29using System.Reflection;
29using log4net; 30using log4net;
@@ -36,9 +37,10 @@ using OpenSim.Region.Framework.Scenes;
36 37
37namespace OpenSim.Region.CoreModules.Avatar.InstantMessage 38namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
38{ 39{
39 public class InstantMessageModule : IRegionModule 40 public class InstantMessageModule : ISharedRegionModule
40 { 41 {
41 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 42 private static readonly ILog m_log = LogManager.GetLogger(
43 MethodBase.GetCurrentMethod().DeclaringType);
42 44
43 /// <value> 45 /// <value>
44 /// Is this module enabled? 46 /// Is this module enabled?
@@ -51,7 +53,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
51 53
52 private IMessageTransferModule m_TransferModule = null; 54 private IMessageTransferModule m_TransferModule = null;
53 55
54 public void Initialise(Scene scene, IConfigSource config) 56 public void Initialise(IConfigSource config)
55 { 57 {
56 if (config.Configs["Messaging"] != null) 58 if (config.Configs["Messaging"] != null)
57 { 59 {
@@ -62,6 +64,12 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
62 } 64 }
63 65
64 m_enabled = true; 66 m_enabled = true;
67 }
68
69 public void AddRegion(Scene scene)
70 {
71 if (!m_enabled)
72 return;
65 73
66 lock (m_scenes) 74 lock (m_scenes)
67 { 75 {
@@ -74,6 +82,39 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
74 } 82 }
75 } 83 }
76 84
85 public void RegionLoaded(Scene scene)
86 {
87 if (!m_enabled)
88 return;
89
90 if (m_TransferModule == null)
91 {
92 m_TransferModule =
93 scene.RequestModuleInterface<IMessageTransferModule>();
94
95 if (m_TransferModule == null)
96 {
97 m_log.Error("[INSTANT MESSAGE]: No message transfer module, IM will not work!");
98 scene.EventManager.OnClientConnect -= OnClientConnect;
99 scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
100
101 m_scenes.Clear();
102 m_enabled = false;
103 }
104 }
105 }
106
107 public void RemoveRegion(Scene scene)
108 {
109 if (!m_enabled)
110 return;
111
112 lock (m_scenes)
113 {
114 m_scenes.Remove(scene);
115 }
116 }
117
77 void OnClientConnect(IClientCore client) 118 void OnClientConnect(IClientCore client)
78 { 119 {
79 IClientIM clientIM; 120 IClientIM clientIM;
@@ -85,15 +126,6 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
85 126
86 public void PostInitialise() 127 public void PostInitialise()
87 { 128 {
88 if (!m_enabled)
89 return;
90
91 m_TransferModule =
92 m_scenes[0].RequestModuleInterface<IMessageTransferModule>();
93
94 if (m_TransferModule == null)
95 m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
96 "IM will not work!");
97 } 129 }
98 130
99 public void Close() 131 public void Close()
@@ -105,9 +137,9 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
105 get { return "InstantMessageModule"; } 137 get { return "InstantMessageModule"; }
106 } 138 }
107 139
108 public bool IsSharedModule 140 public Type ReplaceableInterface
109 { 141 {
110 get { return true; } 142 get { return null; }
111 } 143 }
112 144
113 #endregion 145 #endregion
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs
index e5159b3..ad050a1 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs
@@ -37,21 +37,33 @@ using OpenSim.Framework;
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
39using GridRegion = OpenSim.Services.Interfaces.GridRegion; 39using GridRegion = OpenSim.Services.Interfaces.GridRegion;
40using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
41using OpenSim.Services.Interfaces;
40 42
41namespace OpenSim.Region.CoreModules.Avatar.InstantMessage 43namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
42{ 44{
43 public class MessageTransferModule : IRegionModule, IMessageTransferModule 45 public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
44 { 46 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46 48
47 // private bool m_Enabled = false; 49 private bool m_Enabled = false;
48 protected bool m_Gridmode = false;
49 protected List<Scene> m_Scenes = new List<Scene>(); 50 protected List<Scene> m_Scenes = new List<Scene>();
50 protected Dictionary<UUID, ulong> m_UserRegionMap = new Dictionary<UUID, ulong>(); 51 protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
51 52
52 public event UndeliveredMessage OnUndeliveredMessage; 53 public event UndeliveredMessage OnUndeliveredMessage;
53 54
54 public virtual void Initialise(Scene scene, IConfigSource config) 55 private IPresenceService m_PresenceService;
56 protected IPresenceService PresenceService
57 {
58 get
59 {
60 if (m_PresenceService == null)
61 m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
62 return m_PresenceService;
63 }
64 }
65
66 public virtual void Initialise(IConfigSource config)
55 { 67 {
56 IConfig cnf = config.Configs["Messaging"]; 68 IConfig cnf = config.Configs["Messaging"];
57 if (cnf != null && cnf.GetString( 69 if (cnf != null && cnf.GetString(
@@ -62,20 +74,16 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
62 return; 74 return;
63 } 75 }
64 76
65 cnf = config.Configs["Startup"]; 77 m_Enabled = true;
66 if (cnf != null) 78 }
67 m_Gridmode = cnf.GetBoolean("gridmode", false);
68 79
69 // m_Enabled = true; 80 public virtual void AddRegion(Scene scene)
81 {
82 if (!m_Enabled)
83 return;
70 84
71 lock (m_Scenes) 85 lock (m_Scenes)
72 { 86 {
73 if (m_Scenes.Count == 0)
74 {
75 MainServer.Instance.AddXmlRPCHandler(
76 "grid_instant_message", processXMLRPCGridInstantMessage);
77 }
78
79 m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active"); 87 m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
80 scene.RegisterModuleInterface<IMessageTransferModule>(this); 88 scene.RegisterModuleInterface<IMessageTransferModule>(this);
81 m_Scenes.Add(scene); 89 m_Scenes.Add(scene);
@@ -84,6 +92,26 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
84 92
85 public virtual void PostInitialise() 93 public virtual void PostInitialise()
86 { 94 {
95 if (!m_Enabled)
96 return;
97
98 MainServer.Instance.AddXmlRPCHandler(
99 "grid_instant_message", processXMLRPCGridInstantMessage);
100 }
101
102 public virtual void RegionLoaded(Scene scene)
103 {
104 }
105
106 public virtual void RemoveRegion(Scene scene)
107 {
108 if (!m_Enabled)
109 return;
110
111 lock (m_Scenes)
112 {
113 m_Scenes.Remove(scene);
114 }
87 } 115 }
88 116
89 public virtual void Close() 117 public virtual void Close()
@@ -95,9 +123,9 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
95 get { return "MessageTransferModule"; } 123 get { return "MessageTransferModule"; }
96 } 124 }
97 125
98 public virtual bool IsSharedModule 126 public virtual Type ReplaceableInterface
99 { 127 {
100 get { return true; } 128 get { return null; }
101 } 129 }
102 130
103 public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result) 131 public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
@@ -148,15 +176,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
148 } 176 }
149 } 177 }
150 178
151 if (m_Gridmode) 179 SendGridInstantMessageViaXMLRPC(im, result);
152 {
153 //m_log.DebugFormat("[INSTANT MESSAGE]: Delivering via grid");
154 // Still here, try send via Grid
155 SendGridInstantMessageViaXMLRPC(im, result);
156 return;
157 }
158
159 HandleUndeliveredMessage(im, result);
160 180
161 return; 181 return;
162 } 182 }
@@ -409,7 +429,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
409 /// <summary> 429 /// <summary>
410 /// delegate for sending a grid instant message asynchronously 430 /// delegate for sending a grid instant message asynchronously
411 /// </summary> 431 /// </summary>
412 public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, ulong prevRegionHandle); 432 public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID);
413 433
414 protected virtual void GridInstantMessageCompleted(IAsyncResult iar) 434 protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
415 { 435 {
@@ -423,7 +443,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
423 { 443 {
424 GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync; 444 GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
425 445
426 d.BeginInvoke(im, result, 0, GridInstantMessageCompleted, d); 446 d.BeginInvoke(im, result, UUID.Zero, GridInstantMessageCompleted, d);
427 } 447 }
428 448
429 /// <summary> 449 /// <summary>
@@ -438,11 +458,11 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
438 /// Pass in 0 the first time this method is called. It will be called recursively with the last 458 /// Pass in 0 the first time this method is called. It will be called recursively with the last
439 /// regionhandle tried 459 /// regionhandle tried
440 /// </param> 460 /// </param>
441 protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, ulong prevRegionHandle) 461 protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID)
442 { 462 {
443 UUID toAgentID = new UUID(im.toAgentID); 463 UUID toAgentID = new UUID(im.toAgentID);
444 464
445 UserAgentData upd = null; 465 PresenceInfo upd = null;
446 466
447 bool lookupAgent = false; 467 bool lookupAgent = false;
448 468
@@ -450,13 +470,13 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
450 { 470 {
451 if (m_UserRegionMap.ContainsKey(toAgentID)) 471 if (m_UserRegionMap.ContainsKey(toAgentID))
452 { 472 {
453 upd = new UserAgentData(); 473 upd = new PresenceInfo();
454 upd.AgentOnline = true; 474 upd.Online = true;
455 upd.Handle = m_UserRegionMap[toAgentID]; 475 upd.RegionID = m_UserRegionMap[toAgentID];
456 476
457 // We need to compare the current regionhandle with the previous region handle 477 // We need to compare the current regionhandle with the previous region handle
458 // or the recursive loop will never end because it will never try to lookup the agent again 478 // or the recursive loop will never end because it will never try to lookup the agent again
459 if (prevRegionHandle == upd.Handle) 479 if (prevRegionID == upd.RegionID)
460 { 480 {
461 lookupAgent = true; 481 lookupAgent = true;
462 } 482 }
@@ -472,14 +492,23 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
472 if (lookupAgent) 492 if (lookupAgent)
473 { 493 {
474 // Non-cached user agent lookup. 494 // Non-cached user agent lookup.
475 upd = m_Scenes[0].CommsManager.UserService.GetAgentByUUID(toAgentID); 495 PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
496 if (presences != null)
497 {
498 foreach (PresenceInfo p in presences)
499 if (p.Online)
500 {
501 upd = presences[0];
502 break;
503 }
504 }
476 505
477 if (upd != null) 506 if (upd != null)
478 { 507 {
479 // check if we've tried this before.. 508 // check if we've tried this before..
480 // This is one way to end the recursive loop 509 // This is one way to end the recursive loop
481 // 510 //
482 if (upd.Handle == prevRegionHandle) 511 if (upd.RegionID == prevRegionID)
483 { 512 {
484 m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message"); 513 m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
485 HandleUndeliveredMessage(im, result); 514 HandleUndeliveredMessage(im, result);
@@ -496,12 +525,10 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
496 525
497 if (upd != null) 526 if (upd != null)
498 { 527 {
499 if (upd.AgentOnline) 528 if (upd.Online)
500 { 529 {
501 uint x = 0, y = 0; 530 GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID,
502 Utils.LongToUInts(upd.Handle, out x, out y); 531 upd.RegionID);
503 GridRegion reginfo = m_Scenes[0].GridService.GetRegionByPosition(m_Scenes[0].RegionInfo.ScopeID,
504 (int)x, (int)y);
505 if (reginfo != null) 532 if (reginfo != null)
506 { 533 {
507 Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); 534 Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
@@ -517,11 +544,11 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
517 { 544 {
518 if (m_UserRegionMap.ContainsKey(toAgentID)) 545 if (m_UserRegionMap.ContainsKey(toAgentID))
519 { 546 {
520 m_UserRegionMap[toAgentID] = upd.Handle; 547 m_UserRegionMap[toAgentID] = upd.RegionID;
521 } 548 }
522 else 549 else
523 { 550 {
524 m_UserRegionMap.Add(toAgentID, upd.Handle); 551 m_UserRegionMap.Add(toAgentID, upd.RegionID);
525 } 552 }
526 } 553 }
527 result(true); 554 result(true);
@@ -536,12 +563,12 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
536 563
537 // This is recursive!!!!! 564 // This is recursive!!!!!
538 SendGridInstantMessageViaXMLRPCAsync(im, result, 565 SendGridInstantMessageViaXMLRPCAsync(im, result,
539 upd.Handle); 566 upd.RegionID);
540 } 567 }
541 } 568 }
542 else 569 else
543 { 570 {
544 m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.Handle); 571 m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID);
545 HandleUndeliveredMessage(im, result); 572 HandleUndeliveredMessage(im, result);
546 } 573 }
547 } 574 }
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MuteListModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MuteListModule.cs
index 2d4a635..24cbaeb 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MuteListModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MuteListModule.cs
@@ -37,9 +37,9 @@ using OpenSim.Framework.Client;
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
39 39
40namespace OpenSim.Region.CoreModules.Avatar.MuteList 40namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
41{ 41{
42 public class MuteListModule : IRegionModule 42 public class MuteListModule : ISharedRegionModule
43 { 43 {
44 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 44 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
45 45
@@ -47,11 +47,8 @@ namespace OpenSim.Region.CoreModules.Avatar.MuteList
47 private List<Scene> m_SceneList = new List<Scene>(); 47 private List<Scene> m_SceneList = new List<Scene>();
48 private string m_RestURL = String.Empty; 48 private string m_RestURL = String.Empty;
49 49
50 public void Initialise(Scene scene, IConfigSource config) 50 public void Initialise(IConfigSource config)
51 { 51 {
52 if (!enabled)
53 return;
54
55 IConfig cnf = config.Configs["Messaging"]; 52 IConfig cnf = config.Configs["Messaging"];
56 if (cnf == null) 53 if (cnf == null)
57 { 54 {
@@ -59,39 +56,53 @@ namespace OpenSim.Region.CoreModules.Avatar.MuteList
59 return; 56 return;
60 } 57 }
61 58
62 if (cnf != null && cnf.GetString( 59 if (cnf != null && cnf.GetString("MuteListModule", "None") !=
63 "MuteListModule", "None") !=
64 "MuteListModule") 60 "MuteListModule")
65 { 61 {
66 enabled = false; 62 enabled = false;
67 return; 63 return;
68 } 64 }
69 65
66 m_RestURL = cnf.GetString("MuteListURL", "");
67 if (m_RestURL == "")
68 {
69 m_log.Error("[MUTE LIST] Module was enabled, but no URL is given, disabling");
70 enabled = false;
71 return;
72 }
73 }
74
75 public void AddRegion(Scene scene)
76 {
77 if (!enabled)
78 return;
79
70 lock (m_SceneList) 80 lock (m_SceneList)
71 { 81 {
72 if (m_SceneList.Count == 0) 82 m_SceneList.Add(scene);
73 {
74 m_RestURL = cnf.GetString("MuteListURL", "");
75 if (m_RestURL == "")
76 {
77 m_log.Error("[MUTE LIST] Module was enabled, but no URL is given, disabling");
78 enabled = false;
79 return;
80 }
81 }
82 if (!m_SceneList.Contains(scene))
83 m_SceneList.Add(scene);
84 83
85 scene.EventManager.OnNewClient += OnNewClient; 84 scene.EventManager.OnNewClient += OnNewClient;
86 } 85 }
87 } 86 }
88 87
89 public void PostInitialise() 88 public void RegionLoaded(Scene scene)
89 {
90 }
91
92 public void RemoveRegion(Scene scene)
90 { 93 {
91 if (!enabled) 94 if (!enabled)
92 return; 95 return;
93 96
94 if (m_SceneList.Count == 0) 97 lock (m_SceneList)
98 {
99 m_SceneList.Remove(scene);
100 }
101 }
102
103 public void PostInitialise()
104 {
105 if (!enabled)
95 return; 106 return;
96 107
97 m_log.Debug("[MUTE LIST] Mute list enabled"); 108 m_log.Debug("[MUTE LIST] Mute list enabled");
@@ -102,26 +113,15 @@ namespace OpenSim.Region.CoreModules.Avatar.MuteList
102 get { return "MuteListModule"; } 113 get { return "MuteListModule"; }
103 } 114 }
104 115
105 public bool IsSharedModule 116 public Type ReplaceableInterface
106 { 117 {
107 get { return true; } 118 get { return null; }
108 } 119 }
109 120
110 public void Close() 121 public void Close()
111 { 122 {
112 } 123 }
113 124
114// private IClientAPI FindClient(UUID agentID)
115// {
116// foreach (Scene s in m_SceneList)
117// {
118// ScenePresence presence = s.GetScenePresence(agentID);
119// if (presence != null && !presence.IsChildAgent)
120// return presence.ControllingClient;
121// }
122// return null;
123// }
124
125 private void OnNewClient(IClientAPI client) 125 private void OnNewClient(IClientAPI client)
126 { 126 {
127 client.OnMuteListRequest += OnMuteListRequest; 127 client.OnMuteListRequest += OnMuteListRequest;
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
index 0727fa9..9412735 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
@@ -40,82 +40,91 @@ using OpenSim.Region.Framework.Scenes;
40 40
41namespace OpenSim.Region.CoreModules.Avatar.InstantMessage 41namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
42{ 42{
43 public class OfflineMessageModule : IRegionModule 43 public class OfflineMessageModule : ISharedRegionModule
44 { 44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46 46
47 private bool enabled = true; 47 private bool enabled = true;
48 private List<Scene> m_SceneList = new List<Scene>(); 48 private List<Scene> m_SceneList = new List<Scene>();
49 private string m_RestURL = String.Empty; 49 private string m_RestURL = String.Empty;
50 IMessageTransferModule m_TransferModule = null;
50 private bool m_ForwardOfflineGroupMessages = true; 51 private bool m_ForwardOfflineGroupMessages = true;
51 52
52 public void Initialise(Scene scene, IConfigSource config) 53 public void Initialise(IConfigSource config)
53 { 54 {
54 if (!enabled)
55 return;
56
57 IConfig cnf = config.Configs["Messaging"]; 55 IConfig cnf = config.Configs["Messaging"];
58 if (cnf == null) 56 if (cnf == null)
59 { 57 {
60 enabled = false; 58 enabled = false;
61 return; 59 return;
62 } 60 }
63 if (cnf != null && cnf.GetString( 61 if (cnf != null && cnf.GetString("OfflineMessageModule", "None") !=
64 "OfflineMessageModule", "None") !=
65 "OfflineMessageModule") 62 "OfflineMessageModule")
66 { 63 {
67 enabled = false; 64 enabled = false;
68 return; 65 return;
69 } 66 }
70 67
71 if (cnf != null) 68 m_RestURL = cnf.GetString("OfflineMessageURL", "");
72 m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages); 69 if (m_RestURL == "")
70 {
71 m_log.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling");
72 enabled = false;
73 return;
74 }
75
76 m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages);
77 }
78
79 public void AddRegion(Scene scene)
80 {
81 if (!enabled)
82 return;
73 83
74 lock (m_SceneList) 84 lock (m_SceneList)
75 { 85 {
76 if (m_SceneList.Count == 0) 86 m_SceneList.Add(scene);
77 {
78 m_RestURL = cnf.GetString("OfflineMessageURL", "");
79 if (m_RestURL == "")
80 {
81 m_log.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling");
82 enabled = false;
83 return;
84 }
85 }
86 if (!m_SceneList.Contains(scene))
87 m_SceneList.Add(scene);
88 87
89 scene.EventManager.OnNewClient += OnNewClient; 88 scene.EventManager.OnNewClient += OnNewClient;
90 } 89 }
91 } 90 }
92 91
93 public void PostInitialise() 92 public void RegionLoaded(Scene scene)
94 { 93 {
95 if (!enabled) 94 if (!enabled)
96 return; 95 return;
97 96
98 if (m_SceneList.Count == 0) 97 if (m_TransferModule == null)
99 return;
100
101 IMessageTransferModule trans = m_SceneList[0].RequestModuleInterface<IMessageTransferModule>();
102 if (trans == null)
103 { 98 {
104 enabled = false; 99 m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
105 100 if (m_TransferModule == null)
106 lock (m_SceneList)
107 { 101 {
108 foreach (Scene s in m_SceneList) 102 scene.EventManager.OnNewClient -= OnNewClient;
109 s.EventManager.OnNewClient -= OnNewClient;
110 103
104 enabled = false;
111 m_SceneList.Clear(); 105 m_SceneList.Clear();
106
107 m_log.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages");
112 } 108 }
109 m_TransferModule.OnUndeliveredMessage += UndeliveredMessage;
110 }
111 }
113 112
114 m_log.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages"); 113 public void RemoveRegion(Scene scene)
114 {
115 if (!enabled)
115 return; 116 return;
117
118 lock (m_SceneList)
119 {
120 m_SceneList.Remove(scene);
116 } 121 }
122 }
117 123
118 trans.OnUndeliveredMessage += UndeliveredMessage; 124 public void PostInitialise()
125 {
126 if (!enabled)
127 return;
119 128
120 m_log.Debug("[OFFLINE MESSAGING] Offline messages enabled"); 129 m_log.Debug("[OFFLINE MESSAGING] Offline messages enabled");
121 } 130 }
@@ -125,9 +134,9 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
125 get { return "OfflineMessageModule"; } 134 get { return "OfflineMessageModule"; }
126 } 135 }
127 136
128 public bool IsSharedModule 137 public Type ReplaceableInterface
129 { 138 {
130 get { return true; } 139 get { return null; }
131 } 140 }
132 141
133 public void Close() 142 public void Close()
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs
index f5ab454..bafad82 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs
@@ -24,6 +24,7 @@
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27using System;
27using System.Collections; 28using System.Collections;
28using System.Collections.Generic; 29using System.Collections.Generic;
29using System.Net; 30using System.Net;
@@ -35,408 +36,123 @@ using OpenMetaverse;
35using OpenSim.Framework; 36using OpenSim.Framework;
36using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion; 40using GridRegion = OpenSim.Services.Interfaces.GridRegion;
41using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
39 42
40namespace OpenSim.Region.CoreModules.Avatar.InstantMessage 43namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
41{ 44{
42 public class PresenceModule : IRegionModule, IPresenceModule 45 public class PresenceModule : ISharedRegionModule, IPresenceModule
43 { 46 {
44 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 47 private static readonly ILog m_log = LogManager.GetLogger(
45 48 MethodBase.GetCurrentMethod().DeclaringType);
46 private bool m_Enabled = false;
47 private bool m_Gridmode = false;
48
49 // some default scene for doing things that aren't connected to a specific scene. Avoids locking.
50 private Scene m_initialScene;
51
52 private List<Scene> m_Scenes = new List<Scene>();
53
54 // we currently are only interested in root-agents. If the root isn't here, we don't know the region the
55 // user is in, so we have to ask the messaging server anyway.
56 private Dictionary<UUID, Scene> m_RootAgents =
57 new Dictionary<UUID, Scene>();
58 49
59 public event PresenceChange OnPresenceChange; 50 public event PresenceChange OnPresenceChange;
60 public event BulkPresenceData OnBulkPresenceData; 51 public event BulkPresenceData OnBulkPresenceData;
61 52
62 public void Initialise(Scene scene, IConfigSource config) 53 protected List<Scene> m_Scenes = new List<Scene>();
63 {
64 lock (m_Scenes)
65 {
66 // This is a shared module; Initialise will be called for every region on this server.
67 // Only check config once for the first region.
68 if (m_Scenes.Count == 0)
69 {
70 IConfig cnf = config.Configs["Messaging"];
71 if (cnf != null && cnf.GetString(
72 "PresenceModule", "PresenceModule") !=
73 "PresenceModule")
74 return;
75
76 cnf = config.Configs["Startup"];
77 if (cnf != null)
78 m_Gridmode = cnf.GetBoolean("gridmode", false);
79 54
80 m_Enabled = true; 55 protected IPresenceService m_PresenceService = null;
81 56
82 m_initialScene = scene; 57 protected IPresenceService PresenceService
83 }
84
85 if (m_Gridmode)
86 NotifyMessageServerOfStartup(scene);
87
88 m_Scenes.Add(scene);
89 }
90
91 scene.RegisterModuleInterface<IPresenceModule>(this);
92
93 scene.EventManager.OnNewClient += OnNewClient;
94 scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene;
95 scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
96 }
97
98 public void PostInitialise()
99 {
100 }
101
102 public void Close()
103 { 58 {
104 if (!m_Gridmode || !m_Enabled) 59 get
105 return;
106
107 if (OnPresenceChange != null)
108 { 60 {
109 lock (m_RootAgents) 61 if (m_PresenceService == null)
110 { 62 {
111 // on shutdown, users are kicked, too 63 if (m_Scenes.Count > 0)
112 foreach (KeyValuePair<UUID, Scene> pair in m_RootAgents) 64 m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
113 {
114 OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero));
115 }
116 } 65 }
117 }
118 66
119 lock (m_Scenes) 67 return m_PresenceService;
120 {
121 foreach (Scene scene in m_Scenes)
122 NotifyMessageServerOfShutdown(scene);
123 } 68 }
124 } 69 }
125 70
126 public string Name 71 public void Initialise(IConfigSource config)
127 {
128 get { return "PresenceModule"; }
129 }
130
131 public bool IsSharedModule
132 { 72 {
133 get { return true; }
134 } 73 }
135 74
136 public void RequestBulkPresenceData(UUID[] users) 75 public void AddRegion(Scene scene)
137 { 76 {
138 if (OnBulkPresenceData != null) 77 m_Scenes.Add(scene);
139 {
140 PresenceInfo[] result = new PresenceInfo[users.Length];
141 if (m_Gridmode)
142 {
143 // first check the local information
144 List<UUID> uuids = new List<UUID>(); // the uuids to check remotely
145 List<int> indices = new List<int>(); // just for performance.
146 lock (m_RootAgents)
147 {
148 for (int i = 0; i < uuids.Count; ++i)
149 {
150 Scene scene;
151 if (m_RootAgents.TryGetValue(users[i], out scene))
152 {
153 result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID);
154 }
155 else
156 {
157 uuids.Add(users[i]);
158 indices.Add(i);
159 }
160 }
161 }
162 78
163 // now we have filtered out all the local root agents. The rest we have to request info about 79 scene.EventManager.OnNewClient += OnNewClient;
164 Dictionary<UUID, FriendRegionInfo> infos = m_initialScene.GetFriendRegionInfos(uuids);
165 for (int i = 0; i < uuids.Count; ++i)
166 {
167 FriendRegionInfo info;
168 if (infos.TryGetValue(uuids[i], out info) && info.isOnline)
169 {
170 UUID regionID = info.regionID;
171 if (regionID == UUID.Zero)
172 {
173 // TODO this is the old messaging-server protocol; only the regionHandle is available.
174 // Fetch region-info to get the id
175 uint x = 0, y = 0;
176 Utils.LongToUInts(info.regionHandle, out x, out y);
177 GridRegion regionInfo = m_initialScene.GridService.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID,
178 (int)x, (int)y);
179 regionID = regionInfo.RegionID;
180 }
181 result[indices[i]] = new PresenceInfo(uuids[i], regionID);
182 }
183 else result[indices[i]] = new PresenceInfo(uuids[i], UUID.Zero);
184 }
185 }
186 else
187 {
188 // in standalone mode, we have all the info locally available.
189 lock (m_RootAgents)
190 {
191 for (int i = 0; i < users.Length; ++i)
192 {
193 Scene scene;
194 if (m_RootAgents.TryGetValue(users[i], out scene))
195 {
196 result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID);
197 }
198 else
199 {
200 result[i] = new PresenceInfo(users[i], UUID.Zero);
201 }
202 }
203 }
204 }
205 80
206 // tell everyone 81 scene.RegisterModuleInterface<IPresenceModule>(this);
207 OnBulkPresenceData(result);
208 }
209 } 82 }
210 83
211 // new client doesn't mean necessarily that user logged in, it just means it entered one of the 84 public void RegionLoaded(Scene scene)
212 // the regions on this server
213 public void OnNewClient(IClientAPI client)
214 { 85 {
215 client.OnConnectionClosed += OnConnectionClosed;
216 client.OnLogout += OnLogout;
217
218 // KLUDGE: See handler for details.
219 client.OnEconomyDataRequest += OnEconomyDataRequest;
220 } 86 }
221 87
222 // connection closed just means *one* client connection has been closed. It doesn't mean that the 88 public void RemoveRegion(Scene scene)
223 // user has logged off; it might have just TPed away.
224 public void OnConnectionClosed(IClientAPI client)
225 { 89 {
226 // TODO: Have to think what we have to do here... 90 m_Scenes.Remove(scene);
227 // Should we just remove the root from the list (if scene matches)?
228 if (!(client.Scene is Scene))
229 return;
230 Scene scene = (Scene)client.Scene;
231
232 lock (m_RootAgents)
233 {
234 Scene rootScene;
235 if (!(m_RootAgents.TryGetValue(client.AgentId, out rootScene)) || scene != rootScene)
236 return;
237
238 m_RootAgents.Remove(client.AgentId);
239 }
240
241 // Should it have logged off, we'll do the logout part in OnLogout, even if no root is stored
242 // anymore. It logged off, after all...
243 } 91 }
244 92
245 // Triggered when the user logs off. 93 public void PostInitialise()
246 public void OnLogout(IClientAPI client)
247 { 94 {
248 if (!(client.Scene is Scene))
249 return;
250 Scene scene = (Scene)client.Scene;
251
252 // On logout, we really remove the client from rootAgents, even if the scene doesn't match
253 lock (m_RootAgents)
254 {
255 if (m_RootAgents.ContainsKey(client.AgentId)) m_RootAgents.Remove(client.AgentId);
256 }
257
258 // now inform the messaging server and anyone who is interested
259 NotifyMessageServerOfAgentLeaving(client.AgentId, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
260 if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(client.AgentId, UUID.Zero));
261 } 95 }
262 96
263 public void OnSetRootAgentScene(UUID agentID, Scene scene) 97 public void Close()
264 { 98 {
265 // OnSetRootAgentScene can be called from several threads at once (with different agentID).
266 // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
267 // correct locking).
268 lock (m_RootAgents)
269 {
270 Scene rootScene;
271 if (m_RootAgents.TryGetValue(agentID, out rootScene) && scene == rootScene)
272 {
273 return;
274 }
275 m_RootAgents[agentID] = scene;
276 }
277
278 // inform messaging server that agent changed the region
279 Util.FireAndForget(
280 delegate(object o)
281 {
282 NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
283 }
284 );
285 } 99 }
286 100
287 private void OnEconomyDataRequest(UUID agentID) 101 public string Name
288 { 102 {
289 // KLUDGE: This is the only way I found to get a message (only) after login was completed and the 103 get { return "PresenceModule"; }
290 // client is connected enough to receive UDP packets.
291 // This packet seems to be sent only once, just after connection was established to the first
292 // region after login.
293 // We use it here to trigger a presence update; the old update-on-login was never be heard by
294 // the freshly logged in viewer, as it wasn't connected to the region at that time.
295 // TODO: Feel free to replace this by a better solution if you find one.
296
297 // get the agent. This should work every time, as we just got a packet from it
298 ScenePresence agent = null;
299 lock (m_Scenes)
300 {
301 foreach (Scene scene in m_Scenes)
302 {
303 agent = scene.GetScenePresence(agentID);
304 if (agent != null) break;
305 }
306 }
307
308 // just to be paranoid...
309 if (agent == null)
310 {
311 m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID);
312 return;
313 }
314
315 // we are a bit premature here, but the next packet will switch this child agent to root.
316 if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID));
317 } 104 }
318 105
319 public void OnMakeChildAgent(ScenePresence agent) 106 public Type ReplaceableInterface
320 { 107 {
321 // OnMakeChildAgent can be called from several threads at once (with different agent). 108 get { return null; }
322 // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
323 // correct locking).
324 lock (m_RootAgents)
325 {
326 Scene rootScene;
327 if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene)
328 {
329 m_RootAgents.Remove(agent.UUID);
330 }
331 }
332 // don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded
333 // to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment,
334 // which will update the messaging-server, too.
335 } 109 }
336 110
337 private void NotifyMessageServerOfStartup(Scene scene) 111 public void RequestBulkPresenceData(UUID[] users)
338 { 112 {
339 Hashtable xmlrpcdata = new Hashtable();
340 xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
341 ArrayList SendParams = new ArrayList();
342 SendParams.Add(xmlrpcdata);
343 try
344 {
345 XmlRpcRequest UpRequest = new XmlRpcRequest("region_startup", SendParams);
346 XmlRpcResponse resp = UpRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
347
348 Hashtable responseData = (Hashtable)resp.Value;
349 if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
350 {
351 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
352 }
353 }
354 catch (WebException)
355 {
356 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
357 }
358 } 113 }
359 114
360 private void NotifyMessageServerOfShutdown(Scene scene) 115 public void OnNewClient(IClientAPI client)
361 { 116 {
362 if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty) 117 client.AddGenericPacketHandler("requestonlinenotification", OnRequestOnlineNotification);
363 return;
364
365 Hashtable xmlrpcdata = new Hashtable();
366 xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
367 ArrayList SendParams = new ArrayList();
368 SendParams.Add(xmlrpcdata);
369 try
370 {
371 XmlRpcRequest DownRequest = new XmlRpcRequest("region_shutdown", SendParams);
372 XmlRpcResponse resp = DownRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
373
374 Hashtable responseData = (Hashtable)resp.Value;
375 if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
376 {
377 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
378 }
379 }
380 catch (WebException)
381 {
382 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
383 }
384 } 118 }
385 119
386 private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle) 120 public void OnRequestOnlineNotification(Object sender, string method, List<String> args)
387 { 121 {
388 if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty) 122 if (!(sender is IClientAPI))
389 return; 123 return;
390 124
391 Hashtable xmlrpcdata = new Hashtable(); 125 IClientAPI client = (IClientAPI)sender;
392 xmlrpcdata["AgentID"] = agentID.ToString(); 126 m_log.DebugFormat("[PRESENCE MODULE]: OnlineNotification requested by {0}", client.Name);
393 xmlrpcdata["RegionUUID"] = region.ToString();
394 xmlrpcdata["RegionHandle"] = regionHandle.ToString();
395 ArrayList SendParams = new ArrayList();
396 SendParams.Add(xmlrpcdata);
397 try
398 {
399 XmlRpcRequest LocationRequest = new XmlRpcRequest("agent_location", SendParams);
400 XmlRpcResponse resp = LocationRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000);
401 127
402 Hashtable responseData = (Hashtable)resp.Value; 128 PresenceInfo[] status = PresenceService.GetAgents(args.ToArray());
403 if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
404 {
405 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
406 }
407 }
408 catch (WebException)
409 {
410 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
411 }
412 }
413 129
414 private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle) 130 List<UUID> online = new List<UUID>();
415 { 131 List<UUID> offline = new List<UUID>();
416 if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty)
417 return;
418 132
419 Hashtable xmlrpcdata = new Hashtable(); 133 foreach (PresenceInfo pi in status)
420 xmlrpcdata["AgentID"] = agentID.ToString();
421 xmlrpcdata["RegionUUID"] = region.ToString();
422 xmlrpcdata["RegionHandle"] = regionHandle.ToString();
423 ArrayList SendParams = new ArrayList();
424 SendParams.Add(xmlrpcdata);
425 try
426 { 134 {
427 XmlRpcRequest LeavingRequest = new XmlRpcRequest("agent_leaving", SendParams); 135 UUID uuid = new UUID(pi.UserID);
428 XmlRpcResponse resp = LeavingRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000); 136 if (pi.Online)
429
430 Hashtable responseData = (Hashtable)resp.Value;
431 if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
432 { 137 {
433 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString()); 138 if (!online.Contains(uuid))
139 {
140 online.Add(uuid);
141 if (offline.Contains(uuid))
142 offline.Remove(uuid);
143 }
144 }
145 else
146 {
147 if (!online.Contains(uuid) && !offline.Contains(uuid))
148 offline.Add(uuid);
434 } 149 }
435 } 150 }
436 catch (WebException) 151
437 { 152 if (online.Count > 0)
438 m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString()); 153 client.SendAgentOnline(online.ToArray());
439 } 154 if (offline.Count > 0)
155 client.SendAgentOffline(offline.ToArray());
440 } 156 }
441 } 157 }
442} 158}
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs
index 160a9bd..dc7439c 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs
@@ -37,7 +37,7 @@ using log4net;
37using OpenMetaverse; 37using OpenMetaverse;
38using OpenSim.Framework; 38using OpenSim.Framework;
39using OpenSim.Framework.Communications; 39using OpenSim.Framework.Communications;
40using OpenSim.Framework.Communications.Cache; 40
41using OpenSim.Framework.Communications.Osp; 41using OpenSim.Framework.Communications.Osp;
42using OpenSim.Framework.Serialization; 42using OpenSim.Framework.Serialization;
43using OpenSim.Framework.Serialization.External; 43using OpenSim.Framework.Serialization.External;
@@ -53,7 +53,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
53 53
54 protected TarArchiveReader archive; 54 protected TarArchiveReader archive;
55 55
56 private CachedUserInfo m_userInfo; 56 private UserAccount m_userInfo;
57 private string m_invPath; 57 private string m_invPath;
58 58
59 /// <value> 59 /// <value>
@@ -67,7 +67,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
67 private Stream m_loadStream; 67 private Stream m_loadStream;
68 68
69 public InventoryArchiveReadRequest( 69 public InventoryArchiveReadRequest(
70 Scene scene, CachedUserInfo userInfo, string invPath, string loadPath) 70 Scene scene, UserAccount userInfo, string invPath, string loadPath)
71 : this( 71 : this(
72 scene, 72 scene,
73 userInfo, 73 userInfo,
@@ -77,7 +77,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
77 } 77 }
78 78
79 public InventoryArchiveReadRequest( 79 public InventoryArchiveReadRequest(
80 Scene scene, CachedUserInfo userInfo, string invPath, Stream loadStream) 80 Scene scene, UserAccount userInfo, string invPath, Stream loadStream)
81 { 81 {
82 m_scene = scene; 82 m_scene = scene;
83 m_userInfo = userInfo; 83 m_userInfo = userInfo;
@@ -103,7 +103,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
103 //InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); 103 //InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath);
104 InventoryFolderBase rootDestinationFolder 104 InventoryFolderBase rootDestinationFolder
105 = InventoryArchiveUtils.FindFolderByPath( 105 = InventoryArchiveUtils.FindFolderByPath(
106 m_scene.InventoryService, m_userInfo.UserProfile.ID, m_invPath); 106 m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath);
107 107
108 if (null == rootDestinationFolder) 108 if (null == rootDestinationFolder)
109 { 109 {
@@ -280,7 +280,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
280 // even though there is a AssetType.RootCategory 280 // even though there is a AssetType.RootCategory
281 destFolder 281 destFolder
282 = new InventoryFolderBase( 282 = new InventoryFolderBase(
283 newFolderId, newFolderName, m_userInfo.UserProfile.ID, 283 newFolderId, newFolderName, m_userInfo.PrincipalID,
284 (short)AssetType.Unknown, destFolder.ID, 1); 284 (short)AssetType.Unknown, destFolder.ID, 1);
285 m_scene.InventoryService.AddFolder(destFolder); 285 m_scene.InventoryService.AddFolder(destFolder);
286 286
@@ -357,7 +357,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
357 // Don't use the item ID that's in the file 357 // Don't use the item ID that's in the file
358 item.ID = UUID.Random(); 358 item.ID = UUID.Random();
359 359
360 UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.CommsManager); 360 UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService);
361 if (UUID.Zero != ospResolvedId) 361 if (UUID.Zero != ospResolvedId)
362 { 362 {
363 item.CreatorIdAsUuid = ospResolvedId; 363 item.CreatorIdAsUuid = ospResolvedId;
@@ -368,10 +368,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
368 } 368 }
369 else 369 else
370 { 370 {
371 item.CreatorIdAsUuid = m_userInfo.UserProfile.ID; 371 item.CreatorIdAsUuid = m_userInfo.PrincipalID;
372 } 372 }
373 373
374 item.Owner = m_userInfo.UserProfile.ID; 374 item.Owner = m_userInfo.PrincipalID;
375 375
376 // Reset folder ID to the one in which we want to load it 376 // Reset folder ID to the one in which we want to load it
377 item.Folder = loadFolder.ID; 377 item.Folder = loadFolder.ID;
@@ -416,7 +416,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
416 416
417 //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); 417 //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
418 418
419 AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType); 419 AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType, UUID.Zero.ToString());
420 asset.Data = data; 420 asset.Data = data;
421 421
422 m_scene.AssetService.Store(asset); 422 m_scene.AssetService.Store(asset);
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
index 98b686e..cfe3caa 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
@@ -37,10 +37,11 @@ using OpenSim.Framework;
37using OpenSim.Framework.Serialization; 37using OpenSim.Framework.Serialization;
38using OpenSim.Framework.Serialization.External; 38using OpenSim.Framework.Serialization.External;
39using OpenSim.Framework.Communications; 39using OpenSim.Framework.Communications;
40using OpenSim.Framework.Communications.Cache; 40
41using OpenSim.Framework.Communications.Osp; 41using OpenSim.Framework.Communications.Osp;
42using OpenSim.Region.CoreModules.World.Archiver; 42using OpenSim.Region.CoreModules.World.Archiver;
43using OpenSim.Region.Framework.Scenes; 43using OpenSim.Region.Framework.Scenes;
44using OpenSim.Services.Interfaces;
44 45
45namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver 46namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
46{ 47{
@@ -54,7 +55,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
54 private const string STAR_WILDCARD = "*"; 55 private const string STAR_WILDCARD = "*";
55 56
56 private InventoryArchiverModule m_module; 57 private InventoryArchiverModule m_module;
57 private CachedUserInfo m_userInfo; 58 private UserAccount m_userInfo;
58 private string m_invPath; 59 private string m_invPath;
59 protected TarArchiveWriter m_archiveWriter; 60 protected TarArchiveWriter m_archiveWriter;
60 protected UuidGatherer m_assetGatherer; 61 protected UuidGatherer m_assetGatherer;
@@ -72,7 +73,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
72 /// <value> 73 /// <value>
73 /// Used to collect the uuids of the assets that we need to save into the archive 74 /// Used to collect the uuids of the assets that we need to save into the archive
74 /// </value> 75 /// </value>
75 protected Dictionary<UUID, int> m_assetUuids = new Dictionary<UUID, int>(); 76 protected Dictionary<UUID, AssetType> m_assetUuids = new Dictionary<UUID, AssetType>();
76 77
77 /// <value> 78 /// <value>
78 /// Used to collect the uuids of the users that we need to save into the archive 79 /// Used to collect the uuids of the users that we need to save into the archive
@@ -89,7 +90,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
89 /// </summary> 90 /// </summary>
90 public InventoryArchiveWriteRequest( 91 public InventoryArchiveWriteRequest(
91 Guid id, InventoryArchiverModule module, Scene scene, 92 Guid id, InventoryArchiverModule module, Scene scene,
92 CachedUserInfo userInfo, string invPath, string savePath) 93 UserAccount userInfo, string invPath, string savePath)
93 : this( 94 : this(
94 id, 95 id,
95 module, 96 module,
@@ -105,7 +106,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
105 /// </summary> 106 /// </summary>
106 public InventoryArchiveWriteRequest( 107 public InventoryArchiveWriteRequest(
107 Guid id, InventoryArchiverModule module, Scene scene, 108 Guid id, InventoryArchiverModule module, Scene scene,
108 CachedUserInfo userInfo, string invPath, Stream saveStream) 109 UserAccount userInfo, string invPath, Stream saveStream)
109 { 110 {
110 m_id = id; 111 m_id = id;
111 m_module = module; 112 m_module = module;
@@ -148,7 +149,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
148 m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; 149 m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;
149 150
150 InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone(); 151 InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone();
151 saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_scene.CommsManager); 152 saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_scene.UserAccountService);
152 153
153 string serialization = UserInventoryItemSerializer.Serialize(saveItem); 154 string serialization = UserInventoryItemSerializer.Serialize(saveItem);
154 m_archiveWriter.WriteFile(filename, serialization); 155 m_archiveWriter.WriteFile(filename, serialization);
@@ -215,7 +216,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
215 { 216 {
216 InventoryFolderBase inventoryFolder = null; 217 InventoryFolderBase inventoryFolder = null;
217 InventoryItemBase inventoryItem = null; 218 InventoryItemBase inventoryItem = null;
218 InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.UserProfile.ID); 219 InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID);
219 220
220 bool foundStar = false; 221 bool foundStar = false;
221 222
@@ -304,7 +305,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
304 } 305 }
305 306
306 new AssetsRequest( 307 new AssetsRequest(
307 new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys, 308 new AssetsArchiver(m_archiveWriter), m_assetUuids,
308 m_scene.AssetService, ReceivedAllAssets).Execute(); 309 m_scene.AssetService, ReceivedAllAssets).Execute();
309 } 310 }
310 311
@@ -318,14 +319,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
318 foreach (UUID creatorId in m_userUuids.Keys) 319 foreach (UUID creatorId in m_userUuids.Keys)
319 { 320 {
320 // Record the creator of this item 321 // Record the creator of this item
321 CachedUserInfo creator 322 UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId);
322 = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(creatorId);
323 323
324 if (creator != null) 324 if (creator != null)
325 { 325 {
326 m_archiveWriter.WriteFile( 326 m_archiveWriter.WriteFile(
327 ArchiveConstants.USERS_PATH + creator.UserProfile.Name + ".xml", 327 ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml",
328 UserProfileSerializer.Serialize(creator.UserProfile)); 328 UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName));
329 } 329 }
330 else 330 else
331 { 331 {
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
index a898992..f570999 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
@@ -34,7 +34,7 @@ using Nini.Config;
34using OpenMetaverse; 34using OpenMetaverse;
35using OpenSim.Framework; 35using OpenSim.Framework;
36using OpenSim.Framework.Communications; 36using OpenSim.Framework.Communications;
37using OpenSim.Framework.Communications.Cache; 37
38using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
40using OpenSim.Services.Interfaces; 40using OpenSim.Services.Interfaces;
@@ -113,7 +113,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
113 /// Trigger the inventory archive saved event. 113 /// Trigger the inventory archive saved event.
114 /// </summary> 114 /// </summary>
115 protected internal void TriggerInventoryArchiveSaved( 115 protected internal void TriggerInventoryArchiveSaved(
116 Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, 116 Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
117 Exception reportedException) 117 Exception reportedException)
118 { 118 {
119 InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; 119 InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
@@ -125,11 +125,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
125 { 125 {
126 if (m_scenes.Count > 0) 126 if (m_scenes.Count > 0)
127 { 127 {
128 CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass); 128 UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
129 129
130 if (userInfo != null) 130 if (userInfo != null)
131 { 131 {
132 if (CheckPresence(userInfo.UserProfile.ID)) 132 if (CheckPresence(userInfo.PrincipalID))
133 { 133 {
134 try 134 try
135 { 135 {
@@ -150,8 +150,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
150 else 150 else
151 { 151 {
152 m_log.ErrorFormat( 152 m_log.ErrorFormat(
153 "[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator", 153 "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
154 userInfo.UserProfile.Name, userInfo.UserProfile.ID); 154 userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
155 } 155 }
156 } 156 }
157 } 157 }
@@ -163,11 +163,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
163 { 163 {
164 if (m_scenes.Count > 0) 164 if (m_scenes.Count > 0)
165 { 165 {
166 CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass); 166 UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
167 167
168 if (userInfo != null) 168 if (userInfo != null)
169 { 169 {
170 if (CheckPresence(userInfo.UserProfile.ID)) 170 if (CheckPresence(userInfo.PrincipalID))
171 { 171 {
172 try 172 try
173 { 173 {
@@ -188,8 +188,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
188 else 188 else
189 { 189 {
190 m_log.ErrorFormat( 190 m_log.ErrorFormat(
191 "[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator", 191 "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
192 userInfo.UserProfile.Name, userInfo.UserProfile.ID); 192 userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
193 } 193 }
194 } 194 }
195 } 195 }
@@ -201,11 +201,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
201 { 201 {
202 if (m_scenes.Count > 0) 202 if (m_scenes.Count > 0)
203 { 203 {
204 CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass); 204 UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
205 205
206 if (userInfo != null) 206 if (userInfo != null)
207 { 207 {
208 if (CheckPresence(userInfo.UserProfile.ID)) 208 if (CheckPresence(userInfo.PrincipalID))
209 { 209 {
210 InventoryArchiveReadRequest request; 210 InventoryArchiveReadRequest request;
211 211
@@ -230,8 +230,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
230 else 230 else
231 { 231 {
232 m_log.ErrorFormat( 232 m_log.ErrorFormat(
233 "[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator", 233 "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
234 userInfo.UserProfile.Name, userInfo.UserProfile.ID); 234 userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
235 } 235 }
236 } 236 }
237 } 237 }
@@ -243,11 +243,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
243 { 243 {
244 if (m_scenes.Count > 0) 244 if (m_scenes.Count > 0)
245 { 245 {
246 CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass); 246 UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
247 247
248 if (userInfo != null) 248 if (userInfo != null)
249 { 249 {
250 if (CheckPresence(userInfo.UserProfile.ID)) 250 if (CheckPresence(userInfo.PrincipalID))
251 { 251 {
252 InventoryArchiveReadRequest request; 252 InventoryArchiveReadRequest request;
253 253
@@ -272,8 +272,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
272 else 272 else
273 { 273 {
274 m_log.ErrorFormat( 274 m_log.ErrorFormat(
275 "[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator", 275 "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
276 userInfo.UserProfile.Name, userInfo.UserProfile.ID); 276 userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
277 } 277 }
278 } 278 }
279 } 279 }
@@ -345,7 +345,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
345 } 345 }
346 346
347 private void SaveInvConsoleCommandCompleted( 347 private void SaveInvConsoleCommandCompleted(
348 Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, 348 Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
349 Exception reportedException) 349 Exception reportedException)
350 { 350 {
351 lock (m_pendingConsoleSaves) 351 lock (m_pendingConsoleSaves)
@@ -358,13 +358,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
358 358
359 if (succeeded) 359 if (succeeded)
360 { 360 {
361 m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0}", userInfo.UserProfile.Name); 361 m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName);
362 } 362 }
363 else 363 else
364 { 364 {
365 m_log.ErrorFormat( 365 m_log.ErrorFormat(
366 "[INVENTORY ARCHIVER]: Archive save for {0} failed - {1}", 366 "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
367 userInfo.UserProfile.Name, reportedException.Message); 367 userInfo.FirstName, userInfo.LastName, reportedException.Message);
368 } 368 }
369 } 369 }
370 370
@@ -375,11 +375,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
375 /// <param name="lastName"></param> 375 /// <param name="lastName"></param>
376 /// <param name="pass">User password</param> 376 /// <param name="pass">User password</param>
377 /// <returns></returns> 377 /// <returns></returns>
378 protected CachedUserInfo GetUserInfo(string firstName, string lastName, string pass) 378 protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
379 { 379 {
380 CachedUserInfo userInfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(firstName, lastName); 380 UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
381 //m_aScene.CommsManager.UserService.GetUserProfile(firstName, lastName); 381 if (null == account)
382 if (null == userInfo)
383 { 382 {
384 m_log.ErrorFormat( 383 m_log.ErrorFormat(
385 "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", 384 "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
@@ -389,9 +388,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
389 388
390 try 389 try
391 { 390 {
392 if (m_aScene.CommsManager.UserService.AuthenticateUserByPassword(userInfo.UserProfile.ID, pass)) 391 string encpass = Util.Md5Hash(pass);
392 if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
393 { 393 {
394 return userInfo; 394 return account;
395 } 395 }
396 else 396 else
397 { 397 {
@@ -412,14 +412,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
412 /// Notify the client of loaded nodes if they are logged in 412 /// Notify the client of loaded nodes if they are logged in
413 /// </summary> 413 /// </summary>
414 /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param> 414 /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
415 private void UpdateClientWithLoadedNodes(CachedUserInfo userInfo, List<InventoryNodeBase> loadedNodes) 415 private void UpdateClientWithLoadedNodes(UserAccount userInfo, List<InventoryNodeBase> loadedNodes)
416 { 416 {
417 if (loadedNodes.Count == 0) 417 if (loadedNodes.Count == 0)
418 return; 418 return;
419 419
420 foreach (Scene scene in m_scenes.Values) 420 foreach (Scene scene in m_scenes.Values)
421 { 421 {
422 ScenePresence user = scene.GetScenePresence(userInfo.UserProfile.ID); 422 ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);
423 423
424 if (user != null && !user.IsChildAgent) 424 if (user != null && !user.IsChildAgent)
425 { 425 {
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs
index e4dad18..9c95e78 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs
@@ -38,7 +38,7 @@ using OpenSim.Framework;
38using OpenSim.Framework.Serialization; 38using OpenSim.Framework.Serialization;
39using OpenSim.Framework.Serialization.External; 39using OpenSim.Framework.Serialization.External;
40using OpenSim.Framework.Communications; 40using OpenSim.Framework.Communications;
41using OpenSim.Framework.Communications.Cache; 41
42using OpenSim.Framework.Communications.Osp; 42using OpenSim.Framework.Communications.Osp;
43using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; 43using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver;
44using OpenSim.Region.CoreModules.World.Serialiser; 44using OpenSim.Region.CoreModules.World.Serialiser;
@@ -65,7 +65,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
65 } 65 }
66 66
67 private void SaveCompleted( 67 private void SaveCompleted(
68 Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, 68 Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
69 Exception reportedException) 69 Exception reportedException)
70 { 70 {
71 mre.Set(); 71 mre.Set();
@@ -76,124 +76,126 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
76 /// </summary> 76 /// </summary>
77 // Commenting for now! The mock inventory service needs more beef, at least for 77 // Commenting for now! The mock inventory service needs more beef, at least for
78 // GetFolderForType 78 // GetFolderForType
79 [Test] 79 // REFACTORING PROBLEM. This needs to be rewritten.
80 public void TestSaveIarV0_1() 80
81 { 81// [Test]
82 TestHelper.InMethod(); 82// public void TestSaveIarV0_1()
83 //log4net.Config.XmlConfigurator.Configure(); 83// {
84 84// TestHelper.InMethod();
85 InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); 85// //log4net.Config.XmlConfigurator.Configure();
86 86
87 Scene scene = SceneSetupHelpers.SetupScene("Inventory"); 87// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
88 SceneSetupHelpers.SetupSceneModules(scene, archiverModule); 88
89 CommunicationsManager cm = scene.CommsManager; 89// Scene scene = SceneSetupHelpers.SetupScene("Inventory");
90 90// SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
91 // Create user 91// CommunicationsManager cm = scene.CommsManager;
92 string userFirstName = "Jock"; 92
93 string userLastName = "Stirrup"; 93// // Create user
94 UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); 94// string userFirstName = "Jock";
95 95// string userLastName = "Stirrup";
96 lock (this) 96// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
97 { 97
98 UserProfileTestUtils.CreateUserWithInventory( 98// lock (this)
99 cm, userFirstName, userLastName, userId, InventoryReceived); 99// {
100 Monitor.Wait(this, 60000); 100// UserProfileTestUtils.CreateUserWithInventory(
101 } 101// cm, userFirstName, userLastName, userId, InventoryReceived);
102 102// Monitor.Wait(this, 60000);
103 // Create asset 103// }
104 SceneObjectGroup object1; 104
105 SceneObjectPart part1; 105// // Create asset
106 { 106// SceneObjectGroup object1;
107 string partName = "My Little Dog Object"; 107// SceneObjectPart part1;
108 UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); 108// {
109 PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); 109// string partName = "My Little Dog Object";
110 Vector3 groupPosition = new Vector3(10, 20, 30); 110// UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
111 Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); 111// PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
112 Vector3 offsetPosition = new Vector3(5, 10, 15); 112// Vector3 groupPosition = new Vector3(10, 20, 30);
113 113// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
114 part1 114// Vector3 offsetPosition = new Vector3(5, 10, 15);
115 = new SceneObjectPart( 115
116 ownerId, shape, groupPosition, rotationOffset, offsetPosition); 116// part1
117 part1.Name = partName; 117// = new SceneObjectPart(
118 118// ownerId, shape, groupPosition, rotationOffset, offsetPosition);
119 object1 = new SceneObjectGroup(part1); 119// part1.Name = partName;
120 scene.AddNewSceneObject(object1, false); 120
121 } 121// object1 = new SceneObjectGroup(part1);
122 122// scene.AddNewSceneObject(object1, false);
123 UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); 123// }
124 AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); 124
125 scene.AssetService.Store(asset1); 125// UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
126 126// AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
127 // Create item 127// scene.AssetService.Store(asset1);
128 UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); 128
129 InventoryItemBase item1 = new InventoryItemBase(); 129// // Create item
130 item1.Name = "My Little Dog"; 130// UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
131 item1.AssetID = asset1.FullID; 131// InventoryItemBase item1 = new InventoryItemBase();
132 item1.ID = item1Id; 132// item1.Name = "My Little Dog";
133 InventoryFolderBase objsFolder 133// item1.AssetID = asset1.FullID;
134 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); 134// item1.ID = item1Id;
135 item1.Folder = objsFolder.ID; 135// InventoryFolderBase objsFolder
136 scene.AddInventoryItem(userId, item1); 136// = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
137 137// item1.Folder = objsFolder.ID;
138 MemoryStream archiveWriteStream = new MemoryStream(); 138// scene.AddInventoryItem(userId, item1);
139 archiverModule.OnInventoryArchiveSaved += SaveCompleted; 139
140 140// MemoryStream archiveWriteStream = new MemoryStream();
141 mre.Reset(); 141// archiverModule.OnInventoryArchiveSaved += SaveCompleted;
142 archiverModule.ArchiveInventory( 142
143 Guid.NewGuid(), userFirstName, userLastName, "Objects", "troll", archiveWriteStream); 143// mre.Reset();
144 mre.WaitOne(60000, false); 144// archiverModule.ArchiveInventory(
145 145// Guid.NewGuid(), userFirstName, userLastName, "Objects", "troll", archiveWriteStream);
146 byte[] archive = archiveWriteStream.ToArray(); 146// mre.WaitOne(60000, false);
147 MemoryStream archiveReadStream = new MemoryStream(archive); 147
148 TarArchiveReader tar = new TarArchiveReader(archiveReadStream); 148// byte[] archive = archiveWriteStream.ToArray();
149 149// MemoryStream archiveReadStream = new MemoryStream(archive);
150 //bool gotControlFile = false; 150// TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
151 bool gotObject1File = false; 151
152 //bool gotObject2File = false; 152// //bool gotControlFile = false;
153 string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); 153// bool gotObject1File = false;
154 string expectedObject1FilePath = string.Format( 154// //bool gotObject2File = false;
155 "{0}{1}{2}", 155// string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1);
156 ArchiveConstants.INVENTORY_PATH, 156// string expectedObject1FilePath = string.Format(
157 InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), 157// "{0}{1}{2}",
158 expectedObject1FileName); 158// ArchiveConstants.INVENTORY_PATH,
159 159// InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder),
160 string filePath; 160// expectedObject1FileName);
161 TarArchiveReader.TarEntryType tarEntryType; 161
162 162// string filePath;
163 Console.WriteLine("Reading archive"); 163// TarArchiveReader.TarEntryType tarEntryType;
164 164
165 while (tar.ReadEntry(out filePath, out tarEntryType) != null) 165// Console.WriteLine("Reading archive");
166 { 166
167 Console.WriteLine("Got {0}", filePath); 167// while (tar.ReadEntry(out filePath, out tarEntryType) != null)
168 168// {
169// if (ArchiveConstants.CONTROL_FILE_PATH == filePath) 169// Console.WriteLine("Got {0}", filePath);
170
171//// if (ArchiveConstants.CONTROL_FILE_PATH == filePath)
172//// {
173//// gotControlFile = true;
174//// }
175
176// if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml"))
170// { 177// {
171// gotControlFile = true; 178//// string fileName = filePath.Remove(0, "Objects/".Length);
179////
180//// if (fileName.StartsWith(part1.Name))
181//// {
182// Assert.That(expectedObject1FilePath, Is.EqualTo(filePath));
183// gotObject1File = true;
184//// }
185//// else if (fileName.StartsWith(part2.Name))
186//// {
187//// Assert.That(fileName, Is.EqualTo(expectedObject2FileName));
188//// gotObject2File = true;
189//// }
172// } 190// }
173 191// }
174 if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml"))
175 {
176// string fileName = filePath.Remove(0, "Objects/".Length);
177//
178// if (fileName.StartsWith(part1.Name))
179// {
180 Assert.That(expectedObject1FilePath, Is.EqualTo(filePath));
181 gotObject1File = true;
182// }
183// else if (fileName.StartsWith(part2.Name))
184// {
185// Assert.That(fileName, Is.EqualTo(expectedObject2FileName));
186// gotObject2File = true;
187// }
188 }
189 }
190 192
191// Assert.That(gotControlFile, Is.True, "No control file in archive"); 193//// Assert.That(gotControlFile, Is.True, "No control file in archive");
192 Assert.That(gotObject1File, Is.True, "No item1 file in archive"); 194// Assert.That(gotObject1File, Is.True, "No item1 file in archive");
193// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); 195//// Assert.That(gotObject2File, Is.True, "No object2 file in archive");
194 196
195 // TODO: Test presence of more files and contents of files. 197// // TODO: Test presence of more files and contents of files.
196 } 198// }
197 199
198 /// <summary> 200 /// <summary>
199 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where 201 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
@@ -201,187 +203,189 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
201 /// </summary> 203 /// </summary>
202 /// 204 ///
203 /// This test also does some deeper probing of loading into nested inventory structures 205 /// This test also does some deeper probing of loading into nested inventory structures
204 [Test] 206 /// REFACTORING PROBLEM. This needs to be rewritten.
205 public void TestLoadIarV0_1ExistingUsers() 207// [Test]
206 { 208// public void TestLoadIarV0_1ExistingUsers()
207 TestHelper.InMethod(); 209// {
208 210// TestHelper.InMethod();
209 //log4net.Config.XmlConfigurator.Configure(); 211
210 212// //log4net.Config.XmlConfigurator.Configure();
211 string userFirstName = "Mr"; 213
212 string userLastName = "Tiddles"; 214// string userFirstName = "Mr";
213 UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555"); 215// string userLastName = "Tiddles";
214 string userItemCreatorFirstName = "Lord"; 216// UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555");
215 string userItemCreatorLastName = "Lucan"; 217// string userItemCreatorFirstName = "Lord";
216 UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); 218// string userItemCreatorLastName = "Lucan";
217 219// UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
218 string item1Name = "b.lsl"; 220
219 string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random()); 221// string item1Name = "b.lsl";
220 222// string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random());
221 MemoryStream archiveWriteStream = new MemoryStream(); 223
222 TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); 224// MemoryStream archiveWriteStream = new MemoryStream();
223 225// TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
224 InventoryItemBase item1 = new InventoryItemBase(); 226
225 item1.Name = item1Name; 227// InventoryItemBase item1 = new InventoryItemBase();
226 item1.AssetID = UUID.Random(); 228// item1.Name = item1Name;
227 item1.GroupID = UUID.Random(); 229// item1.AssetID = UUID.Random();
228 item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); 230// item1.GroupID = UUID.Random();
229 //item1.CreatorId = userUuid.ToString(); 231// item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
230 //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; 232// //item1.CreatorId = userUuid.ToString();
231 item1.Owner = UUID.Zero; 233// //item1.CreatorId = "00000000-0000-0000-0000-000000000444";
232 234// item1.Owner = UUID.Zero;
233 string item1FileName 235
234 = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); 236// string item1FileName
235 tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); 237// = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
236 tar.Close(); 238// tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
237 239// tar.Close();
238 MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); 240
239 SerialiserModule serialiserModule = new SerialiserModule(); 241// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
240 InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); 242// SerialiserModule serialiserModule = new SerialiserModule();
241 243// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
242 // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene 244
243 Scene scene = SceneSetupHelpers.SetupScene("inventory"); 245// // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
244 IUserAdminService userAdminService = scene.CommsManager.UserAdminService; 246// Scene scene = SceneSetupHelpers.SetupScene("inventory");
245 247// IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
246 SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); 248
247 userAdminService.AddUser( 249// SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
248 userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); 250// userAdminService.AddUser(
249 userAdminService.AddUser( 251// userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
250 userItemCreatorFirstName, userItemCreatorLastName, "hampshire", 252// userAdminService.AddUser(
251 String.Empty, 1000, 1000, userItemCreatorUuid); 253// userItemCreatorFirstName, userItemCreatorLastName, "hampshire",
252 254// String.Empty, 1000, 1000, userItemCreatorUuid);
253 archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); 255
254 256// archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
255 CachedUserInfo userInfo 257
256 = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); 258// CachedUserInfo userInfo
257 259// = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
258 InventoryItemBase foundItem1 260
259 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, item1Name); 261// InventoryItemBase foundItem1
260 262// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, item1Name);
261 Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); 263
262 264// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
263// We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the 265
264// UUID, not the OSPA itself. 266//// We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the
267//// UUID, not the OSPA itself.
268//// Assert.That(
269//// foundItem1.CreatorId, Is.EqualTo(item1.CreatorId),
270//// "Loaded item non-uuid creator doesn't match original");
265// Assert.That( 271// Assert.That(
266// foundItem1.CreatorId, Is.EqualTo(item1.CreatorId), 272// foundItem1.CreatorId, Is.EqualTo(userItemCreatorUuid.ToString()),
267// "Loaded item non-uuid creator doesn't match original"); 273// "Loaded item non-uuid creator doesn't match original");
268 Assert.That(
269 foundItem1.CreatorId, Is.EqualTo(userItemCreatorUuid.ToString()),
270 "Loaded item non-uuid creator doesn't match original");
271
272 Assert.That(
273 foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid),
274 "Loaded item uuid creator doesn't match original");
275 Assert.That(foundItem1.Owner, Is.EqualTo(userUuid),
276 "Loaded item owner doesn't match inventory reciever");
277
278 // Now try loading to a root child folder
279 UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xA");
280 archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
281 archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
282
283 InventoryItemBase foundItem2
284 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + item1Name);
285 Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
286
287 // Now try loading to a more deeply nested folder
288 UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC");
289 archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
290 archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
291
292 InventoryItemBase foundItem3
293 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + item1Name);
294 Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
295 }
296
297 [Test]
298 public void TestIarV0_1WithEscapedChars()
299 {
300 TestHelper.InMethod();
301// log4net.Config.XmlConfigurator.Configure();
302
303 string itemName = "You & you are a mean/man/";
304 string humanEscapedItemName = @"You & you are a mean\/man\/";
305 string userPassword = "meowfood";
306
307 InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
308
309 Scene scene = SceneSetupHelpers.SetupScene("Inventory");
310 SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
311 CommunicationsManager cm = scene.CommsManager;
312
313 // Create user
314 string userFirstName = "Jock";
315 string userLastName = "Stirrup";
316 UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
317
318 lock (this)
319 {
320 UserProfileTestUtils.CreateUserWithInventory(
321 cm, userFirstName, userLastName, userPassword, userId, InventoryReceived);
322 Monitor.Wait(this, 60000);
323 }
324
325 // Create asset
326 SceneObjectGroup object1;
327 SceneObjectPart part1;
328 {
329 string partName = "part name";
330 UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
331 PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
332 Vector3 groupPosition = new Vector3(10, 20, 30);
333 Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
334 Vector3 offsetPosition = new Vector3(5, 10, 15);
335
336 part1
337 = new SceneObjectPart(
338 ownerId, shape, groupPosition, rotationOffset, offsetPosition);
339 part1.Name = partName;
340
341 object1 = new SceneObjectGroup(part1);
342 scene.AddNewSceneObject(object1, false);
343 }
344
345 UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
346 AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
347 scene.AssetService.Store(asset1);
348
349 // Create item
350 UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
351 InventoryItemBase item1 = new InventoryItemBase();
352 item1.Name = itemName;
353 item1.AssetID = asset1.FullID;
354 item1.ID = item1Id;
355 InventoryFolderBase objsFolder
356 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
357 item1.Folder = objsFolder.ID;
358 scene.AddInventoryItem(userId, item1);
359
360 MemoryStream archiveWriteStream = new MemoryStream();
361 archiverModule.OnInventoryArchiveSaved += SaveCompleted;
362
363 mre.Reset();
364 archiverModule.ArchiveInventory(
365 Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
366 mre.WaitOne(60000, false);
367
368 // LOAD ITEM
369 MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
370
371 archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);
372
373 InventoryItemBase foundItem1
374 = InventoryArchiveUtils.FindItemByPath(
375 scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);
376 274
377 Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
378// Assert.That( 275// Assert.That(
379// foundItem1.CreatorId, Is.EqualTo(userUuid), 276// foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid),
380// "Loaded item non-uuid creator doesn't match that of the loading user"); 277// "Loaded item uuid creator doesn't match original");
381 Assert.That( 278// Assert.That(foundItem1.Owner, Is.EqualTo(userUuid),
382 foundItem1.Name, Is.EqualTo(itemName), 279// "Loaded item owner doesn't match inventory reciever");
383 "Loaded item name doesn't match saved name"); 280
384 } 281// // Now try loading to a root child folder
282// UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xA");
283// archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
284// archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
285
286// InventoryItemBase foundItem2
287// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + item1Name);
288// Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
289
290// // Now try loading to a more deeply nested folder
291// UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC");
292// archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
293// archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
294
295// InventoryItemBase foundItem3
296// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + item1Name);
297// Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
298 //}
299
300 // REFACTORING PROBLEM. Needs rewrite.
301// [Test]
302// public void TestIarV0_1WithEscapedChars()
303// {
304// TestHelper.InMethod();
305//// log4net.Config.XmlConfigurator.Configure();
306
307// string itemName = "You & you are a mean/man/";
308// string humanEscapedItemName = @"You & you are a mean\/man\/";
309// string userPassword = "meowfood";
310
311// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
312
313// Scene scene = SceneSetupHelpers.SetupScene("Inventory");
314// SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
315// CommunicationsManager cm = scene.CommsManager;
316
317// // Create user
318// string userFirstName = "Jock";
319// string userLastName = "Stirrup";
320// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
321
322// lock (this)
323// {
324// UserProfileTestUtils.CreateUserWithInventory(
325// cm, userFirstName, userLastName, userPassword, userId, InventoryReceived);
326// Monitor.Wait(this, 60000);
327// }
328
329// // Create asset
330// SceneObjectGroup object1;
331// SceneObjectPart part1;
332// {
333// string partName = "part name";
334// UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
335// PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
336// Vector3 groupPosition = new Vector3(10, 20, 30);
337// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
338// Vector3 offsetPosition = new Vector3(5, 10, 15);
339
340// part1
341// = new SceneObjectPart(
342// ownerId, shape, groupPosition, rotationOffset, offsetPosition);
343// part1.Name = partName;
344
345// object1 = new SceneObjectGroup(part1);
346// scene.AddNewSceneObject(object1, false);
347// }
348
349// UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
350// AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
351// scene.AssetService.Store(asset1);
352
353// // Create item
354// UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
355// InventoryItemBase item1 = new InventoryItemBase();
356// item1.Name = itemName;
357// item1.AssetID = asset1.FullID;
358// item1.ID = item1Id;
359// InventoryFolderBase objsFolder
360// = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
361// item1.Folder = objsFolder.ID;
362// scene.AddInventoryItem(userId, item1);
363
364// MemoryStream archiveWriteStream = new MemoryStream();
365// archiverModule.OnInventoryArchiveSaved += SaveCompleted;
366
367// mre.Reset();
368// archiverModule.ArchiveInventory(
369// Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
370// mre.WaitOne(60000, false);
371
372// // LOAD ITEM
373// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
374
375// archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);
376
377// InventoryItemBase foundItem1
378// = InventoryArchiveUtils.FindItemByPath(
379// scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);
380
381// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
382//// Assert.That(
383//// foundItem1.CreatorId, Is.EqualTo(userUuid),
384//// "Loaded item non-uuid creator doesn't match that of the loading user");
385// Assert.That(
386// foundItem1.Name, Is.EqualTo(itemName),
387// "Loaded item name doesn't match saved name");
388// }
385 389
386 /// <summary> 390 /// <summary>
387 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where 391 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
@@ -390,199 +394,203 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
390 /// 394 ///
391 /// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature 395 /// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature
392 /// (as tested in the a later commented out test) 396 /// (as tested in the a later commented out test)
393 [Test] 397 /// REFACTORING PROBLEM. Needs rewrite.
394 public void TestLoadIarV0_1AbsentUsers() 398// [Test]
395 { 399// public void TestLoadIarV0_1AbsentUsers()
396 TestHelper.InMethod(); 400// {
397 401// TestHelper.InMethod();
398 //log4net.Config.XmlConfigurator.Configure(); 402
399 403// //log4net.Config.XmlConfigurator.Configure();
400 string userFirstName = "Charlie"; 404
401 string userLastName = "Chan"; 405// string userFirstName = "Charlie";
402 UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999"); 406// string userLastName = "Chan";
403 string userItemCreatorFirstName = "Bat"; 407// UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999");
404 string userItemCreatorLastName = "Man"; 408// string userItemCreatorFirstName = "Bat";
405 //UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888"); 409// string userItemCreatorLastName = "Man";
406 410// //UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888");
407 string itemName = "b.lsl"; 411
408 string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); 412// string itemName = "b.lsl";
409 413// string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
410 MemoryStream archiveWriteStream = new MemoryStream(); 414
411 TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); 415// MemoryStream archiveWriteStream = new MemoryStream();
412 416// TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
413 InventoryItemBase item1 = new InventoryItemBase(); 417
414 item1.Name = itemName; 418// InventoryItemBase item1 = new InventoryItemBase();
415 item1.AssetID = UUID.Random(); 419// item1.Name = itemName;
416 item1.GroupID = UUID.Random(); 420// item1.AssetID = UUID.Random();
417 item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); 421// item1.GroupID = UUID.Random();
418 //item1.CreatorId = userUuid.ToString(); 422// item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
419 //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; 423// //item1.CreatorId = userUuid.ToString();
420 item1.Owner = UUID.Zero; 424// //item1.CreatorId = "00000000-0000-0000-0000-000000000444";
421 425// item1.Owner = UUID.Zero;
422 string item1FileName 426
423 = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); 427// string item1FileName
424 tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); 428// = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
425 tar.Close(); 429// tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
426 430// tar.Close();
427 MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); 431
428 SerialiserModule serialiserModule = new SerialiserModule(); 432// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
429 InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); 433// SerialiserModule serialiserModule = new SerialiserModule();
430 434// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
431 // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene 435
432 Scene scene = SceneSetupHelpers.SetupScene("inventory"); 436// // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
433 IUserAdminService userAdminService = scene.CommsManager.UserAdminService; 437// Scene scene = SceneSetupHelpers.SetupScene("inventory");
434 438// IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
435 SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); 439
436 userAdminService.AddUser( 440// SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
437 userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); 441// userAdminService.AddUser(
438 442// userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
439 archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); 443
440 444// archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
441 CachedUserInfo userInfo 445
442 = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); 446// CachedUserInfo userInfo
443 447// = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
444 InventoryItemBase foundItem1 448
445 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName); 449// InventoryItemBase foundItem1
446 450// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName);
447 Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); 451
452// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
453//// Assert.That(
454//// foundItem1.CreatorId, Is.EqualTo(userUuid),
455//// "Loaded item non-uuid creator doesn't match that of the loading user");
448// Assert.That( 456// Assert.That(
449// foundItem1.CreatorId, Is.EqualTo(userUuid), 457// foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid),
450// "Loaded item non-uuid creator doesn't match that of the loading user"); 458// "Loaded item uuid creator doesn't match that of the loading user");
451 Assert.That( 459// }
452 foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid),
453 "Loaded item uuid creator doesn't match that of the loading user");
454 }
455 460
456 /// <summary> 461 /// <summary>
457 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where 462 /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
458 /// no account exists with the creator name 463 /// no account exists with the creator name
459 /// </summary> 464 /// </summary>
460 /// Disabled since temporary profiles have not yet been implemented. 465 /// Disabled since temporary profiles have not yet been implemented.
466 /// REFACTORING PROBLEM. Needs rewrite.
467 ///
461 //[Test] 468 //[Test]
462 public void TestLoadIarV0_1TempProfiles() 469 //public void TestLoadIarV0_1TempProfiles()
463 { 470 //{
464 TestHelper.InMethod(); 471 // TestHelper.InMethod();
465 472
466 //log4net.Config.XmlConfigurator.Configure(); 473 // //log4net.Config.XmlConfigurator.Configure();
467 474
468 string userFirstName = "Dennis"; 475 // string userFirstName = "Dennis";
469 string userLastName = "Menace"; 476 // string userLastName = "Menace";
470 UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa"); 477 // UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa");
471 string user2FirstName = "Walter"; 478 // string user2FirstName = "Walter";
472 string user2LastName = "Mitty"; 479 // string user2LastName = "Mitty";
473 480
474 string itemName = "b.lsl"; 481 // string itemName = "b.lsl";
475 string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); 482 // string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
476 483
477 MemoryStream archiveWriteStream = new MemoryStream(); 484 // MemoryStream archiveWriteStream = new MemoryStream();
478 TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); 485 // TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
479 486
480 InventoryItemBase item1 = new InventoryItemBase(); 487 // InventoryItemBase item1 = new InventoryItemBase();
481 item1.Name = itemName; 488 // item1.Name = itemName;
482 item1.AssetID = UUID.Random(); 489 // item1.AssetID = UUID.Random();
483 item1.GroupID = UUID.Random(); 490 // item1.GroupID = UUID.Random();
484 item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName); 491 // item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName);
485 item1.Owner = UUID.Zero; 492 // item1.Owner = UUID.Zero;
486 493
487 string item1FileName 494 // string item1FileName
488 = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); 495 // = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
489 tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); 496 // tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
490 tar.Close(); 497 // tar.Close();
491 498
492 MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); 499 // MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
493 SerialiserModule serialiserModule = new SerialiserModule(); 500 // SerialiserModule serialiserModule = new SerialiserModule();
494 InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); 501 // InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
495 502
496 // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene 503 // // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
497 Scene scene = SceneSetupHelpers.SetupScene(); 504 // Scene scene = SceneSetupHelpers.SetupScene();
498 IUserAdminService userAdminService = scene.CommsManager.UserAdminService; 505 // IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
499 506
500 SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); 507 // SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
501 userAdminService.AddUser( 508 // userAdminService.AddUser(
502 userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); 509 // userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
503 510
504 archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "troll", archiveReadStream); 511 // archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "troll", archiveReadStream);
505 512
506 // Check that a suitable temporary user profile has been created. 513 // // Check that a suitable temporary user profile has been created.
507 UserProfileData user2Profile 514 // UserProfileData user2Profile
508 = scene.CommsManager.UserService.GetUserProfile( 515 // = scene.CommsManager.UserService.GetUserProfile(
509 OspResolver.HashName(user2FirstName + " " + user2LastName)); 516 // OspResolver.HashName(user2FirstName + " " + user2LastName));
510 Assert.That(user2Profile, Is.Not.Null); 517 // Assert.That(user2Profile, Is.Not.Null);
511 Assert.That(user2Profile.FirstName == user2FirstName); 518 // Assert.That(user2Profile.FirstName == user2FirstName);
512 Assert.That(user2Profile.SurName == user2LastName); 519 // Assert.That(user2Profile.SurName == user2LastName);
513 520
514 CachedUserInfo userInfo 521 // CachedUserInfo userInfo
515 = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); 522 // = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
516 userInfo.OnInventoryReceived += InventoryReceived; 523 // userInfo.OnInventoryReceived += InventoryReceived;
517 524
518 lock (this) 525 // lock (this)
519 { 526 // {
520 userInfo.FetchInventory(); 527 // userInfo.FetchInventory();
521 Monitor.Wait(this, 60000); 528 // Monitor.Wait(this, 60000);
522 } 529 // }
523 530
524 InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName); 531 // InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName);
525 532
526 Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId)); 533 // Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId));
527 Assert.That( 534 // Assert.That(
528 foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName))); 535 // foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName)));
529 Assert.That(foundItem.Owner, Is.EqualTo(userUuid)); 536 // Assert.That(foundItem.Owner, Is.EqualTo(userUuid));
530 537
531 Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod()); 538 // Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod());
532 } 539 //}
533 540
534 /// <summary> 541 /// <summary>
535 /// Test replication of an archive path to the user's inventory. 542 /// Test replication of an archive path to the user's inventory.
536 /// </summary> 543 /// </summary>
537 [Test] 544 //[Test]
538 public void TestReplicateArchivePathToUserInventory() 545 //public void TestReplicateArchivePathToUserInventory()
539 { 546 //{
540 TestHelper.InMethod(); 547 // TestHelper.InMethod();
541 548
542 //log4net.Config.XmlConfigurator.Configure(); 549 // //log4net.Config.XmlConfigurator.Configure();
543 550
544 Scene scene = SceneSetupHelpers.SetupScene("inventory"); 551 // Scene scene = SceneSetupHelpers.SetupScene("inventory");
545 CommunicationsManager commsManager = scene.CommsManager; 552 // CommunicationsManager commsManager = scene.CommsManager;
546 CachedUserInfo userInfo; 553 // CachedUserInfo userInfo;
547 554
548 lock (this) 555 // lock (this)
549 { 556 // {
550 userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived); 557 // // !!! REFACTORING PROBLEM. This needs to be rewritten
551 Monitor.Wait(this, 60000); 558 // userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived);
552 } 559 // Monitor.Wait(this, 60000);
553 560 // }
554 //Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder); 561
555 562 // //Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder);
556 Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); 563
557 List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>(); 564 // Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>();
558 565 // List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
559 string folder1Name = "a"; 566
560 string folder2Name = "b"; 567 // string folder1Name = "a";
561 string itemName = "c.lsl"; 568 // string folder2Name = "b";
562 569 // string itemName = "c.lsl";
563 string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); 570
564 string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); 571 // string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random());
565 string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); 572 // string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random());
566 573 // string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
567 string itemArchivePath 574
568 = string.Format( 575 // string itemArchivePath
569 "{0}{1}{2}{3}", 576 // = string.Format(
570 ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName); 577 // "{0}{1}{2}{3}",
571 578 // ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName);
572 //Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder); 579
573 580 // //Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder);
574 new InventoryArchiveReadRequest(scene, userInfo, null, (Stream)null) 581
575 .ReplicateArchivePathToUserInventory( 582 // new InventoryArchiveReadRequest(scene, userInfo, null, (Stream)null)
576 itemArchivePath, false, scene.InventoryService.GetRootFolder(userInfo.UserProfile.ID), 583 // .ReplicateArchivePathToUserInventory(
577 foldersCreated, nodesLoaded); 584 // itemArchivePath, false, scene.InventoryService.GetRootFolder(userInfo.UserProfile.ID),
578 585 // foldersCreated, nodesLoaded);
579 //Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder); 586
580 //InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a"); 587 // //Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder);
581 InventoryFolderBase folder1 588 // //InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a");
582 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userInfo.UserProfile.ID, "a"); 589 // InventoryFolderBase folder1
583 Assert.That(folder1, Is.Not.Null, "Could not find folder a"); 590 // = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userInfo.UserProfile.ID, "a");
584 InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b"); 591 // Assert.That(folder1, Is.Not.Null, "Could not find folder a");
585 Assert.That(folder2, Is.Not.Null, "Could not find folder b"); 592 // InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b");
586 } 593 // Assert.That(folder2, Is.Not.Null, "Could not find folder b");
594 //}
587 } 595 }
588} 596}
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Transfer/InventoryTransferModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Transfer/InventoryTransferModule.cs
index b60b32b..7142442 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Transfer/InventoryTransferModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Transfer/InventoryTransferModule.cs
@@ -32,14 +32,14 @@ using log4net;
32using Nini.Config; 32using Nini.Config;
33using OpenMetaverse; 33using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
38using OpenSim.Services.Interfaces; 38using OpenSim.Services.Interfaces;
39 39
40namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer 40namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
41{ 41{
42 public class InventoryTransferModule : IInventoryTransferModule, IRegionModule 42 public class InventoryTransferModule : IInventoryTransferModule, ISharedRegionModule
43 { 43 {
44 private static readonly ILog m_log 44 private static readonly ILog m_log
45 = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 45 = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@@ -50,10 +50,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
50 new Dictionary<UUID, Scene>(); 50 new Dictionary<UUID, Scene>();
51 51
52 private IMessageTransferModule m_TransferModule = null; 52 private IMessageTransferModule m_TransferModule = null;
53 private bool m_Enabled = true;
53 54
54 #region IRegionModule Members 55 #region IRegionModule Members
55 56
56 public void Initialise(Scene scene, IConfigSource config) 57 public void Initialise(IConfigSource config)
57 { 58 {
58 if (config.Configs["Messaging"] != null) 59 if (config.Configs["Messaging"] != null)
59 { 60 {
@@ -62,29 +63,56 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
62 if (config.Configs["Messaging"].GetString( 63 if (config.Configs["Messaging"].GetString(
63 "InventoryTransferModule", "InventoryTransferModule") != 64 "InventoryTransferModule", "InventoryTransferModule") !=
64 "InventoryTransferModule") 65 "InventoryTransferModule")
66 {
67 m_Enabled = false;
65 return; 68 return;
69 }
66 } 70 }
71 }
67 72
68 if (!m_Scenelist.Contains(scene)) 73 public void AddRegion(Scene scene)
69 { 74 {
70 m_Scenelist.Add(scene); 75 if (!m_Enabled)
76 return;
71 77
72 scene.RegisterModuleInterface<IInventoryTransferModule>(this); 78 m_Scenelist.Add(scene);
73 79
74 scene.EventManager.OnNewClient += OnNewClient; 80 scene.RegisterModuleInterface<IInventoryTransferModule>(this);
75 scene.EventManager.OnClientClosed += ClientLoggedOut; 81
76 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; 82 scene.EventManager.OnNewClient += OnNewClient;
77 } 83 scene.EventManager.OnClientClosed += ClientLoggedOut;
84 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
78 } 85 }
79 86
80 public void PostInitialise() 87 public void RegionLoaded(Scene scene)
81 { 88 {
82 if (m_Scenelist.Count > 0) 89 if (m_TransferModule == null)
83 { 90 {
84 m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>(); 91 m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>();
85 if (m_TransferModule == null) 92 if (m_TransferModule == null)
93 {
86 m_log.Error("[INVENTORY TRANSFER] No Message transfer module found, transfers will be local only"); 94 m_log.Error("[INVENTORY TRANSFER] No Message transfer module found, transfers will be local only");
95 m_Enabled = false;
96
97 m_Scenelist.Clear();
98 scene.EventManager.OnNewClient -= OnNewClient;
99 scene.EventManager.OnClientClosed -= ClientLoggedOut;
100 scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
101 }
87 } 102 }
103
104 }
105
106 public void RemoveRegion(Scene scene)
107 {
108 scene.EventManager.OnNewClient -= OnNewClient;
109 scene.EventManager.OnClientClosed -= ClientLoggedOut;
110 scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
111 m_Scenelist.Remove(scene);
112 }
113
114 public void PostInitialise()
115 {
88 } 116 }
89 117
90 public void Close() 118 public void Close()
@@ -96,9 +124,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
96 get { return "InventoryModule"; } 124 get { return "InventoryModule"; }
97 } 125 }
98 126
99 public bool IsSharedModule 127 public Type ReplaceableInterface
100 { 128 {
101 get { return true; } 129 get { return null; }
102 } 130 }
103 131
104 #endregion 132 #endregion
@@ -330,7 +358,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
330 { 358 {
331 ScenePresence presence; 359 ScenePresence presence;
332 360
333 if (s.TryGetAvatar(agentID, out presence)) 361 if (s.TryGetScenePresence(agentID, out presence))
334 { 362 {
335 // If the agent is in this scene, then we 363 // If the agent is in this scene, then we
336 // are being called twice in a single 364 // are being called twice in a single
diff --git a/OpenSim/Region/CoreModules/Avatar/Lure/LureModule.cs b/OpenSim/Region/CoreModules/Avatar/Lure/LureModule.cs
index 261bd6c..d1d7df2 100644
--- a/OpenSim/Region/CoreModules/Avatar/Lure/LureModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Lure/LureModule.cs
@@ -37,34 +37,72 @@ using OpenSim.Region.Framework.Scenes;
37 37
38namespace OpenSim.Region.CoreModules.Avatar.Lure 38namespace OpenSim.Region.CoreModules.Avatar.Lure
39{ 39{
40 public class LureModule : IRegionModule 40 public class LureModule : ISharedRegionModule
41 { 41 {
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 42 private static readonly ILog m_log = LogManager.GetLogger(
43 MethodBase.GetCurrentMethod().DeclaringType);
43 44
44 private readonly List<Scene> m_scenes = new List<Scene>(); 45 private readonly List<Scene> m_scenes = new List<Scene>();
45 46
46 private IMessageTransferModule m_TransferModule = null; 47 private IMessageTransferModule m_TransferModule = null;
48 private bool m_Enabled = true;
47 49
48 public void Initialise(Scene scene, IConfigSource config) 50 public void Initialise(IConfigSource config)
49 { 51 {
50 if (config.Configs["Messaging"] != null) 52 if (config.Configs["Messaging"] != null)
51 { 53 {
52 if (config.Configs["Messaging"].GetString( 54 if (config.Configs["Messaging"].GetString(
53 "LureModule", "LureModule") != 55 "LureModule", "LureModule") !=
54 "LureModule") 56 "LureModule")
55 return; 57 m_Enabled = false;
56 } 58 }
59 }
60
61 public void AddRegion(Scene scene)
62 {
63 if (!m_Enabled)
64 return;
57 65
58 lock (m_scenes) 66 lock (m_scenes)
59 { 67 {
60 if (!m_scenes.Contains(scene)) 68 m_scenes.Add(scene);
69 scene.EventManager.OnNewClient += OnNewClient;
70 scene.EventManager.OnIncomingInstantMessage +=
71 OnGridInstantMessage;
72 }
73 }
74
75 public void RegionLoaded(Scene scene)
76 {
77 if (m_TransferModule == null)
78 {
79 m_TransferModule =
80 scene.RequestModuleInterface<IMessageTransferModule>();
81
82 if (m_TransferModule == null)
61 { 83 {
62 m_scenes.Add(scene); 84 m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
63 scene.EventManager.OnNewClient += OnNewClient; 85 "lures will not work!");
64 scene.EventManager.OnIncomingInstantMessage += 86
87 m_Enabled = false;
88 m_scenes.Clear();
89 scene.EventManager.OnNewClient -= OnNewClient;
90 scene.EventManager.OnIncomingInstantMessage -=
65 OnGridInstantMessage; 91 OnGridInstantMessage;
66 } 92 }
67 } 93 }
94
95 }
96
97 public void RemoveRegion(Scene scene)
98 {
99 lock (m_scenes)
100 {
101 m_scenes.Remove(scene);
102 scene.EventManager.OnNewClient -= OnNewClient;
103 scene.EventManager.OnIncomingInstantMessage -=
104 OnGridInstantMessage;
105 }
68 } 106 }
69 107
70 void OnNewClient(IClientAPI client) 108 void OnNewClient(IClientAPI client)
@@ -76,12 +114,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
76 114
77 public void PostInitialise() 115 public void PostInitialise()
78 { 116 {
79 m_TransferModule =
80 m_scenes[0].RequestModuleInterface<IMessageTransferModule>();
81
82 if (m_TransferModule == null)
83 m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
84 "lures will not work!");
85 } 117 }
86 118
87 public void Close() 119 public void Close()
@@ -93,9 +125,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
93 get { return "LureModule"; } 125 get { return "LureModule"; }
94 } 126 }
95 127
96 public bool IsSharedModule 128 public Type ReplaceableInterface
97 { 129 {
98 get { return true; } 130 get { return null; }
99 } 131 }
100 132
101 public void OnInstantMessage(IClientAPI client, GridInstantMessage im) 133 public void OnInstantMessage(IClientAPI client, GridInstantMessage im)
diff --git a/OpenSim/Region/CoreModules/Avatar/ObjectCaps/ObjectAdd.cs b/OpenSim/Region/CoreModules/Avatar/ObjectCaps/ObjectAdd.cs
index 63a93aa..c011776 100644
--- a/OpenSim/Region/CoreModules/Avatar/ObjectCaps/ObjectAdd.cs
+++ b/OpenSim/Region/CoreModules/Avatar/ObjectCaps/ObjectAdd.cs
@@ -82,7 +82,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
82 responsedata["str_response_string"] = "Request wasn't what was expected"; 82 responsedata["str_response_string"] = "Request wasn't what was expected";
83 ScenePresence avatar; 83 ScenePresence avatar;
84 84
85 if (!m_scene.TryGetAvatar(AgentId, out avatar)) 85 if (!m_scene.TryGetScenePresence(AgentId, out avatar))
86 return responsedata; 86 return responsedata;
87 87
88 88
diff --git a/OpenSim/Region/CoreModules/Avatar/Profiles/AvatarProfilesModule.cs b/OpenSim/Region/CoreModules/Avatar/Profiles/AvatarProfilesModule.cs
deleted file mode 100644
index 8cf58c6..0000000
--- a/OpenSim/Region/CoreModules/Avatar/Profiles/AvatarProfilesModule.cs
+++ /dev/null
@@ -1,168 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Globalization;
31using System.Reflection;
32using log4net;
33using Nini.Config;
34using OpenMetaverse;
35using OpenSim.Framework;
36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes;
38
39namespace OpenSim.Region.CoreModules.Avatar.Profiles
40{
41 public class AvatarProfilesModule : IRegionModule
42 {
43 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
44 private Scene m_scene;
45 private IProfileModule m_profileModule = null;
46 private bool m_enabled = true;
47
48 public AvatarProfilesModule()
49 {
50 }
51
52 #region IRegionModule Members
53
54 public void Initialise(Scene scene, IConfigSource config)
55 {
56 IConfig profileConfig = config.Configs["Profile"];
57 if (profileConfig != null)
58 {
59 if (profileConfig.GetString("Module", Name) != Name)
60 {
61 m_enabled = false;
62 return;
63 }
64 }
65
66 m_scene = scene;
67 m_scene.EventManager.OnNewClient += NewClient;
68 }
69
70 public void PostInitialise()
71 {
72 if (!m_enabled)
73 return;
74 m_profileModule = m_scene.RequestModuleInterface<IProfileModule>();
75 }
76
77 public void Close()
78 {
79 }
80
81 public string Name
82 {
83 get { return "AvatarProfilesModule"; }
84 }
85
86 public bool IsSharedModule
87 {
88 get { return false; }
89 }
90
91 #endregion
92
93 public void NewClient(IClientAPI client)
94 {
95 client.OnRequestAvatarProperties += RequestAvatarProperty;
96 client.OnUpdateAvatarProperties += UpdateAvatarProperties;
97 }
98
99 public void RemoveClient(IClientAPI client)
100 {
101 client.OnRequestAvatarProperties -= RequestAvatarProperty;
102 client.OnUpdateAvatarProperties -= UpdateAvatarProperties;
103 }
104
105 /// <summary>
106 ///
107 /// </summary>
108 /// <param name="remoteClient"></param>
109 /// <param name="avatarID"></param>
110 public void RequestAvatarProperty(IClientAPI remoteClient, UUID avatarID)
111 {
112 // FIXME: finish adding fields such as url, masking, etc.
113 UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(avatarID);
114 if (null != profile)
115 {
116 Byte[] charterMember;
117 if (profile.CustomType == "")
118 {
119 charterMember = new Byte[1];
120 charterMember[0] = (Byte)((profile.UserFlags & 0xf00) >> 8);
121 }
122 else
123 {
124 charterMember = Utils.StringToBytes(profile.CustomType);
125 }
126
127 if (m_profileModule != null)
128 {
129 Hashtable profileData = m_profileModule.GetProfileData(remoteClient.AgentId);
130 if (profileData["ProfileUrl"] != null)
131 profile.ProfileUrl = profileData["ProfileUrl"].ToString();
132 }
133 remoteClient.SendAvatarProperties(profile.ID, profile.AboutText,
134 Util.ToDateTime(profile.Created).ToString("M/d/yyyy", CultureInfo.InvariantCulture),
135 charterMember, profile.FirstLifeAboutText, (uint)(profile.UserFlags & 0xff),
136 profile.FirstLifeImage, profile.Image, profile.ProfileUrl, profile.Partner);
137 }
138 else
139 {
140 m_log.Debug("[AvatarProfilesModule]: Got null for profile for " + avatarID.ToString());
141 }
142 }
143
144 public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile)
145 {
146 UserProfileData Profile = m_scene.CommsManager.UserService.GetUserProfile(newProfile.ID);
147
148 // if it's the profile of the user requesting the update, then we change only a few things.
149 if (remoteClient.AgentId.CompareTo(Profile.ID) == 0)
150 {
151 Profile.Image = newProfile.Image;
152 Profile.FirstLifeImage = newProfile.FirstLifeImage;
153 Profile.AboutText = newProfile.AboutText;
154 Profile.FirstLifeAboutText = newProfile.FirstLifeAboutText;
155 Profile.ProfileUrl = newProfile.ProfileUrl;
156 }
157 else
158 {
159 return;
160 }
161
162 if (m_scene.CommsManager.UserService.UpdateUserProfile(Profile))
163 {
164 RequestAvatarProperty(remoteClient, newProfile.ID);
165 }
166 }
167 }
168}
diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs
new file mode 100644
index 0000000..ef37f63
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs
@@ -0,0 +1,1609 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Reflection;
32using System.Threading;
33
34using OpenSim.Framework;
35using OpenSim.Framework.Capabilities;
36using OpenSim.Framework.Client;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Services.Interfaces;
40
41using GridRegion = OpenSim.Services.Interfaces.GridRegion;
42
43using OpenMetaverse;
44using log4net;
45using Nini.Config;
46
47namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
48{
49 public class EntityTransferModule : ISharedRegionModule, IEntityTransferModule
50 {
51 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
52
53 protected bool m_Enabled = false;
54 protected Scene m_aScene;
55 protected List<UUID> m_agentsInTransit;
56
57 #region ISharedRegionModule
58
59 public Type ReplaceableInterface
60 {
61 get { return null; }
62 }
63
64 public virtual string Name
65 {
66 get { return "BasicEntityTransferModule"; }
67 }
68
69 public virtual void Initialise(IConfigSource source)
70 {
71 IConfig moduleConfig = source.Configs["Modules"];
72 if (moduleConfig != null)
73 {
74 string name = moduleConfig.GetString("EntityTransferModule", "");
75 if (name == Name)
76 {
77 m_agentsInTransit = new List<UUID>();
78 m_Enabled = true;
79 m_log.InfoFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
80 }
81 }
82 }
83
84 public virtual void PostInitialise()
85 {
86 }
87
88 public virtual void AddRegion(Scene scene)
89 {
90 if (!m_Enabled)
91 return;
92
93 if (m_aScene == null)
94 m_aScene = scene;
95
96 scene.RegisterModuleInterface<IEntityTransferModule>(this);
97 scene.EventManager.OnNewClient += OnNewClient;
98 }
99
100 protected virtual void OnNewClient(IClientAPI client)
101 {
102 client.OnTeleportHomeRequest += TeleportHome;
103 }
104
105 public virtual void Close()
106 {
107 if (!m_Enabled)
108 return;
109 }
110
111
112 public virtual void RemoveRegion(Scene scene)
113 {
114 if (!m_Enabled)
115 return;
116 if (scene == m_aScene)
117 m_aScene = null;
118 }
119
120 public virtual void RegionLoaded(Scene scene)
121 {
122 if (!m_Enabled)
123 return;
124
125 }
126
127
128 #endregion
129
130 #region Agent Teleports
131
132 public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
133 {
134 if (!sp.Scene.Permissions.CanTeleport(sp.UUID))
135 return;
136
137 IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
138
139 // Reset animations; the viewer does that in teleports.
140 sp.Animator.ResetAnimations();
141
142 try
143 {
144 if (regionHandle == sp.Scene.RegionInfo.RegionHandle)
145 {
146 m_log.DebugFormat(
147 "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation {0} within {1}",
148 position, sp.Scene.RegionInfo.RegionName);
149
150 // Teleport within the same region
151 if (IsOutsideRegion(sp.Scene, position) || position.Z < 0)
152 {
153 Vector3 emergencyPos = new Vector3(128, 128, 128);
154
155 m_log.WarnFormat(
156 "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
157 position, sp.Name, sp.UUID, emergencyPos);
158 position = emergencyPos;
159 }
160
161 // TODO: Get proper AVG Height
162 float localAVHeight = 1.56f;
163 float posZLimit = 22;
164
165 // TODO: Check other Scene HeightField
166 if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
167 {
168 posZLimit = (float)sp.Scene.Heightmap[(int)position.X, (int)position.Y];
169 }
170
171 float newPosZ = posZLimit + localAVHeight;
172 if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
173 {
174 position.Z = newPosZ;
175 }
176
177 // Only send this if the event queue is null
178 if (eq == null)
179 sp.ControllingClient.SendTeleportLocationStart();
180
181 sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
182 sp.Teleport(position);
183 }
184 else // Another region possibly in another simulator
185 {
186 uint x = 0, y = 0;
187 Utils.LongToUInts(regionHandle, out x, out y);
188 GridRegion reg = m_aScene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y);
189
190 if (reg != null)
191 {
192 GridRegion finalDestination = GetFinalDestination(reg);
193 if (finalDestination == null)
194 {
195 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final destination is having problems. Unable to teleport agent.");
196 sp.ControllingClient.SendTeleportFailed("Problem at destination");
197 return;
198 }
199 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final destination is x={0} y={1} uuid={2}",
200 finalDestination.RegionLocX / Constants.RegionSize, finalDestination.RegionLocY / Constants.RegionSize, finalDestination.RegionID);
201
202 //
203 // This is it
204 //
205 DoTeleport(sp, reg, finalDestination, position, lookAt, teleportFlags, eq);
206 //
207 //
208 //
209 }
210 else
211 {
212 // TP to a place that doesn't exist (anymore)
213 // Inform the viewer about that
214 sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
215
216 // and set the map-tile to '(Offline)'
217 uint regX, regY;
218 Utils.LongToUInts(regionHandle, out regX, out regY);
219
220 MapBlockData block = new MapBlockData();
221 block.X = (ushort)(regX / Constants.RegionSize);
222 block.Y = (ushort)(regY / Constants.RegionSize);
223 block.Access = 254; // == not there
224
225 List<MapBlockData> blocks = new List<MapBlockData>();
226 blocks.Add(block);
227 sp.ControllingClient.SendMapBlock(blocks, 0);
228 }
229 }
230 }
231 catch (Exception e)
232 {
233 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0}\n{1}", e.Message, e.StackTrace);
234 sp.ControllingClient.SendTeleportFailed("Internal error");
235 }
236 }
237
238 protected void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
239 {
240 if (reg == null || finalDestination == null)
241 {
242 sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
243 return;
244 }
245
246 m_log.DebugFormat(
247 "[ENTITY TRANSFER MODULE]: Request Teleport to {0}:{1}:{2}/{3}",
248 reg.ExternalHostName, reg.HttpPort, finalDestination.RegionName, position);
249
250 uint newRegionX = (uint)(reg.RegionHandle >> 40);
251 uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
252 uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
253 uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);
254
255 ulong destinationHandle = finalDestination.RegionHandle;
256
257 if (eq == null)
258 sp.ControllingClient.SendTeleportLocationStart();
259
260 // Let's do DNS resolution only once in this process, please!
261 // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
262 // it's actually doing a lot of work.
263 IPEndPoint endPoint = finalDestination.ExternalEndPoint;
264 if (endPoint.Address != null)
265 {
266 // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
267 // both regions
268 if (sp.ParentID != (uint)0)
269 sp.StandUp();
270
271 if (!sp.ValidateAttachments())
272 {
273 sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
274 return;
275 }
276
277 // the avatar.Close below will clear the child region list. We need this below for (possibly)
278 // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
279 //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
280 // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
281 // failure at this point (unlike a border crossing failure). So perhaps this can never fail
282 // once we reach here...
283 //avatar.Scene.RemoveCapsHandler(avatar.UUID);
284
285 string capsPath = String.Empty;
286
287 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
288 AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
289 agentCircuit.startpos = position;
290 agentCircuit.child = true;
291 agentCircuit.Appearance = sp.Appearance;
292 if (currentAgentCircuit != null)
293 {
294 agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
295 agentCircuit.Viewer = currentAgentCircuit.Viewer;
296 }
297
298 if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
299 {
300 // brand new agent, let's create a new caps seed
301 agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
302 }
303
304 string reason = String.Empty;
305
306 // Let's create an agent there if one doesn't exist yet.
307 if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason))
308 {
309 sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
310 reason));
311 return;
312 }
313
314 // OK, it got this agent. Let's close some child agents
315 sp.CloseChildAgents(newRegionX, newRegionY);
316
317 if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
318 {
319 #region IP Translation for NAT
320 IClientIPEndpoint ipepClient;
321 if (sp.ClientView.TryGet(out ipepClient))
322 {
323 capsPath
324 = "http://"
325 + NetworkUtil.GetHostFor(ipepClient.EndPoint, finalDestination.ExternalHostName)
326 + ":"
327 + finalDestination.HttpPort
328 + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
329 }
330 else
331 {
332 capsPath
333 = "http://"
334 + finalDestination.ExternalHostName
335 + ":"
336 + finalDestination.HttpPort
337 + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
338 }
339 #endregion
340
341 if (eq != null)
342 {
343 #region IP Translation for NAT
344 // Uses ipepClient above
345 if (sp.ClientView.TryGet(out ipepClient))
346 {
347 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
348 }
349 #endregion
350
351 eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);
352
353 // ES makes the client send a UseCircuitCode message to the destination,
354 // which triggers a bunch of things there.
355 // So let's wait
356 Thread.Sleep(200);
357
358 eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
359
360 }
361 else
362 {
363 sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
364 }
365 }
366 else
367 {
368 agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
369 capsPath = "http://" + finalDestination.ExternalHostName + ":" + finalDestination.HttpPort
370 + "/CAPS/" + agentCircuit.CapsPath + "0000/";
371 }
372
373 // Expect avatar crossing is a heavy-duty function at the destination.
374 // That is where MakeRoot is called, which fetches appearance and inventory.
375 // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
376 //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
377 // position, false);
378
379 //{
380 // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
381 // // We should close that agent we just created over at destination...
382 // List<ulong> lst = new List<ulong>();
383 // lst.Add(reg.RegionHandle);
384 // SendCloseChildAgentAsync(avatar.UUID, lst);
385 // return;
386 //}
387
388 SetInTransit(sp.UUID);
389
390 // Let's send a full update of the agent. This is a synchronous call.
391 AgentData agent = new AgentData();
392 sp.CopyTo(agent);
393 agent.Position = position;
394 SetCallbackURL(agent, sp.Scene.RegionInfo);
395
396 UpdateAgent(reg, finalDestination, agent);
397
398 m_log.DebugFormat(
399 "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);
400
401
402 if (eq != null)
403 {
404 eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
405 0, teleportFlags, capsPath, sp.UUID);
406 }
407 else
408 {
409 sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
410 teleportFlags, capsPath);
411 }
412
413 // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
414 // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
415 // that the client contacted the destination before we send the attachments and close things here.
416 if (!WaitForCallback(sp.UUID))
417 {
418 // Client never contacted destination. Let's restore everything back
419 sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
420
421 ResetFromTransit(sp.UUID);
422
423 // Yikes! We should just have a ref to scene here.
424 //sp.Scene.InformClientOfNeighbours(sp);
425 EnableChildAgents(sp);
426
427 // Finally, kill the agent we just created at the destination.
428 m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);
429
430 return;
431 }
432
433
434 // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
435 CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
436
437 KillEntity(sp.Scene, sp.LocalId);
438
439 sp.MakeChildAgent();
440 // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
441
442 if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
443 {
444 Thread.Sleep(5000);
445 sp.Close();
446 sp.Scene.IncomingCloseAgent(sp.UUID);
447 }
448 else
449 // now we have a child agent in this region.
450 sp.Reset();
451
452
453 // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
454 if (sp.Scene.NeedSceneCacheClear(sp.UUID))
455 {
456 m_log.DebugFormat(
457 "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
458 sp.UUID);
459 }
460 }
461 else
462 {
463 sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
464 }
465 }
466
467
468 protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason)
469 {
470 return m_aScene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
471 }
472
473 protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent)
474 {
475 return m_aScene.SimulationService.UpdateAgent(finalDestination, agent);
476 }
477
478 protected virtual void SetCallbackURL(AgentData agent, RegionInfo region)
479 {
480 agent.CallbackURI = "http://" + region.ExternalHostName + ":" + region.HttpPort +
481 "/agent/" + agent.AgentID.ToString() + "/" + region.RegionID.ToString() + "/release/";
482
483 }
484
485 protected void KillEntity(Scene scene, uint localID)
486 {
487 scene.SendKillObject(localID);
488 }
489
490 protected virtual GridRegion GetFinalDestination(GridRegion region)
491 {
492 return region;
493 }
494
495 protected virtual bool NeedsNewAgent(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY)
496 {
497 return Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY);
498 }
499
500 protected virtual bool NeedsClosing(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
501 {
502 return Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY);
503 }
504
505 protected virtual bool IsOutsideRegion(Scene s, Vector3 pos)
506 {
507
508 if (s.TestBorderCross(pos, Cardinals.N))
509 return true;
510 if (s.TestBorderCross(pos, Cardinals.S))
511 return true;
512 if (s.TestBorderCross(pos, Cardinals.E))
513 return true;
514 if (s.TestBorderCross(pos, Cardinals.W))
515 return true;
516
517 return false;
518 }
519
520
521 #endregion
522
523 #region Teleport Home
524
525 public virtual void TeleportHome(UUID id, IClientAPI client)
526 {
527 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName);
528
529 //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId);
530 GridUserInfo uinfo = m_aScene.GridUserService.GetGridUserInfo(client.AgentId.ToString());
531
532 if (uinfo != null)
533 {
534 GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
535 if (regionInfo == null)
536 {
537 // can't find the Home region: Tell viewer and abort
538 client.SendTeleportFailed("Your home region could not be found.");
539 return;
540 }
541 // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
542 ((Scene)(client.Scene)).RequestTeleportLocation(
543 client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
544 (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
545 }
546 }
547
548 #endregion
549
550
551 #region Agent Crossings
552
553 public void Cross(ScenePresence agent, bool isFlying)
554 {
555 Scene scene = agent.Scene;
556 Vector3 pos = agent.AbsolutePosition;
557 Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
558 uint neighbourx = scene.RegionInfo.RegionLocX;
559 uint neighboury = scene.RegionInfo.RegionLocY;
560 const float boundaryDistance = 1.7f;
561 Vector3 northCross = new Vector3(0, boundaryDistance, 0);
562 Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
563 Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
564 Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
565
566 // distance to edge that will trigger crossing
567
568
569 // distance into new region to place avatar
570 const float enterDistance = 0.5f;
571
572 if (scene.TestBorderCross(pos + westCross, Cardinals.W))
573 {
574 if (scene.TestBorderCross(pos + northCross, Cardinals.N))
575 {
576 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
577 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
578 }
579 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
580 {
581 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
582 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
583 {
584 neighboury--;
585 newpos.Y = Constants.RegionSize - enterDistance;
586 }
587 else
588 {
589 neighboury = b.TriggerRegionY;
590 neighbourx = b.TriggerRegionX;
591
592 Vector3 newposition = pos;
593 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
594 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
595 agent.ControllingClient.SendAgentAlertMessage(
596 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
597 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
598 return;
599 }
600 }
601
602 Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
603 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
604 {
605 neighbourx--;
606 newpos.X = Constants.RegionSize - enterDistance;
607 }
608 else
609 {
610 neighboury = ba.TriggerRegionY;
611 neighbourx = ba.TriggerRegionX;
612
613
614 Vector3 newposition = pos;
615 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
616 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
617 agent.ControllingClient.SendAgentAlertMessage(
618 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
619 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
620
621
622 return;
623 }
624
625 }
626 else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
627 {
628 Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
629 neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
630 newpos.X = enterDistance;
631
632 if (scene.TestBorderCross(pos + southCross, Cardinals.S))
633 {
634 Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
635 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
636 {
637 neighboury--;
638 newpos.Y = Constants.RegionSize - enterDistance;
639 }
640 else
641 {
642 neighboury = ba.TriggerRegionY;
643 neighbourx = ba.TriggerRegionX;
644 Vector3 newposition = pos;
645 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
646 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
647 agent.ControllingClient.SendAgentAlertMessage(
648 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
649 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
650 return;
651 }
652 }
653 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
654 {
655 Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
656 neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
657 newpos.Y = enterDistance;
658 }
659
660
661 }
662 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
663 {
664 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
665 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
666 {
667 neighboury--;
668 newpos.Y = Constants.RegionSize - enterDistance;
669 }
670 else
671 {
672 neighboury = b.TriggerRegionY;
673 neighbourx = b.TriggerRegionX;
674 Vector3 newposition = pos;
675 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
676 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
677 agent.ControllingClient.SendAgentAlertMessage(
678 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
679 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
680 return;
681 }
682 }
683 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
684 {
685
686 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
687 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
688 newpos.Y = enterDistance;
689 }
690
691 /*
692
693 if (pos.X < boundaryDistance) //West
694 {
695 neighbourx--;
696 newpos.X = Constants.RegionSize - enterDistance;
697 }
698 else if (pos.X > Constants.RegionSize - boundaryDistance) // East
699 {
700 neighbourx++;
701 newpos.X = enterDistance;
702 }
703
704 if (pos.Y < boundaryDistance) // South
705 {
706 neighboury--;
707 newpos.Y = Constants.RegionSize - enterDistance;
708 }
709 else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
710 {
711 neighboury++;
712 newpos.Y = enterDistance;
713 }
714 */
715
716 CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
717 d.BeginInvoke(agent, newpos, neighbourx, neighboury, isFlying, CrossAgentToNewRegionCompleted, d);
718
719 }
720
721
722 public delegate void InformClientToInitateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
723 Vector3 position,
724 Scene initiatingScene);
725
726 private void InformClientToInitateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position, Scene initiatingScene)
727 {
728
729 // This assumes that we know what our neighbors are.
730
731 InformClientToInitateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
732 d.BeginInvoke(agent, regionX, regionY, position, initiatingScene,
733 InformClientToInitiateTeleportToLocationCompleted,
734 d);
735 }
736
737 public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
738 Scene initiatingScene)
739 {
740 Thread.Sleep(10000);
741 IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
742 if (im != null)
743 {
744 UUID gotoLocation = Util.BuildFakeParcelID(
745 Util.UIntsToLong(
746 (regionX *
747 (uint)Constants.RegionSize),
748 (regionY *
749 (uint)Constants.RegionSize)),
750 (uint)(int)position.X,
751 (uint)(int)position.Y,
752 (uint)(int)position.Z);
753 GridInstantMessage m = new GridInstantMessage(initiatingScene, UUID.Zero,
754 "Region", agent.UUID,
755 (byte)InstantMessageDialog.GodLikeRequestTeleport, false,
756 "", gotoLocation, false, new Vector3(127, 0, 0),
757 new Byte[0]);
758 im.SendInstantMessage(m, delegate(bool success)
759 {
760 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Client Initiating Teleport sending IM success = {0}", success);
761 });
762
763 }
764 }
765
766 private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
767 {
768 InformClientToInitateTeleportToLocationDelegate icon =
769 (InformClientToInitateTeleportToLocationDelegate)iar.AsyncState;
770 icon.EndInvoke(iar);
771 }
772
773 public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying);
774
775 /// <summary>
776 /// This Closes child agents on neighboring regions
777 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
778 /// </summary>
779 protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying)
780 {
781 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3}", agent.Firstname, agent.Lastname, neighbourx, neighboury);
782
783 Scene m_scene = agent.Scene;
784 ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
785
786 int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
787 GridRegion neighbourRegion = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
788
789 if (neighbourRegion != null && agent.ValidateAttachments())
790 {
791 pos = pos + (agent.Velocity);
792
793 SetInTransit(agent.UUID);
794 AgentData cAgent = new AgentData();
795 agent.CopyTo(cAgent);
796 cAgent.Position = pos;
797 if (isFlying)
798 cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
799 cAgent.CallbackURI = "http://" + m_scene.RegionInfo.ExternalHostName + ":" + m_scene.RegionInfo.HttpPort +
800 "/agent/" + agent.UUID.ToString() + "/" + m_scene.RegionInfo.RegionID.ToString() + "/release/";
801
802 m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent);
803
804 // Next, let's close the child agent connections that are too far away.
805 agent.CloseChildAgents(neighbourx, neighboury);
806
807 //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
808 agent.ControllingClient.RequestClientInfo();
809
810 //m_log.Debug("BEFORE CROSS");
811 //Scene.DumpChildrenSeeds(UUID);
812 //DumpKnownRegions();
813 string agentcaps;
814 if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
815 {
816 m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
817 neighbourRegion.RegionHandle);
818 return agent;
819 }
820 // TODO Should construct this behind a method
821 string capsPath =
822 "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort
823 + "/CAPS/" + agentcaps /*circuitdata.CapsPath*/ + "0000/";
824
825 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
826
827 IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
828 if (eq != null)
829 {
830 eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
831 capsPath, agent.UUID, agent.ControllingClient.SessionId);
832 }
833 else
834 {
835 agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
836 capsPath);
837 }
838
839 if (!WaitForCallback(agent.UUID))
840 {
841 m_log.Debug("[ENTITY TRANSFER MODULE]: Callback never came in crossing agent");
842 ResetFromTransit(agent.UUID);
843
844 // Yikes! We should just have a ref to scene here.
845 //agent.Scene.InformClientOfNeighbours(agent);
846 EnableChildAgents(agent);
847
848 return agent;
849 }
850
851 agent.MakeChildAgent();
852 // now we have a child agent in this region. Request all interesting data about other (root) agents
853 agent.SendInitialFullUpdateToAllClients();
854
855 CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
856
857 // m_scene.SendKillObject(m_localId);
858
859 agent.Scene.NotifyMyCoarseLocationChange();
860 // the user may change their profile information in other region,
861 // so the userinfo in UserProfileCache is not reliable any more, delete it
862 // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
863 if (agent.Scene.NeedSceneCacheClear(agent.UUID))
864 {
865 m_log.DebugFormat(
866 "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID);
867 }
868 }
869
870 //m_log.Debug("AFTER CROSS");
871 //Scene.DumpChildrenSeeds(UUID);
872 //DumpKnownRegions();
873 return agent;
874 }
875
876 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
877 {
878 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
879 ScenePresence agent = icon.EndInvoke(iar);
880
881 // If the cross was successful, this agent is a child agent
882 if (agent.IsChildAgent)
883 agent.Reset();
884 else // Not successful
885 agent.RestoreInCurrentScene();
886
887 // In any case
888 agent.NotInTransit();
889
890 //m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
891 }
892
893 #endregion
894
895 #region Enable Child Agent
896 /// <summary>
897 /// This informs a single neighboring region about agent "avatar".
898 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
899 /// </summary>
900 public void EnableChildAgent(ScenePresence sp, GridRegion region)
901 {
902 AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
903 agent.BaseFolder = UUID.Zero;
904 agent.InventoryFolder = UUID.Zero;
905 agent.startpos = new Vector3(128, 128, 70);
906 agent.child = true;
907 agent.Appearance = sp.Appearance;
908
909 InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
910 d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
911 InformClientOfNeighbourCompleted,
912 d);
913 }
914 #endregion
915
916 #region Enable Child Agents
917
918 private delegate void InformClientOfNeighbourDelegate(
919 ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
920
921 /// <summary>
922 /// This informs all neighboring regions about agent "avatar".
923 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
924 /// </summary>
925 public void EnableChildAgents(ScenePresence sp)
926 {
927 List<GridRegion> neighbours = new List<GridRegion>();
928 RegionInfo m_regionInfo = sp.Scene.RegionInfo;
929
930 if (m_regionInfo != null)
931 {
932 neighbours = RequestNeighbours(sp.Scene, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
933 }
934 else
935 {
936 m_log.Debug("[ENTITY TRANSFER MODULE]: m_regionInfo was null in EnableChildAgents, is this a NPC?");
937 }
938
939 /// We need to find the difference between the new regions where there are no child agents
940 /// and the regions where there are already child agents. We only send notification to the former.
941 List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
942 neighbourHandles.Add(sp.Scene.RegionInfo.RegionHandle); // add this region too
943 List<ulong> previousRegionNeighbourHandles;
944
945 if (sp.Scene.CapsModule != null)
946 {
947 previousRegionNeighbourHandles =
948 new List<ulong>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID).Keys);
949 }
950 else
951 {
952 previousRegionNeighbourHandles = new List<ulong>();
953 }
954
955 List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
956 List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
957
958 //Dump("Current Neighbors", neighbourHandles);
959 //Dump("Previous Neighbours", previousRegionNeighbourHandles);
960 //Dump("New Neighbours", newRegions);
961 //Dump("Old Neighbours", oldRegions);
962
963 /// Update the scene presence's known regions here on this region
964 sp.DropOldNeighbours(oldRegions);
965
966 /// Collect as many seeds as possible
967 Dictionary<ulong, string> seeds;
968 if (sp.Scene.CapsModule != null)
969 seeds
970 = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
971 else
972 seeds = new Dictionary<ulong, string>();
973
974 //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
975 if (!seeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
976 seeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
977
978 /// Create the necessary child agents
979 List<AgentCircuitData> cagents = new List<AgentCircuitData>();
980 foreach (GridRegion neighbour in neighbours)
981 {
982 if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
983 {
984
985 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
986 AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
987 agent.BaseFolder = UUID.Zero;
988 agent.InventoryFolder = UUID.Zero;
989 agent.startpos = new Vector3(128, 128, 70);
990 agent.child = true;
991 agent.Appearance = sp.Appearance;
992 if (currentAgentCircuit != null)
993 {
994 agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
995 agent.Viewer = currentAgentCircuit.Viewer;
996 }
997
998 if (newRegions.Contains(neighbour.RegionHandle))
999 {
1000 agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
1001 sp.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
1002 seeds.Add(neighbour.RegionHandle, agent.CapsPath);
1003 }
1004 else
1005 agent.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, neighbour.RegionHandle);
1006
1007 cagents.Add(agent);
1008 }
1009 }
1010
1011 /// Update all child agent with everyone's seeds
1012 foreach (AgentCircuitData a in cagents)
1013 {
1014 a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
1015 }
1016
1017 if (sp.Scene.CapsModule != null)
1018 {
1019 sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, seeds);
1020 }
1021 sp.KnownRegions = seeds;
1022 //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
1023 //avatar.DumpKnownRegions();
1024
1025 bool newAgent = false;
1026 int count = 0;
1027 foreach (GridRegion neighbour in neighbours)
1028 {
1029 //m_log.WarnFormat("--> Going to send child agent to {0}", neighbour.RegionName);
1030 // Don't do it if there's already an agent in that region
1031 if (newRegions.Contains(neighbour.RegionHandle))
1032 newAgent = true;
1033 else
1034 newAgent = false;
1035
1036 if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
1037 {
1038 InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
1039 try
1040 {
1041 d.BeginInvoke(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
1042 InformClientOfNeighbourCompleted,
1043 d);
1044 }
1045
1046 catch (ArgumentOutOfRangeException)
1047 {
1048 m_log.ErrorFormat(
1049 "[ENTITY TRANSFER MODULE]: Neighbour Regions response included the current region in the neighbor list. The following region will not display to the client: {0} for region {1} ({2}, {3}).",
1050 neighbour.ExternalHostName,
1051 neighbour.RegionHandle,
1052 neighbour.RegionLocX,
1053 neighbour.RegionLocY);
1054 }
1055 catch (Exception e)
1056 {
1057 m_log.ErrorFormat(
1058 "[ENTITY TRANSFER MODULE]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
1059 neighbour.ExternalHostName,
1060 neighbour.RegionHandle,
1061 neighbour.RegionLocX,
1062 neighbour.RegionLocY,
1063 e);
1064
1065 // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
1066 // since I don't know what will happen if we just let the client continue
1067
1068 // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
1069 // throw e;
1070
1071 }
1072 }
1073 count++;
1074 }
1075 }
1076
1077 private void InformClientOfNeighbourCompleted(IAsyncResult iar)
1078 {
1079 InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate)iar.AsyncState;
1080 icon.EndInvoke(iar);
1081 //m_log.WarnFormat(" --> InformClientOfNeighbourCompleted");
1082 }
1083
1084 /// <summary>
1085 /// Async component for informing client of which neighbours exist
1086 /// </summary>
1087 /// <remarks>
1088 /// This needs to run asynchronously, as a network timeout may block the thread for a long while
1089 /// </remarks>
1090 /// <param name="remoteClient"></param>
1091 /// <param name="a"></param>
1092 /// <param name="regionHandle"></param>
1093 /// <param name="endPoint"></param>
1094 private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData a, GridRegion reg,
1095 IPEndPoint endPoint, bool newAgent)
1096 {
1097 // Let's wait just a little to give time to originating regions to catch up with closing child agents
1098 // after a cross here
1099 Thread.Sleep(500);
1100
1101 Scene m_scene = sp.Scene;
1102
1103 uint x, y;
1104 Utils.LongToUInts(reg.RegionHandle, out x, out y);
1105 x = x / Constants.RegionSize;
1106 y = y / Constants.RegionSize;
1107 m_log.Info("[ENTITY TRANSFER MODULE]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
1108
1109 string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
1110 + "/CAPS/" + a.CapsPath + "0000/";
1111
1112 string reason = String.Empty;
1113
1114
1115 bool regionAccepted = m_scene.SimulationService.CreateAgent(reg, a, 0, out reason); // m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, 0, out reason);
1116
1117 if (regionAccepted && newAgent)
1118 {
1119 IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
1120 if (eq != null)
1121 {
1122 #region IP Translation for NAT
1123 IClientIPEndpoint ipepClient;
1124 if (sp.ClientView.TryGet(out ipepClient))
1125 {
1126 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
1127 }
1128 #endregion
1129
1130 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} is sending {1} EnableSimulator for neighbor region {2} @ {3} " +
1131 "and EstablishAgentCommunication with seed cap {4}",
1132 m_scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath);
1133
1134 eq.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID);
1135 eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
1136 }
1137 else
1138 {
1139 sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
1140 // TODO: make Event Queue disablable!
1141 }
1142
1143 m_log.Info("[ENTITY TRANSFER MODULE]: Completed inform client about neighbour " + endPoint.ToString());
1144
1145 }
1146
1147 }
1148
1149 protected List<GridRegion> RequestNeighbours(Scene pScene, uint pRegionLocX, uint pRegionLocY)
1150 {
1151 RegionInfo m_regionInfo = pScene.RegionInfo;
1152
1153 Border[] northBorders = pScene.NorthBorders.ToArray();
1154 Border[] southBorders = pScene.SouthBorders.ToArray();
1155 Border[] eastBorders = pScene.EastBorders.ToArray();
1156 Border[] westBorders = pScene.WestBorders.ToArray();
1157
1158 // Legacy one region. Provided for simplicity while testing the all inclusive method in the else statement.
1159 if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1)
1160 {
1161 return pScene.GridService.GetNeighbours(m_regionInfo.ScopeID, m_regionInfo.RegionID);
1162 }
1163 else
1164 {
1165 Vector2 extent = Vector2.Zero;
1166 for (int i = 0; i < eastBorders.Length; i++)
1167 {
1168 extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
1169 }
1170 for (int i = 0; i < northBorders.Length; i++)
1171 {
1172 extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
1173 }
1174
1175 // Loss of fraction on purpose
1176 extent.X = ((int)extent.X / (int)Constants.RegionSize) + 1;
1177 extent.Y = ((int)extent.Y / (int)Constants.RegionSize) + 1;
1178
1179 int startX = (int)(pRegionLocX - 1) * (int)Constants.RegionSize;
1180 int startY = (int)(pRegionLocY - 1) * (int)Constants.RegionSize;
1181
1182 int endX = ((int)pRegionLocX + (int)extent.X) * (int)Constants.RegionSize;
1183 int endY = ((int)pRegionLocY + (int)extent.Y) * (int)Constants.RegionSize;
1184
1185 List<GridRegion> neighbours = pScene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
1186 neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
1187
1188 return neighbours;
1189 }
1190 }
1191
1192 private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1193 {
1194 return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
1195 }
1196
1197 // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1198 // {
1199 // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
1200 // }
1201
1202 private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1203 {
1204 return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
1205 }
1206
1207 private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
1208 {
1209 List<ulong> handles = new List<ulong>();
1210 foreach (GridRegion reg in neighbours)
1211 {
1212 handles.Add(reg.RegionHandle);
1213 }
1214 return handles;
1215 }
1216
1217 private void Dump(string msg, List<ulong> handles)
1218 {
1219 m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
1220 foreach (ulong handle in handles)
1221 {
1222 uint x, y;
1223 Utils.LongToUInts(handle, out x, out y);
1224 x = x / Constants.RegionSize;
1225 y = y / Constants.RegionSize;
1226 m_log.InfoFormat("({0}, {1})", x, y);
1227 }
1228 }
1229
1230 #endregion
1231
1232
1233 #region Agent Arrived
1234 public void AgentArrivedAtDestination(UUID id)
1235 {
1236 //m_log.Debug(" >>> ReleaseAgent called <<< ");
1237 ResetFromTransit(id);
1238 }
1239
1240 #endregion
1241
1242 #region Object Transfers
1243 /// <summary>
1244 /// Move the given scene object into a new region depending on which region its absolute position has moved
1245 /// into.
1246 ///
1247 /// This method locates the new region handle and offsets the prim position for the new region
1248 /// </summary>
1249 /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
1250 /// <param name="grp">the scene object that we're crossing</param>
1251 public void Cross(SceneObjectGroup grp, Vector3 attemptedPosition, bool silent)
1252 {
1253 if (grp == null)
1254 return;
1255 if (grp.IsDeleted)
1256 return;
1257
1258 Scene scene = grp.Scene;
1259 if (scene == null)
1260 return;
1261
1262 if (grp.RootPart.DIE_AT_EDGE)
1263 {
1264 // We remove the object here
1265 try
1266 {
1267 scene.DeleteSceneObject(grp, false);
1268 }
1269 catch (Exception)
1270 {
1271 m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
1272 }
1273 return;
1274 }
1275
1276 int thisx = (int)scene.RegionInfo.RegionLocX;
1277 int thisy = (int)scene.RegionInfo.RegionLocY;
1278 Vector3 EastCross = new Vector3(0.1f, 0, 0);
1279 Vector3 WestCross = new Vector3(-0.1f, 0, 0);
1280 Vector3 NorthCross = new Vector3(0, 0.1f, 0);
1281 Vector3 SouthCross = new Vector3(0, -0.1f, 0);
1282
1283
1284 // use this if no borders were crossed!
1285 ulong newRegionHandle
1286 = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
1287 (uint)((thisy) * Constants.RegionSize));
1288
1289 Vector3 pos = attemptedPosition;
1290
1291 int changeX = 1;
1292 int changeY = 1;
1293
1294 if (scene.TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
1295 {
1296 if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
1297 {
1298
1299 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
1300
1301 if (crossedBorderx.BorderLine.Z > 0)
1302 {
1303 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
1304 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
1305 }
1306 else
1307 pos.X = ((pos.X + Constants.RegionSize));
1308
1309 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
1310 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
1311
1312 if (crossedBordery.BorderLine.Z > 0)
1313 {
1314 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
1315 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
1316 }
1317 else
1318 pos.Y = ((pos.Y + Constants.RegionSize));
1319
1320
1321
1322 newRegionHandle
1323 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
1324 (uint)((thisy - changeY) * Constants.RegionSize));
1325 // x - 1
1326 // y - 1
1327 }
1328 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
1329 {
1330 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
1331
1332 if (crossedBorderx.BorderLine.Z > 0)
1333 {
1334 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
1335 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
1336 }
1337 else
1338 pos.X = ((pos.X + Constants.RegionSize));
1339
1340
1341 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
1342 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
1343
1344 if (crossedBordery.BorderLine.Z > 0)
1345 {
1346 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
1347 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
1348 }
1349 else
1350 pos.Y = ((pos.Y + Constants.RegionSize));
1351
1352 newRegionHandle
1353 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
1354 (uint)((thisy + changeY) * Constants.RegionSize));
1355 // x - 1
1356 // y + 1
1357 }
1358 else
1359 {
1360 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
1361
1362 if (crossedBorderx.BorderLine.Z > 0)
1363 {
1364 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
1365 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
1366 }
1367 else
1368 pos.X = ((pos.X + Constants.RegionSize));
1369
1370 newRegionHandle
1371 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
1372 (uint)(thisy * Constants.RegionSize));
1373 // x - 1
1374 }
1375 }
1376 else if (scene.TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
1377 {
1378 if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
1379 {
1380
1381 pos.X = ((pos.X - Constants.RegionSize));
1382 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
1383 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
1384
1385 if (crossedBordery.BorderLine.Z > 0)
1386 {
1387 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
1388 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
1389 }
1390 else
1391 pos.Y = ((pos.Y + Constants.RegionSize));
1392
1393
1394 newRegionHandle
1395 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
1396 (uint)((thisy - changeY) * Constants.RegionSize));
1397 // x + 1
1398 // y - 1
1399 }
1400 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
1401 {
1402 pos.X = ((pos.X - Constants.RegionSize));
1403 pos.Y = ((pos.Y - Constants.RegionSize));
1404 newRegionHandle
1405 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
1406 (uint)((thisy + changeY) * Constants.RegionSize));
1407 // x + 1
1408 // y + 1
1409 }
1410 else
1411 {
1412 pos.X = ((pos.X - Constants.RegionSize));
1413 newRegionHandle
1414 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
1415 (uint)(thisy * Constants.RegionSize));
1416 // x + 1
1417 }
1418 }
1419 else if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
1420 {
1421 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
1422 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
1423
1424 if (crossedBordery.BorderLine.Z > 0)
1425 {
1426 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
1427 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
1428 }
1429 else
1430 pos.Y = ((pos.Y + Constants.RegionSize));
1431
1432 newRegionHandle
1433 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
1434 // y - 1
1435 }
1436 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
1437 {
1438
1439 pos.Y = ((pos.Y - Constants.RegionSize));
1440 newRegionHandle
1441 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
1442 // y + 1
1443 }
1444
1445 // Offset the positions for the new region across the border
1446 Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
1447 grp.OffsetForNewRegion(pos);
1448
1449 // If we fail to cross the border, then reset the position of the scene object on that border.
1450 uint x = 0, y = 0;
1451 Utils.LongToUInts(newRegionHandle, out x, out y);
1452 GridRegion destination = scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
1453 if (destination != null && !CrossPrimGroupIntoNewRegion(destination, grp, silent))
1454 {
1455 grp.OffsetForNewRegion(oldGroupPosition);
1456 grp.ScheduleGroupForFullUpdate();
1457 }
1458 }
1459
1460
1461 /// <summary>
1462 /// Move the given scene object into a new region
1463 /// </summary>
1464 /// <param name="newRegionHandle"></param>
1465 /// <param name="grp">Scene Object Group that we're crossing</param>
1466 /// <returns>
1467 /// true if the crossing itself was successful, false on failure
1468 /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
1469 /// </returns>
1470 protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, SceneObjectGroup grp, bool silent)
1471 {
1472 //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
1473
1474 bool successYN = false;
1475 grp.RootPart.UpdateFlag = 0;
1476 //int primcrossingXMLmethod = 0;
1477
1478 if (destination != null)
1479 {
1480 //string objectState = grp.GetStateSnapshot();
1481
1482 //successYN
1483 // = m_sceneGridService.PrimCrossToNeighboringRegion(
1484 // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
1485 //if (successYN && (objectState != "") && m_allowScriptCrossings)
1486 //{
1487 // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
1488 // newRegionHandle, grp.UUID, objectState, 100);
1489 //}
1490
1491 //// And the new channel...
1492 //if (m_interregionCommsOut != null)
1493 // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
1494 if (m_aScene.SimulationService != null)
1495 successYN = m_aScene.SimulationService.CreateObject(destination, grp, true);
1496
1497 if (successYN)
1498 {
1499 // We remove the object here
1500 try
1501 {
1502 grp.Scene.DeleteSceneObject(grp, silent);
1503 }
1504 catch (Exception e)
1505 {
1506 m_log.ErrorFormat(
1507 "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
1508 grp, e);
1509 }
1510 }
1511 else
1512 {
1513 if (!grp.IsDeleted)
1514 {
1515 if (grp.RootPart.PhysActor != null)
1516 {
1517 grp.RootPart.PhysActor.CrossingFailure();
1518 }
1519 }
1520
1521 m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
1522 }
1523 }
1524 else
1525 {
1526 m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
1527 }
1528
1529 return successYN;
1530 }
1531
1532 protected bool CrossAttachmentsIntoNewRegion(GridRegion destination, ScenePresence sp, bool silent)
1533 {
1534 List<SceneObjectGroup> m_attachments = sp.Attachments;
1535 lock (m_attachments)
1536 {
1537 // Validate
1538 foreach (SceneObjectGroup gobj in m_attachments)
1539 {
1540 if (gobj == null || gobj.IsDeleted)
1541 return false;
1542 }
1543
1544 foreach (SceneObjectGroup gobj in m_attachments)
1545 {
1546 // If the prim group is null then something must have happened to it!
1547 if (gobj != null && gobj.RootPart != null)
1548 {
1549 // Set the parent localID to 0 so it transfers over properly.
1550 gobj.RootPart.SetParentLocalId(0);
1551 gobj.AbsolutePosition = gobj.RootPart.AttachedPos;
1552 gobj.RootPart.IsAttachment = false;
1553 //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
1554 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending attachment {0} to region {1}", gobj.UUID, destination.RegionName);
1555 CrossPrimGroupIntoNewRegion(destination, gobj, silent);
1556 }
1557 }
1558 m_attachments.Clear();
1559
1560 return true;
1561 }
1562 }
1563
1564 #endregion
1565
1566 #region Misc
1567
1568 protected bool WaitForCallback(UUID id)
1569 {
1570 int count = 200;
1571 while (m_agentsInTransit.Contains(id) && count-- > 0)
1572 {
1573 //m_log.Debug(" >>> Waiting... " + count);
1574 Thread.Sleep(100);
1575 }
1576
1577 if (count > 0)
1578 return true;
1579 else
1580 return false;
1581 }
1582
1583 protected void SetInTransit(UUID id)
1584 {
1585 lock (m_agentsInTransit)
1586 {
1587 if (!m_agentsInTransit.Contains(id))
1588 m_agentsInTransit.Add(id);
1589 }
1590 }
1591
1592 protected bool ResetFromTransit(UUID id)
1593 {
1594 lock (m_agentsInTransit)
1595 {
1596 if (m_agentsInTransit.Contains(id))
1597 {
1598 m_agentsInTransit.Remove(id);
1599 return true;
1600 }
1601 }
1602 return false;
1603 }
1604
1605
1606 #endregion
1607
1608 }
1609}
diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs
new file mode 100644
index 0000000..137dfec
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs
@@ -0,0 +1,280 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31
32using OpenSim.Framework;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Services.Connectors.Hypergrid;
36using OpenSim.Services.Interfaces;
37using OpenSim.Server.Base;
38
39using GridRegion = OpenSim.Services.Interfaces.GridRegion;
40
41using OpenMetaverse;
42using log4net;
43using Nini.Config;
44
45namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
46{
47 public class HGEntityTransferModule : EntityTransferModule, ISharedRegionModule, IEntityTransferModule, IUserAgentVerificationModule
48 {
49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 private bool m_Initialized = false;
52
53 private GatekeeperServiceConnector m_GatekeeperConnector;
54
55 #region ISharedRegionModule
56
57 public override string Name
58 {
59 get { return "HGEntityTransferModule"; }
60 }
61
62 public override void Initialise(IConfigSource source)
63 {
64 IConfig moduleConfig = source.Configs["Modules"];
65 if (moduleConfig != null)
66 {
67 string name = moduleConfig.GetString("EntityTransferModule", "");
68 if (name == Name)
69 {
70 m_agentsInTransit = new List<UUID>();
71
72 m_Enabled = true;
73 m_log.InfoFormat("[HG ENTITY TRANSFER MODULE]: {0} enabled.", Name);
74 }
75 }
76 }
77
78 public override void AddRegion(Scene scene)
79 {
80 base.AddRegion(scene);
81 if (m_Enabled)
82 {
83 scene.RegisterModuleInterface<IUserAgentVerificationModule>(this);
84 }
85 }
86
87 protected override void OnNewClient(IClientAPI client)
88 {
89 client.OnTeleportHomeRequest += TeleportHome;
90 client.OnConnectionClosed += new Action<IClientAPI>(OnConnectionClosed);
91 }
92
93
94 public override void RegionLoaded(Scene scene)
95 {
96 base.RegionLoaded(scene);
97 if (m_Enabled)
98 if (!m_Initialized)
99 {
100 m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService);
101 m_Initialized = true;
102 }
103
104 }
105 public override void RemoveRegion(Scene scene)
106 {
107 base.AddRegion(scene);
108 if (m_Enabled)
109 {
110 scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this);
111 }
112 }
113
114
115 #endregion
116
117 #region HG overrides of IEntiryTransferModule
118
119 protected override GridRegion GetFinalDestination(GridRegion region)
120 {
121 int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, region.RegionID);
122 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionID, flags);
123 if ((flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
124 {
125 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region {0} is hyperlink", region.RegionID);
126 return m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID);
127 }
128 return region;
129 }
130
131 protected override bool NeedsClosing(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
132 {
133 if (base.NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
134 return true;
135
136 int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, reg.RegionID);
137 if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
138 return true;
139
140 return false;
141 }
142
143 protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason)
144 {
145 reason = string.Empty;
146 int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, reg.RegionID);
147 if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
148 {
149 // this user is going to another grid
150 if (agentCircuit.ServiceURLs.ContainsKey("HomeURI"))
151 {
152 string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString();
153 IUserAgentService connector = new UserAgentServiceConnector(userAgentDriver);
154 bool success = connector.LoginAgentToGrid(agentCircuit, reg, finalDestination, out reason);
155 if (success)
156 // Log them out of this grid
157 m_aScene.PresenceService.LogoutAgent(agentCircuit.SessionID);
158
159 return success;
160 }
161 else
162 {
163 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address");
164 return false;
165 }
166 }
167
168 return m_aScene.SimulationService.CreateAgent(reg, agentCircuit, teleportFlags, out reason);
169 }
170
171 public override void TeleportHome(UUID id, IClientAPI client)
172 {
173 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName);
174
175 // Let's find out if this is a foreign user or a local user
176 UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, id);
177 if (account != null)
178 {
179 // local grid user
180 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: User is local");
181 base.TeleportHome(id, client);
182 return;
183 }
184
185 // Foreign user wants to go home
186 //
187 AgentCircuitData aCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode);
188 if (aCircuit == null || (aCircuit != null && !aCircuit.ServiceURLs.ContainsKey("HomeURI")))
189 {
190 client.SendTeleportFailed("Your information has been lost");
191 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
192 return;
193 }
194
195 IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString());
196 Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
197 GridRegion finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt);
198 if (finalDestination == null)
199 {
200 client.SendTeleportFailed("Your home region could not be found");
201 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
202 return;
203 }
204
205 ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(client.AgentId);
206 if (sp == null)
207 {
208 client.SendTeleportFailed("Internal error");
209 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be");
210 return;
211 }
212
213 IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
214 GridRegion homeGatekeeper = MakeRegion(aCircuit);
215
216 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}:{5}",
217 aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ExternalHostName, homeGatekeeper.HttpPort, homeGatekeeper.RegionName);
218
219 DoTeleport(sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome), eq);
220 }
221 #endregion
222
223 #region IUserAgentVerificationModule
224
225 public bool VerifyClient(AgentCircuitData aCircuit, string token)
226 {
227 if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
228 {
229 string url = aCircuit.ServiceURLs["HomeURI"].ToString();
230 IUserAgentService security = new UserAgentServiceConnector(url);
231 return security.VerifyClient(aCircuit.SessionID, token);
232 }
233
234 return false;
235 }
236
237 void OnConnectionClosed(IClientAPI obj)
238 {
239 if (obj.IsLoggingOut)
240 {
241 object sp = null;
242 if (obj.Scene.TryGetScenePresence(obj.AgentId, out sp))
243 {
244 if (((ScenePresence)sp).IsChildAgent)
245 return;
246 }
247
248 AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
249
250 if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
251 {
252 string url = aCircuit.ServiceURLs["HomeURI"].ToString();
253 IUserAgentService security = new UserAgentServiceConnector(url);
254 security.LogoutAgent(obj.AgentId, obj.SessionId);
255 //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
256 }
257 else
258 m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
259 }
260 }
261
262 #endregion
263
264 private GridRegion MakeRegion(AgentCircuitData aCircuit)
265 {
266 GridRegion region = new GridRegion();
267
268 Uri uri = null;
269 if (!aCircuit.ServiceURLs.ContainsKey("HomeURI") ||
270 (aCircuit.ServiceURLs.ContainsKey("HomeURI") && !Uri.TryCreate(aCircuit.ServiceURLs["HomeURI"].ToString(), UriKind.Absolute, out uri)))
271 return null;
272
273 region.ExternalHostName = uri.Host;
274 region.HttpPort = (uint)uri.Port;
275 region.RegionName = string.Empty;
276 region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0);
277 return region;
278 }
279 }
280}
diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGAssetMapper.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGAssetMapper.cs
new file mode 100644
index 0000000..58ce550
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGAssetMapper.cs
@@ -0,0 +1,200 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using System.Threading;
32using log4net;
33using OpenMetaverse;
34using OpenSim.Framework;
35
36using OpenSim.Region.Framework.Scenes;
37using OpenSim.Region.Framework.Scenes.Serialization;
38using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Services.Interfaces;
40
41//using HyperGrid.Framework;
42//using OpenSim.Region.Communications.Hypergrid;
43
44namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
45{
46 public class HGAssetMapper
47 {
48 #region Fields
49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 // This maps between inventory server urls and inventory server clients
52// private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
53
54 private Scene m_scene;
55
56 #endregion
57
58 #region Constructor
59
60 public HGAssetMapper(Scene scene)
61 {
62 m_scene = scene;
63 }
64
65 #endregion
66
67 #region Internal functions
68
69 public AssetBase FetchAsset(string url, UUID assetID)
70 {
71 AssetBase asset = m_scene.AssetService.Get(url + "/" + assetID.ToString());
72
73 if (asset != null)
74 {
75 m_log.DebugFormat("[HG ASSET MAPPER]: Copied asset {0} from {1} to local asset server. ", asset.ID, url);
76 return asset;
77 }
78 return null;
79 }
80
81 public bool PostAsset(string url, AssetBase asset)
82 {
83 if (asset != null)
84 {
85 // See long comment in AssetCache.AddAsset
86 if (!asset.Temporary || asset.Local)
87 {
88 // We need to copy the asset into a new asset, because
89 // we need to set its ID to be URL+UUID, so that the
90 // HGAssetService dispatches it to the remote grid.
91 // It's not pretty, but the best that can be done while
92 // not having a global naming infrastructure
93 AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID);
94 Copy(asset, asset1);
95 try
96 {
97 asset1.ID = url + "/" + asset.ID;
98 }
99 catch
100 {
101 m_log.Warn("[HG ASSET MAPPER]: Oops.");
102 }
103
104 m_scene.AssetService.Store(asset1);
105 m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
106 }
107 return true;
108 }
109 else
110 m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache.");
111
112 return false;
113 }
114
115 private void Copy(AssetBase from, AssetBase to)
116 {
117 to.Data = from.Data;
118 to.Description = from.Description;
119 to.FullID = from.FullID;
120 to.ID = from.ID;
121 to.Local = from.Local;
122 to.Name = from.Name;
123 to.Temporary = from.Temporary;
124 to.Type = from.Type;
125
126 }
127
128 // TODO: unused
129 // private void Dump(Dictionary<UUID, bool> lst)
130 // {
131 // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
132 // foreach (KeyValuePair<UUID, bool> kvp in lst)
133 // m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
134 // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
135 // }
136
137 #endregion
138
139
140 #region Public interface
141
142 public void Get(UUID assetID, UUID ownerID, string userAssetURL)
143 {
144 // Get the item from the remote asset server onto the local AssetCache
145 // and place an entry in m_assetMap
146
147 m_log.Debug("[HG ASSET MAPPER]: Fetching object " + assetID + " from asset server " + userAssetURL);
148 AssetBase asset = FetchAsset(userAssetURL, assetID);
149
150 if (asset != null)
151 {
152 // OK, now fetch the inside.
153 Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>();
154 HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL);
155 uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
156 foreach (UUID uuid in ids.Keys)
157 FetchAsset(userAssetURL, uuid);
158
159 m_log.DebugFormat("[HG ASSET MAPPER]: Successfully fetched asset {0} from asset server {1}", asset.ID, userAssetURL);
160
161 }
162 else
163 m_log.Warn("[HG ASSET MAPPER]: Could not fetch asset from remote asset server " + userAssetURL);
164 }
165
166
167 public void Post(UUID assetID, UUID ownerID, string userAssetURL)
168 {
169 // Post the item from the local AssetCache onto the remote asset server
170 // and place an entry in m_assetMap
171
172 m_log.Debug("[HG ASSET MAPPER]: Posting object " + assetID + " to asset server " + userAssetURL);
173 AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
174 if (asset != null)
175 {
176 Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>();
177 HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, string.Empty);
178 uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
179 foreach (UUID uuid in ids.Keys)
180 {
181 asset = m_scene.AssetService.Get(uuid.ToString());
182 if (asset == null)
183 m_log.DebugFormat("[HG ASSET MAPPER]: Could not find asset {0}", uuid);
184 else
185 PostAsset(userAssetURL, asset);
186 }
187
188 // maybe all pieces got there...
189 m_log.DebugFormat("[HG ASSET MAPPER]: Successfully posted item {0} to asset server {1}", assetID, userAssetURL);
190
191 }
192 else
193 m_log.DebugFormat("[HG ASSET MAPPER]: Something wrong with asset {0}, it could not be found", assetID);
194
195 }
196
197 #endregion
198
199 }
200}
diff --git a/OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.Inventory.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs
index 6f7f34f..93aeb94 100644
--- a/OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.Inventory.cs
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs
@@ -1,4 +1,4 @@
1/* 1/*
2 * Copyright (c) Contributors, http://opensimulator.org/ 2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders. 3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 * 4 *
@@ -25,55 +25,67 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System;
29using System.Collections.Generic;
28using System.Reflection; 30using System.Reflection;
29using log4net; 31
30using Nini.Config;
31using OpenMetaverse;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Framework.Communications;
34using OpenSim.Framework.Communications.Cache;
35using OpenSim.Region.Framework.Interfaces; 33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Services.Connectors.Hypergrid;
36using OpenSim.Services.Interfaces;
37using OpenSim.Server.Base;
36 38
37namespace OpenSim.Region.Framework.Scenes.Hypergrid 39using GridRegion = OpenSim.Services.Interfaces.GridRegion;
40
41using OpenMetaverse;
42using log4net;
43using Nini.Config;
44
45namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
38{ 46{
39 public partial class HGScene : Scene 47 public class HGInventoryAccessModule : BasicInventoryAccessModule, INonSharedRegionModule, IInventoryAccessModule
40 { 48 {
41 #region Fields
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43 50
44 private HGAssetMapper m_assMapper; 51 private static HGAssetMapper m_assMapper;
45 public HGAssetMapper AssetMapper 52 public static HGAssetMapper AssetMapper
46 { 53 {
47 get { return m_assMapper; } 54 get { return m_assMapper; }
48 } 55 }
49 56
50 private IHyperAssetService m_hyper; 57 private bool m_Initialized = false;
51 private IHyperAssetService HyperAssets 58
59 #region INonSharedRegionModule
60
61 public override string Name
62 {
63 get { return "HGInventoryAccessModule"; }
64 }
65
66 public override void Initialise(IConfigSource source)
52 { 67 {
53 get 68 IConfig moduleConfig = source.Configs["Modules"];
69 if (moduleConfig != null)
54 { 70 {
55 if (m_hyper == null) 71 string name = moduleConfig.GetString("InventoryAccessModule", "");
56 m_hyper = RequestModuleInterface<IHyperAssetService>(); 72 if (name == Name)
57 return m_hyper; 73 {
74 m_Enabled = true;
75 m_log.InfoFormat("[HG INVENTORY ACCESS MODULE]: {0} enabled.", Name);
76 }
58 } 77 }
59 } 78 }
60 79
61 #endregion 80 public override void AddRegion(Scene scene)
62
63 #region Constructors
64
65 public HGScene(RegionInfo regInfo, AgentCircuitManager authen,
66 CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
67 StorageManager storeManager,
68 ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
69 bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
70 : base(regInfo, authen, commsMan, sceneGridService, storeManager, moduleLoader,
71 dumpAssetsToFile, physicalPrim, SeeIntoRegionFromNeighbor, config, simulatorVersion)
72 { 81 {
73 m_log.Info("[HGScene]: Starting HGScene."); 82 if (!m_Enabled)
74 m_assMapper = new HGAssetMapper(this); 83 return;
84
85 base.AddRegion(scene);
86 m_assMapper = new HGAssetMapper(scene);
87 scene.EventManager.OnNewInventoryItemUploadComplete += UploadInventoryItem;
75 88
76 EventManager.OnNewInventoryItemUploadComplete += UploadInventoryItem;
77 } 89 }
78 90
79 #endregion 91 #endregion
@@ -82,17 +94,16 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
82 94
83 public void UploadInventoryItem(UUID avatarID, UUID assetID, string name, int userlevel) 95 public void UploadInventoryItem(UUID avatarID, UUID assetID, string name, int userlevel)
84 { 96 {
85 CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(avatarID); 97 string userAssetServer = string.Empty;
86 if (userInfo != null) 98 if (IsForeignUser(avatarID, out userAssetServer))
87 { 99 {
88 m_assMapper.Post(assetID, avatarID); 100 m_assMapper.Post(assetID, avatarID, userAssetServer);
89 } 101 }
90 } 102 }
91 103
92 #endregion 104 #endregion
93 105
94 #region Overrides of Scene.Inventory methods 106 #region Overrides of Basic Inventory Access methods
95
96 /// 107 ///
97 /// CapsUpdateInventoryItemAsset 108 /// CapsUpdateInventoryItemAsset
98 /// 109 ///
@@ -135,7 +146,7 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
135 //{ 146 //{
136 InventoryItemBase item = new InventoryItemBase(itemID); 147 InventoryItemBase item = new InventoryItemBase(itemID);
137 item.Owner = remoteClient.AgentId; 148 item.Owner = remoteClient.AgentId;
138 item = InventoryService.GetItem(item); 149 item = m_Scene.InventoryService.GetItem(item);
139 //if (item == null) 150 //if (item == null)
140 //{ // Fetch the item 151 //{ // Fetch the item
141 // item = new InventoryItemBase(); 152 // item = new InventoryItemBase();
@@ -143,32 +154,54 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
143 // item.ID = itemID; 154 // item.ID = itemID;
144 // item = m_assMapper.Get(item, userInfo.RootFolder.ID, userInfo); 155 // item = m_assMapper.Get(item, userInfo.RootFolder.ID, userInfo);
145 //} 156 //}
146 if (item != null) 157 string userAssetServer = string.Empty;
158 if (item != null && IsForeignUser(remoteClient.AgentId, out userAssetServer))
147 { 159 {
148 m_assMapper.Get(item.AssetID, remoteClient.AgentId); 160 m_assMapper.Get(item.AssetID, remoteClient.AgentId, userAssetServer);
149 161
150 } 162 }
151 //} 163 //}
152 164
153 // OK, we're done fetching. Pass it up to the default RezObject 165 // OK, we're done fetching. Pass it up to the default RezObject
154 return base.RezObject(remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, 166 return base.RezObject(remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
155 RezSelected, RemoveItem, fromTaskID, attachment); 167 RezSelected, RemoveItem, fromTaskID, attachment);
156 168
157 } 169 }
158 170
159 protected override void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver) 171 public override void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
160 { 172 {
161 string userAssetServer = HyperAssets.GetUserAssetServer(sender); 173 string userAssetServer = string.Empty;
162 if ((userAssetServer != string.Empty) && (userAssetServer != HyperAssets.GetSimAssetServer())) 174 if (IsForeignUser(sender, out userAssetServer))
163 m_assMapper.Get(item.AssetID, sender); 175 m_assMapper.Get(item.AssetID, sender, userAssetServer);
164 176
165 userAssetServer = HyperAssets.GetUserAssetServer(receiver); 177 if (IsForeignUser(receiver, out userAssetServer))
166 if ((userAssetServer != string.Empty) && (userAssetServer != HyperAssets.GetSimAssetServer())) 178 m_assMapper.Post(item.AssetID, receiver, userAssetServer);
167 m_assMapper.Post(item.AssetID, receiver);
168 } 179 }
169 180
170 #endregion 181 #endregion
171 182
172 } 183 public bool IsForeignUser(UUID userID, out string assetServerURL)
184 {
185 assetServerURL = string.Empty;
186 UserAccount account = null;
187 if (m_Scene.UserAccountService != null)
188 account = m_Scene.UserAccountService.GetUserAccount(m_Scene.RegionInfo.ScopeID, userID);
189
190 if (account == null) // foreign
191 {
192 ScenePresence sp = null;
193 if (m_Scene.TryGetScenePresence(userID, out sp))
194 {
195 AgentCircuitData aCircuit = m_Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
196 if (aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
197 {
198 assetServerURL = aCircuit.ServiceURLs["AssetServerURI"].ToString();
199 assetServerURL = assetServerURL.Trim(new char[] { '/' }); return true;
200 }
201 }
202 }
173 203
204 return false;
205 }
206 }
174} 207}
diff --git a/OpenSim/Region/Framework/Scenes/Hypergrid/HGUuidGatherer.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGUuidGatherer.cs
index 5d4e7ac..fcb544f 100644
--- a/OpenSim/Region/Framework/Scenes/Hypergrid/HGUuidGatherer.cs
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGUuidGatherer.cs
@@ -29,10 +29,11 @@ using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30 30
31using OpenSim.Framework; 31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes;
32using OpenSim.Services.Interfaces; 33using OpenSim.Services.Interfaces;
33using OpenMetaverse; 34using OpenMetaverse;
34 35
35namespace OpenSim.Region.Framework.Scenes.Hypergrid 36namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
36{ 37{
37 public class HGUuidGatherer : UuidGatherer 38 public class HGUuidGatherer : UuidGatherer
38 { 39 {
diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs
new file mode 100644
index 0000000..2352ced
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs
@@ -0,0 +1,660 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Reflection;
32using System.Threading;
33
34using OpenSim.Framework;
35using OpenSim.Framework.Capabilities;
36using OpenSim.Framework.Client;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Region.Framework.Scenes.Serialization;
40using OpenSim.Services.Interfaces;
41
42using GridRegion = OpenSim.Services.Interfaces.GridRegion;
43
44using OpenMetaverse;
45using log4net;
46using Nini.Config;
47
48namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
49{
50 public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule
51 {
52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
53
54 protected bool m_Enabled = false;
55 protected Scene m_Scene;
56
57 #region INonSharedRegionModule
58
59 public Type ReplaceableInterface
60 {
61 get { return null; }
62 }
63
64 public virtual string Name
65 {
66 get { return "BasicInventoryAccessModule"; }
67 }
68
69 public virtual void Initialise(IConfigSource source)
70 {
71 IConfig moduleConfig = source.Configs["Modules"];
72 if (moduleConfig != null)
73 {
74 string name = moduleConfig.GetString("InventoryAccessModule", "");
75 if (name == Name)
76 {
77 m_Enabled = true;
78 m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name);
79 }
80 }
81 }
82
83 public virtual void PostInitialise()
84 {
85 }
86
87 public virtual void AddRegion(Scene scene)
88 {
89 if (!m_Enabled)
90 return;
91
92 m_Scene = scene;
93
94 scene.RegisterModuleInterface<IInventoryAccessModule>(this);
95 scene.EventManager.OnNewClient += OnNewClient;
96 }
97
98 protected virtual void OnNewClient(IClientAPI client)
99 {
100
101 }
102
103 public virtual void Close()
104 {
105 if (!m_Enabled)
106 return;
107 }
108
109
110 public virtual void RemoveRegion(Scene scene)
111 {
112 if (!m_Enabled)
113 return;
114 m_Scene = null;
115 }
116
117 public virtual void RegionLoaded(Scene scene)
118 {
119 if (!m_Enabled)
120 return;
121
122 }
123
124 #endregion
125
126 #region Inventory Access
127
128 /// <summary>
129 /// Capability originating call to update the asset of an item in an agent's inventory
130 /// </summary>
131 /// <param name="remoteClient"></param>
132 /// <param name="itemID"></param>
133 /// <param name="data"></param>
134 /// <returns></returns>
135 public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
136 {
137 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
138 item = m_Scene.InventoryService.GetItem(item);
139
140 if (item != null)
141 {
142 if ((InventoryType)item.InvType == InventoryType.Notecard)
143 {
144 if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
145 {
146 remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
147 return UUID.Zero;
148 }
149
150 remoteClient.SendAgentAlertMessage("Notecard saved", false);
151 }
152 else if ((InventoryType)item.InvType == InventoryType.LSL)
153 {
154 if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
155 {
156 remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
157 return UUID.Zero;
158 }
159
160 remoteClient.SendAgentAlertMessage("Script saved", false);
161 }
162
163 AssetBase asset =
164 CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString());
165 item.AssetID = asset.FullID;
166 m_Scene.AssetService.Store(asset);
167
168 m_Scene.InventoryService.UpdateItem(item);
169
170 // remoteClient.SendInventoryItemCreateUpdate(item);
171 return (asset.FullID);
172 }
173 else
174 {
175 m_log.ErrorFormat(
176 "[AGENT INVENTORY]: Could not find item {0} for caps inventory update",
177 itemID);
178 }
179
180 return UUID.Zero;
181 }
182
183 /// <summary>
184 /// Delete a scene object from a scene and place in the given avatar's inventory.
185 /// Returns the UUID of the newly created asset.
186 /// </summary>
187 /// <param name="action"></param>
188 /// <param name="folderID"></param>
189 /// <param name="objectGroup"></param>
190 /// <param name="remoteClient"> </param>
191 public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID,
192 SceneObjectGroup objectGroup, IClientAPI remoteClient)
193 {
194 UUID assetID = UUID.Zero;
195
196 Vector3 inventoryStoredPosition = new Vector3
197 (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
198 ? 250
199 : objectGroup.AbsolutePosition.X)
200 ,
201 (objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
202 ? 250
203 : objectGroup.AbsolutePosition.X,
204 objectGroup.AbsolutePosition.Z);
205
206 Vector3 originalPosition = objectGroup.AbsolutePosition;
207
208 objectGroup.AbsolutePosition = inventoryStoredPosition;
209
210 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(objectGroup);
211
212 objectGroup.AbsolutePosition = originalPosition;
213
214 // Get the user info of the item destination
215 //
216 UUID userID = UUID.Zero;
217
218 if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
219 action == DeRezAction.SaveToExistingUserInventoryItem)
220 {
221 // Take or take copy require a taker
222 // Saving changes requires a local user
223 //
224 if (remoteClient == null)
225 return UUID.Zero;
226
227 userID = remoteClient.AgentId;
228 }
229 else
230 {
231 // All returns / deletes go to the object owner
232 //
233
234 userID = objectGroup.RootPart.OwnerID;
235 }
236
237 if (userID == UUID.Zero) // Can't proceed
238 {
239 return UUID.Zero;
240 }
241
242 // If we're returning someone's item, it goes back to the
243 // owner's Lost And Found folder.
244 // Delete is treated like return in this case
245 // Deleting your own items makes them go to trash
246 //
247
248 InventoryFolderBase folder = null;
249 InventoryItemBase item = null;
250
251 if (DeRezAction.SaveToExistingUserInventoryItem == action)
252 {
253 item = new InventoryItemBase(objectGroup.RootPart.FromUserInventoryItemID, userID);
254 item = m_Scene.InventoryService.GetItem(item);
255
256 //item = userInfo.RootFolder.FindItem(
257 // objectGroup.RootPart.FromUserInventoryItemID);
258
259 if (null == item)
260 {
261 m_log.DebugFormat(
262 "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.",
263 objectGroup.Name, objectGroup.UUID);
264 return UUID.Zero;
265 }
266 }
267 else
268 {
269 // Folder magic
270 //
271 if (action == DeRezAction.Delete)
272 {
273 // Deleting someone else's item
274 //
275
276
277 if (remoteClient == null ||
278 objectGroup.OwnerID != remoteClient.AgentId)
279 {
280 // Folder skeleton may not be loaded and we
281 // have to wait for the inventory to find
282 // the destination folder
283 //
284 folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
285 }
286 else
287 {
288 // Assume inventory skeleton was loaded during login
289 // and all folders can be found
290 //
291 folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
292 }
293 }
294 else if (action == DeRezAction.Return)
295 {
296
297 // Dump to lost + found unconditionally
298 //
299 folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
300 }
301
302 if (folderID == UUID.Zero && folder == null)
303 {
304 if (action == DeRezAction.Delete)
305 {
306 // Deletes go to trash by default
307 //
308 folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
309 }
310 else
311 {
312 // Catch all. Use lost & found
313 //
314
315 folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
316 }
317 }
318
319 if (folder == null) // None of the above
320 {
321 //folder = userInfo.RootFolder.FindFolder(folderID);
322 folder = new InventoryFolderBase(folderID);
323
324 if (folder == null) // Nowhere to put it
325 {
326 return UUID.Zero;
327 }
328 }
329
330 item = new InventoryItemBase();
331 item.CreatorId = objectGroup.RootPart.CreatorID.ToString();
332 item.ID = UUID.Random();
333 item.InvType = (int)InventoryType.Object;
334 item.Folder = folder.ID;
335 item.Owner = userID;
336 }
337
338 AssetBase asset = CreateAsset(
339 objectGroup.GetPartName(objectGroup.RootPart.LocalId),
340 objectGroup.GetPartDescription(objectGroup.RootPart.LocalId),
341 (sbyte)AssetType.Object,
342 Utils.StringToBytes(sceneObjectXml),
343 objectGroup.OwnerID.ToString());
344 m_Scene.AssetService.Store(asset);
345 assetID = asset.FullID;
346
347 if (DeRezAction.SaveToExistingUserInventoryItem == action)
348 {
349 item.AssetID = asset.FullID;
350 m_Scene.InventoryService.UpdateItem(item);
351 }
352 else
353 {
354 item.AssetID = asset.FullID;
355
356 if (remoteClient != null && (remoteClient.AgentId != objectGroup.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions())
357 {
358 uint perms = objectGroup.GetEffectivePermissions();
359 uint nextPerms = (perms & 7) << 13;
360 if ((nextPerms & (uint)PermissionMask.Copy) == 0)
361 perms &= ~(uint)PermissionMask.Copy;
362 if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
363 perms &= ~(uint)PermissionMask.Transfer;
364 if ((nextPerms & (uint)PermissionMask.Modify) == 0)
365 perms &= ~(uint)PermissionMask.Modify;
366
367 item.BasePermissions = perms & objectGroup.RootPart.NextOwnerMask;
368 item.CurrentPermissions = item.BasePermissions;
369 item.NextPermissions = objectGroup.RootPart.NextOwnerMask;
370 item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask & objectGroup.RootPart.NextOwnerMask;
371 item.GroupPermissions = objectGroup.RootPart.GroupMask & objectGroup.RootPart.NextOwnerMask;
372 item.CurrentPermissions |= 8; // Slam!
373 }
374 else
375 {
376 item.BasePermissions = objectGroup.GetEffectivePermissions();
377 item.CurrentPermissions = objectGroup.GetEffectivePermissions();
378 item.NextPermissions = objectGroup.RootPart.NextOwnerMask;
379 item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask;
380 item.GroupPermissions = objectGroup.RootPart.GroupMask;
381
382 item.CurrentPermissions |= 8; // Slam!
383 }
384
385 // TODO: add the new fields (Flags, Sale info, etc)
386 item.CreationDate = Util.UnixTimeSinceEpoch();
387 item.Description = asset.Description;
388 item.Name = asset.Name;
389 item.AssetType = asset.Type;
390
391 m_Scene.InventoryService.AddItem(item);
392
393 if (remoteClient != null && item.Owner == remoteClient.AgentId)
394 {
395 remoteClient.SendInventoryItemCreateUpdate(item, 0);
396 }
397 else
398 {
399 ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner);
400 if (notifyUser != null)
401 {
402 notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
403 }
404 }
405 }
406
407 return assetID;
408 }
409
410
411 /// <summary>
412 /// Rez an object into the scene from the user's inventory
413 /// </summary>
414 /// FIXME: It would be really nice if inventory access modules didn't also actually do the work of rezzing
415 /// things to the scene. The caller should be doing that, I think.
416 /// <param name="remoteClient"></param>
417 /// <param name="itemID"></param>
418 /// <param name="RayEnd"></param>
419 /// <param name="RayStart"></param>
420 /// <param name="RayTargetID"></param>
421 /// <param name="BypassRayCast"></param>
422 /// <param name="RayEndIsIntersection"></param>
423 /// <param name="RezSelected"></param>
424 /// <param name="RemoveItem"></param>
425 /// <param name="fromTaskID"></param>
426 /// <param name="attachment"></param>
427 /// <returns>The SceneObjectGroup rezzed or null if rez was unsuccessful.</returns>
428 public virtual SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
429 UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
430 bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
431 {
432 // Work out position details
433 byte bRayEndIsIntersection = (byte)0;
434
435 if (RayEndIsIntersection)
436 {
437 bRayEndIsIntersection = (byte)1;
438 }
439 else
440 {
441 bRayEndIsIntersection = (byte)0;
442 }
443
444 Vector3 scale = new Vector3(0.5f, 0.5f, 0.5f);
445
446
447 Vector3 pos = m_Scene.GetNewRezLocation(
448 RayStart, RayEnd, RayTargetID, Quaternion.Identity,
449 BypassRayCast, bRayEndIsIntersection, true, scale, false);
450
451 // Rez object
452 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
453 item = m_Scene.InventoryService.GetItem(item);
454
455 if (item != null)
456 {
457 AssetBase rezAsset = m_Scene.AssetService.Get(item.AssetID.ToString());
458
459 if (rezAsset != null)
460 {
461 UUID itemId = UUID.Zero;
462
463 // If we have permission to copy then link the rezzed object back to the user inventory
464 // item that it came from. This allows us to enable 'save object to inventory'
465 if (!m_Scene.Permissions.BypassPermissions())
466 {
467 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy)
468 {
469 itemId = item.ID;
470 }
471 }
472 else
473 {
474 // Brave new fullperm world
475 //
476 itemId = item.ID;
477 }
478
479 string xmlData = Utils.BytesToString(rezAsset.Data);
480 SceneObjectGroup group
481 = SceneObjectSerializer.FromOriginalXmlFormat(itemId, xmlData);
482
483 if (!m_Scene.Permissions.CanRezObject(
484 group.Children.Count, remoteClient.AgentId, pos)
485 && !attachment)
486 {
487 // The client operates in no fail mode. It will
488 // have already removed the item from the folder
489 // if it's no copy.
490 // Put it back if it's not an attachment
491 //
492 if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!attachment))
493 remoteClient.SendBulkUpdateInventory(item);
494 return null;
495 }
496
497 group.ResetIDs();
498
499 if (attachment)
500 {
501 group.RootPart.ObjectFlags |= (uint)PrimFlags.Phantom;
502 group.RootPart.IsAttachment = true;
503 }
504
505 // For attachments, we must make sure that only a single object update occurs after we've finished
506 // all the necessary operations.
507 m_Scene.AddNewSceneObject(group, true, false);
508
509 // m_log.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z);
510 // if attachment we set it's asset id so object updates can reflect that
511 // if not, we set it's position in world.
512 if (!attachment)
513 {
514 group.ScheduleGroupForFullUpdate();
515
516 float offsetHeight = 0;
517 pos = m_Scene.GetNewRezLocation(
518 RayStart, RayEnd, RayTargetID, Quaternion.Identity,
519 BypassRayCast, bRayEndIsIntersection, true, group.GetAxisAlignedBoundingBox(out offsetHeight), false);
520 pos.Z += offsetHeight;
521 group.AbsolutePosition = pos;
522 // m_log.InfoFormat("rezx point for inventory rezz is {0} {1} {2} and offsetheight was {3}", pos.X, pos.Y, pos.Z, offsetHeight);
523
524 }
525 else
526 {
527 group.SetFromItemID(itemID);
528 }
529
530 SceneObjectPart rootPart = null;
531 try
532 {
533 rootPart = group.GetChildPart(group.UUID);
534 }
535 catch (NullReferenceException)
536 {
537 string isAttachment = "";
538
539 if (attachment)
540 isAttachment = " Object was an attachment";
541
542 m_log.Error("[AGENT INVENTORY]: Error rezzing ItemID: " + itemID + " object has no rootpart." + isAttachment);
543 }
544
545 // Since renaming the item in the inventory does not affect the name stored
546 // in the serialization, transfer the correct name from the inventory to the
547 // object itself before we rez.
548 rootPart.Name = item.Name;
549 rootPart.Description = item.Description;
550
551 List<SceneObjectPart> partList = new List<SceneObjectPart>(group.Children.Values);
552
553 group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
554 if (rootPart.OwnerID != item.Owner)
555 {
556 //Need to kill the for sale here
557 rootPart.ObjectSaleType = 0;
558 rootPart.SalePrice = 10;
559
560 if (m_Scene.Permissions.PropagatePermissions())
561 {
562 if ((item.CurrentPermissions & 8) != 0)
563 {
564 foreach (SceneObjectPart part in partList)
565 {
566 part.EveryoneMask = item.EveryOnePermissions;
567 part.NextOwnerMask = item.NextPermissions;
568 part.GroupMask = 0; // DO NOT propagate here
569 }
570 }
571
572 group.ApplyNextOwnerPermissions();
573 }
574 }
575
576 foreach (SceneObjectPart part in partList)
577 {
578 if (part.OwnerID != item.Owner)
579 {
580 part.LastOwnerID = part.OwnerID;
581 part.OwnerID = item.Owner;
582 part.Inventory.ChangeInventoryOwner(item.Owner);
583 }
584 else if (((item.CurrentPermissions & 8) != 0) && (!attachment)) // Slam!
585 {
586 part.EveryoneMask = item.EveryOnePermissions;
587 part.NextOwnerMask = item.NextPermissions;
588
589 part.GroupMask = 0; // DO NOT propagate here
590 }
591 }
592
593 rootPart.TrimPermissions();
594
595 if (!attachment)
596 {
597 if (group.RootPart.Shape.PCode == (byte)PCode.Prim)
598 {
599 group.ClearPartAttachmentData();
600 }
601
602 // Fire on_rez
603 group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 0);
604 rootPart.ParentGroup.ResumeScripts();
605
606 rootPart.ScheduleFullUpdate();
607 }
608
609 if (!m_Scene.Permissions.BypassPermissions())
610 {
611 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
612 {
613 // If this is done on attachments, no
614 // copy ones will be lost, so avoid it
615 //
616 if (!attachment)
617 {
618 List<UUID> uuids = new List<UUID>();
619 uuids.Add(item.ID);
620 m_Scene.InventoryService.DeleteItems(item.Owner, uuids);
621 }
622 }
623 }
624
625 return rootPart.ParentGroup;
626 }
627 }
628
629 return null;
630 }
631
632 public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
633 {
634 }
635
636 #endregion
637
638 #region Misc
639
640 /// <summary>
641 /// Create a new asset data structure.
642 /// </summary>
643 /// <param name="name"></param>
644 /// <param name="description"></param>
645 /// <param name="invType"></param>
646 /// <param name="assetType"></param>
647 /// <param name="data"></param>
648 /// <returns></returns>
649 private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID)
650 {
651 AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID);
652 asset.Description = description;
653 asset.Data = (data == null) ? new byte[1] : data;
654
655 return asset;
656 }
657
658 #endregion
659 }
660}
diff --git a/OpenSim/Region/CoreModules/Framework/Library/LibraryModule.cs b/OpenSim/Region/CoreModules/Framework/Library/LibraryModule.cs
index 13f58bd..36dae6b 100644
--- a/OpenSim/Region/CoreModules/Framework/Library/LibraryModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/Library/LibraryModule.cs
@@ -31,12 +31,13 @@ using System.Reflection;
31 31
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Framework.Communications; 33using OpenSim.Framework.Communications;
34using OpenSim.Framework.Communications.Cache; 34
35using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; 35using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver;
36using OpenSim.Region.Framework; 36using OpenSim.Region.Framework;
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Services.Interfaces; 39using OpenSim.Services.Interfaces;
40using OpenSim.Server.Base;
40 41
41using OpenMetaverse; 42using OpenMetaverse;
42using log4net; 43using log4net;
@@ -53,6 +54,8 @@ namespace OpenSim.Region.CoreModules.Framework.Library
53 private string m_LibraryName = "OpenSim Library"; 54 private string m_LibraryName = "OpenSim Library";
54 private Scene m_Scene; 55 private Scene m_Scene;
55 56
57 private ILibraryService m_Library;
58
56 #region ISharedRegionModule 59 #region ISharedRegionModule
57 60
58 public void Initialise(IConfigSource config) 61 public void Initialise(IConfigSource config)
@@ -60,9 +63,22 @@ namespace OpenSim.Region.CoreModules.Framework.Library
60 m_Enabled = config.Configs["Modules"].GetBoolean("LibraryModule", m_Enabled); 63 m_Enabled = config.Configs["Modules"].GetBoolean("LibraryModule", m_Enabled);
61 if (m_Enabled) 64 if (m_Enabled)
62 { 65 {
63 IConfig libConfig = config.Configs["LibraryModule"]; 66 IConfig libConfig = config.Configs["LibraryService"];
64 if (libConfig != null) 67 if (libConfig != null)
65 m_LibraryName = libConfig.GetString("LibraryName", m_LibraryName); 68 {
69 string dllName = libConfig.GetString("LocalServiceModule", string.Empty);
70 m_log.Debug("[LIBRARY MODULE]: Library service dll is " + dllName);
71 if (dllName != string.Empty)
72 {
73 Object[] args = new Object[] { config };
74 m_Library = ServerUtils.LoadPlugin<ILibraryService>(dllName, args);
75 }
76 }
77 }
78 if (m_Library == null)
79 {
80 m_log.Warn("[LIBRARY MODULE]: No local library service. Module will be disabled.");
81 m_Enabled = false;
66 } 82 }
67 } 83 }
68 84
@@ -91,10 +107,15 @@ namespace OpenSim.Region.CoreModules.Framework.Library
91 { 107 {
92 m_Scene = scene; 108 m_Scene = scene;
93 } 109 }
110 scene.RegisterModuleInterface<ILibraryService>(m_Library);
94 } 111 }
95 112
96 public void RemoveRegion(Scene scene) 113 public void RemoveRegion(Scene scene)
97 { 114 {
115 if (!m_Enabled)
116 return;
117
118 scene.UnregisterModuleInterface<ILibraryService>(m_Library);
98 } 119 }
99 120
100 public void RegionLoaded(Scene scene) 121 public void RegionLoaded(Scene scene)
@@ -127,27 +148,23 @@ namespace OpenSim.Region.CoreModules.Framework.Library
127 148
128 protected void LoadLibrariesFromArchives() 149 protected void LoadLibrariesFromArchives()
129 { 150 {
130 InventoryFolderImpl lib = m_Scene.CommsManager.UserProfileCacheService.LibraryRoot; 151 InventoryFolderImpl lib = m_Library.LibraryRootFolder;
131 if (lib == null) 152 if (lib == null)
132 { 153 {
133 m_log.Debug("[LIBRARY MODULE]: No library. Ignoring Library Module"); 154 m_log.Debug("[LIBRARY MODULE]: No library. Ignoring Library Module");
134 return; 155 return;
135 } 156 }
136 157
137 lib.Name = m_LibraryName;
138
139 RegionInfo regInfo = new RegionInfo(); 158 RegionInfo regInfo = new RegionInfo();
140 Scene m_MockScene = new Scene(regInfo); 159 Scene m_MockScene = new Scene(regInfo);
141 m_MockScene.CommsManager = m_Scene.CommsManager; 160 LocalInventoryService invService = new LocalInventoryService(lib);
142 LocalInventoryService invService = new LocalInventoryService((LibraryRootFolder)lib);
143 m_MockScene.RegisterModuleInterface<IInventoryService>(invService); 161 m_MockScene.RegisterModuleInterface<IInventoryService>(invService);
144 m_MockScene.RegisterModuleInterface<IAssetService>(m_Scene.AssetService); 162 m_MockScene.RegisterModuleInterface<IAssetService>(m_Scene.AssetService);
145 163
146 UserProfileData profile = new UserProfileData(); 164 UserAccount uinfo = new UserAccount(lib.Owner);
147 profile.FirstName = "OpenSim"; 165 uinfo.FirstName = "OpenSim";
148 profile.ID = lib.Owner; 166 uinfo.LastName = "Library";
149 profile.SurName = "Library"; 167 uinfo.ServiceURLs = new Dictionary<string, object>();
150 CachedUserInfo uinfo = new CachedUserInfo(invService, profile);
151 168
152 foreach (string iarFileName in Directory.GetFiles(pathToLibraries, "*.iar")) 169 foreach (string iarFileName in Directory.GetFiles(pathToLibraries, "*.iar"))
153 { 170 {
@@ -156,11 +173,11 @@ namespace OpenSim.Region.CoreModules.Framework.Library
156 m_log.InfoFormat("[LIBRARY MODULE]: Loading library archive {0} ({1})...", iarFileName, simpleName); 173 m_log.InfoFormat("[LIBRARY MODULE]: Loading library archive {0} ({1})...", iarFileName, simpleName);
157 simpleName = GetInventoryPathFromName(simpleName); 174 simpleName = GetInventoryPathFromName(simpleName);
158 175
176 InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, simpleName, iarFileName);
159 try 177 try
160 { 178 {
161 InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, simpleName, iarFileName);
162 List<InventoryNodeBase> nodes = archread.Execute(); 179 List<InventoryNodeBase> nodes = archread.Execute();
163 if (nodes.Count == 0) 180 if (nodes != null && nodes.Count == 0)
164 { 181 {
165 // didn't find the subfolder with the given name; place it on the top 182 // didn't find the subfolder with the given name; place it on the top
166 m_log.InfoFormat("[LIBRARY MODULE]: Didn't find {0} in library. Placing archive on the top level", simpleName); 183 m_log.InfoFormat("[LIBRARY MODULE]: Didn't find {0} in library. Placing archive on the top level", simpleName);
@@ -168,13 +185,39 @@ namespace OpenSim.Region.CoreModules.Framework.Library
168 archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, "/", iarFileName); 185 archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, "/", iarFileName);
169 archread.Execute(); 186 archread.Execute();
170 } 187 }
171 archread.Close(); 188 foreach (InventoryNodeBase node in nodes)
189 FixPerms(node);
172 } 190 }
173 catch (Exception e) 191 catch (Exception e)
174 { 192 {
175 m_log.DebugFormat("[LIBRARY MODULE]: Exception when processing archive {0}: {1}", iarFileName, e.Message); 193 m_log.DebugFormat("[LIBRARY MODULE]: Exception when processing archive {0}: {1}", iarFileName, e.StackTrace);
194 }
195 finally
196 {
197 archread.Close();
176 } 198 }
177 } 199 }
200
201 }
202
203 private void FixPerms(InventoryNodeBase node)
204 {
205 if (node is InventoryItemBase)
206 {
207 InventoryItemBase item = (InventoryItemBase)node;
208 item.BasePermissions = 0x7FFFFFFF;
209 item.EveryOnePermissions = 0x7FFFFFFF;
210 item.CurrentPermissions = 0x7FFFFFFF;
211 item.NextPermissions = 0x7FFFFFFF;
212 }
213 }
214
215 private void DumpLibrary()
216 {
217 InventoryFolderImpl lib = m_Library.LibraryRootFolder;
218
219 m_log.DebugFormat(" - folder {0}", lib.Name);
220 DumpFolder(lib);
178 } 221 }
179// 222//
180// private void DumpLibrary() 223// private void DumpLibrary()
diff --git a/OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs b/OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs
index 2c95b5a..49589fd 100644
--- a/OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs
+++ b/OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs
@@ -29,7 +29,7 @@ using System.Collections.Generic;
29using System.Reflection; 29using System.Reflection;
30 30
31using OpenSim.Framework; 31using OpenSim.Framework;
32using OpenSim.Framework.Communications.Cache; 32
33using OpenSim.Services.Interfaces; 33using OpenSim.Services.Interfaces;
34 34
35using OpenMetaverse; 35using OpenMetaverse;
@@ -41,9 +41,9 @@ namespace OpenSim.Region.CoreModules.Framework.Library
41 { 41 {
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43 43
44 private LibraryRootFolder m_Library; 44 private InventoryFolderImpl m_Library;
45 45
46 public LocalInventoryService(LibraryRootFolder lib) 46 public LocalInventoryService(InventoryFolderImpl lib)
47 { 47 {
48 m_Library = lib; 48 m_Library = lib;
49 } 49 }
diff --git a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs b/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs
deleted file mode 100644
index 0b54746..0000000
--- a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs
+++ /dev/null
@@ -1,311 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Net;
32using System.Reflection;
33using System.Text.RegularExpressions;
34using log4net;
35using Nini.Config;
36using OpenMetaverse;
37using Nwc.XmlRpc;
38using OpenSim.Framework;
39using OpenSim.Framework.Communications;
40using OpenSim.Framework.Communications.Services;
41using OpenSim.Framework.Communications.Cache;
42using OpenSim.Framework.Capabilities;
43using OpenSim.Framework.Servers.HttpServer;
44using OpenSim.Region.Framework.Scenes;
45using OpenSim.Region.Framework.Interfaces;
46
47namespace OpenSim.Region.CoreModules.Hypergrid
48{
49 public class HGStandaloneLoginModule : IRegionModule, ILoginServiceToRegionsConnector
50 {
51 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
52
53 protected List<Scene> m_scenes = new List<Scene>();
54 protected Scene m_firstScene;
55
56 protected bool m_enabled = false; // Module is only enabled if running in standalone mode
57
58 protected HGLoginAuthService m_loginService;
59
60 #region IRegionModule Members
61
62 public void Initialise(Scene scene, IConfigSource source)
63 {
64 if (m_firstScene == null)
65 {
66 m_firstScene = scene;
67
68 IConfig startupConfig = source.Configs["Startup"];
69 if (startupConfig != null)
70 {
71 m_enabled = !startupConfig.GetBoolean("gridmode", false);
72 }
73
74 if (m_enabled)
75 {
76 m_log.Debug("[HGLogin]: HGlogin module enabled");
77 bool authenticate = true;
78 string welcomeMessage = "Welcome to OpenSim";
79 IConfig standaloneConfig = source.Configs["StandAlone"];
80 if (standaloneConfig != null)
81 {
82 authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
83 welcomeMessage = standaloneConfig.GetString("welcome_message");
84 }
85
86 //TODO: fix casting.
87 LibraryRootFolder rootFolder = m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder;
88
89 IHttpServer httpServer = MainServer.Instance;
90
91 //TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference
92 m_loginService
93 = new HGLoginAuthService(
94 (UserManagerBase)m_firstScene.CommsManager.UserAdminService,
95 welcomeMessage,
96 m_firstScene.CommsManager.InterServiceInventoryService,
97 m_firstScene.CommsManager.NetworkServersInfo,
98 authenticate,
99 rootFolder,
100 this);
101
102 httpServer.AddXmlRPCHandler("hg_login", m_loginService.XmlRpcLoginMethod);
103 httpServer.AddXmlRPCHandler("check_auth_session", m_loginService.XmlRPCCheckAuthSession, false);
104 httpServer.AddXmlRPCHandler("get_avatar_appearance", XmlRPCGetAvatarAppearance);
105 httpServer.AddXmlRPCHandler("update_avatar_appearance", XmlRPCUpdateAvatarAppearance);
106
107 }
108 }
109
110 if (m_enabled)
111 {
112 AddScene(scene);
113 }
114 }
115
116 public void PostInitialise()
117 {
118
119 }
120
121 public void Close()
122 {
123
124 }
125
126 public string Name
127 {
128 get { return "HGStandaloneLoginModule"; }
129 }
130
131 public bool IsSharedModule
132 {
133 get { return true; }
134 }
135
136 #endregion
137
138 protected void AddScene(Scene scene)
139 {
140 lock (m_scenes)
141 {
142 if (!m_scenes.Contains(scene))
143 {
144 m_scenes.Add(scene);
145 }
146 }
147 }
148
149 public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent, out string reason)
150 {
151 reason = String.Empty;
152 return true;
153 }
154
155 public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message)
156 {
157 Scene scene;
158 if (TryGetRegion(regionHandle, out scene))
159 {
160 scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message);
161 }
162 }
163
164 public RegionInfo RequestNeighbourInfo(ulong regionhandle)
165 {
166 Scene scene;
167 if (TryGetRegion(regionhandle, out scene))
168 {
169 return scene.RegionInfo;
170 }
171 return null;
172 }
173
174 public RegionInfo RequestClosestRegion(string region)
175 {
176 Scene scene;
177 if (TryGetRegion(region, out scene))
178 {
179 return scene.RegionInfo;
180 }
181 else if (m_scenes.Count > 0)
182 {
183 return m_scenes[0].RegionInfo;
184 }
185 return null;
186 }
187
188 public RegionInfo RequestNeighbourInfo(UUID regionID)
189 {
190 Scene scene;
191 if (TryGetRegion(regionID, out scene))
192 {
193 return scene.RegionInfo;
194 }
195 return null;
196 }
197
198 protected bool TryGetRegion(ulong regionHandle, out Scene scene)
199 {
200 lock (m_scenes)
201 {
202 foreach (Scene nextScene in m_scenes)
203 {
204 if (nextScene.RegionInfo.RegionHandle == regionHandle)
205 {
206 scene = nextScene;
207 return true;
208 }
209 }
210 }
211
212 scene = null;
213 return false;
214 }
215
216 protected bool TryGetRegion(UUID regionID, out Scene scene)
217 {
218 lock (m_scenes)
219 {
220 foreach (Scene nextScene in m_scenes)
221 {
222 if (nextScene.RegionInfo.RegionID == regionID)
223 {
224 scene = nextScene;
225 return true;
226 }
227 }
228 }
229
230 scene = null;
231 return false;
232 }
233
234 protected bool TryGetRegion(string regionName, out Scene scene)
235 {
236 lock (m_scenes)
237 {
238 foreach (Scene nextScene in m_scenes)
239 {
240 if (nextScene.RegionInfo.RegionName.Equals(regionName, StringComparison.InvariantCultureIgnoreCase))
241 {
242 scene = nextScene;
243 return true;
244 }
245 }
246 }
247
248 scene = null;
249 return false;
250 }
251
252 public XmlRpcResponse XmlRPCGetAvatarAppearance(XmlRpcRequest request, IPEndPoint remoteClient)
253 {
254 XmlRpcResponse response = new XmlRpcResponse();
255 Hashtable requestData = (Hashtable)request.Params[0];
256 AvatarAppearance appearance;
257 Hashtable responseData;
258 if (requestData.Contains("owner"))
259 {
260 appearance = m_firstScene.CommsManager.AvatarService.GetUserAppearance(new UUID((string)requestData["owner"]));
261 if (appearance == null)
262 {
263 responseData = new Hashtable();
264 responseData["error_type"] = "no appearance";
265 responseData["error_desc"] = "There was no appearance found for this avatar";
266 }
267 else
268 {
269 responseData = appearance.ToHashTable();
270 }
271 }
272 else
273 {
274 responseData = new Hashtable();
275 responseData["error_type"] = "unknown_avatar";
276 responseData["error_desc"] = "The avatar appearance requested is not in the database";
277 }
278
279 response.Value = responseData;
280 return response;
281 }
282
283 public XmlRpcResponse XmlRPCUpdateAvatarAppearance(XmlRpcRequest request, IPEndPoint remoteClient)
284 {
285 XmlRpcResponse response = new XmlRpcResponse();
286 Hashtable requestData = (Hashtable)request.Params[0];
287 Hashtable responseData;
288 if (requestData.Contains("owner"))
289 {
290 AvatarAppearance appearance = new AvatarAppearance(requestData);
291
292 // TODO: Sometime in the future we may have a database layer that is capable of updating appearance when
293 // the TextureEntry is null. When that happens, this check can be removed
294 if (appearance.Texture != null)
295 m_firstScene.CommsManager.AvatarService.UpdateUserAppearance(new UUID((string)requestData["owner"]), appearance);
296
297 responseData = new Hashtable();
298 responseData["returnString"] = "TRUE";
299 }
300 else
301 {
302 responseData = new Hashtable();
303 responseData["error_type"] = "unknown_avatar";
304 responseData["error_desc"] = "The avatar appearance requested is not in the database";
305 }
306 response.Value = responseData;
307 return response;
308 }
309 }
310
311}
diff --git a/OpenSim/Region/CoreModules/InterGrid/OGSRadmin.cs b/OpenSim/Region/CoreModules/InterGrid/OGSRadmin.cs
index 0f2ba32..b7d3904 100644
--- a/OpenSim/Region/CoreModules/InterGrid/OGSRadmin.cs
+++ b/OpenSim/Region/CoreModules/InterGrid/OGSRadmin.cs
@@ -46,7 +46,6 @@ namespace OpenSim.Region.CoreModules.InterGrid
46 { 46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48 private readonly List<Scene> m_scenes = new List<Scene>(); 48 private readonly List<Scene> m_scenes = new List<Scene>();
49 private CommunicationsManager m_com;
50 private IConfigSource m_settings; 49 private IConfigSource m_settings;
51 50
52 #region Implementation of IRegionModuleBase 51 #region Implementation of IRegionModuleBase
@@ -88,7 +87,6 @@ namespace OpenSim.Region.CoreModules.InterGrid
88 { 87 {
89 if (m_settings.Configs["Startup"].GetBoolean("gridmode", false)) 88 if (m_settings.Configs["Startup"].GetBoolean("gridmode", false))
90 { 89 {
91 m_com = m_scenes[0].CommsManager;
92 MainServer.Instance.AddXmlRPCHandler("grid_message", GridWideMessage); 90 MainServer.Instance.AddXmlRPCHandler("grid_message", GridWideMessage);
93 } 91 }
94 } 92 }
@@ -119,14 +117,15 @@ namespace OpenSim.Region.CoreModules.InterGrid
119 117
120 Hashtable requestData = (Hashtable)req.Params[0]; 118 Hashtable requestData = (Hashtable)req.Params[0];
121 119
122 if ((!requestData.Contains("password") || (string)requestData["password"] != m_com.NetworkServersInfo.GridRecvKey)) 120 // REFACTORING PROBLEM. This authorization needs to be replaced with some other
123 { 121 //if ((!requestData.Contains("password") || (string)requestData["password"] != m_com.NetworkServersInfo.GridRecvKey))
124 responseData["accepted"] = false; 122 //{
125 responseData["success"] = false; 123 // responseData["accepted"] = false;
126 responseData["error"] = "Invalid Key"; 124 // responseData["success"] = false;
127 response.Value = responseData; 125 // responseData["error"] = "Invalid Key";
128 return response; 126 // response.Value = responseData;
129 } 127 // return response;
128 //}
130 129
131 string message = (string)requestData["message"]; 130 string message = (string)requestData["message"];
132 string user = (string)requestData["user"]; 131 string user = (string)requestData["user"];
diff --git a/OpenSim/Region/CoreModules/InterGrid/OpenGridProtocolModule.cs b/OpenSim/Region/CoreModules/InterGrid/OpenGridProtocolModule.cs
index 10a3232..e95d2f8 100644
--- a/OpenSim/Region/CoreModules/InterGrid/OpenGridProtocolModule.cs
+++ b/OpenSim/Region/CoreModules/InterGrid/OpenGridProtocolModule.cs
@@ -528,32 +528,34 @@ namespace OpenSim.Region.CoreModules.InterGrid
528 userProfile.PasswordHash = "$1$"; 528 userProfile.PasswordHash = "$1$";
529 userProfile.PasswordSalt = ""; 529 userProfile.PasswordSalt = "";
530 userProfile.SurName = agentData.lastname; 530 userProfile.SurName = agentData.lastname;
531 userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL; 531 //userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL;
532 userProfile.UserFlags = 0; 532 userProfile.UserFlags = 0;
533 userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL; 533 //userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL;
534 userProfile.WantDoMask = 0; 534 userProfile.WantDoMask = 0;
535 userProfile.WebLoginKey = UUID.Random(); 535 userProfile.WebLoginKey = UUID.Random();
536 536
537 // Do caps registration 537 // !!! REFACTORING PROBLEM. This needs to be changed for 0.7
538 // get seed capagentData.firstname = FirstName;agentData.lastname = LastName; 538 //
539 if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode) 539 //// Do caps registration
540 { 540 //// get seed capagentData.firstname = FirstName;agentData.lastname = LastName;
541 homeScene.CommsManager.UserAdminService.AddUser( 541 //if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode)
542 agentData.firstname, agentData.lastname, CreateRandomStr(7), "", 542 //{
543 homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID); 543 // homeScene.CommsManager.UserAdminService.AddUser(
544 // agentData.firstname, agentData.lastname, CreateRandomStr(7), "",
545 // homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID);
544 546
545 UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID); 547 // UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID);
546 if (userProfile2 != null) 548 // if (userProfile2 != null)
547 { 549 // {
548 userProfile = userProfile2; 550 // userProfile = userProfile2;
549 userProfile.AboutText = "OGP USER"; 551 // userProfile.AboutText = "OGP USER";
550 userProfile.FirstLifeAboutText = "OGP USER"; 552 // userProfile.FirstLifeAboutText = "OGP USER";
551 homeScene.CommsManager.UserService.UpdateUserProfile(userProfile); 553 // homeScene.CommsManager.UserService.UpdateUserProfile(userProfile);
552 } 554 // }
553 } 555 //}
554 556
555 // Stick our data in the cache so the region will know something about us 557 //// Stick our data in the cache so the region will know something about us
556 homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile); 558 //homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile);
557 559
558 // Call 'new user' event handler 560 // Call 'new user' event handler
559 string reason; 561 string reason;
@@ -1204,7 +1206,7 @@ namespace OpenSim.Region.CoreModules.InterGrid
1204 { 1206 {
1205 Scene homeScene = GetRootScene(); 1207 Scene homeScene = GetRootScene();
1206 ScenePresence avatar = null; 1208 ScenePresence avatar = null;
1207 if (homeScene.TryGetAvatar(avatarId,out avatar)) 1209 if (homeScene.TryGetScenePresence(avatarId,out avatar))
1208 { 1210 {
1209 KillAUser ku = new KillAUser(avatar,mod); 1211 KillAUser ku = new KillAUser(avatar,mod);
1210 Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true); 1212 Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true);
diff --git a/OpenSim/Region/CoreModules/World/Meta7Windlight/Meta7WindlightModule.cs b/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs
index 72b0b38..e6cab1d 100644
--- a/OpenSim/Region/CoreModules/World/Meta7Windlight/Meta7WindlightModule.cs
+++ b/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs
@@ -1,9 +1,28 @@
1/* 1/*
2 * Copyright (c) Thomas Grimshaw and Magne Metaverse Research 2 * Copyright (c) Contributors, http://opensimulator.org/
3 * 3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 * This module is not open source. All rights reserved.
5 * Unauthorised copying, distribution or public display is prohibited.
6 * 4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7 */ 26 */
8 27
9using System; 28using System;
@@ -20,9 +39,9 @@ using OpenSim.Region.Framework.Interfaces;
20using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
21 40
22 41
23namespace OpenSim.Region.CoreModules.World.Meta7Windlight 42namespace OpenSim.Region.CoreModules.World.LightShare
24{ 43{
25 public class Meta7WindlightModule : IRegionModule, ICommandableModule 44 public class LightShareModule : IRegionModule, ICommandableModule
26 { 45 {
27 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
28 private readonly Commander m_commander = new Commander("windlight"); 47 private readonly Commander m_commander = new Commander("windlight");
@@ -60,7 +79,7 @@ namespace OpenSim.Region.CoreModules.World.Meta7Windlight
60 // ini file settings 79 // ini file settings
61 try 80 try
62 { 81 {
63 m_enableWindlight = config.Configs["Meta7Windlight"].GetBoolean("enable_windlight", false); 82 m_enableWindlight = config.Configs["LightShare"].GetBoolean("enable_windlight", false);
64 } 83 }
65 catch (Exception) 84 catch (Exception)
66 { 85 {
@@ -70,68 +89,68 @@ namespace OpenSim.Region.CoreModules.World.Meta7Windlight
70 if (m_enableWindlight) 89 if (m_enableWindlight)
71 { 90 {
72 m_scene.EventManager.OnMakeRootAgent += EventManager_OnMakeRootAgent; 91 m_scene.EventManager.OnMakeRootAgent += EventManager_OnMakeRootAgent;
73 m_scene.EventManager.OnSaveNewWindlightProfile += EventManager_OnSaveNewWindlightProfile; 92 m_scene.EventManager.OnSaveNewWindlightProfile += EventManager_OnSaveNewWindlightProfile;
74 m_scene.EventManager.OnSendNewWindlightProfileTargeted += EventManager_OnSendNewWindlightProfileTargeted; 93 m_scene.EventManager.OnSendNewWindlightProfileTargeted += EventManager_OnSendNewWindlightProfileTargeted;
75 } 94 }
76 95
77 InstallCommands(); 96 InstallCommands();
78 97
79 m_log.Debug("[WINDLIGHT]: Initialised windlight module"); 98 m_log.Debug("[WINDLIGHT]: Initialised windlight module");
80 } 99 }
81 100
82 private List<byte[]> compileWindlightSettings(RegionMeta7WindlightData wl) 101 private List<byte[]> compileWindlightSettings(RegionLightShareData wl)
83 { 102 {
84 byte[] mBlock = new Byte[249]; 103 byte[] mBlock = new Byte[249];
85 int pos = 0; 104 int pos = 0;
86 105
87 wl.waterColor.ToBytes(mBlock, 0); pos += 12; 106 wl.waterColor.ToBytes(mBlock, 0); pos += 12;
88 Utils.FloatToBytes(wl.waterFogDensityExponent).CopyTo(mBlock, pos); pos += 4; 107 Utils.FloatToBytes(wl.waterFogDensityExponent).CopyTo(mBlock, pos); pos += 4;
89 Utils.FloatToBytes(wl.underwaterFogModifier).CopyTo(mBlock, pos); pos += 4; 108 Utils.FloatToBytes(wl.underwaterFogModifier).CopyTo(mBlock, pos); pos += 4;
90 wl.reflectionWaveletScale.ToBytes(mBlock, pos); pos += 12; 109 wl.reflectionWaveletScale.ToBytes(mBlock, pos); pos += 12;
91 Utils.FloatToBytes(wl.fresnelScale).CopyTo(mBlock, pos); pos += 4; 110 Utils.FloatToBytes(wl.fresnelScale).CopyTo(mBlock, pos); pos += 4;
92 Utils.FloatToBytes(wl.fresnelOffset).CopyTo(mBlock, pos); pos += 4; 111 Utils.FloatToBytes(wl.fresnelOffset).CopyTo(mBlock, pos); pos += 4;
93 Utils.FloatToBytes(wl.refractScaleAbove).CopyTo(mBlock, pos); pos += 4; 112 Utils.FloatToBytes(wl.refractScaleAbove).CopyTo(mBlock, pos); pos += 4;
94 Utils.FloatToBytes(wl.refractScaleBelow).CopyTo(mBlock, pos); pos += 4; 113 Utils.FloatToBytes(wl.refractScaleBelow).CopyTo(mBlock, pos); pos += 4;
95 Utils.FloatToBytes(wl.blurMultiplier).CopyTo(mBlock, pos); pos += 4; 114 Utils.FloatToBytes(wl.blurMultiplier).CopyTo(mBlock, pos); pos += 4;
96 wl.bigWaveDirection.ToBytes(mBlock, pos); pos += 8; 115 wl.bigWaveDirection.ToBytes(mBlock, pos); pos += 8;
97 wl.littleWaveDirection.ToBytes(mBlock, pos); pos += 8; 116 wl.littleWaveDirection.ToBytes(mBlock, pos); pos += 8;
98 wl.normalMapTexture.ToBytes(mBlock, pos); pos += 16; 117 wl.normalMapTexture.ToBytes(mBlock, pos); pos += 16;
99 wl.horizon.ToBytes(mBlock, pos); pos += 16; 118 wl.horizon.ToBytes(mBlock, pos); pos += 16;
100 Utils.FloatToBytes(wl.hazeHorizon).CopyTo(mBlock, pos); pos += 4; 119 Utils.FloatToBytes(wl.hazeHorizon).CopyTo(mBlock, pos); pos += 4;
101 wl.blueDensity.ToBytes(mBlock, pos); pos += 16; 120 wl.blueDensity.ToBytes(mBlock, pos); pos += 16;
102 Utils.FloatToBytes(wl.hazeDensity).CopyTo(mBlock, pos); pos += 4; 121 Utils.FloatToBytes(wl.hazeDensity).CopyTo(mBlock, pos); pos += 4;
103 Utils.FloatToBytes(wl.densityMultiplier).CopyTo(mBlock, pos); pos += 4; 122 Utils.FloatToBytes(wl.densityMultiplier).CopyTo(mBlock, pos); pos += 4;
104 Utils.FloatToBytes(wl.distanceMultiplier).CopyTo(mBlock, pos); pos += 4; 123 Utils.FloatToBytes(wl.distanceMultiplier).CopyTo(mBlock, pos); pos += 4;
105 wl.sunMoonColor.ToBytes(mBlock, pos); pos += 16; 124 wl.sunMoonColor.ToBytes(mBlock, pos); pos += 16;
106 Utils.FloatToBytes(wl.sunMoonPosition).CopyTo(mBlock, pos); pos += 4; 125 Utils.FloatToBytes(wl.sunMoonPosition).CopyTo(mBlock, pos); pos += 4;
107 wl.ambient.ToBytes(mBlock, pos); pos += 16; 126 wl.ambient.ToBytes(mBlock, pos); pos += 16;
108 Utils.FloatToBytes(wl.eastAngle).CopyTo(mBlock, pos); pos += 4; 127 Utils.FloatToBytes(wl.eastAngle).CopyTo(mBlock, pos); pos += 4;
109 Utils.FloatToBytes(wl.sunGlowFocus).CopyTo(mBlock, pos); pos += 4; 128 Utils.FloatToBytes(wl.sunGlowFocus).CopyTo(mBlock, pos); pos += 4;
110 Utils.FloatToBytes(wl.sunGlowSize).CopyTo(mBlock, pos); pos += 4; 129 Utils.FloatToBytes(wl.sunGlowSize).CopyTo(mBlock, pos); pos += 4;
111 Utils.FloatToBytes(wl.sceneGamma).CopyTo(mBlock, pos); pos += 4; 130 Utils.FloatToBytes(wl.sceneGamma).CopyTo(mBlock, pos); pos += 4;
112 Utils.FloatToBytes(wl.starBrightness).CopyTo(mBlock, pos); pos += 4; 131 Utils.FloatToBytes(wl.starBrightness).CopyTo(mBlock, pos); pos += 4;
113 wl.cloudColor.ToBytes(mBlock, pos); pos += 16; 132 wl.cloudColor.ToBytes(mBlock, pos); pos += 16;
114 wl.cloudXYDensity.ToBytes(mBlock, pos); pos += 12; 133 wl.cloudXYDensity.ToBytes(mBlock, pos); pos += 12;
115 Utils.FloatToBytes(wl.cloudCoverage).CopyTo(mBlock, pos); pos += 4; 134 Utils.FloatToBytes(wl.cloudCoverage).CopyTo(mBlock, pos); pos += 4;
116 Utils.FloatToBytes(wl.cloudScale).CopyTo(mBlock, pos); pos += 4; 135 Utils.FloatToBytes(wl.cloudScale).CopyTo(mBlock, pos); pos += 4;
117 wl.cloudDetailXYDensity.ToBytes(mBlock, pos); pos += 12; 136 wl.cloudDetailXYDensity.ToBytes(mBlock, pos); pos += 12;
118 Utils.FloatToBytes(wl.cloudScrollX).CopyTo(mBlock, pos); pos += 4; 137 Utils.FloatToBytes(wl.cloudScrollX).CopyTo(mBlock, pos); pos += 4;
119 Utils.FloatToBytes(wl.cloudScrollY).CopyTo(mBlock, pos); pos += 4; 138 Utils.FloatToBytes(wl.cloudScrollY).CopyTo(mBlock, pos); pos += 4;
120 Utils.UInt16ToBytes(wl.maxAltitude).CopyTo(mBlock, pos); pos += 2; 139 Utils.UInt16ToBytes(wl.maxAltitude).CopyTo(mBlock, pos); pos += 2;
121 mBlock[pos] = Convert.ToByte(wl.cloudScrollXLock); pos++; 140 mBlock[pos] = Convert.ToByte(wl.cloudScrollXLock); pos++;
122 mBlock[pos] = Convert.ToByte(wl.cloudScrollYLock); pos++; 141 mBlock[pos] = Convert.ToByte(wl.cloudScrollYLock); pos++;
123 mBlock[pos] = Convert.ToByte(wl.drawClassicClouds); pos++; 142 mBlock[pos] = Convert.ToByte(wl.drawClassicClouds); pos++;
124 List<byte[]> param = new List<byte[]>(); 143 List<byte[]> param = new List<byte[]>();
125 param.Add(mBlock); 144 param.Add(mBlock);
126 return param; 145 return param;
127 } 146 }
128 public void SendProfileToClient(ScenePresence presence) 147 public void SendProfileToClient(ScenePresence presence)
129 { 148 {
130 IClientAPI client = presence.ControllingClient; 149 IClientAPI client = presence.ControllingClient;
131 if (m_enableWindlight) 150 if (m_enableWindlight)
132 { 151 {
133 if (presence.IsChildAgent == false) 152 if (presence.IsChildAgent == false)
134 { 153 {
135 List<byte[]> param = compileWindlightSettings(m_scene.RegionInfo.WindlightSettings); 154 List<byte[]> param = compileWindlightSettings(m_scene.RegionInfo.WindlightSettings);
136 client.SendGenericMessage("Windlight", param); 155 client.SendGenericMessage("Windlight", param);
137 } 156 }
@@ -141,36 +160,36 @@ namespace OpenSim.Region.CoreModules.World.Meta7Windlight
141 //We probably don't want to spam chat with this.. probably 160 //We probably don't want to spam chat with this.. probably
142 //m_log.Debug("[WINDLIGHT]: Module disabled"); 161 //m_log.Debug("[WINDLIGHT]: Module disabled");
143 } 162 }
144 } 163 }
145 public void SendProfileToClient(ScenePresence presence, RegionMeta7WindlightData wl) 164 public void SendProfileToClient(ScenePresence presence, RegionLightShareData wl)
146 { 165 {
147 IClientAPI client = presence.ControllingClient; 166 IClientAPI client = presence.ControllingClient;
148 if (m_enableWindlight) 167 if (m_enableWindlight)
149 { 168 {
150 if (presence.IsChildAgent == false) 169 if (presence.IsChildAgent == false)
151 { 170 {
152 List<byte[]> param = compileWindlightSettings(wl); 171 List<byte[]> param = compileWindlightSettings(wl);
153 client.SendGenericMessage("Windlight", param); 172 client.SendGenericMessage("Windlight", param);
154 } 173 }
155 } 174 }
156 else 175 else
157 { 176 {
158 //We probably don't want to spam chat with this.. probably 177 //We probably don't want to spam chat with this.. probably
159 //m_log.Debug("[WINDLIGHT]: Module disabled"); 178 //m_log.Debug("[WINDLIGHT]: Module disabled");
160 } 179 }
161 } 180 }
162 private void EventManager_OnMakeRootAgent(ScenePresence presence) 181 private void EventManager_OnMakeRootAgent(ScenePresence presence)
163 { 182 {
164 m_log.Debug("[WINDLIGHT]: Sending windlight scene to new client"); 183 m_log.Debug("[WINDLIGHT]: Sending windlight scene to new client");
165 SendProfileToClient(presence); 184 SendProfileToClient(presence);
166 } 185 }
167 private void EventManager_OnSendNewWindlightProfileTargeted(RegionMeta7WindlightData wl, UUID pUUID) 186 private void EventManager_OnSendNewWindlightProfileTargeted(RegionLightShareData wl, UUID pUUID)
168 { 187 {
169 ScenePresence Sc; 188 ScenePresence Sc;
170 if (m_scene.TryGetAvatar(pUUID,out Sc)) 189 if (m_scene.TryGetScenePresence(pUUID,out Sc))
171 { 190 {
172 SendProfileToClient(Sc,wl); 191 SendProfileToClient(Sc,wl);
173 } 192 }
174 } 193 }
175 private void EventManager_OnSaveNewWindlightProfile() 194 private void EventManager_OnSaveNewWindlightProfile()
176 { 195 {
@@ -188,7 +207,7 @@ namespace OpenSim.Region.CoreModules.World.Meta7Windlight
188 207
189 public string Name 208 public string Name
190 { 209 {
191 get { return "Meta7WindlightModule"; } 210 get { return "LightShareModule"; }
192 } 211 }
193 212
194 public bool IsSharedModule 213 public bool IsSharedModule
diff --git a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml
index ebc7f59..ee07075 100644
--- a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml
+++ b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml
@@ -8,6 +8,10 @@
8 </Dependencies> 8 </Dependencies>
9 9
10 <Extension path = "/OpenSim/RegionModules"> 10 <Extension path = "/OpenSim/RegionModules">
11 <RegionModule id="EntityTransferModule" type="OpenSim.Region.CoreModules.Framework.EntityTransfer.EntityTransferModule" />
12 <RegionModule id="HGEntityTransferModule" type="OpenSim.Region.CoreModules.Framework.EntityTransfer.HGEntityTransferModule" />
13 <RegionModule id="InventoryAccessModule" type="OpenSim.Region.CoreModules.Framework.InventoryAccess.BasicInventoryAccessModule" />
14 <RegionModule id="HGInventoryAccessModule" type="OpenSim.Region.CoreModules.Framework.InventoryAccess.HGInventoryAccessModule" />
11 <RegionModule id="LandManagementModule" type="OpenSim.Region.CoreModules.World.Land.LandManagementModule" /> 15 <RegionModule id="LandManagementModule" type="OpenSim.Region.CoreModules.World.Land.LandManagementModule" />
12 <RegionModule id="ExportSerialisationModule" type="OpenSim.Region.CoreModules.World.Serialiser.SerialiserModule" /> 16 <RegionModule id="ExportSerialisationModule" type="OpenSim.Region.CoreModules.World.Serialiser.SerialiserModule" />
13 <RegionModule id="ArchiverModule" type="OpenSim.Region.CoreModules.World.Archiver.ArchiverModule" /> 17 <RegionModule id="ArchiverModule" type="OpenSim.Region.CoreModules.World.Archiver.ArchiverModule" />
@@ -17,36 +21,59 @@
17 <RegionModule id="HGWorldMapModule" type="OpenSim.Region.CoreModules.Hypergrid.HGWorldMapModule" /> 21 <RegionModule id="HGWorldMapModule" type="OpenSim.Region.CoreModules.Hypergrid.HGWorldMapModule" />
18 <RegionModule id="UrlModule" type="OpenSim.Region.CoreModules.Scripting.LSLHttp.UrlModule" /> 22 <RegionModule id="UrlModule" type="OpenSim.Region.CoreModules.Scripting.LSLHttp.UrlModule" />
19 <RegionModule id="Chat" type="OpenSim.Region.CoreModules.Avatar.Chat.ChatModule" /> 23 <RegionModule id="Chat" type="OpenSim.Region.CoreModules.Avatar.Chat.ChatModule" />
24 <RegionModule id="FriendsModule" type="OpenSim.Region.CoreModules.Avatar.Friends.FriendsModule" />
25 <RegionModule id="PresenceModule" type="OpenSim.Region.CoreModules.Avatar.InstantMessage.PresenceModule" />
26 <RegionModule id="MuteListModule" type="OpenSim.Region.CoreModules.Avatar.InstantMessage.MuteListModule" />
27 <RegionModule id="OfflineMessageModule" type="OpenSim.Region.CoreModules.Avatar.InstantMessage.OfflineMessageModule" />
28 <RegionModule id="InstantMessageModule" type="OpenSim.Region.CoreModules.Avatar.InstantMessage.InstantMessageModule" />
29 <RegionModule id="MessageTransferModule" type="OpenSim.Region.CoreModules.Avatar.InstantMessage.MessageTransferModule" />
30 <RegionModule id="LureModule" type="OpenSim.Region.CoreModules.Avatar.Lure.LureModule" />
31 <RegionModule id="InventoryTransferModule" type="OpenSim.Region.CoreModules.Avatar.Inventory.Transfer.InventoryTransferModule" />
20 <RegionModule id="CoreAssetCache" type="OpenSim.Region.CoreModules.Asset.CoreAssetCache" /> 32 <RegionModule id="CoreAssetCache" type="OpenSim.Region.CoreModules.Asset.CoreAssetCache" />
21 <RegionModule id="GlynnTuckerAssetCache" type="OpenSim.Region.CoreModules.Asset.GlynnTuckerAssetCache" /> 33 <RegionModule id="GlynnTuckerAssetCache" type="OpenSim.Region.CoreModules.Asset.GlynnTuckerAssetCache" />
22 <RegionModule id="CenomeMemoryAssetCache" type="OpenSim.Region.CoreModules.Asset.CenomeMemoryAssetCache"/> 34 <RegionModule id="CenomeMemoryAssetCache" type="OpenSim.Region.CoreModules.Asset.CenomeMemoryAssetCache"/>
23 <RegionModule id="LibraryModule" type="OpenSim.Region.CoreModules.Framework.Library.LibraryModule"/> 35 <RegionModule id="LibraryModule" type="OpenSim.Region.CoreModules.Framework.Library.LibraryModule"/>
24 <!-- Service connectors OUT modules --> 36 <!-- Service connectors OUT modules -->
25 <RegionModule id="LocalUserServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.User.LocalUserServicesConnector" />
26 <RegionModule id="RemoteUserServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.User.RemoteUserServicesConnector" />
27 <RegionModule id="LocalAssetServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.LocalAssetServicesConnector" /> 37 <RegionModule id="LocalAssetServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.LocalAssetServicesConnector" />
28 <RegionModule id="RemoteAssetServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.RemoteAssetServicesConnector" /> 38 <RegionModule id="RemoteAssetServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.RemoteAssetServicesConnector" />
39 <RegionModule id="LocalAvatarServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Avatar.LocalAvatarServicesConnector" />
40 <RegionModule id="RemoteAvatarServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Avatar.RemoteAvatarServicesConnector" />
41 <RegionModule id="LocalAuthenticationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication.LocalAuthenticationServicesConnector" />
42 <RegionModule id="RemoteAuthenticationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication.RemoteAuthenticationServicesConnector" />
29 <RegionModule id="LocalAuthorizationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization.LocalAuthorizationServicesConnector" /> 43 <RegionModule id="LocalAuthorizationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization.LocalAuthorizationServicesConnector" />
30 <RegionModule id="RemoteAuthorizationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization.RemoteAuthorizationServicesConnector" /> 44 <RegionModule id="RemoteAuthorizationServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization.RemoteAuthorizationServicesConnector" />
31 <RegionModule id="HGAssetBroker" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.HGAssetBroker" /> 45 <RegionModule id="HGAssetBroker" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset.HGAssetBroker" />
32 <RegionModule id="LocalInventoryServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.LocalInventoryServicesConnector" /> 46 <RegionModule id="LocalInventoryServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.LocalInventoryServicesConnector" />
33 <RegionModule id="RemoteInventoryServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.RemoteInventoryServicesConnector" /> 47 <RegionModule id="RemoteInventoryServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.RemoteInventoryServicesConnector" />
48 <RegionModule id="RemoteXInventoryServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.RemoteXInventoryServicesConnector" />
34 <RegionModule id="HGInventoryBroker" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.HGInventoryBroker" /> 49 <RegionModule id="HGInventoryBroker" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory.HGInventoryBroker" />
35 <RegionModule id="LocalNeighbourServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour.LocalNeighbourServicesConnector" /> 50 <RegionModule id="LocalNeighbourServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour.LocalNeighbourServicesConnector" />
36 <RegionModule id="RemoteNeighbourServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour.RemoteNeighbourServicesConnector" /> 51 <RegionModule id="RemoteNeighbourServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour.RemoteNeighbourServicesConnector" />
37 <RegionModule id="LocalLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.LocalLandServicesConnector" /> 52 <RegionModule id="LocalLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.LocalLandServicesConnector" />
38 <RegionModule id="RemoteLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.RemoteLandServicesConnector" /> 53 <RegionModule id="RemoteLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.RemoteLandServicesConnector" />
39 <RegionModule id="LocalInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.LocalInterregionComms" />
40 <RegionModule id="RESTInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.RESTInterregionComms" />
41 <RegionModule id="LocalGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.LocalGridServicesConnector" /> 54 <RegionModule id="LocalGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.LocalGridServicesConnector" />
42 <RegionModule id="RemoteGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.RemoteGridServicesConnector" /> 55 <RegionModule id="RemoteGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.RemoteGridServicesConnector" />
43 <RegionModule id="HGGridConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.HGGridConnector" /> 56 <RegionModule id="LocalPresenceServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence.LocalPresenceServicesConnector" />
57 <RegionModule id="RemotePresenceServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence.RemotePresenceServicesConnector" />
58 <RegionModule id="LocalUserAccountServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts.LocalUserAccountServicesConnector" />
59 <RegionModule id="RemoteUserAccountServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts.RemoteUserAccountServicesConnector" />
60
61 <RegionModule id="LocalGridUserServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser.LocalGridUserServicesConnector" />
62 <RegionModule id="RemoteGridUserServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser.RemoteGridUserServicesConnector" />
63
64 <RegionModule id="LocalSimulationConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation.LocalSimulationConnectorModule" />
65 <RegionModule id="RemoteSimulationConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation.RemoteSimulationConnectorModule" />
66
44 <!-- Service connectors IN modules --> 67 <!-- Service connectors IN modules -->
45 <RegionModule id="AssetServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Asset.AssetServiceInConnectorModule" /> 68 <RegionModule id="AssetServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Asset.AssetServiceInConnectorModule" />
46 <RegionModule id="InventoryServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory.InventoryServiceInConnectorModule" /> 69 <RegionModule id="InventoryServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory.InventoryServiceInConnectorModule" />
47 <RegionModule id="LandServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Land.LandServiceInConnectorModule" /> 70 <RegionModule id="LandServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Land.LandServiceInConnectorModule" />
48 <RegionModule id="NeighbourServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Neighbour.NeighbourServiceInConnectorModule" /> \ 71 <RegionModule id="NeighbourServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Neighbour.NeighbourServiceInConnectorModule" /> \
49 <RegionModule id="HypergridServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid.HypergridServiceInConnectorModule" /> \ 72 <RegionModule id="HypergridServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Hypergrid.HypergridServiceInConnectorModule" /> \
73 <RegionModule id="LLLoginServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Login.LLLoginServiceInConnectorModule" /> \
74 <RegionModule id="SimulationServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Simulation.SimulationServiceInConnectorModule" /> \
75 <RegionModule id="GridInfoServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid.GridInfoServiceInConnectorModule" /> \
76 <RegionModule id="AuthenticationServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Authentication.AuthenticationServiceInConnectorModule" />
50 <RegionModule id="AccessModule" type="OpenSim.Region.CoreModules.World.AccessModule" /> \ 77 <RegionModule id="AccessModule" type="OpenSim.Region.CoreModules.World.AccessModule" /> \
51 78
52 </Extension> 79 </Extension>
diff --git a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
index e3c7bbf..678e772 100644
--- a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
@@ -285,31 +285,30 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
285 return; 285 return;
286 } 286 }
287 287
288 byte[] assetData; 288 byte[] assetData = null;
289 AssetBase oldAsset = null; 289 AssetBase oldAsset = null;
290 290
291 if (BlendWithOldTexture) 291 if (BlendWithOldTexture)
292 { 292 {
293 UUID lastTextureID = part.Shape.Textures.DefaultTexture.TextureID; 293 Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
294 oldAsset = scene.AssetService.Get(lastTextureID.ToString()); 294 if (defaultFace != null)
295 if (oldAsset != null)
296 {
297 assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
298 }
299 else
300 { 295 {
301 assetData = new byte[data.Length]; 296 oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());
302 Array.Copy(data, assetData, data.Length); 297
298 if (oldAsset != null)
299 assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
303 } 300 }
304 } 301 }
305 else 302
303 if (assetData == null)
306 { 304 {
307 assetData = new byte[data.Length]; 305 assetData = new byte[data.Length];
308 Array.Copy(data, assetData, data.Length); 306 Array.Copy(data, assetData, data.Length);
309 } 307 }
310 308
311 // Create a new asset for user 309 // Create a new asset for user
312 AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture); 310 AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
311 scene.RegionInfo.RegionID.ToString());
313 asset.Data = assetData; 312 asset.Data = assetData;
314 asset.Description = String.Format("URL image : {0}", Url); 313 asset.Description = String.Format("URL image : {0}", Url);
315 asset.Local = false; 314 asset.Local = false;
diff --git a/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs b/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
index 27b64bf..40ffcb4 100644
--- a/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
@@ -131,8 +131,8 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
131 { 131 {
132 // Start http server 132 // Start http server
133 // Attach xmlrpc handlers 133 // Attach xmlrpc handlers
134 m_log.Info("[REMOTE_DATA]: " + 134 m_log.Info("[XML RPC MODULE]: " +
135 "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands."); 135 "Starting up XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
136 BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort); 136 BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort);
137 httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); 137 httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
138 httpServer.Start(); 138 httpServer.Start();
@@ -192,7 +192,7 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
192 // This should no longer happen, but the check is reasonable anyway 192 // This should no longer happen, but the check is reasonable anyway
193 if (null == m_openChannels) 193 if (null == m_openChannels)
194 { 194 {
195 m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete"); 195 m_log.Warn("[XML RPC MODULE]: Attempt to open channel before initialization is complete");
196 return newChannel; 196 return newChannel;
197 } 197 }
198 198
@@ -279,7 +279,7 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
279 } 279 }
280 else 280 else
281 { 281 {
282 m_log.Warn("[RemoteDataReply]: Channel or message_id not found"); 282 m_log.Warn("[XML RPC MODULE]: Channel or message_id not found");
283 } 283 }
284 } 284 }
285 285
@@ -340,7 +340,7 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
340 } 340 }
341 else 341 else
342 { 342 {
343 m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST"); 343 m_log.Error("[XML RPC MODULE]: UNABLE TO REMOVE COMPLETED REQUEST");
344 } 344 }
345 } 345 }
346 } 346 }
@@ -728,4 +728,4 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
728 return ReqID; 728 return ReqID;
729 } 729 }
730 } 730 }
731} 731} \ No newline at end of file
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs
index 879cc70..2324380 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs
@@ -51,11 +51,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Asset
51 51
52 public void Initialise(IConfigSource config) 52 public void Initialise(IConfigSource config)
53 { 53 {
54 //// This module is only on for standalones in hypergrid mode
55 //enabled = ((!config.Configs["Startup"].GetBoolean("gridmode", true)) &&
56 // config.Configs["Startup"].GetBoolean("hypergrid", true)) ||
57 // ((config.Configs["MXP"] != null) && config.Configs["MXP"].GetBoolean("Enabled", true));
58 //m_log.DebugFormat("[RegionAssetService]: enabled? {0}", enabled);
59 m_Config = config; 54 m_Config = config;
60 IConfig moduleConfig = config.Configs["Modules"]; 55 IConfig moduleConfig = config.Configs["Modules"];
61 if (moduleConfig != null) 56 if (moduleConfig != null)
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs
new file mode 100644
index 0000000..02acddc
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs
@@ -0,0 +1,119 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Reflection;
30using System.Collections.Generic;
31using log4net;
32using Nini.Config;
33using OpenSim.Framework;
34using OpenSim.Framework.Servers.HttpServer;
35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Server.Base;
38using OpenSim.Server.Handlers.Base;
39using OpenSim.Server.Handlers.Authentication;
40using OpenSim.Services.Interfaces;
41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Authentication
43{
44 public class AuthenticationServiceInConnectorModule : ISharedRegionModule
45 {
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47 private static bool m_Enabled = false;
48
49 private IConfigSource m_Config;
50 bool m_Registered = false;
51
52 #region IRegionModule interface
53
54 public void Initialise(IConfigSource config)
55 {
56 m_Config = config;
57 IConfig moduleConfig = config.Configs["Modules"];
58 if (moduleConfig != null)
59 {
60 m_Enabled = moduleConfig.GetBoolean("AuthenticationServiceInConnector", false);
61 if (m_Enabled)
62 {
63 m_log.Info("[AUTHENTICATION IN CONNECTOR]: Authentication Service In Connector enabled");
64 }
65
66 }
67
68 }
69
70 public void PostInitialise()
71 {
72 }
73
74 public void Close()
75 {
76 }
77
78 public Type ReplaceableInterface
79 {
80 get { return null; }
81 }
82
83 public string Name
84 {
85 get { return "AuthenticationServiceInConnectorModule"; }
86 }
87
88 public void AddRegion(Scene scene)
89 {
90 if (!m_Enabled)
91 return;
92 }
93
94 public void RemoveRegion(Scene scene)
95 {
96 if (!m_Enabled)
97 return;
98 }
99
100 public void RegionLoaded(Scene scene)
101 {
102 if (!m_Enabled)
103 return;
104
105 if (!m_Registered)
106 {
107 m_Registered = true;
108
109 m_log.Info("[AUTHENTICATION IN CONNECTOR]: Starting...");
110
111 new AuthenticationServiceConnector(m_Config, MainServer.Instance, "AuthenticationService");
112 }
113
114 }
115
116 #endregion
117
118 }
119}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs
new file mode 100644
index 0000000..6d975af
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs
@@ -0,0 +1,119 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Reflection;
30using System.Collections.Generic;
31using log4net;
32using Nini.Config;
33using OpenSim.Framework;
34using OpenSim.Framework.Servers.HttpServer;
35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Server.Base;
38using OpenSim.Server.Handlers.Base;
39using OpenSim.Server.Handlers.Grid;
40using OpenSim.Services.Interfaces;
41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
43{
44 public class GridInfoServiceInConnectorModule : ISharedRegionModule
45 {
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47 private static bool m_Enabled = false;
48
49 private IConfigSource m_Config;
50 bool m_Registered = false;
51
52 #region IRegionModule interface
53
54 public void Initialise(IConfigSource config)
55 {
56 m_Config = config;
57 IConfig moduleConfig = config.Configs["Modules"];
58 if (moduleConfig != null)
59 {
60 m_Enabled = moduleConfig.GetBoolean("GridInfoServiceInConnector", false);
61 if (m_Enabled)
62 {
63 m_log.Info("[GRIDINFO IN CONNECTOR]: GridInfo Service In Connector enabled");
64 }
65
66 }
67
68 }
69
70 public void PostInitialise()
71 {
72 }
73
74 public void Close()
75 {
76 }
77
78 public Type ReplaceableInterface
79 {
80 get { return null; }
81 }
82
83 public string Name
84 {
85 get { return "GridInfoService"; }
86 }
87
88 public void AddRegion(Scene scene)
89 {
90 if (!m_Enabled)
91 return;
92 }
93
94 public void RemoveRegion(Scene scene)
95 {
96 if (!m_Enabled)
97 return;
98 }
99
100 public void RegionLoaded(Scene scene)
101 {
102 if (!m_Enabled)
103 return;
104
105 if (!m_Registered)
106 {
107 m_Registered = true;
108
109 m_log.Info("[GridInfo]: Starting...");
110
111 new GridInfoServerInConnector(m_Config, MainServer.Instance, "GridInfoService");
112 }
113
114 }
115
116 #endregion
117
118 }
119}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/HypergridServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs
index b12d778..235914a 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/HypergridServiceInConnectorModule.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs
@@ -36,11 +36,11 @@ using OpenSim.Region.Framework.Scenes;
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Server.Base; 37using OpenSim.Server.Base;
38using OpenSim.Server.Handlers.Base; 38using OpenSim.Server.Handlers.Base;
39using OpenSim.Server.Handlers.Grid; 39using OpenSim.Server.Handlers.Hypergrid;
40using OpenSim.Services.Interfaces; 40using OpenSim.Services.Interfaces;
41using GridRegion = OpenSim.Services.Interfaces.GridRegion; 41using GridRegion = OpenSim.Services.Interfaces.GridRegion;
42 42
43namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid 43namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Hypergrid
44{ 44{
45 public class HypergridServiceInConnectorModule : ISharedRegionModule 45 public class HypergridServiceInConnectorModule : ISharedRegionModule
46 { 46 {
@@ -49,16 +49,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
49 49
50 private IConfigSource m_Config; 50 private IConfigSource m_Config;
51 bool m_Registered = false; 51 bool m_Registered = false;
52 HypergridServiceInConnector m_HypergridHandler; 52 GatekeeperServiceInConnector m_HypergridHandler;
53 53
54 #region IRegionModule interface 54 #region IRegionModule interface
55 55
56 public void Initialise(IConfigSource config) 56 public void Initialise(IConfigSource config)
57 { 57 {
58 //// This module is only on for standalones in hypergrid mode
59 //enabled = (!config.Configs["Startup"].GetBoolean("gridmode", true)) &&
60 // config.Configs["Startup"].GetBoolean("hypergrid", true);
61 //m_log.DebugFormat("[RegionInventoryService]: enabled? {0}", enabled);
62 m_Config = config; 58 m_Config = config;
63 IConfig moduleConfig = config.Configs["Modules"]; 59 IConfig moduleConfig = config.Configs["Modules"];
64 if (moduleConfig != null) 60 if (moduleConfig != null)
@@ -102,9 +98,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
102 { 98 {
103 if (!m_Enabled) 99 if (!m_Enabled)
104 return; 100 return;
105
106 GridRegion rinfo = new GridRegion(scene.RegionInfo);
107 m_HypergridHandler.RemoveRegion(rinfo);
108 } 101 }
109 102
110 public void RegionLoaded(Scene scene) 103 public void RegionLoaded(Scene scene)
@@ -118,14 +111,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
118 111
119 m_log.Info("[HypergridService]: Starting..."); 112 m_log.Info("[HypergridService]: Starting...");
120 113
121// Object[] args = new Object[] { m_Config, MainServer.Instance }; 114 ISimulationService simService = scene.RequestModuleInterface<ISimulationService>();
115 m_HypergridHandler = new GatekeeperServiceInConnector(m_Config, MainServer.Instance, simService);
122 116
123 m_HypergridHandler = new HypergridServiceInConnector(m_Config, MainServer.Instance, scene.RequestModuleInterface<IHyperlinkService>()); 117 new UserAgentServerConnector(m_Config, MainServer.Instance);
124 //ServerUtils.LoadPlugin<HypergridServiceInConnector>("OpenSim.Server.Handlers.dll:HypergridServiceInConnector", args);
125 } 118 }
126 119 scene.RegisterModuleInterface<IGatekeeperService>(m_HypergridHandler.GateKeeper);
127 GridRegion rinfo = new GridRegion(scene.RegionInfo);
128 m_HypergridHandler.AddRegion(rinfo);
129 } 120 }
130 121
131 #endregion 122 #endregion
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs
index 54c6d89..ae03cdf 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs
@@ -51,10 +51,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory
51 51
52 public void Initialise(IConfigSource config) 52 public void Initialise(IConfigSource config)
53 { 53 {
54 //// This module is only on for standalones in hypergrid mode
55 //enabled = (!config.Configs["Startup"].GetBoolean("gridmode", true)) &&
56 // config.Configs["Startup"].GetBoolean("hypergrid", true);
57 //m_log.DebugFormat("[RegionInventoryService]: enabled? {0}", enabled);
58 m_Config = config; 54 m_Config = config;
59 IConfig moduleConfig = config.Configs["Modules"]; 55 IConfig moduleConfig = config.Configs["Modules"];
60 if (moduleConfig != null) 56 if (moduleConfig != null)
@@ -98,9 +94,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory
98 94
99 m_log.Info("[RegionInventoryService]: Starting..."); 95 m_log.Info("[RegionInventoryService]: Starting...");
100 96
101 Object[] args = new Object[] { m_Config, MainServer.Instance, String.Empty }; 97 Object[] args = new Object[] { m_Config, MainServer.Instance, "HGInventoryService" };
102 98
103 ServerUtils.LoadPlugin<IServiceConnector>("OpenSim.Server.Handlers.dll:InventoryServiceInConnector", args); 99 ServerUtils.LoadPlugin<IServiceConnector>("OpenSim.Server.Handlers.dll:HGInventoryServiceInConnector", args);
104 } 100 }
105 } 101 }
106 102
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs
new file mode 100644
index 0000000..2a9366c
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs
@@ -0,0 +1,128 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Reflection;
30using System.Collections.Generic;
31using log4net;
32using Nini.Config;
33using OpenSim.Framework;
34using OpenSim.Framework.Servers.HttpServer;
35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Server.Base;
38using OpenSim.Server.Handlers.Base;
39using OpenSim.Server.Handlers.Login;
40using OpenSim.Services.Interfaces;
41
42
43namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Login
44{
45 public class LLLoginServiceInConnectorModule : ISharedRegionModule
46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48 private static bool m_Enabled = false;
49 private static bool m_Registered = false;
50
51 private IConfigSource m_Config;
52 private List<Scene> m_Scenes = new List<Scene>();
53
54 #region IRegionModule interface
55
56 public void Initialise(IConfigSource config)
57 {
58 m_Config = config;
59
60 IConfig moduleConfig = config.Configs["Modules"];
61 if (moduleConfig != null)
62 {
63 m_Enabled = moduleConfig.GetBoolean("LLLoginServiceInConnector", false);
64 if (m_Enabled)
65 {
66 m_log.Info("[LLLOGIN IN CONNECTOR]: LLLoginerviceInConnector enabled");
67 }
68
69 }
70
71 }
72
73 public void PostInitialise()
74 {
75 if (!m_Enabled)
76 return;
77
78 m_log.Info("[LLLOGIN IN CONNECTOR]: Starting...");
79 }
80
81 public void Close()
82 {
83 }
84
85 public Type ReplaceableInterface
86 {
87 get { return null; }
88 }
89
90 public string Name
91 {
92 get { return "LLLoginServiceInConnectorModule"; }
93 }
94
95 public void AddRegion(Scene scene)
96 {
97 if (!m_Enabled)
98 return;
99
100 m_Scenes.Add(scene);
101
102 }
103
104 public void RemoveRegion(Scene scene)
105 {
106 if (m_Enabled && m_Scenes.Contains(scene))
107 m_Scenes.Remove(scene);
108 }
109
110 public void RegionLoaded(Scene scene)
111 {
112 if (!m_Enabled)
113 return;
114
115 if (!m_Registered)
116 {
117 m_Registered = true;
118 new LLLoginServiceInConnector(m_Config, MainServer.Instance, scene);
119 //Object[] args = new Object[] { m_Config, MainServer.Instance, this, scene };
120 //ServerUtils.LoadPlugin<IServiceConnector>("OpenSim.Server.Handlers.dll:LLLoginServiceInConnector", args);
121 }
122
123 }
124
125 #endregion
126
127 }
128}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs
index f28a318..5ee1c97 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs
@@ -58,11 +58,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Simulation
58 IConfig moduleConfig = config.Configs["Modules"]; 58 IConfig moduleConfig = config.Configs["Modules"];
59 if (moduleConfig != null) 59 if (moduleConfig != null)
60 { 60 {
61 string name = moduleConfig.GetString("SimulationService", ""); 61 m_Enabled = moduleConfig.GetBoolean("SimulationServiceInConnector", false);
62 if (name == Name) 62 if (m_Enabled)
63 { 63 {
64 m_Enabled = true; 64 m_log.Info("[SIM SERVICE]: SimulationService IN connector enabled");
65 m_log.Info("[SIM SERVICE]: SimulationService enabled");
66 65
67 } 66 }
68 } 67 }
@@ -84,7 +83,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Simulation
84 83
85 public string Name 84 public string Name
86 { 85 {
87 get { return "SimulationService"; } 86 get { return "SimulationServiceInConnectorModule"; }
88 } 87 }
89 88
90 public void AddRegion(Scene scene) 89 public void AddRegion(Scene scene)
@@ -92,6 +91,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Simulation
92 if (!m_Enabled) 91 if (!m_Enabled)
93 return; 92 return;
94 93
94 }
95
96 public void RemoveRegion(Scene scene)
97 {
98 }
99
100 public void RegionLoaded(Scene scene)
101 {
102 if (!m_Enabled)
103 return;
104
95 if (!m_Registered) 105 if (!m_Registered)
96 { 106 {
97 m_Registered = true; 107 m_Registered = true;
@@ -104,14 +114,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Simulation
104 } 114 }
105 } 115 }
106 116
107 public void RemoveRegion(Scene scene)
108 {
109 }
110
111 public void RegionLoaded(Scene scene)
112 {
113 }
114
115 #endregion 117 #endregion
116 118
117 } 119 }
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
index 0522256..ebd6bbd 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
@@ -31,7 +31,7 @@ using System;
31using System.Collections.Generic; 31using System.Collections.Generic;
32using System.Reflection; 32using System.Reflection;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications.Cache; 34
35using OpenSim.Server.Base; 35using OpenSim.Server.Base;
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
@@ -374,18 +374,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
374 374
375 public string GetUserAssetServer(UUID userID) 375 public string GetUserAssetServer(UUID userID)
376 { 376 {
377 CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(userID); 377 UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, userID);
378 if ((uinfo != null) && (uinfo.UserProfile != null)) 378
379 { 379 if (account != null && account.ServiceURLs.ContainsKey("AssetServerURI") && account.ServiceURLs["AssetServerURI"] != null)
380 if ((uinfo.UserProfile.UserAssetURI == string.Empty) || (uinfo.UserProfile.UserAssetURI == "")) 380 return account.ServiceURLs["AssetServerURI"].ToString();
381 return m_LocalAssetServiceURI; 381
382 return uinfo.UserProfile.UserAssetURI.Trim('/'); 382 return string.Empty;
383 }
384 else
385 {
386 // we don't know anyting about this user
387 return string.Empty;
388 }
389 } 383 }
390 384
391 public string GetSimAssetServer() 385 public string GetSimAssetServer()
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/RemoteAssetServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/RemoteAssetServiceConnector.cs
index 4eff60e..8a22cfc 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/RemoteAssetServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/RemoteAssetServiceConnector.cs
@@ -69,7 +69,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
69 IConfig assetConfig = source.Configs["AssetService"]; 69 IConfig assetConfig = source.Configs["AssetService"];
70 if (assetConfig == null) 70 if (assetConfig == null)
71 { 71 {
72 m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpanSim.ini"); 72 m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
73 return; 73 return;
74 } 74 }
75 75
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/LocalAuthenticationServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/LocalAuthenticationServiceConnector.cs
new file mode 100644
index 0000000..acc362b
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/LocalAuthenticationServiceConnector.cs
@@ -0,0 +1,164 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Server.Base;
36using OpenSim.Services.Interfaces;
37
38using OpenMetaverse;
39
40namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication
41{
42 public class LocalAuthenticationServicesConnector : ISharedRegionModule, IAuthenticationService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 private IAuthenticationService m_AuthenticationService;
49
50 private bool m_Enabled = false;
51
52 #region ISharedRegionModule
53
54 public Type ReplaceableInterface
55 {
56 get { return null; }
57 }
58
59 public string Name
60 {
61 get { return "LocalAuthenticationServicesConnector"; }
62 }
63
64 public void Initialise(IConfigSource source)
65 {
66 IConfig moduleConfig = source.Configs["Modules"];
67 if (moduleConfig != null)
68 {
69 string name = moduleConfig.GetString("AuthenticationServices", "");
70 if (name == Name)
71 {
72 IConfig userConfig = source.Configs["AuthenticationService"];
73 if (userConfig == null)
74 {
75 m_log.Error("[AUTH CONNECTOR]: AuthenticationService missing from OpenSim.ini");
76 return;
77 }
78
79 string serviceDll = userConfig.GetString("LocalServiceModule",
80 String.Empty);
81
82 if (serviceDll == String.Empty)
83 {
84 m_log.Error("[AUTH CONNECTOR]: No LocalServiceModule named in section AuthenticationService");
85 return;
86 }
87
88 Object[] args = new Object[] { source };
89 m_AuthenticationService =
90 ServerUtils.LoadPlugin<IAuthenticationService>(serviceDll,
91 args);
92
93 if (m_AuthenticationService == null)
94 {
95 m_log.Error("[AUTH CONNECTOR]: Can't load Authentication service");
96 return;
97 }
98 m_Enabled = true;
99 m_log.Info("[AUTH CONNECTOR]: Local Authentication connector enabled");
100 }
101 }
102 }
103
104 public void PostInitialise()
105 {
106 if (!m_Enabled)
107 return;
108 }
109
110 public void Close()
111 {
112 if (!m_Enabled)
113 return;
114 }
115
116 public void AddRegion(Scene scene)
117 {
118 if (!m_Enabled)
119 return;
120
121 scene.RegisterModuleInterface<IAuthenticationService>(m_AuthenticationService);
122 }
123
124 public void RemoveRegion(Scene scene)
125 {
126 if (!m_Enabled)
127 return;
128 }
129
130 public void RegionLoaded(Scene scene)
131 {
132 if (!m_Enabled)
133 return;
134 }
135
136 #endregion
137
138 #region IAuthenticationService
139
140 public string Authenticate(UUID principalID, string password, int lifetime)
141 {
142 // Not implemented at the regions
143 return string.Empty;
144 }
145
146 public bool Verify(UUID principalID, string token, int lifetime)
147 {
148 return m_AuthenticationService.Verify(principalID, token, lifetime);
149 }
150
151 public bool Release(UUID principalID, string token)
152 {
153 return m_AuthenticationService.Release(principalID, token);
154 }
155
156 public bool SetPassword(UUID principalID, string passwd)
157 {
158 return m_AuthenticationService.SetPassword(principalID, passwd);
159 }
160
161 #endregion
162
163 }
164}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/User/LocalUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/RemoteAuthenticationServiceConnector.cs
index cca5bb4..a053bc2 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/User/LocalUserServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authentication/RemoteAuthenticationServiceConnector.cs
@@ -26,24 +26,23 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Reflection;
30using log4net;
31using Nini.Config; 29using Nini.Config;
30using log4net;
31using System.Reflection;
32using OpenSim.Region.Framework.Interfaces; 32using OpenSim.Region.Framework.Interfaces;
33using OpenSim.Region.Framework.Scenes; 33using OpenSim.Region.Framework.Scenes;
34using OpenSim.Server.Base;
35using OpenSim.Services.Interfaces; 34using OpenSim.Services.Interfaces;
35using OpenSim.Services.Connectors;
36 36
37namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User 37namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication
38{ 38{
39 public class LocalUserServicesConnector : ISharedRegionModule 39 public class RemoteAuthenticationServicesConnector : AuthenticationServicesConnector,
40 ISharedRegionModule, IAuthenticationService
40 { 41 {
41 private static readonly ILog m_log = 42 private static readonly ILog m_log =
42 LogManager.GetLogger( 43 LogManager.GetLogger(
43 MethodBase.GetCurrentMethod().DeclaringType); 44 MethodBase.GetCurrentMethod().DeclaringType);
44 45
45 private IUserAccountService m_UserService;
46
47 private bool m_Enabled = false; 46 private bool m_Enabled = false;
48 47
49 public Type ReplaceableInterface 48 public Type ReplaceableInterface
@@ -53,45 +52,29 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
53 52
54 public string Name 53 public string Name
55 { 54 {
56 get { return "LocalUserServicesConnector"; } 55 get { return "RemoteAuthenticationServicesConnector"; }
57 } 56 }
58 57
59 public void Initialise(IConfigSource source) 58 public override void Initialise(IConfigSource source)
60 { 59 {
61 IConfig moduleConfig = source.Configs["Modules"]; 60 IConfig moduleConfig = source.Configs["Modules"];
62 if (moduleConfig != null) 61 if (moduleConfig != null)
63 { 62 {
64 string name = moduleConfig.GetString("UserServices", ""); 63 string name = moduleConfig.GetString("AuthenticationServices", "");
65 if (name == Name) 64 if (name == Name)
66 { 65 {
67 IConfig userConfig = source.Configs["UserService"]; 66 IConfig userConfig = source.Configs["AuthenticationService"];
68 if (userConfig == null) 67 if (userConfig == null)
69 { 68 {
70 m_log.Error("[USER CONNECTOR]: UserService missing from OpenSim.ini"); 69 m_log.Error("[AUTH CONNECTOR]: AuthenticationService missing from OpenSim.ini");
71 return; 70 return;
72 } 71 }
73 72
74 string serviceDll = userConfig.GetString("LocalServiceModule", 73 m_Enabled = true;
75 String.Empty);
76
77 if (serviceDll == String.Empty)
78 {
79 m_log.Error("[USER CONNECTOR]: No LocalServiceModule named in section UserService");
80 return;
81 }
82 74
83 Object[] args = new Object[] { source }; 75 base.Initialise(source);
84 m_UserService =
85 ServerUtils.LoadPlugin<IUserAccountService>(serviceDll,
86 args);
87 76
88 if (m_UserService == null) 77 m_log.Info("[AUTH CONNECTOR]: Remote Authentication enabled");
89 {
90 m_log.Error("[USER CONNECTOR]: Can't load user service");
91 return;
92 }
93 m_Enabled = true;
94 m_log.Info("[USER CONNECTOR]: Local user connector enabled");
95 } 78 }
96 } 79 }
97 } 80 }
@@ -113,7 +96,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
113 if (!m_Enabled) 96 if (!m_Enabled)
114 return; 97 return;
115 98
116 scene.RegisterModuleInterface<IUserAccountService>(m_UserService); 99 scene.RegisterModuleInterface<IAuthenticationService>(this);
117 } 100 }
118 101
119 public void RemoveRegion(Scene scene) 102 public void RemoveRegion(Scene scene)
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs
index 68499f3..01a2615 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs
@@ -139,9 +139,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization
139 139
140 if (scene != null) 140 if (scene != null)
141 { 141 {
142 UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(new UUID(userID)); 142 UserAccount account = scene.UserAccountService.GetUserAccount(UUID.Zero, userID);
143 isAuthorized = IsAuthorizedForRegion(userID, profile.FirstName, profile.SurName, 143 isAuthorized = IsAuthorizedForRegion(userID, account.FirstName, account.LastName,
144 profile.Email, scene.RegionInfo.RegionName, regionID, out message); 144 account.Email, scene.RegionInfo.RegionName, regionID, out message);
145 } 145 }
146 else 146 else
147 { 147 {
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/LocalAvatarServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/LocalAvatarServiceConnector.cs
new file mode 100644
index 0000000..47f19a3
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/LocalAvatarServiceConnector.cs
@@ -0,0 +1,168 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Server.Base;
36using OpenSim.Services.Interfaces;
37
38using OpenMetaverse;
39
40namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Avatar
41{
42 public class LocalAvatarServicesConnector : ISharedRegionModule, IAvatarService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 private IAvatarService m_AvatarService;
49
50 private bool m_Enabled = false;
51
52 #region ISharedRegionModule
53
54 public Type ReplaceableInterface
55 {
56 get { return null; }
57 }
58
59 public string Name
60 {
61 get { return "LocalAvatarServicesConnector"; }
62 }
63
64 public void Initialise(IConfigSource source)
65 {
66 IConfig moduleConfig = source.Configs["Modules"];
67 if (moduleConfig != null)
68 {
69 string name = moduleConfig.GetString("AvatarServices", "");
70 if (name == Name)
71 {
72 IConfig userConfig = source.Configs["AvatarService"];
73 if (userConfig == null)
74 {
75 m_log.Error("[AVATAR CONNECTOR]: AvatarService missing from OpenSim.ini");
76 return;
77 }
78
79 string serviceDll = userConfig.GetString("LocalServiceModule",
80 String.Empty);
81
82 if (serviceDll == String.Empty)
83 {
84 m_log.Error("[AVATAR CONNECTOR]: No LocalServiceModule named in section AvatarService");
85 return;
86 }
87
88 Object[] args = new Object[] { source };
89 m_AvatarService =
90 ServerUtils.LoadPlugin<IAvatarService>(serviceDll,
91 args);
92
93 if (m_AvatarService == null)
94 {
95 m_log.Error("[AVATAR CONNECTOR]: Can't load user account service");
96 return;
97 }
98 m_Enabled = true;
99 m_log.Info("[AVATAR CONNECTOR]: Local avatar connector enabled");
100 }
101 }
102 }
103
104 public void PostInitialise()
105 {
106 if (!m_Enabled)
107 return;
108 }
109
110 public void Close()
111 {
112 if (!m_Enabled)
113 return;
114 }
115
116 public void AddRegion(Scene scene)
117 {
118 if (!m_Enabled)
119 return;
120
121 scene.RegisterModuleInterface<IAvatarService>(this);
122 }
123
124 public void RemoveRegion(Scene scene)
125 {
126 if (!m_Enabled)
127 return;
128 }
129
130 public void RegionLoaded(Scene scene)
131 {
132 if (!m_Enabled)
133 return;
134 }
135
136 #endregion
137
138 #region IAvatarService
139
140 public AvatarData GetAvatar(UUID userID)
141 {
142 return m_AvatarService.GetAvatar(userID);
143 }
144
145 public bool SetAvatar(UUID userID, AvatarData avatar)
146 {
147 return m_AvatarService.SetAvatar(userID, avatar);
148 }
149
150 public bool ResetAvatar(UUID userID)
151 {
152 return m_AvatarService.ResetAvatar(userID);
153 }
154
155 public bool SetItems(UUID userID, string[] names, string[] values)
156 {
157 return m_AvatarService.SetItems(userID, names, values);
158 }
159
160 public bool RemoveItems(UUID userID, string[] names)
161 {
162 return m_AvatarService.RemoveItems(userID, names);
163 }
164
165 #endregion
166
167 }
168}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/User/RemoteUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/RemoteAvatarServiceConnector.cs
index cef9129..d665a54 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/User/RemoteUserServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Avatar/RemoteAvatarServiceConnector.cs
@@ -34,10 +34,10 @@ using OpenSim.Region.Framework.Scenes;
34using OpenSim.Services.Interfaces; 34using OpenSim.Services.Interfaces;
35using OpenSim.Services.Connectors; 35using OpenSim.Services.Connectors;
36 36
37namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User 37namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Avatar
38{ 38{
39 public class RemoteUserServicesConnector : UserServicesConnector, 39 public class RemoteAvatarServicesConnector : AvatarServicesConnector,
40 ISharedRegionModule, IUserAccountService 40 ISharedRegionModule, IAvatarService
41 { 41 {
42 private static readonly ILog m_log = 42 private static readonly ILog m_log =
43 LogManager.GetLogger( 43 LogManager.GetLogger(
@@ -52,7 +52,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
52 52
53 public string Name 53 public string Name
54 { 54 {
55 get { return "RemoteUserServicesConnector"; } 55 get { return "RemoteAvatarServicesConnector"; }
56 } 56 }
57 57
58 public override void Initialise(IConfigSource source) 58 public override void Initialise(IConfigSource source)
@@ -60,13 +60,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
60 IConfig moduleConfig = source.Configs["Modules"]; 60 IConfig moduleConfig = source.Configs["Modules"];
61 if (moduleConfig != null) 61 if (moduleConfig != null)
62 { 62 {
63 string name = moduleConfig.GetString("UserServices", ""); 63 string name = moduleConfig.GetString("AvatarServices", "");
64 if (name == Name) 64 if (name == Name)
65 { 65 {
66 IConfig userConfig = source.Configs["UserService"]; 66 IConfig userConfig = source.Configs["AvatarService"];
67 if (userConfig == null) 67 if (userConfig == null)
68 { 68 {
69 m_log.Error("[USER CONNECTOR]: UserService missing from OpanSim.ini"); 69 m_log.Error("[AVATAR CONNECTOR]: AvatarService missing from OpenSim.ini");
70 return; 70 return;
71 } 71 }
72 72
@@ -74,7 +74,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
74 74
75 base.Initialise(source); 75 base.Initialise(source);
76 76
77 m_log.Info("[USER CONNECTOR]: Remote users enabled"); 77 m_log.Info("[AVATAR CONNECTOR]: Remote avatars enabled");
78 } 78 }
79 } 79 }
80 } 80 }
@@ -96,7 +96,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.User
96 if (!m_Enabled) 96 if (!m_Enabled)
97 return; 97 return;
98 98
99 scene.RegisterModuleInterface<IUserAccountService>(this); 99 scene.RegisterModuleInterface<IAvatarService>(this);
100 } 100 }
101 101
102 public void RemoveRegion(Scene scene) 102 public void RemoveRegion(Scene scene)
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGCommands.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGCommands.cs
deleted file mode 100644
index 0974372..0000000
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGCommands.cs
+++ /dev/null
@@ -1,303 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using System.Xml;
32using log4net;
33using Nini.Config;
34using OpenSim.Framework;
35//using OpenSim.Framework.Communications;
36using OpenSim.Framework.Console;
37using OpenSim.Region.Framework;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Region.Framework.Scenes.Hypergrid;
40using GridRegion = OpenSim.Services.Interfaces.GridRegion;
41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
43{
44 public class HGCommands
45 {
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47 private HGGridConnector m_HGGridConnector;
48 private Scene m_scene;
49
50 private static uint m_autoMappingX = 0;
51 private static uint m_autoMappingY = 0;
52 private static bool m_enableAutoMapping = false;
53
54 public HGCommands(HGGridConnector hgConnector, Scene scene)
55 {
56 m_HGGridConnector = hgConnector;
57 m_scene = scene;
58 }
59
60 //public static Scene CreateScene(RegionInfo regionInfo, AgentCircuitManager circuitManager, CommunicationsManager m_commsManager,
61 // StorageManager storageManager, ModuleLoader m_moduleLoader, ConfigSettings m_configSettings, OpenSimConfigSource m_config, string m_version)
62 //{
63 // HGSceneCommunicationService sceneGridService = new HGSceneCommunicationService(m_commsManager, HGServices);
64
65 // return
66 // new HGScene(
67 // regionInfo, circuitManager, m_commsManager, sceneGridService, storageManager,
68 // m_moduleLoader, false, m_configSettings.PhysicalPrim,
69 // m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
70 //}
71
72 public void RunCommand(string module, string[] cmdparams)
73 {
74 List<string> args = new List<string>(cmdparams);
75 if (args.Count < 1)
76 return;
77
78 string command = args[0];
79 args.RemoveAt(0);
80
81 cmdparams = args.ToArray();
82
83 RunHGCommand(command, cmdparams);
84
85 }
86
87 private void RunHGCommand(string command, string[] cmdparams)
88 {
89 if (command.Equals("link-mapping"))
90 {
91 if (cmdparams.Length == 2)
92 {
93 try
94 {
95 m_autoMappingX = Convert.ToUInt32(cmdparams[0]);
96 m_autoMappingY = Convert.ToUInt32(cmdparams[1]);
97 m_enableAutoMapping = true;
98 }
99 catch (Exception)
100 {
101 m_autoMappingX = 0;
102 m_autoMappingY = 0;
103 m_enableAutoMapping = false;
104 }
105 }
106 }
107 else if (command.Equals("link-region"))
108 {
109 if (cmdparams.Length < 3)
110 {
111 if ((cmdparams.Length == 1) || (cmdparams.Length == 2))
112 {
113 LoadXmlLinkFile(cmdparams);
114 }
115 else
116 {
117 LinkRegionCmdUsage();
118 }
119 return;
120 }
121
122 if (cmdparams[2].Contains(":"))
123 {
124 // New format
125 int xloc, yloc;
126 string mapName;
127 try
128 {
129 xloc = Convert.ToInt32(cmdparams[0]);
130 yloc = Convert.ToInt32(cmdparams[1]);
131 mapName = cmdparams[2];
132 if (cmdparams.Length > 3)
133 for (int i = 3; i < cmdparams.Length; i++)
134 mapName += " " + cmdparams[i];
135
136 m_log.Info(">> MapName: " + mapName);
137 //internalPort = Convert.ToUInt32(cmdparams[4]);
138 //remotingPort = Convert.ToUInt32(cmdparams[5]);
139 }
140 catch (Exception e)
141 {
142 m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
143 LinkRegionCmdUsage();
144 return;
145 }
146
147 // Convert cell coordinates given by the user to meters
148 xloc = xloc * (int)Constants.RegionSize;
149 yloc = yloc * (int)Constants.RegionSize;
150 m_HGGridConnector.TryLinkRegionToCoords(m_scene, null, mapName, xloc, yloc);
151 }
152 else
153 {
154 // old format
155 GridRegion regInfo;
156 int xloc, yloc;
157 uint externalPort;
158 string externalHostName;
159 try
160 {
161 xloc = Convert.ToInt32(cmdparams[0]);
162 yloc = Convert.ToInt32(cmdparams[1]);
163 externalPort = Convert.ToUInt32(cmdparams[3]);
164 externalHostName = cmdparams[2];
165 //internalPort = Convert.ToUInt32(cmdparams[4]);
166 //remotingPort = Convert.ToUInt32(cmdparams[5]);
167 }
168 catch (Exception e)
169 {
170 m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
171 LinkRegionCmdUsage();
172 return;
173 }
174
175 // Convert cell coordinates given by the user to meters
176 xloc = xloc * (int)Constants.RegionSize;
177 yloc = yloc * (int)Constants.RegionSize;
178 if (m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort, externalHostName, out regInfo))
179 {
180 if (cmdparams.Length >= 5)
181 {
182 regInfo.RegionName = "";
183 for (int i = 4; i < cmdparams.Length; i++)
184 regInfo.RegionName += cmdparams[i] + " ";
185 }
186 }
187 }
188 return;
189 }
190 else if (command.Equals("unlink-region"))
191 {
192 if (cmdparams.Length < 1)
193 {
194 UnlinkRegionCmdUsage();
195 return;
196 }
197 if (m_HGGridConnector.TryUnlinkRegion(m_scene, cmdparams[0]))
198 m_log.InfoFormat("[HGrid]: Successfully unlinked {0}", cmdparams[0]);
199 else
200 m_log.InfoFormat("[HGrid]: Unable to unlink {0}, region not found", cmdparams[0]);
201 }
202 }
203
204 private void LoadXmlLinkFile(string[] cmdparams)
205 {
206 //use http://www.hgurl.com/hypergrid.xml for test
207 try
208 {
209 XmlReader r = XmlReader.Create(cmdparams[0]);
210 XmlConfigSource cs = new XmlConfigSource(r);
211 string[] excludeSections = null;
212
213 if (cmdparams.Length == 2)
214 {
215 if (cmdparams[1].ToLower().StartsWith("excludelist:"))
216 {
217 string excludeString = cmdparams[1].ToLower();
218 excludeString = excludeString.Remove(0, 12);
219 char[] splitter = { ';' };
220
221 excludeSections = excludeString.Split(splitter);
222 }
223 }
224
225 for (int i = 0; i < cs.Configs.Count; i++)
226 {
227 bool skip = false;
228 if ((excludeSections != null) && (excludeSections.Length > 0))
229 {
230 for (int n = 0; n < excludeSections.Length; n++)
231 {
232 if (excludeSections[n] == cs.Configs[i].Name.ToLower())
233 {
234 skip = true;
235 break;
236 }
237 }
238 }
239 if (!skip)
240 {
241 ReadLinkFromConfig(cs.Configs[i]);
242 }
243 }
244 }
245 catch (Exception e)
246 {
247 m_log.Error(e.ToString());
248 }
249 }
250
251
252 private void ReadLinkFromConfig(IConfig config)
253 {
254 GridRegion regInfo;
255 int xloc, yloc;
256 uint externalPort;
257 string externalHostName;
258 uint realXLoc, realYLoc;
259
260 xloc = Convert.ToInt32(config.GetString("xloc", "0"));
261 yloc = Convert.ToInt32(config.GetString("yloc", "0"));
262 externalPort = Convert.ToUInt32(config.GetString("externalPort", "0"));
263 externalHostName = config.GetString("externalHostName", "");
264 realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0"));
265 realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0"));
266
267 if (m_enableAutoMapping)
268 {
269 xloc = (int)((xloc % 100) + m_autoMappingX);
270 yloc = (int)((yloc % 100) + m_autoMappingY);
271 }
272
273 if (((realXLoc == 0) && (realYLoc == 0)) ||
274 (((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) &&
275 ((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896))))
276 {
277 xloc = xloc * (int)Constants.RegionSize;
278 yloc = yloc * (int)Constants.RegionSize;
279 if (
280 m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort,
281 externalHostName, out regInfo))
282 {
283 regInfo.RegionName = config.GetString("localName", "");
284 }
285 }
286 }
287
288
289 private void LinkRegionCmdUsage()
290 {
291 m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]");
292 m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]");
293 m_log.Info("Usage: link-region <URI_of_xml> [<exclude>]");
294 }
295
296 private void UnlinkRegionCmdUsage()
297 {
298 m_log.Info("Usage: unlink-region <HostName>:<HttpPort>");
299 m_log.Info("Usage: unlink-region <LocalName>");
300 }
301
302 }
303}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGGridConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGGridConnector.cs
deleted file mode 100644
index 131febd..0000000
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/HGGridConnector.cs
+++ /dev/null
@@ -1,811 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Reflection;
32using System.Xml;
33
34using OpenSim.Framework.Communications.Cache;
35using OpenSim.Framework;
36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes;
38using OpenSim.Region.Framework.Scenes.Hypergrid;
39using OpenSim.Services.Interfaces;
40using GridRegion = OpenSim.Services.Interfaces.GridRegion;
41using OpenSim.Server.Base;
42using OpenSim.Services.Connectors.Grid;
43using OpenSim.Framework.Console;
44
45using OpenMetaverse;
46using log4net;
47using Nini.Config;
48
49namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
50{
51 public class HGGridConnector : ISharedRegionModule, IGridService, IHyperlinkService
52 {
53 private static readonly ILog m_log =
54 LogManager.GetLogger(
55 MethodBase.GetCurrentMethod().DeclaringType);
56 private static string LocalAssetServerURI, LocalInventoryServerURI, LocalUserServerURI;
57
58 private bool m_Enabled = false;
59 private bool m_Initialized = false;
60
61 private Scene m_aScene;
62 private Dictionary<ulong, Scene> m_LocalScenes = new Dictionary<ulong, Scene>();
63
64 private IGridService m_GridServiceConnector;
65 private HypergridServiceConnector m_HypergridServiceConnector;
66
67 // Hyperlink regions are hyperlinks on the map
68 protected Dictionary<UUID, GridRegion> m_HyperlinkRegions = new Dictionary<UUID, GridRegion>();
69
70 // Known regions are home regions of visiting foreign users.
71 // They are not on the map as static hyperlinks. They are dynamic hyperlinks, they go away when
72 // the visitor goes away. They are mapped to X=0 on the map.
73 // This is key-ed on agent ID
74 protected Dictionary<UUID, GridRegion> m_knownRegions = new Dictionary<UUID, GridRegion>();
75
76 protected Dictionary<UUID, ulong> m_HyperlinkHandles = new Dictionary<UUID, ulong>();
77
78 #region ISharedRegionModule
79
80 public Type ReplaceableInterface
81 {
82 get { return null; }
83 }
84
85 public string Name
86 {
87 get { return "HGGridServicesConnector"; }
88 }
89
90 public void Initialise(IConfigSource source)
91 {
92 IConfig moduleConfig = source.Configs["Modules"];
93 if (moduleConfig != null)
94 {
95 string name = moduleConfig.GetString("GridServices", "");
96 if (name == Name)
97 {
98 IConfig gridConfig = source.Configs["GridService"];
99 if (gridConfig == null)
100 {
101 m_log.Error("[HGGRID CONNECTOR]: GridService missing from OpenSim.ini");
102 return;
103 }
104
105
106 InitialiseConnectorModule(source);
107
108 m_Enabled = true;
109 m_log.Info("[HGGRID CONNECTOR]: HG grid enabled");
110 }
111 }
112 }
113
114 private void InitialiseConnectorModule(IConfigSource source)
115 {
116 IConfig gridConfig = source.Configs["GridService"];
117 if (gridConfig == null)
118 {
119 m_log.Error("[HGGRID CONNECTOR]: GridService missing from OpenSim.ini");
120 throw new Exception("Grid connector init error");
121 }
122
123 string module = gridConfig.GetString("GridServiceConnectorModule", String.Empty);
124 if (module == String.Empty)
125 {
126 m_log.Error("[HGGRID CONNECTOR]: No GridServiceConnectorModule named in section GridService");
127 //return;
128 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
129 }
130
131 Object[] args = new Object[] { source };
132 m_GridServiceConnector = ServerUtils.LoadPlugin<IGridService>(module, args);
133
134 }
135
136 public void PostInitialise()
137 {
138 if (m_Enabled)
139 ((ISharedRegionModule)m_GridServiceConnector).PostInitialise();
140 }
141
142 public void Close()
143 {
144 }
145
146 public void AddRegion(Scene scene)
147 {
148 if (!m_Enabled)
149 return;
150
151 m_LocalScenes[scene.RegionInfo.RegionHandle] = scene;
152 scene.RegisterModuleInterface<IGridService>(this);
153 scene.RegisterModuleInterface<IHyperlinkService>(this);
154
155 ((ISharedRegionModule)m_GridServiceConnector).AddRegion(scene);
156
157 // Yikes!! Remove this as soon as user services get refactored
158 LocalAssetServerURI = scene.CommsManager.NetworkServersInfo.AssetURL;
159 LocalInventoryServerURI = scene.CommsManager.NetworkServersInfo.InventoryURL;
160 LocalUserServerURI = scene.CommsManager.NetworkServersInfo.UserURL;
161 HGNetworkServersInfo.Init(LocalAssetServerURI, LocalInventoryServerURI, LocalUserServerURI);
162
163 }
164
165 public void RemoveRegion(Scene scene)
166 {
167 if (m_Enabled)
168 {
169 m_LocalScenes.Remove(scene.RegionInfo.RegionHandle);
170 ((ISharedRegionModule)m_GridServiceConnector).RemoveRegion(scene);
171 }
172 }
173
174 public void RegionLoaded(Scene scene)
175 {
176 if (!m_Enabled)
177 return;
178
179 if (!m_Initialized)
180 {
181 m_aScene = scene;
182
183 m_HypergridServiceConnector = new HypergridServiceConnector(scene.AssetService);
184
185 HGCommands hgCommands = new HGCommands(this, scene);
186 MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "link-region",
187 "link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>] <cr>",
188 "Link a hypergrid region", hgCommands.RunCommand);
189 MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "unlink-region",
190 "unlink-region <local name> or <HostName>:<HttpPort> <cr>",
191 "Unlink a hypergrid region", hgCommands.RunCommand);
192 MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "link-mapping", "link-mapping [<x> <y>] <cr>",
193 "Set local coordinate to map HG regions to", hgCommands.RunCommand);
194
195 m_Initialized = true;
196 }
197 }
198
199 #endregion
200
201 #region IGridService
202
203 public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
204 {
205 // Region doesn't exist here. Trying to link remote region
206 if (regionInfo.RegionID.Equals(UUID.Zero))
207 {
208 m_log.Info("[HGrid]: Linking remote region " + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort);
209 ulong regionHandle = 0;
210 regionInfo.RegionID = m_HypergridServiceConnector.LinkRegion(regionInfo, out regionHandle);
211 if (!regionInfo.RegionID.Equals(UUID.Zero))
212 {
213 AddHyperlinkRegion(regionInfo, regionHandle);
214 m_log.Info("[HGrid]: Successfully linked to region_uuid " + regionInfo.RegionID);
215
216 // Try get the map image
217 m_HypergridServiceConnector.GetMapImage(regionInfo);
218 return String.Empty;
219 }
220 else
221 {
222 m_log.Info("[HGrid]: No such region " + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort + "(" + regionInfo.InternalEndPoint.Port + ")");
223 return "No such region";
224 }
225 // Note that these remote regions aren't registered in localBackend, so return null, no local listeners
226 }
227 else // normal grid
228 return m_GridServiceConnector.RegisterRegion(scopeID, regionInfo);
229 }
230
231 public bool DeregisterRegion(UUID regionID)
232 {
233 // Try the hyperlink collection
234 if (m_HyperlinkRegions.ContainsKey(regionID))
235 {
236 RemoveHyperlinkRegion(regionID);
237 return true;
238 }
239 // Try the foreign users home collection
240
241 foreach (GridRegion r in m_knownRegions.Values)
242 if (r.RegionID == regionID)
243 {
244 RemoveHyperlinkHomeRegion(regionID);
245 return true;
246 }
247
248 // Finally, try the normal route
249 return m_GridServiceConnector.DeregisterRegion(regionID);
250 }
251
252 public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
253 {
254 // No serving neighbours on hyperliked regions.
255 // Just the regular regions.
256 return m_GridServiceConnector.GetNeighbours(scopeID, regionID);
257 }
258
259 public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
260 {
261 // Try the hyperlink collection
262 if (m_HyperlinkRegions.ContainsKey(regionID))
263 return m_HyperlinkRegions[regionID];
264
265 // Try the foreign users home collection
266 foreach (GridRegion r in m_knownRegions.Values)
267 if (r.RegionID == regionID)
268 return r;
269
270 // Finally, try the normal route
271 return m_GridServiceConnector.GetRegionByUUID(scopeID, regionID);
272 }
273
274 public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
275 {
276 int snapX = (int) (x / Constants.RegionSize) * (int)Constants.RegionSize;
277 int snapY = (int) (y / Constants.RegionSize) * (int)Constants.RegionSize;
278 // Try the hyperlink collection
279 foreach (GridRegion r in m_HyperlinkRegions.Values)
280 {
281 if ((r.RegionLocX == snapX) && (r.RegionLocY == snapY))
282 return r;
283 }
284
285 // Try the foreign users home collection
286 foreach (GridRegion r in m_knownRegions.Values)
287 {
288 if ((r.RegionLocX == snapX) && (r.RegionLocY == snapY))
289 {
290 return r;
291 }
292 }
293
294 // Finally, try the normal route
295 return m_GridServiceConnector.GetRegionByPosition(scopeID, x, y);
296 }
297
298 public GridRegion GetRegionByName(UUID scopeID, string regionName)
299 {
300 // Try normal grid first
301 GridRegion region = m_GridServiceConnector.GetRegionByName(scopeID, regionName);
302 if (region != null)
303 return region;
304
305 // Try the hyperlink collection
306 foreach (GridRegion r in m_HyperlinkRegions.Values)
307 {
308 if (r.RegionName == regionName)
309 return r;
310 }
311
312 // Try the foreign users home collection
313 foreach (GridRegion r in m_knownRegions.Values)
314 {
315 if (r.RegionName == regionName)
316 return r;
317 }
318 return null;
319 }
320
321 public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
322 {
323 List<GridRegion> rinfos = new List<GridRegion>();
324
325 if (name == string.Empty)
326 return rinfos;
327
328 foreach (GridRegion r in m_HyperlinkRegions.Values)
329 if ((r.RegionName != null) && r.RegionName.ToLower().StartsWith(name.ToLower()))
330 rinfos.Add(r);
331
332 rinfos.AddRange(m_GridServiceConnector.GetRegionsByName(scopeID, name, maxNumber));
333 return rinfos;
334 }
335
336 public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
337 {
338 int snapXmin = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
339// int snapXmax = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
340 int snapYmin = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
341 int snapYmax = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
342
343 List<GridRegion> rinfos = new List<GridRegion>();
344 foreach (GridRegion r in m_HyperlinkRegions.Values)
345 if ((r.RegionLocX > snapXmin) && (r.RegionLocX < snapYmax) &&
346 (r.RegionLocY > snapYmin) && (r.RegionLocY < snapYmax))
347 rinfos.Add(r);
348
349 rinfos.AddRange(m_GridServiceConnector.GetRegionRange(scopeID, xmin, xmax, ymin, ymax));
350
351 return rinfos;
352 }
353
354 #endregion
355
356 #region Auxiliary
357
358 private void AddHyperlinkRegion(GridRegion regionInfo, ulong regionHandle)
359 {
360 m_HyperlinkRegions[regionInfo.RegionID] = regionInfo;
361 m_HyperlinkHandles[regionInfo.RegionID] = regionHandle;
362 }
363
364 private void RemoveHyperlinkRegion(UUID regionID)
365 {
366 m_HyperlinkRegions.Remove(regionID);
367 m_HyperlinkHandles.Remove(regionID);
368 }
369
370 private void AddHyperlinkHomeRegion(UUID userID, GridRegion regionInfo, ulong regionHandle)
371 {
372 m_knownRegions[userID] = regionInfo;
373 m_HyperlinkHandles[regionInfo.RegionID] = regionHandle;
374 }
375
376 private void RemoveHyperlinkHomeRegion(UUID regionID)
377 {
378 foreach (KeyValuePair<UUID, GridRegion> kvp in m_knownRegions)
379 {
380 if (kvp.Value.RegionID == regionID)
381 {
382 m_knownRegions.Remove(kvp.Key);
383 }
384 }
385 m_HyperlinkHandles.Remove(regionID);
386 }
387 #endregion
388
389 #region IHyperlinkService
390
391 private static Random random = new Random();
392
393
394 public GridRegion TryLinkRegionToCoords(Scene m_scene, IClientAPI client, string mapName, int xloc, int yloc)
395 {
396 string host = "127.0.0.1";
397 string portstr;
398 string regionName = "";
399 uint port = 9000;
400 string[] parts = mapName.Split(new char[] { ':' });
401 if (parts.Length >= 1)
402 {
403 host = parts[0];
404 }
405 if (parts.Length >= 2)
406 {
407 portstr = parts[1];
408 //m_log.Debug("-- port = " + portstr);
409 if (!UInt32.TryParse(portstr, out port))
410 regionName = parts[1];
411 }
412 // always take the last one
413 if (parts.Length >= 3)
414 {
415 regionName = parts[2];
416 }
417
418 // Sanity check. Don't ever link to this sim.
419 IPAddress ipaddr = null;
420 try
421 {
422 ipaddr = Util.GetHostFromDNS(host);
423 }
424 catch { }
425
426 if ((ipaddr != null) &&
427 !((m_scene.RegionInfo.ExternalEndPoint.Address.Equals(ipaddr)) && (m_scene.RegionInfo.HttpPort == port)))
428 {
429 GridRegion regInfo;
430 bool success = TryCreateLink(m_scene, client, xloc, yloc, regionName, port, host, out regInfo);
431 if (success)
432 {
433 regInfo.RegionName = mapName;
434 return regInfo;
435 }
436 }
437
438 return null;
439 }
440
441
442 // From the map search and secondlife://blah
443 public GridRegion TryLinkRegion(Scene m_scene, IClientAPI client, string mapName)
444 {
445 int xloc = random.Next(0, Int16.MaxValue) * (int) Constants.RegionSize;
446 return TryLinkRegionToCoords(m_scene, client, mapName, xloc, 0);
447 }
448
449 public bool TryCreateLink(Scene m_scene, IClientAPI client, int xloc, int yloc,
450 string externalRegionName, uint externalPort, string externalHostName, out GridRegion regInfo)
451 {
452 m_log.DebugFormat("[HGrid]: Link to {0}:{1}, in {2}-{3}", externalHostName, externalPort, xloc, yloc);
453
454 regInfo = new GridRegion();
455 regInfo.RegionName = externalRegionName;
456 regInfo.HttpPort = externalPort;
457 regInfo.ExternalHostName = externalHostName;
458 regInfo.RegionLocX = xloc;
459 regInfo.RegionLocY = yloc;
460
461 try
462 {
463 regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
464 }
465 catch (Exception e)
466 {
467 m_log.Warn("[HGrid]: Wrong format for link-region: " + e.Message);
468 return false;
469 }
470
471 // Finally, link it
472 if (RegisterRegion(UUID.Zero, regInfo) != String.Empty)
473 {
474 m_log.Warn("[HGrid]: Unable to link region");
475 return false;
476 }
477
478 int x, y;
479 if (!Check4096(m_scene, regInfo, out x, out y))
480 {
481 DeregisterRegion(regInfo.RegionID);
482 if (client != null)
483 client.SendAlertMessage("Region is too far (" + x + ", " + y + ")");
484 m_log.Info("[HGrid]: Unable to link, region is too far (" + x + ", " + y + ")");
485 return false;
486 }
487
488 if (!CheckCoords(m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY, x, y))
489 {
490 DeregisterRegion(regInfo.RegionID);
491 if (client != null)
492 client.SendAlertMessage("Region has incompatible coordinates (" + x + ", " + y + ")");
493 m_log.Info("[HGrid]: Unable to link, region has incompatible coordinates (" + x + ", " + y + ")");
494 return false;
495 }
496
497 m_log.Debug("[HGrid]: link region succeeded");
498 return true;
499 }
500
501 public bool TryUnlinkRegion(Scene m_scene, string mapName)
502 {
503 GridRegion regInfo = null;
504 if (mapName.Contains(":"))
505 {
506 string host = "127.0.0.1";
507 //string portstr;
508 //string regionName = "";
509 uint port = 9000;
510 string[] parts = mapName.Split(new char[] { ':' });
511 if (parts.Length >= 1)
512 {
513 host = parts[0];
514 }
515 // if (parts.Length >= 2)
516 // {
517 // portstr = parts[1];
518 // if (!UInt32.TryParse(portstr, out port))
519 // regionName = parts[1];
520 // }
521 // always take the last one
522 // if (parts.Length >= 3)
523 // {
524 // regionName = parts[2];
525 // }
526 foreach (GridRegion r in m_HyperlinkRegions.Values)
527 if (host.Equals(r.ExternalHostName) && (port == r.HttpPort))
528 regInfo = r;
529 }
530 else
531 {
532 foreach (GridRegion r in m_HyperlinkRegions.Values)
533 if (r.RegionName.Equals(mapName))
534 regInfo = r;
535 }
536 if (regInfo != null)
537 {
538 return DeregisterRegion(regInfo.RegionID);
539 }
540 else
541 {
542 m_log.InfoFormat("[HGrid]: Region {0} not found", mapName);
543 return false;
544 }
545 }
546
547 /// <summary>
548 /// Cope with this viewer limitation.
549 /// </summary>
550 /// <param name="regInfo"></param>
551 /// <returns></returns>
552 public bool Check4096(Scene m_scene, GridRegion regInfo, out int x, out int y)
553 {
554 ulong realHandle = m_HyperlinkHandles[regInfo.RegionID];
555 uint ux = 0, uy = 0;
556 Utils.LongToUInts(realHandle, out ux, out uy);
557 x = (int)(ux / Constants.RegionSize);
558 y = (int)(uy / Constants.RegionSize);
559
560 if ((Math.Abs((int)m_scene.RegionInfo.RegionLocX - x) >= 4096) ||
561 (Math.Abs((int)m_scene.RegionInfo.RegionLocY - y) >= 4096))
562 {
563 return false;
564 }
565 return true;
566 }
567
568 public bool CheckCoords(uint thisx, uint thisy, int x, int y)
569 {
570 if ((thisx == x) && (thisy == y))
571 return false;
572 return true;
573 }
574
575 public GridRegion TryLinkRegion(IClientAPI client, string regionDescriptor)
576 {
577 return TryLinkRegion((Scene)client.Scene, client, regionDescriptor);
578 }
579
580 public GridRegion GetHyperlinkRegion(ulong handle)
581 {
582 foreach (GridRegion r in m_HyperlinkRegions.Values)
583 if (r.RegionHandle == handle)
584 return r;
585 foreach (GridRegion r in m_knownRegions.Values)
586 if (r.RegionHandle == handle)
587 return r;
588 return null;
589 }
590
591 public ulong FindRegionHandle(ulong handle)
592 {
593 foreach (GridRegion r in m_HyperlinkRegions.Values)
594 if ((r.RegionHandle == handle) && (m_HyperlinkHandles.ContainsKey(r.RegionID)))
595 return m_HyperlinkHandles[r.RegionID];
596
597 foreach (GridRegion r in m_knownRegions.Values)
598 if ((r.RegionHandle == handle) && (m_HyperlinkHandles.ContainsKey(r.RegionID)))
599 return m_HyperlinkHandles[r.RegionID];
600
601 return handle;
602 }
603
604 public bool SendUserInformation(GridRegion regInfo, AgentCircuitData agentData)
605 {
606 CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(agentData.AgentID);
607
608 if (uinfo == null)
609 return false;
610
611 if ((IsLocalUser(uinfo) && (GetHyperlinkRegion(regInfo.RegionHandle) != null)) ||
612 (!IsLocalUser(uinfo) && !IsGoingHome(uinfo, regInfo)))
613 {
614 m_log.Info("[HGrid]: Local user is going to foreign region or foreign user is going elsewhere");
615
616 // Set the position of the region on the remote grid
617// ulong realHandle = FindRegionHandle(regInfo.RegionHandle);
618 uint x = 0, y = 0;
619 Utils.LongToUInts(regInfo.RegionHandle, out x, out y);
620 GridRegion clonedRegion = new GridRegion(regInfo);
621 clonedRegion.RegionLocX = (int)x;
622 clonedRegion.RegionLocY = (int)y;
623
624 // Get the user's home region information and adapt the region handle
625 GridRegion home = GetRegionByUUID(m_aScene.RegionInfo.ScopeID, uinfo.UserProfile.HomeRegionID);
626 if (m_HyperlinkHandles.ContainsKey(uinfo.UserProfile.HomeRegionID))
627 {
628 ulong realHandle = m_HyperlinkHandles[uinfo.UserProfile.HomeRegionID];
629 Utils.LongToUInts(realHandle, out x, out y);
630 m_log.DebugFormat("[HGrid]: Foreign user is going elsewhere. Adjusting home handle from {0}-{1} to {2}-{3}", home.RegionLocX, home.RegionLocY, x, y);
631 home.RegionLocX = (int)x;
632 home.RegionLocY = (int)y;
633 }
634
635 // Get the user's service URLs
636 string serverURI = "";
637 if (uinfo.UserProfile is ForeignUserProfileData)
638 serverURI = Util.ServerURI(((ForeignUserProfileData)uinfo.UserProfile).UserServerURI);
639 string userServer = (serverURI == "") || (serverURI == null) ? LocalUserServerURI : serverURI;
640
641 string assetServer = Util.ServerURI(uinfo.UserProfile.UserAssetURI);
642 if ((assetServer == null) || (assetServer == ""))
643 assetServer = LocalAssetServerURI;
644
645 string inventoryServer = Util.ServerURI(uinfo.UserProfile.UserInventoryURI);
646 if ((inventoryServer == null) || (inventoryServer == ""))
647 inventoryServer = LocalInventoryServerURI;
648
649 if (!m_HypergridServiceConnector.InformRegionOfUser(clonedRegion, agentData, home, userServer, assetServer, inventoryServer))
650 {
651 m_log.Warn("[HGrid]: Could not inform remote region of transferring user.");
652 return false;
653 }
654 }
655 //if ((uinfo == null) || !IsGoingHome(uinfo, regInfo))
656 //{
657 // m_log.Info("[HGrid]: User seems to be going to foreign region.");
658 // if (!InformRegionOfUser(regInfo, agentData))
659 // {
660 // m_log.Warn("[HGrid]: Could not inform remote region of transferring user.");
661 // return false;
662 // }
663 //}
664 //else
665 // m_log.Info("[HGrid]: User seems to be going home " + uinfo.UserProfile.FirstName + " " + uinfo.UserProfile.SurName);
666
667 // May need to change agent's name
668 if (IsLocalUser(uinfo) && (GetHyperlinkRegion(regInfo.RegionHandle) != null))
669 {
670 agentData.firstname = agentData.firstname + "." + agentData.lastname;
671 agentData.lastname = "@" + LocalUserServerURI.Replace("http://", ""); ; //HGNetworkServersInfo.Singleton.LocalUserServerURI;
672 }
673
674 return true;
675 }
676
677 public void AdjustUserInformation(AgentCircuitData agentData)
678 {
679 CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(agentData.AgentID);
680 if ((uinfo != null) && (uinfo.UserProfile != null) &&
681 (IsLocalUser(uinfo) || !(uinfo.UserProfile is ForeignUserProfileData)))
682 {
683 //m_log.Debug("---------------> Local User!");
684 string[] parts = agentData.firstname.Split(new char[] { '.' });
685 if (parts.Length == 2)
686 {
687 agentData.firstname = parts[0];
688 agentData.lastname = parts[1];
689 }
690 }
691 //else
692 // m_log.Debug("---------------> Foreign User!");
693 }
694
695 // Check if a local user exists with the same UUID as the incoming foreign user
696 public bool CheckUserAtEntry(UUID userID, UUID sessionID, out bool comingHome)
697 {
698 comingHome = false;
699
700 CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
701 if (uinfo != null)
702 {
703 // uh-oh we have a potential intruder
704 if (uinfo.SessionID != sessionID)
705 // can't have a foreigner with a local UUID
706 return false;
707 else
708 // oh, so it's you! welcome back
709 comingHome = true;
710 }
711
712 // OK, user can come in
713 return true;
714 }
715
716 public void AcceptUser(ForeignUserProfileData user, GridRegion home)
717 {
718 m_aScene.CommsManager.UserProfileCacheService.PreloadUserCache(user);
719 ulong realHandle = home.RegionHandle;
720 // Change the local coordinates
721 // X=0 on the map
722 home.RegionLocX = 0;
723 home.RegionLocY = random.Next(0, 10000) * (int)Constants.RegionSize;
724
725 AddHyperlinkHomeRegion(user.ID, home, realHandle);
726
727 DumpUserData(user);
728 DumpRegionData(home);
729
730 }
731
732 public bool IsLocalUser(UUID userID)
733 {
734 CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
735 return IsLocalUser(uinfo);
736 }
737
738 #endregion
739
740 #region IHyperlink Misc
741
742 protected bool IsComingHome(ForeignUserProfileData userData)
743 {
744 return (userData.UserServerURI == LocalUserServerURI);
745 }
746
747 // Is the user going back to the home region or the home grid?
748 protected bool IsGoingHome(CachedUserInfo uinfo, GridRegion rinfo)
749 {
750 if (uinfo == null)
751 return false;
752
753 if (uinfo.UserProfile == null)
754 return false;
755
756 if (!(uinfo.UserProfile is ForeignUserProfileData))
757 // it's a home user, can't be outside to return home
758 return false;
759
760 // OK, it's a foreign user with a ForeignUserProfileData
761 // and is going back to exactly the home region.
762 // We can't check if it's going back to a non-home region
763 // of the home grid. That will be dealt with in the
764 // receiving end
765 return (uinfo.UserProfile.HomeRegionID == rinfo.RegionID);
766 }
767
768 protected bool IsLocalUser(CachedUserInfo uinfo)
769 {
770 if (uinfo == null)
771 return false;
772
773 return !(uinfo.UserProfile is ForeignUserProfileData);
774
775 }
776
777
778 protected bool IsLocalRegion(ulong handle)
779 {
780 return m_LocalScenes.ContainsKey(handle);
781 }
782
783 private void DumpUserData(ForeignUserProfileData userData)
784 {
785 m_log.Info(" ------------ User Data Dump ----------");
786 m_log.Info(" >> Name: " + userData.FirstName + " " + userData.SurName);
787 m_log.Info(" >> HomeID: " + userData.HomeRegionID);
788 m_log.Info(" >> UserServer: " + userData.UserServerURI);
789 m_log.Info(" >> InvServer: " + userData.UserInventoryURI);
790 m_log.Info(" >> AssetServer: " + userData.UserAssetURI);
791 m_log.Info(" ------------ -------------- ----------");
792 }
793
794 private void DumpRegionData(GridRegion rinfo)
795 {
796 m_log.Info(" ------------ Region Data Dump ----------");
797 m_log.Info(" >> handle: " + rinfo.RegionHandle);
798 m_log.Info(" >> coords: " + rinfo.RegionLocX + ", " + rinfo.RegionLocY);
799 m_log.Info(" >> external host name: " + rinfo.ExternalHostName);
800 m_log.Info(" >> http port: " + rinfo.HttpPort);
801 m_log.Info(" >> external EP address: " + rinfo.ExternalEndPoint.Address);
802 m_log.Info(" >> external EP port: " + rinfo.ExternalEndPoint.Port);
803 m_log.Info(" ------------ -------------- ----------");
804 }
805
806
807 #endregion
808
809
810 }
811}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs
index 144b5a4..1b00c8a 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs
@@ -238,6 +238,21 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
238 return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); 238 return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
239 } 239 }
240 240
241 public List<GridRegion> GetDefaultRegions(UUID scopeID)
242 {
243 return m_GridService.GetDefaultRegions(scopeID);
244 }
245
246 public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
247 {
248 return m_GridService.GetFallbackRegions(scopeID, x, y);
249 }
250
251 public int GetRegionFlags(UUID scopeID, UUID regionID)
252 {
253 return m_GridService.GetRegionFlags(scopeID, regionID);
254 }
255
241 #endregion 256 #endregion
242 257
243 public void NeighboursCommand(string module, string[] cmdparams) 258 public void NeighboursCommand(string module, string[] cmdparams)
@@ -250,5 +265,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
250 m_log.InfoFormat(" {0} @ {1}={2}", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize); 265 m_log.InfoFormat(" {0} @ {1}={2}", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize);
251 } 266 }
252 } 267 }
268
253 } 269 }
254} 270}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs
index 391e7c8..d44ddf4 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs
@@ -188,9 +188,31 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
188 return rinfo; 188 return rinfo;
189 } 189 }
190 190
191 // Let's not override GetRegionsByName -- let's get them all from the grid server 191 public override List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
192 {
193 List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber);
194 //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count);
195 List<GridRegion> grinfo = base.GetRegionsByName(scopeID, name, maxNumber);
196
197 if (grinfo != null)
198 {
199 //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count);
200 rinfo.AddRange(grinfo);
201 }
202
203 return rinfo;
204 }
205
192 // Let's not override GetRegionRange -- let's get them all from the grid server 206 // Let's not override GetRegionRange -- let's get them all from the grid server
193 207
208 public override int GetRegionFlags(UUID scopeID, UUID regionID)
209 {
210 int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID);
211 if (flags == -1)
212 flags = base.GetRegionFlags(scopeID, regionID);
213
214 return flags;
215 }
194 #endregion 216 #endregion
195 } 217 }
196} 218}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs
index 2ca90f8..95d8737 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs
@@ -56,7 +56,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests
56 config.AddConfig("GridService"); 56 config.AddConfig("GridService");
57 config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); 57 config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
58 config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); 58 config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
59 config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); 59 config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
60 60
61 m_LocalConnector = new LocalGridServicesConnector(config); 61 m_LocalConnector = new LocalGridServicesConnector(config);
62 } 62 }
@@ -92,7 +92,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests
92 r2.HttpPort = 9002; 92 r2.HttpPort = 9002;
93 r2.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0); 93 r2.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
94 s = new Scene(new RegionInfo()); 94 s = new Scene(new RegionInfo());
95 s.RegionInfo.RegionID = r1.RegionID; 95 s.RegionInfo.RegionID = r2.RegionID;
96 m_LocalConnector.AddRegion(s); 96 m_LocalConnector.AddRegion(s);
97 97
98 GridRegion r3 = new GridRegion(); 98 GridRegion r3 = new GridRegion();
@@ -104,7 +104,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests
104 r3.HttpPort = 9003; 104 r3.HttpPort = 9003;
105 r3.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0); 105 r3.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
106 s = new Scene(new RegionInfo()); 106 s = new Scene(new RegionInfo());
107 s.RegionInfo.RegionID = r1.RegionID; 107 s.RegionInfo.RegionID = r3.RegionID;
108 m_LocalConnector.AddRegion(s); 108 m_LocalConnector.AddRegion(s);
109 109
110 m_LocalConnector.RegisterRegion(UUID.Zero, r1); 110 m_LocalConnector.RegisterRegion(UUID.Zero, r1);
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs
new file mode 100644
index 0000000..6c01927
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs
@@ -0,0 +1,116 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.Reflection;
30
31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Services.Interfaces;
34
35using OpenMetaverse;
36using log4net;
37
38namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser
39{
40 public class ActivityDetector
41 {
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43
44 private IGridUserService m_GridUserService;
45 private Scene m_aScene;
46
47 public ActivityDetector(IGridUserService guservice)
48 {
49 m_GridUserService = guservice;
50 m_log.DebugFormat("[ACTIVITY DETECTOR]: starting ");
51 }
52
53 public void AddRegion(Scene scene)
54 {
55 // For now the only events we listen to are these
56 // But we could trigger the position update more often
57 scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
58 scene.EventManager.OnNewClient += OnNewClient;
59 scene.EventManager.OnAvatarEnteringNewParcel += OnEnteringNewParcel;
60
61 if (m_aScene == null)
62 m_aScene = scene;
63 }
64
65 public void RemoveRegion(Scene scene)
66 {
67 scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent;
68 scene.EventManager.OnNewClient -= OnNewClient;
69 }
70
71 public void OnMakeRootAgent(ScenePresence sp)
72 {
73 m_log.DebugFormat("[ACTIVITY DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName);
74
75 m_GridUserService.SetLastPosition(sp.UUID.ToString(), sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
76 }
77
78 public void OnNewClient(IClientAPI client)
79 {
80 client.OnConnectionClosed += OnConnectionClose;
81 }
82
83 public void OnConnectionClose(IClientAPI client)
84 {
85 if (client.IsLoggingOut)
86 {
87 object sp = null;
88 Vector3 position = new Vector3(128, 128, 0);
89 Vector3 lookat = new Vector3(0, 1, 0);
90
91 if (client.Scene.TryGetScenePresence(client.AgentId, out sp))
92 {
93 if (sp is ScenePresence)
94 {
95 if (((ScenePresence)sp).IsChildAgent)
96 return;
97
98 position = ((ScenePresence)sp).AbsolutePosition;
99 lookat = ((ScenePresence)sp).Lookat;
100 }
101 }
102 m_log.DebugFormat("[ACTIVITY DETECTOR]: Detected client logout {0} in {1}", client.AgentId, client.Scene.RegionInfo.RegionName);
103 m_GridUserService.LoggedOut(client.AgentId.ToString(), client.Scene.RegionInfo.RegionID, position, lookat);
104 }
105
106 }
107
108 void OnEnteringNewParcel(ScenePresence sp, int localLandID, UUID regionID)
109 {
110 // TODO: grab the parcel ID from ILandModule
111 // and send that along
112 m_GridUserService.SetLastPosition(sp.UUID.ToString(), sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
113 }
114
115 }
116}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs
new file mode 100644
index 0000000..d914a57
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs
@@ -0,0 +1,178 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Server.Base;
36using OpenSim.Services.Interfaces;
37
38using OpenMetaverse;
39
40namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser
41{
42 public class LocalGridUserServicesConnector : ISharedRegionModule, IGridUserService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 private IGridUserService m_GridUserService;
49
50 private ActivityDetector m_ActivityDetector;
51
52 private bool m_Enabled = false;
53
54 #region ISharedRegionModule
55
56 public Type ReplaceableInterface
57 {
58 get { return null; }
59 }
60
61 public string Name
62 {
63 get { return "LocalGridUserServicesConnector"; }
64 }
65
66 public void Initialise(IConfigSource source)
67 {
68 IConfig moduleConfig = source.Configs["Modules"];
69 if (moduleConfig != null)
70 {
71 string name = moduleConfig.GetString("GridUserServices", "");
72 if (name == Name)
73 {
74 IConfig userConfig = source.Configs["GridUserService"];
75 if (userConfig == null)
76 {
77 m_log.Error("[LOCAL GRID USER SERVICE CONNECTOR]: GridUserService missing from OpenSim.ini");
78 return;
79 }
80
81 string serviceDll = userConfig.GetString("LocalServiceModule", String.Empty);
82
83 if (serviceDll == String.Empty)
84 {
85 m_log.Error("[LOCAL GRID USER SERVICE CONNECTOR]: No LocalServiceModule named in section GridUserService");
86 return;
87 }
88
89 Object[] args = new Object[] { source };
90 m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(serviceDll, args);
91
92 if (m_GridUserService == null)
93 {
94 m_log.ErrorFormat(
95 "[LOCAL GRID USER SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll);
96 return;
97 }
98
99 m_ActivityDetector = new ActivityDetector(this);
100
101 m_Enabled = true;
102
103 m_log.Info("[LOCAL GRID USER SERVICE CONNECTOR]: Local grid user connector enabled");
104 }
105 }
106 }
107
108 public void PostInitialise()
109 {
110 if (!m_Enabled)
111 return;
112 }
113
114 public void Close()
115 {
116 if (!m_Enabled)
117 return;
118 }
119
120 public void AddRegion(Scene scene)
121 {
122 if (!m_Enabled)
123 return;
124
125 scene.RegisterModuleInterface<IGridUserService>(m_GridUserService);
126 m_ActivityDetector.AddRegion(scene);
127 }
128
129 public void RemoveRegion(Scene scene)
130 {
131 if (!m_Enabled)
132 return;
133
134 scene.UnregisterModuleInterface<IGridUserService>(this);
135 m_ActivityDetector.RemoveRegion(scene);
136 }
137
138 public void RegionLoaded(Scene scene)
139 {
140 if (!m_Enabled)
141 return;
142
143 m_log.InfoFormat("[LOCAL GRID USER SERVICE CONNECTOR]: Enabled local grid user for region {0}", scene.RegionInfo.RegionName);
144 }
145
146 #endregion
147
148 #region IGridUserService
149
150 public GridUserInfo LoggedIn(string userID)
151 {
152 return m_GridUserService.LoggedIn(userID);
153 }
154
155 public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
156 {
157 return m_GridUserService.LoggedOut(userID, regionID, lastPosition, lastLookAt);
158 }
159
160 public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt)
161 {
162 return m_GridUserService.SetHome(userID, homeID, homePosition, homeLookAt);
163 }
164
165 public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
166 {
167 return m_GridUserService.SetLastPosition(userID, regionID, lastPosition, lastLookAt);
168 }
169
170 public GridUserInfo GetGridUserInfo(string userID)
171 {
172 return m_GridUserService.GetGridUserInfo(userID);
173 }
174
175 #endregion
176
177 }
178}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs
new file mode 100644
index 0000000..e3e2e61
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs
@@ -0,0 +1,153 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.Reflection;
30
31using OpenSim.Region.Framework.Interfaces;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Server.Base;
34using OpenSim.Services.Interfaces;
35using OpenSim.Services.Connectors;
36
37using OpenMetaverse;
38using log4net;
39using Nini.Config;
40
41namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser
42{
43 public class RemoteGridUserServicesConnector : ISharedRegionModule, IGridUserService
44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 #region ISharedRegionModule
48
49 private bool m_Enabled = false;
50
51 private ActivityDetector m_ActivityDetector;
52 private IGridUserService m_RemoteConnector;
53
54 public Type ReplaceableInterface
55 {
56 get { return null; }
57 }
58
59 public string Name
60 {
61 get { return "RemoteGridUserServicesConnector"; }
62 }
63
64 public void Initialise(IConfigSource source)
65 {
66 IConfig moduleConfig = source.Configs["Modules"];
67 if (moduleConfig != null)
68 {
69 string name = moduleConfig.GetString("GridUserServices", "");
70 if (name == Name)
71 {
72 m_RemoteConnector = new GridUserServicesConnector(source);
73
74 m_Enabled = true;
75
76 m_ActivityDetector = new ActivityDetector(this);
77
78 m_log.Info("[REMOTE GRID USER CONNECTOR]: Remote grid user enabled");
79 }
80 }
81
82 }
83
84 public void PostInitialise()
85 {
86 }
87
88 public void Close()
89 {
90 }
91
92 public void AddRegion(Scene scene)
93 {
94 if (!m_Enabled)
95 return;
96
97 scene.RegisterModuleInterface<IGridUserService>(this);
98 m_ActivityDetector.AddRegion(scene);
99
100 m_log.InfoFormat("[REMOTE GRID USER CONNECTOR]: Enabled remote grid user for region {0}", scene.RegionInfo.RegionName);
101
102 }
103
104 public void RemoveRegion(Scene scene)
105 {
106 if (!m_Enabled)
107 return;
108
109 m_ActivityDetector.RemoveRegion(scene);
110 }
111
112 public void RegionLoaded(Scene scene)
113 {
114 if (!m_Enabled)
115 return;
116
117 }
118
119 #endregion
120
121 #region IGridUserService
122
123 public GridUserInfo LoggedIn(string userID)
124 {
125 m_log.Warn("[REMOTE GRID USER CONNECTOR]: LoggedIn not implemented at the simulators");
126 return null;
127 }
128
129 public bool LoggedOut(string userID, UUID region, Vector3 position, Vector3 lookat)
130 {
131 return m_RemoteConnector.LoggedOut(userID, region, position, lookat);
132 }
133
134
135 public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
136 {
137 return m_RemoteConnector.SetHome(userID, regionID, position, lookAt);
138 }
139
140 public bool SetLastPosition(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
141 {
142 return m_RemoteConnector.SetLastPosition(userID, regionID, position, lookAt);
143 }
144
145 public GridUserInfo GetGridUserInfo(string userID)
146 {
147 return m_RemoteConnector.GetGridUserInfo(userID);
148 }
149
150 #endregion
151
152 }
153}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/RESTInterregionComms.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/RESTInterregionComms.cs
deleted file mode 100644
index b7f3adf..0000000
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/RESTInterregionComms.cs
+++ /dev/null
@@ -1,842 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34using log4net;
35using Nini.Config;
36using OpenMetaverse;
37using OpenMetaverse.StructuredData;
38using OpenSim.Framework;
39using OpenSim.Framework.Communications;
40using OpenSim.Framework.Communications.Clients;
41using OpenSim.Region.Framework.Interfaces;
42using OpenSim.Region.Framework.Scenes;
43using OpenSim.Region.Framework.Scenes.Hypergrid;
44using OpenSim.Region.Framework.Scenes.Serialization;
45using OpenSim.Services.Interfaces;
46using GridRegion = OpenSim.Services.Interfaces.GridRegion;
47
48namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
49{
50 public class RESTInterregionComms : ISharedRegionModule, IInterregionCommsOut
51 {
52 private bool initialized = false;
53 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
54
55 protected bool m_enabled = false;
56 protected Scene m_aScene;
57 // RESTInterregionComms does not care about local regions; it delegates that to the Local module
58 protected LocalInterregionComms m_localBackend;
59
60 protected CommunicationsManager m_commsManager;
61
62 protected RegionToRegionClient m_regionClient;
63
64 protected IHyperlinkService m_hyperlinkService;
65
66 protected bool m_safemode;
67 protected IPAddress m_thisIP;
68
69 #region IRegionModule
70
71 public virtual void Initialise(IConfigSource config)
72 {
73 IConfig startupConfig = config.Configs["Communications"];
74
75 if ((startupConfig == null) || ((startupConfig != null)
76 && (startupConfig.GetString("InterregionComms", "RESTComms") == "RESTComms")))
77 {
78 m_log.Info("[REST COMMS]: Enabling InterregionComms RESTComms module");
79 m_enabled = true;
80 if (config.Configs["Hypergrid"] != null)
81 m_safemode = config.Configs["Hypergrid"].GetBoolean("safemode", false);
82 }
83 }
84
85 public virtual void PostInitialise()
86 {
87 }
88
89 public virtual void Close()
90 {
91 }
92
93 public void AddRegion(Scene scene)
94 {
95 }
96
97 public void RemoveRegion(Scene scene)
98 {
99 if (m_enabled)
100 {
101 m_localBackend.RemoveScene(scene);
102 scene.UnregisterModuleInterface<IInterregionCommsOut>(this);
103 }
104 }
105
106 public void RegionLoaded(Scene scene)
107 {
108 if (m_enabled)
109 {
110 if (!initialized)
111 {
112 InitOnce(scene);
113 initialized = true;
114 AddHTTPHandlers();
115 }
116 InitEach(scene);
117 }
118 }
119
120 public Type ReplaceableInterface
121 {
122 get { return null; }
123 }
124
125 public virtual string Name
126 {
127 get { return "RESTInterregionCommsModule"; }
128 }
129
130 protected virtual void InitEach(Scene scene)
131 {
132 m_localBackend.Init(scene);
133 scene.RegisterModuleInterface<IInterregionCommsOut>(this);
134 }
135
136 protected virtual void InitOnce(Scene scene)
137 {
138 m_localBackend = new LocalInterregionComms();
139 m_commsManager = scene.CommsManager;
140 m_aScene = scene;
141 m_hyperlinkService = m_aScene.RequestModuleInterface<IHyperlinkService>();
142 m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService);
143 m_thisIP = Util.GetHostFromDNS(scene.RegionInfo.ExternalHostName);
144 }
145
146 protected virtual void AddHTTPHandlers()
147 {
148 MainServer.Instance.AddHTTPHandler("/agent/", AgentHandler);
149 MainServer.Instance.AddHTTPHandler("/object/", ObjectHandler);
150 }
151
152 #endregion /* IRegionModule */
153
154 #region IInterregionComms
155
156 /**
157 * Agent-related communications
158 */
159
160 public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
161 {
162 // Try local first
163 if (m_localBackend.SendCreateChildAgent(regionHandle, aCircuit, teleportFlags, out reason))
164 return true;
165
166 // else do the remote thing
167 if (!m_localBackend.IsLocalRegion(regionHandle))
168 {
169 uint x = 0, y = 0;
170 Utils.LongToUInts(regionHandle, out x, out y);
171 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
172 if (regInfo != null)
173 {
174 m_regionClient.SendUserInformation(regInfo, aCircuit);
175
176 return m_regionClient.DoCreateChildAgentCall(regInfo, aCircuit, "None", teleportFlags, out reason);
177 }
178 //else
179 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
180 }
181 return false;
182 }
183
184 public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
185 {
186 // Try local first
187 if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
188 return true;
189
190 // else do the remote thing
191 if (!m_localBackend.IsLocalRegion(regionHandle))
192 {
193 uint x = 0, y = 0;
194 Utils.LongToUInts(regionHandle, out x, out y);
195 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
196 if (regInfo != null)
197 {
198 return m_regionClient.DoChildAgentUpdateCall(regInfo, cAgentData);
199 }
200 //else
201 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
202 }
203 return false;
204
205 }
206
207 public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
208 {
209 // Try local first
210 if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
211 return true;
212
213 // else do the remote thing
214 if (!m_localBackend.IsLocalRegion(regionHandle))
215 {
216 uint x = 0, y = 0;
217 Utils.LongToUInts(regionHandle, out x, out y);
218 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
219 if (regInfo != null)
220 {
221 return m_regionClient.DoChildAgentUpdateCall(regInfo, cAgentData);
222 }
223 //else
224 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
225 }
226 return false;
227
228 }
229
230 public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
231 {
232 // Try local first
233 if (m_localBackend.SendRetrieveRootAgent(regionHandle, id, out agent))
234 return true;
235
236 // else do the remote thing
237 if (!m_localBackend.IsLocalRegion(regionHandle))
238 {
239 uint x = 0, y = 0;
240 Utils.LongToUInts(regionHandle, out x, out y);
241 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
242 if (regInfo != null)
243 {
244 return m_regionClient.DoRetrieveRootAgentCall(regInfo, id, out agent);
245 }
246 //else
247 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
248 }
249 return false;
250
251 }
252
253 public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
254 {
255 // Try local first
256 if (m_localBackend.SendReleaseAgent(regionHandle, id, uri))
257 return true;
258
259 // else do the remote thing
260 return m_regionClient.DoReleaseAgentCall(regionHandle, id, uri);
261 }
262
263
264 public bool SendCloseAgent(ulong regionHandle, UUID id)
265 {
266 // Try local first
267 if (m_localBackend.SendCloseAgent(regionHandle, id))
268 return true;
269
270 // else do the remote thing
271 if (!m_localBackend.IsLocalRegion(regionHandle))
272 {
273 uint x = 0, y = 0;
274 Utils.LongToUInts(regionHandle, out x, out y);
275 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
276 if (regInfo != null)
277 {
278 return m_regionClient.DoCloseAgentCall(regInfo, id);
279 }
280 //else
281 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
282 }
283 return false;
284 }
285
286 /**
287 * Object-related communications
288 */
289
290 public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall)
291 {
292 // Try local first
293 if (m_localBackend.SendCreateObject(regionHandle, sog, true))
294 {
295 //m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
296 return true;
297 }
298
299 // else do the remote thing
300 if (!m_localBackend.IsLocalRegion(regionHandle))
301 {
302 uint x = 0, y = 0;
303 Utils.LongToUInts(regionHandle, out x, out y);
304 GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
305 if (regInfo != null)
306 {
307 return m_regionClient.DoCreateObjectCall(
308 regInfo, sog, SceneObjectSerializer.ToXml2Format(sog), m_aScene.m_allowScriptCrossings);
309 }
310 //else
311 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
312 }
313 return false;
314 }
315
316 public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID)
317 {
318 // Not Implemented
319 return false;
320 }
321
322 #endregion /* IInterregionComms */
323
324 #region Incoming calls from remote instances
325
326 /**
327 * Agent-related incoming calls
328 */
329
330 public Hashtable AgentHandler(Hashtable request)
331 {
332 //m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
333
334/* m_log.Debug("---------------------------");
335 m_log.Debug(" >> uri=" + request["uri"]);
336 m_log.Debug(" >> content-type=" + request["content-type"]);
337 m_log.Debug(" >> http-method=" + request["http-method"]);
338 m_log.Debug("---------------------------\n"); */
339 Hashtable responsedata = new Hashtable();
340 responsedata["content_type"] = "text/html";
341 responsedata["keepalive"] = false;
342
343
344 UUID agentID;
345 string action;
346 ulong regionHandle;
347 if (!GetParams((string)request["uri"], out agentID, out regionHandle, out action))
348 {
349 m_log.InfoFormat("[REST COMMS]: Invalid parameters for agent message {0}", request["uri"]);
350 responsedata["int_response_code"] = 404;
351 responsedata["str_response_string"] = "false";
352
353 return responsedata;
354 }
355
356 // Next, let's parse the verb
357 string method = (string)request["http-method"];
358 if (method.Equals("PUT"))
359 {
360 DoAgentPut(request, responsedata);
361 return responsedata;
362 }
363 else if (method.Equals("POST"))
364 {
365 DoAgentPost(request, responsedata, agentID);
366 return responsedata;
367 }
368 else if (method.Equals("GET"))
369 {
370 DoAgentGet(request, responsedata, agentID, regionHandle);
371 return responsedata;
372 }
373 else if (method.Equals("DELETE"))
374 {
375 DoAgentDelete(request, responsedata, agentID, action, regionHandle);
376 return responsedata;
377 }
378 else
379 {
380 m_log.InfoFormat("[REST COMMS]: method {0} not supported in agent message", method);
381 responsedata["int_response_code"] = 404;
382 responsedata["str_response_string"] = "false";
383
384 return responsedata;
385 }
386
387 }
388
389 protected virtual void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
390 {
391 if (m_safemode)
392 {
393 // Authentication
394 string authority = string.Empty;
395 string authToken = string.Empty;
396 if (!GetAuthentication(request, out authority, out authToken))
397 {
398 m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
399 responsedata["int_response_code"] = 403;
400 responsedata["str_response_string"] = "Forbidden";
401 return ;
402 }
403 if (!VerifyKey(id, authority, authToken))
404 {
405 m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
406 responsedata["int_response_code"] = 403;
407 responsedata["str_response_string"] = "Forbidden";
408 return ;
409 }
410 m_log.DebugFormat("[REST COMMS]: Authentication succeeded for {0}", id);
411 }
412
413 OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
414 if (args == null)
415 {
416 responsedata["int_response_code"] = 400;
417 responsedata["str_response_string"] = "false";
418 return;
419 }
420
421 // retrieve the regionhandle
422 ulong regionhandle = 0;
423 if (args["destination_handle"] != null)
424 UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
425
426 AgentCircuitData aCircuit = new AgentCircuitData();
427 try
428 {
429 aCircuit.UnpackAgentCircuitData(args);
430 }
431 catch (Exception ex)
432 {
433 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildCreate message {0}", ex.Message);
434 return;
435 }
436
437 OSDMap resp = new OSDMap(2);
438 string reason = String.Empty;
439 uint teleportFlags = 0;
440 if (args.ContainsKey("teleport_flags"))
441 {
442 teleportFlags = args["teleport_flags"].AsUInteger();
443 }
444
445 // This is the meaning of POST agent
446 m_regionClient.AdjustUserInformation(aCircuit);
447 bool result = m_localBackend.SendCreateChildAgent(regionhandle, aCircuit, teleportFlags, out reason);
448
449 resp["reason"] = OSD.FromString(reason);
450 resp["success"] = OSD.FromBoolean(result);
451
452 // TODO: add reason if not String.Empty?
453 responsedata["int_response_code"] = 200;
454 responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
455 }
456
457 protected virtual void DoAgentPut(Hashtable request, Hashtable responsedata)
458 {
459 OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
460 if (args == null)
461 {
462 responsedata["int_response_code"] = 400;
463 responsedata["str_response_string"] = "false";
464 return;
465 }
466
467 // retrieve the regionhandle
468 ulong regionhandle = 0;
469 if (args["destination_handle"] != null)
470 UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
471
472 string messageType;
473 if (args["message_type"] != null)
474 messageType = args["message_type"].AsString();
475 else
476 {
477 m_log.Warn("[REST COMMS]: Agent Put Message Type not found. ");
478 messageType = "AgentData";
479 }
480
481 bool result = true;
482 if ("AgentData".Equals(messageType))
483 {
484 AgentData agent = new AgentData();
485 try
486 {
487 agent.Unpack(args);
488 }
489 catch (Exception ex)
490 {
491 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
492 return;
493 }
494
495 //agent.Dump();
496 // This is one of the meanings of PUT agent
497 result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
498
499 }
500 else if ("AgentPosition".Equals(messageType))
501 {
502 AgentPosition agent = new AgentPosition();
503 try
504 {
505 agent.Unpack(args);
506 }
507 catch (Exception ex)
508 {
509 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
510 return;
511 }
512 //agent.Dump();
513 // This is one of the meanings of PUT agent
514 result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
515
516 }
517
518 responsedata["int_response_code"] = 200;
519 responsedata["str_response_string"] = result.ToString();
520 }
521
522 protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, ulong regionHandle)
523 {
524 IAgentData agent = null;
525 bool result = m_localBackend.SendRetrieveRootAgent(regionHandle, id, out agent);
526 OSDMap map = null;
527 if (result)
528 {
529 if (agent != null) // just to make sure
530 {
531 map = agent.Pack();
532 string strBuffer = "";
533 try
534 {
535 strBuffer = OSDParser.SerializeJsonString(map);
536 }
537 catch (Exception e)
538 {
539 m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
540 // ignore. buffer will be empty, caller should check.
541 }
542
543 responsedata["content_type"] = "application/json";
544 responsedata["int_response_code"] = 200;
545 responsedata["str_response_string"] = strBuffer;
546 }
547 else
548 {
549 responsedata["int_response_code"] = 500;
550 responsedata["str_response_string"] = "Internal error";
551 }
552 }
553 else
554 {
555 responsedata["int_response_code"] = 404;
556 responsedata["str_response_string"] = "Not Found";
557 }
558 }
559
560 protected virtual void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, ulong regionHandle)
561 {
562 //m_log.Debug(" >>> DoDelete action:" + action + "; regionHandle:" + regionHandle);
563
564 if (action.Equals("release"))
565 m_localBackend.SendReleaseAgent(regionHandle, id, "");
566 else
567 m_localBackend.SendCloseAgent(regionHandle, id);
568
569 responsedata["int_response_code"] = 200;
570 responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
571
572 m_log.Debug("[REST COMMS]: Agent Deleted.");
573 }
574
575 /**
576 * Object-related incoming calls
577 */
578
579 public Hashtable ObjectHandler(Hashtable request)
580 {
581 m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
582
583 /* m_log.Debug("---------------------------");
584 m_log.Debug(" >> uri=" + request["uri"]);
585 m_log.Debug(" >> content-type=" + request["content-type"]);
586 m_log.Debug(" >> http-method=" + request["http-method"]);
587 m_log.Debug("---------------------------\n"); */
588
589 Hashtable responsedata = new Hashtable();
590 responsedata["content_type"] = "text/html";
591
592 UUID objectID;
593 string action;
594 ulong regionHandle;
595 if (!GetParams((string)request["uri"], out objectID, out regionHandle, out action))
596 {
597 m_log.InfoFormat("[REST COMMS]: Invalid parameters for object message {0}", request["uri"]);
598 responsedata["int_response_code"] = 404;
599 responsedata["str_response_string"] = "false";
600
601 return responsedata;
602 }
603
604 // Next, let's parse the verb
605 string method = (string)request["http-method"];
606 if (method.Equals("POST"))
607 {
608 DoObjectPost(request, responsedata, regionHandle);
609 return responsedata;
610 }
611 else if (method.Equals("PUT"))
612 {
613 DoObjectPut(request, responsedata, regionHandle);
614 return responsedata;
615 }
616 //else if (method.Equals("DELETE"))
617 //{
618 // DoObjectDelete(request, responsedata, agentID, action, regionHandle);
619 // return responsedata;
620 //}
621 else
622 {
623 m_log.InfoFormat("[REST COMMS]: method {0} not supported in object message", method);
624 responsedata["int_response_code"] = 404;
625 responsedata["str_response_string"] = "false";
626
627 return responsedata;
628 }
629
630 }
631
632 protected virtual void DoObjectPost(Hashtable request, Hashtable responsedata, ulong regionhandle)
633 {
634 OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
635 if (args == null)
636 {
637 responsedata["int_response_code"] = 400;
638 responsedata["str_response_string"] = "false";
639 return;
640 }
641
642 string sogXmlStr = "", extraStr = "", stateXmlStr = "";
643 if (args["sog"] != null)
644 sogXmlStr = args["sog"].AsString();
645 if (args["extra"] != null)
646 extraStr = args["extra"].AsString();
647
648 IScene s = m_localBackend.GetScene(regionhandle);
649 SceneObjectGroup sog = null;
650 try
651 {
652 sog = SceneObjectSerializer.FromXml2Format(sogXmlStr);
653 sog.ExtraFromXmlString(extraStr);
654 }
655 catch (Exception ex)
656 {
657 m_log.InfoFormat("[REST COMMS]: exception on deserializing scene object {0}", ex.Message);
658 responsedata["int_response_code"] = 400;
659 responsedata["str_response_string"] = "false";
660 return;
661 }
662
663 if ((args["state"] != null) && m_aScene.m_allowScriptCrossings)
664 {
665 stateXmlStr = args["state"].AsString();
666 if (stateXmlStr != "")
667 {
668 try
669 {
670 sog.SetState(stateXmlStr, s);
671 }
672 catch (Exception ex)
673 {
674 m_log.InfoFormat("[REST COMMS]: exception on setting state for scene object {0}", ex.Message);
675
676 }
677 }
678 }
679 // This is the meaning of POST object
680 bool result = m_localBackend.SendCreateObject(regionhandle, sog, false);
681
682 responsedata["int_response_code"] = 200;
683 responsedata["str_response_string"] = result.ToString();
684 }
685
686 protected virtual void DoObjectPut(Hashtable request, Hashtable responsedata, ulong regionhandle)
687 {
688 OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
689 if (args == null)
690 {
691 responsedata["int_response_code"] = 400;
692 responsedata["str_response_string"] = "false";
693 return;
694 }
695
696 UUID userID = UUID.Zero, itemID = UUID.Zero;
697 if (args["userid"] != null)
698 userID = args["userid"].AsUUID();
699 if (args["itemid"] != null)
700 itemID = args["itemid"].AsUUID();
701
702 // This is the meaning of PUT object
703 bool result = m_localBackend.SendCreateObject(regionhandle, userID, itemID);
704
705 responsedata["int_response_code"] = 200;
706 responsedata["str_response_string"] = result.ToString();
707 }
708
709 #endregion
710
711 #region Misc
712
713
714 /// <summary>
715 /// Extract the param from an uri.
716 /// </summary>
717 /// <param name="uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release</param>
718 /// <param name="uri">uuid on uuid field</param>
719 /// <param name="action">optional action</param>
720 public static bool GetParams(string uri, out UUID uuid, out ulong regionHandle, out string action)
721 {
722 uuid = UUID.Zero;
723 action = "";
724 regionHandle = 0;
725
726 uri = uri.Trim(new char[] { '/' });
727 string[] parts = uri.Split('/');
728 if (parts.Length <= 1)
729 {
730 return false;
731 }
732 else
733 {
734 if (!UUID.TryParse(parts[1], out uuid))
735 return false;
736
737 if (parts.Length >= 3)
738 UInt64.TryParse(parts[2], out regionHandle);
739 if (parts.Length >= 4)
740 action = parts[3];
741
742 return true;
743 }
744 }
745
746 public static bool GetAuthentication(Hashtable request, out string authority, out string authKey)
747 {
748 authority = string.Empty;
749 authKey = string.Empty;
750
751 Uri authUri;
752 Hashtable headers = (Hashtable)request["headers"];
753
754 // Authorization keys look like this:
755 // http://orgrid.org:8002/<uuid>
756 if (headers.ContainsKey("authorization") && (string)headers["authorization"] != "None")
757 {
758 if (Uri.TryCreate((string)headers["authorization"], UriKind.Absolute, out authUri))
759 {
760 authority = authUri.Authority;
761 authKey = authUri.PathAndQuery.Trim('/');
762 m_log.DebugFormat("[REST COMMS]: Got authority {0} and key {1}", authority, authKey);
763 return true;
764 }
765 else
766 m_log.Debug("[REST COMMS]: Wrong format for Authorization header: " + (string)headers["authorization"]);
767 }
768 else
769 m_log.Debug("[REST COMMS]: Authorization header not found");
770
771 return false;
772 }
773
774 bool VerifyKey(UUID userID, string authority, string key)
775 {
776 string[] parts = authority.Split(':');
777 IPAddress ipaddr = IPAddress.None;
778 uint port = 0;
779 if (parts.Length <= 2)
780 ipaddr = Util.GetHostFromDNS(parts[0]);
781 if (parts.Length == 2)
782 UInt32.TryParse(parts[1], out port);
783
784 // local authority (standalone), local call
785 if (m_thisIP.Equals(ipaddr) && (m_aScene.RegionInfo.HttpPort == port))
786 return ((IAuthentication)m_aScene.CommsManager.UserAdminService).VerifyKey(userID, key);
787 // remote call
788 else
789 return AuthClient.VerifyKey("http://" + authority, userID, key);
790 }
791
792
793 #endregion Misc
794
795 protected class RegionToRegionClient : RegionClient
796 {
797 Scene m_aScene = null;
798 IHyperlinkService m_hyperlinkService;
799
800 public RegionToRegionClient(Scene s, IHyperlinkService hyperService)
801 {
802 m_aScene = s;
803 m_hyperlinkService = hyperService;
804 }
805
806 public override ulong GetRegionHandle(ulong handle)
807 {
808 if (m_aScene.SceneGridService is HGSceneCommunicationService)
809 {
810 if (m_hyperlinkService != null)
811 return m_hyperlinkService.FindRegionHandle(handle);
812 }
813
814 return handle;
815 }
816
817 public override bool IsHyperlink(ulong handle)
818 {
819 if (m_aScene.SceneGridService is HGSceneCommunicationService)
820 {
821 if ((m_hyperlinkService != null) && (m_hyperlinkService.GetHyperlinkRegion(handle) != null))
822 return true;
823 }
824 return false;
825 }
826
827 public override void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit)
828 {
829 if (m_hyperlinkService != null)
830 m_hyperlinkService.SendUserInformation(regInfo, aCircuit);
831
832 }
833
834 public override void AdjustUserInformation(AgentCircuitData aCircuit)
835 {
836 if (m_hyperlinkService != null)
837 m_hyperlinkService.AdjustUserInformation(aCircuit);
838 }
839 }
840
841 }
842}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/BaseInventoryConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/BaseInventoryConnector.cs
index 811569f..1e51187 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/BaseInventoryConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/BaseInventoryConnector.cs
@@ -40,12 +40,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
40{ 40{
41 public abstract class BaseInventoryConnector : IInventoryService 41 public abstract class BaseInventoryConnector : IInventoryService
42 { 42 {
43 protected InventoryCache m_cache; 43 protected static InventoryCache m_cache;
44 private static bool m_Initialized;
44 45
45 protected virtual void Init(IConfigSource source) 46 protected virtual void Init(IConfigSource source)
46 { 47 {
47 m_cache = new InventoryCache(); 48 if (!m_Initialized)
48 m_cache.Init(source, this); 49 {
50 m_cache = new InventoryCache();
51 m_cache.Init(source, this);
52 m_Initialized = true;
53 }
49 } 54 }
50 55
51 /// <summary> 56 /// <summary>
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
index 1fdf1ef..e09db15 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
@@ -31,7 +31,7 @@ using System;
31using System.Collections.Generic; 31using System.Collections.Generic;
32using System.Reflection; 32using System.Reflection;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications.Cache; 34
35using OpenSim.Server.Base; 35using OpenSim.Server.Base;
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
@@ -41,31 +41,21 @@ using OpenMetaverse;
41 41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory 42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
43{ 43{
44 public class HGInventoryBroker : BaseInventoryConnector, ISharedRegionModule, IInventoryService 44 public class HGInventoryBroker : ISharedRegionModule, IInventoryService
45 { 45 {
46 private static readonly ILog m_log = 46 private static readonly ILog m_log =
47 LogManager.GetLogger( 47 LogManager.GetLogger(
48 MethodBase.GetCurrentMethod().DeclaringType); 48 MethodBase.GetCurrentMethod().DeclaringType);
49 49
50 private bool m_Enabled = false; 50 private static bool m_Enabled = false;
51 private bool m_Initialized = false;
52 private Scene m_Scene;
53 private UserProfileCacheService m_UserProfileService; // This should change to IUserProfileService
54 51
55 private IInventoryService m_GridService; 52 private static IInventoryService m_LocalGridInventoryService;
56 private ISessionAuthInventoryService m_HGService; 53 private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>();
57 54
58 private string m_LocalGridInventoryURI = string.Empty; 55 // A cache of userIDs --> ServiceURLs, for HGBroker only
56 protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>();
59 57
60 private string LocalGridInventory 58 private List<Scene> m_Scenes = new List<Scene>();
61 {
62 get
63 {
64 if (m_LocalGridInventoryURI == null || m_LocalGridInventoryURI == "")
65 m_LocalGridInventoryURI = m_Scene.CommsManager.NetworkServersInfo.InventoryURL;
66 return m_LocalGridInventoryURI;
67 }
68 }
69 59
70 public Type ReplaceableInterface 60 public Type ReplaceableInterface
71 { 61 {
@@ -94,8 +84,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
94 84
95 string localDll = inventoryConfig.GetString("LocalGridInventoryService", 85 string localDll = inventoryConfig.GetString("LocalGridInventoryService",
96 String.Empty); 86 String.Empty);
97 string HGDll = inventoryConfig.GetString("HypergridInventoryService", 87 //string HGDll = inventoryConfig.GetString("HypergridInventoryService",
98 String.Empty); 88 // String.Empty);
99 89
100 if (localDll == String.Empty) 90 if (localDll == String.Empty)
101 { 91 {
@@ -104,39 +94,19 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
104 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); 94 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
105 } 95 }
106 96
107 if (HGDll == String.Empty)
108 {
109 m_log.Error("[HG INVENTORY CONNECTOR]: No HypergridInventoryService named in section InventoryService");
110 //return;
111 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
112 }
113
114 Object[] args = new Object[] { source }; 97 Object[] args = new Object[] { source };
115 m_GridService = 98 m_LocalGridInventoryService =
116 ServerUtils.LoadPlugin<IInventoryService>(localDll, 99 ServerUtils.LoadPlugin<IInventoryService>(localDll,
117 args); 100 args);
118 101
119 m_HGService = 102 if (m_LocalGridInventoryService == null)
120 ServerUtils.LoadPlugin<ISessionAuthInventoryService>(HGDll,
121 args);
122
123 if (m_GridService == null)
124 { 103 {
125 m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service"); 104 m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
126 return; 105 return;
127 } 106 }
128 if (m_HGService == null)
129 {
130 m_log.Error("[HG INVENTORY CONNECTOR]: Can't load hypergrid inventory service");
131 return;
132 }
133
134 m_LocalGridInventoryURI = inventoryConfig.GetString("InventoryServerURI", string.Empty);
135
136 Init(source);
137 107
138 m_Enabled = true; 108 m_Enabled = true;
139 m_log.Info("[HG INVENTORY CONNECTOR]: HG inventory broker enabled"); 109 m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType());
140 } 110 }
141 } 111 }
142 } 112 }
@@ -154,28 +124,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
154 if (!m_Enabled) 124 if (!m_Enabled)
155 return; 125 return;
156 126
157 if (!m_Initialized) 127 m_Scenes.Add(scene);
158 {
159 m_Scene = scene;
160 // HACK for now. Ugh!
161 m_UserProfileService = m_Scene.CommsManager.UserProfileCacheService;
162 // ugh!
163 m_UserProfileService.SetInventoryService(this);
164 scene.CommsManager.UserService.SetInventoryService(this);
165
166 m_Initialized = true;
167 }
168 128
169 scene.RegisterModuleInterface<IInventoryService>(this); 129 scene.RegisterModuleInterface<IInventoryService>(this);
170 m_cache.AddRegion(scene); 130
131 scene.EventManager.OnClientClosed += OnClientClosed;
132
171 } 133 }
172 134
173 public void RemoveRegion(Scene scene) 135 public void RemoveRegion(Scene scene)
174 { 136 {
175 if (!m_Enabled) 137 if (!m_Enabled)
176 return; 138 return;
177 139
178 m_cache.RemoveRegion(scene); 140 m_Scenes.Remove(scene);
179 } 141 }
180 142
181 public void RegionLoaded(Scene scene) 143 public void RegionLoaded(Scene scene)
@@ -187,260 +149,307 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
187 149
188 } 150 }
189 151
190 #region IInventoryService 152 #region URL Cache
191 153
192 public override bool CreateUserInventory(UUID userID) 154 void OnClientClosed(UUID clientID, Scene scene)
193 { 155 {
194 return m_GridService.CreateUserInventory(userID); 156 if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache
157 {
158 ScenePresence sp = null;
159 foreach (Scene s in m_Scenes)
160 {
161 s.TryGetScenePresence(clientID, out sp);
162 if ((sp != null) && !sp.IsChildAgent && (s != scene))
163 {
164 m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache",
165 scene.RegionInfo.RegionName, clientID);
166 return;
167 }
168 }
169 DropInventoryServiceURL(clientID);
170 }
195 } 171 }
196 172
197 public override List<InventoryFolderBase> GetInventorySkeleton(UUID userId) 173 /// <summary>
174 /// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
175 /// and sticks it in the cache
176 /// </summary>
177 /// <param name="userID"></param>
178 private void CacheInventoryServiceURL(UUID userID)
198 { 179 {
199 return m_GridService.GetInventorySkeleton(userId); 180 if (m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, userID) == null)
181 {
182 // The user does not have a local account; let's cache its service URL
183 string inventoryURL = string.Empty;
184 ScenePresence sp = null;
185 foreach (Scene scene in m_Scenes)
186 {
187 scene.TryGetScenePresence(userID, out sp);
188 if (sp != null)
189 {
190 AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
191 if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
192 {
193 inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
194 if (inventoryURL != null && inventoryURL != string.Empty)
195 {
196 inventoryURL = inventoryURL.Trim(new char[] { '/' });
197 m_InventoryURLs.Add(userID, inventoryURL);
198 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
199 return;
200 }
201 }
202 }
203 }
204 }
205
206 // else put a null; it means that the methods should forward to local grid's inventory
207 m_InventoryURLs.Add(userID, null);
200 } 208 }
201 209
202 public override InventoryCollection GetUserInventory(UUID userID) 210 private void DropInventoryServiceURL(UUID userID)
203 { 211 {
204 if (IsLocalGridUser(userID)) 212 lock (m_InventoryURLs)
205 return m_GridService.GetUserInventory(userID); 213 if (m_InventoryURLs.ContainsKey(userID))
206 else 214 {
207 return null; 215 string url = m_InventoryURLs[userID];
216 m_InventoryURLs.Remove(userID);
217 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
218 }
208 } 219 }
209 220
210 public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback) 221 public string GetInventoryServiceURL(UUID userID)
211 { 222 {
212 if (IsLocalGridUser(userID)) 223 if (m_InventoryURLs.ContainsKey(userID))
213 m_GridService.GetUserInventory(userID, callback); 224 return m_InventoryURLs[userID];
225
214 else 226 else
215 { 227 CacheInventoryServiceURL(userID);
216 UUID sessionID = GetSessionID(userID); 228
217 string uri = GetUserInventoryURI(userID) + "/" + userID.ToString(); 229 return m_InventoryURLs[userID];
218 m_HGService.GetUserInventory(uri, sessionID, callback);
219 }
220 } 230 }
231 #endregion
221 232
222 // Inherited. See base 233 #region IInventoryService
223 //public override InventoryFolderBase GetFolderForType(UUID userID, AssetType type) 234
224 //{ 235 public bool CreateUserInventory(UUID userID)
225 // if (IsLocalGridUser(userID)) 236 {
226 // return m_GridService.GetFolderForType(userID, type); 237 return m_LocalGridInventoryService.CreateUserInventory(userID);
227 // else
228 // {
229 // UUID sessionID = GetSessionID(userID);
230 // string uri = GetUserInventoryURI(userID) + "/" + userID.ToString();
231 // // !!!!!!
232 // return null;
233 // //return m_HGService.GetFolderForType(uri, sessionID, type);
234 // }
235 //}
236
237 public override InventoryCollection GetFolderContent(UUID userID, UUID folderID)
238 {
239 if (IsLocalGridUser(userID))
240 return m_GridService.GetFolderContent(userID, folderID);
241 else
242 {
243 UUID sessionID = GetSessionID(userID);
244 string uri = GetUserInventoryURI(userID) + "/" + userID.ToString();
245 return m_HGService.GetFolderContent(uri, folderID, sessionID);
246 }
247 } 238 }
248 239
249 public override Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID) 240 public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
250 { 241 {
251 if (IsLocalGridUser(userID)) 242 return m_LocalGridInventoryService.GetInventorySkeleton(userId);
252 {
253 // This is not pretty, but it will have to do for now
254 if (m_GridService is BaseInventoryConnector)
255 {
256 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetSystemsFolders redirected to RemoteInventoryServiceConnector module");
257 return ((BaseInventoryConnector)m_GridService).GetSystemFolders(userID);
258 }
259 else
260 {
261 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetSystemsFolders redirected to GetSystemFoldersLocal");
262 return GetSystemFoldersLocal(userID);
263 }
264 }
265 else
266 {
267 UUID sessionID = GetSessionID(userID);
268 string uri = GetUserInventoryURI(userID) + "/" + userID.ToString();
269 return m_HGService.GetSystemFolders(uri, sessionID);
270 }
271 } 243 }
272 244
273 private Dictionary<AssetType, InventoryFolderBase> GetSystemFoldersLocal(UUID userID) 245 public InventoryCollection GetUserInventory(UUID userID)
274 { 246 {
275 InventoryFolderBase root = m_GridService.GetRootFolder(userID); 247 return null;
276 if (root != null) 248 }
277 {
278 InventoryCollection content = m_GridService.GetFolderContent(userID, root.ID);
279 if (content != null)
280 {
281 Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>();
282 foreach (InventoryFolderBase folder in content.Folders)
283 {
284 //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: scanning folder type {0}", (AssetType)folder.Type);
285 if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
286 folders[(AssetType)folder.Type] = folder;
287 }
288 // Put the root folder there, as type Folder
289 folders[AssetType.Folder] = root;
290 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: System folders count for {0}: {1}", userID, folders.Count);
291 return folders;
292 }
293 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Root folder content not found for {0}", userID);
294 249
295 } 250 public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
251 {
252 }
253
254 public InventoryFolderBase GetRootFolder(UUID userID)
255 {
256 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
257
258 string invURL = GetInventoryServiceURL(userID);
296 259
297 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Root folder not found for {0}", userID); 260 if (invURL == null) // not there, forward to local inventory connector to resolve
261 return m_LocalGridInventoryService.GetRootFolder(userID);
298 262
299 return new Dictionary<AssetType, InventoryFolderBase>(); 263 IInventoryService connector = GetConnector(invURL);
264
265 return connector.GetRootFolder(userID);
300 } 266 }
301 267
302 public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) 268 public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
303 { 269 {
304 if (IsLocalGridUser(userID)) 270 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
305 return m_GridService.GetFolderItems(userID, folderID); 271
306 else 272 string invURL = GetInventoryServiceURL(userID);
307 { 273
308 UUID sessionID = GetSessionID(userID); 274 if (invURL == null) // not there, forward to local inventory connector to resolve
309 string uri = GetUserInventoryURI(userID) + "/" + userID; 275 return m_LocalGridInventoryService.GetFolderForType(userID, type);
310 return m_HGService.GetFolderItems(uri, folderID, sessionID); 276
311 } 277 IInventoryService connector = GetConnector(invURL);
278
279 return connector.GetFolderForType(userID, type);
280 }
281
282 public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
283 {
284 m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
285
286 string invURL = GetInventoryServiceURL(userID);
287
288 if (invURL == null) // not there, forward to local inventory connector to resolve
289 return m_LocalGridInventoryService.GetFolderContent(userID, folderID);
290
291 IInventoryService connector = GetConnector(invURL);
292
293 return connector.GetFolderContent(userID, folderID);
294
295 }
296
297 public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
298 {
299 m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
300
301 string invURL = GetInventoryServiceURL(userID);
302
303 if (invURL == null) // not there, forward to local inventory connector to resolve
304 return m_LocalGridInventoryService.GetFolderItems(userID, folderID);
305
306 IInventoryService connector = GetConnector(invURL);
307
308 return connector.GetFolderItems(userID, folderID);
309
312 } 310 }
313 311
314 public override bool AddFolder(InventoryFolderBase folder) 312 public bool AddFolder(InventoryFolderBase folder)
315 { 313 {
316 if (folder == null) 314 if (folder == null)
317 return false; 315 return false;
318 316
319 if (IsLocalGridUser(folder.Owner)) 317 m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
320 return m_GridService.AddFolder(folder); 318
321 else 319 string invURL = GetInventoryServiceURL(folder.Owner);
322 { 320
323 UUID sessionID = GetSessionID(folder.Owner); 321 if (invURL == null) // not there, forward to local inventory connector to resolve
324 string uri = GetUserInventoryURI(folder.Owner) + "/" + folder.Owner.ToString(); 322 return m_LocalGridInventoryService.AddFolder(folder);
325 return m_HGService.AddFolder(uri, folder, sessionID); 323
326 } 324 IInventoryService connector = GetConnector(invURL);
325
326 return connector.AddFolder(folder);
327 } 327 }
328 328
329 public override bool UpdateFolder(InventoryFolderBase folder) 329 public bool UpdateFolder(InventoryFolderBase folder)
330 { 330 {
331 if (folder == null) 331 if (folder == null)
332 return false; 332 return false;
333 333
334 if (IsLocalGridUser(folder.Owner)) 334 m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
335 return m_GridService.UpdateFolder(folder); 335
336 else 336 string invURL = GetInventoryServiceURL(folder.Owner);
337 { 337
338 UUID sessionID = GetSessionID(folder.Owner); 338 if (invURL == null) // not there, forward to local inventory connector to resolve
339 string uri = GetUserInventoryURI(folder.Owner) + "/" + folder.Owner.ToString(); 339 return m_LocalGridInventoryService.UpdateFolder(folder);
340 return m_HGService.UpdateFolder(uri, folder, sessionID); 340
341 } 341 IInventoryService connector = GetConnector(invURL);
342
343 return connector.UpdateFolder(folder);
342 } 344 }
343 345
344 public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) 346 public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
345 { 347 {
346 if (folderIDs == null) 348 if (folderIDs == null)
347 return false; 349 return false;
348 if (folderIDs.Count == 0) 350 if (folderIDs.Count == 0)
349 return false; 351 return false;
350 352
351 if (IsLocalGridUser(ownerID)) 353 m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
352 return m_GridService.DeleteFolders(ownerID, folderIDs); 354
353 else 355 string invURL = GetInventoryServiceURL(ownerID);
354 { 356
355 UUID sessionID = GetSessionID(ownerID); 357 if (invURL == null) // not there, forward to local inventory connector to resolve
356 string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString(); 358 return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs);
357 return m_HGService.DeleteFolders(uri, folderIDs, sessionID); 359
358 } 360 IInventoryService connector = GetConnector(invURL);
361
362 return connector.DeleteFolders(ownerID, folderIDs);
359 } 363 }
360 364
361 public override bool MoveFolder(InventoryFolderBase folder) 365 public bool MoveFolder(InventoryFolderBase folder)
362 { 366 {
363 if (folder == null) 367 if (folder == null)
364 return false; 368 return false;
365 369
366 if (IsLocalGridUser(folder.Owner)) 370 m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
367 return m_GridService.MoveFolder(folder); 371
368 else 372 string invURL = GetInventoryServiceURL(folder.Owner);
369 { 373
370 UUID sessionID = GetSessionID(folder.Owner); 374 if (invURL == null) // not there, forward to local inventory connector to resolve
371 string uri = GetUserInventoryURI(folder.Owner) + "/" + folder.Owner.ToString(); 375 return m_LocalGridInventoryService.MoveFolder(folder);
372 return m_HGService.MoveFolder(uri, folder, sessionID); 376
373 } 377 IInventoryService connector = GetConnector(invURL);
378
379 return connector.MoveFolder(folder);
374 } 380 }
375 381
376 public override bool PurgeFolder(InventoryFolderBase folder) 382 public bool PurgeFolder(InventoryFolderBase folder)
377 { 383 {
378 if (folder == null) 384 if (folder == null)
379 return false; 385 return false;
380 386
381 if (IsLocalGridUser(folder.Owner)) 387 m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
382 return m_GridService.PurgeFolder(folder);
383 else
384 {
385 UUID sessionID = GetSessionID(folder.Owner);
386 string uri = GetUserInventoryURI(folder.Owner) + "/" + folder.Owner.ToString();
387 return m_HGService.PurgeFolder(uri, folder, sessionID);
388 }
389 }
390 388
391 // public bool AddItem(InventoryItemBase item) inherited 389 string invURL = GetInventoryServiceURL(folder.Owner);
392 // Uses AddItemPlain
393 390
394 protected override bool AddItemPlain(InventoryItemBase item) 391 if (invURL == null) // not there, forward to local inventory connector to resolve
392 return m_LocalGridInventoryService.PurgeFolder(folder);
393
394 IInventoryService connector = GetConnector(invURL);
395
396 return connector.PurgeFolder(folder);
397 }
398
399 public bool AddItem(InventoryItemBase item)
395 { 400 {
396 if (item == null) 401 if (item == null)
397 return false; 402 return false;
398 403
399 if (IsLocalGridUser(item.Owner)) 404 m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
400 { 405
401 return m_GridService.AddItem(item); 406 string invURL = GetInventoryServiceURL(item.Owner);
402 } 407
403 else 408 if (invURL == null) // not there, forward to local inventory connector to resolve
404 { 409 return m_LocalGridInventoryService.AddItem(item);
405 UUID sessionID = GetSessionID(item.Owner); 410
406 string uri = GetUserInventoryURI(item.Owner) + "/" + item.Owner.ToString(); 411 IInventoryService connector = GetConnector(invURL);
407 return m_HGService.AddItem(uri, item, sessionID); 412
408 } 413 return connector.AddItem(item);
409 } 414 }
410 415
411 public override bool UpdateItem(InventoryItemBase item) 416 public bool UpdateItem(InventoryItemBase item)
412 { 417 {
413 if (item == null) 418 if (item == null)
414 return false; 419 return false;
415 420
416 if (IsLocalGridUser(item.Owner)) 421 m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
417 return m_GridService.UpdateItem(item); 422
418 else 423 string invURL = GetInventoryServiceURL(item.Owner);
419 { 424
420 UUID sessionID = GetSessionID(item.Owner); 425 if (invURL == null) // not there, forward to local inventory connector to resolve
421 string uri = GetUserInventoryURI(item.Owner) + "/" + item.Owner.ToString(); 426 return m_LocalGridInventoryService.UpdateItem(item);
422 return m_HGService.UpdateItem(uri, item, sessionID); 427
423 } 428 IInventoryService connector = GetConnector(invURL);
429
430 return connector.UpdateItem(item);
424 } 431 }
425 432
426 public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items) 433 public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
427 { 434 {
428 if (items == null) 435 if (items == null)
429 return false; 436 return false;
430 if (items.Count == 0) 437 if (items.Count == 0)
431 return true; 438 return true;
432 439
433 if (IsLocalGridUser(ownerID)) 440 m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
434 return m_GridService.MoveItems(ownerID, items); 441
435 else 442 string invURL = GetInventoryServiceURL(ownerID);
436 { 443
437 UUID sessionID = GetSessionID(ownerID); 444 if (invURL == null) // not there, forward to local inventory connector to resolve
438 string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString(); 445 return m_LocalGridInventoryService.MoveItems(ownerID, items);
439 return m_HGService.MoveItems(uri, items, sessionID); 446
440 } 447 IInventoryService connector = GetConnector(invURL);
448
449 return connector.MoveItems(ownerID, items);
441 } 450 }
442 451
443 public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs) 452 public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
444 { 453 {
445 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID); 454 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
446 455
@@ -449,127 +458,99 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
449 if (itemIDs.Count == 0) 458 if (itemIDs.Count == 0)
450 return true; 459 return true;
451 460
452 if (IsLocalGridUser(ownerID)) 461 m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteItems for " + ownerID);
453 return m_GridService.DeleteItems(ownerID, itemIDs); 462
454 else 463 string invURL = GetInventoryServiceURL(ownerID);
455 { 464
456 UUID sessionID = GetSessionID(ownerID); 465 if (invURL == null) // not there, forward to local inventory connector to resolve
457 string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString(); 466 return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs);
458 return m_HGService.DeleteItems(uri, itemIDs, sessionID); 467
459 } 468 IInventoryService connector = GetConnector(invURL);
469
470 return connector.DeleteItems(ownerID, itemIDs);
460 } 471 }
461 472
462 public override InventoryItemBase GetItem(InventoryItemBase item) 473 public InventoryItemBase GetItem(InventoryItemBase item)
463 { 474 {
464 if (item == null) 475 if (item == null)
465 return null; 476 return null;
466 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetItem {0} for user {1}", item.ID, item.Owner); 477 m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
467 if (IsLocalGridUser(item.Owner)) 478
468 return m_GridService.GetItem(item); 479 string invURL = GetInventoryServiceURL(item.Owner);
469 else 480
470 { 481 if (invURL == null) // not there, forward to local inventory connector to resolve
471 UUID sessionID = GetSessionID(item.Owner); 482 return m_LocalGridInventoryService.GetItem(item);
472 string uri = GetUserInventoryURI(item.Owner) + "/" + item.Owner.ToString(); 483
473 return m_HGService.QueryItem(uri, item, sessionID); 484 IInventoryService connector = GetConnector(invURL);
474 } 485
486 return connector.GetItem(item);
475 } 487 }
476 488
477 public override InventoryFolderBase GetFolder(InventoryFolderBase folder) 489 public InventoryFolderBase GetFolder(InventoryFolderBase folder)
478 { 490 {
479 if (folder == null) 491 if (folder == null)
480 return null; 492 return null;
481 493
482 if (IsLocalGridUser(folder.Owner)) 494 m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
483 return m_GridService.GetFolder(folder); 495
484 else 496 string invURL = GetInventoryServiceURL(folder.Owner);
485 { 497
486 UUID sessionID = GetSessionID(folder.Owner); 498 if (invURL == null) // not there, forward to local inventory connector to resolve
487 string uri = GetUserInventoryURI(folder.Owner) + "/" + folder.Owner.ToString(); 499 return m_LocalGridInventoryService.GetFolder(folder);
488 return m_HGService.QueryFolder(uri, folder, sessionID); 500
489 } 501 IInventoryService connector = GetConnector(invURL);
502
503 return connector.GetFolder(folder);
490 } 504 }
491 505
492 public override bool HasInventoryForUser(UUID userID) 506 public bool HasInventoryForUser(UUID userID)
493 { 507 {
494 return false; 508 return false;
495 } 509 }
496 510
497 public override List<InventoryItemBase> GetActiveGestures(UUID userId) 511 public List<InventoryItemBase> GetActiveGestures(UUID userId)
498 { 512 {
499 return new List<InventoryItemBase>(); 513 return new List<InventoryItemBase>();
500 } 514 }
501 515
502 public override int GetAssetPermissions(UUID userID, UUID assetID) 516 public int GetAssetPermissions(UUID userID, UUID assetID)
503 { 517 {
504 if (IsLocalGridUser(userID)) 518 m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
505 return m_GridService.GetAssetPermissions(userID, assetID);
506 else
507 {
508 UUID sessionID = GetSessionID(userID);
509 string uri = GetUserInventoryURI(userID) + "/" + userID.ToString();
510 return m_HGService.GetAssetPermissions(uri, assetID, sessionID);
511 }
512 }
513 519
514 #endregion 520 string invURL = GetInventoryServiceURL(userID);
515 521
516 private UUID GetSessionID(UUID userID) 522 if (invURL == null) // not there, forward to local inventory connector to resolve
517 { 523 return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID);
518 CachedUserInfo uinfo = m_UserProfileService.GetUserDetails(userID);
519 if (uinfo != null)
520 return uinfo.SessionID;
521 524
522 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: user profile for {0} not found", userID); 525 IInventoryService connector = GetConnector(invURL);
523 return UUID.Zero;
524 }
525 526
526 private bool IsLocalGridUser(UUID userID) 527 return connector.GetAssetPermissions(userID, assetID);
527 { 528 }
528 if (m_UserProfileService == null)
529 {
530 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: IsLocalGridUser, no profile service. Returning false.");
531 return false;
532 }
533
534 CachedUserInfo uinfo = m_UserProfileService.GetUserDetails(userID);
535 if (uinfo == null)
536 {
537 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: IsLocalGridUser, no profile for user {0}. Returning true.", userID);
538 return true;
539 }
540
541 if ((uinfo.UserProfile.UserInventoryURI == null) || (uinfo.UserProfile.UserInventoryURI == ""))
542 // this happens in standalone profiles, apparently
543 return true;
544
545 string userInventoryServerURI = Util.ServerURI(uinfo.UserProfile.UserInventoryURI);
546 529
547 string uri = LocalGridInventory.TrimEnd('/'); 530 #endregion
548 531
549 if ((userInventoryServerURI == uri) || (userInventoryServerURI == "")) 532 private IInventoryService GetConnector(string url)
533 {
534 IInventoryService connector = null;
535 lock (m_connectors)
550 { 536 {
551 return true; 537 if (m_connectors.ContainsKey(url))
538 {
539 connector = m_connectors[url];
540 }
541 else
542 {
543 // We're instantiating this class explicitly, but this won't
544 // work in general, because the remote grid may be running
545 // an inventory server that has a different protocol.
546 // Eventually we will want a piece of protocol asking
547 // the remote server about its kind. Definitely cool thing to do!
548 connector = new RemoteXInventoryServicesConnector(url);
549 m_connectors.Add(url, connector);
550 }
552 } 551 }
553 m_log.DebugFormat("[HG INVENTORY CONNECTOR]: user {0} is foreign({1} - {2})", userID, userInventoryServerURI, uri); 552 return connector;
554 return false;
555 } 553 }
556 554
557 private string GetUserInventoryURI(UUID userID)
558 {
559 string invURI = LocalGridInventory;
560
561 CachedUserInfo uinfo = m_UserProfileService.GetUserDetails(userID);
562 if ((uinfo == null) || (uinfo.UserProfile == null))
563 return invURI;
564
565 string userInventoryServerURI = Util.ServerURI(uinfo.UserProfile.UserInventoryURI);
566
567 if ((userInventoryServerURI != null) &&
568 (userInventoryServerURI != ""))
569 invURI = userInventoryServerURI;
570 return invURI;
571 }
572
573
574 } 555 }
575} 556}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs
index 3c3534f..c97ab9e 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs
@@ -51,6 +51,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
51 // The cache proper 51 // The cache proper
52 protected Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>> m_InventoryCache; 52 protected Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>> m_InventoryCache;
53 53
54 // A cache of userIDs --> ServiceURLs, for HGBroker only
55 protected Dictionary<UUID, string> m_InventoryURLs =
56 new Dictionary<UUID, string>();
57
54 public virtual void Init(IConfigSource source, BaseInventoryConnector connector) 58 public virtual void Init(IConfigSource source, BaseInventoryConnector connector)
55 { 59 {
56 m_Scenes = new List<Scene>(); 60 m_Scenes = new List<Scene>();
@@ -89,8 +93,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
89 93
90 // If not, go get them and place them in the cache 94 // If not, go get them and place them in the cache
91 Dictionary<AssetType, InventoryFolderBase> folders = CacheSystemFolders(presence.UUID); 95 Dictionary<AssetType, InventoryFolderBase> folders = CacheSystemFolders(presence.UUID);
96 CacheInventoryServiceURL(presence.Scene, presence.UUID);
97
92 m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent in {0}, fetched system folders for {1} {2}: count {3}", 98 m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent in {0}, fetched system folders for {1} {2}: count {3}",
93 presence.Scene.RegionInfo.RegionName, presence.Firstname, presence.Lastname, folders.Count); 99 presence.Scene.RegionInfo.RegionName, presence.Firstname, presence.Lastname, folders.Count);
100
94 } 101 }
95 102
96 void OnClientClosed(UUID clientID, Scene scene) 103 void OnClientClosed(UUID clientID, Scene scene)
@@ -100,7 +107,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
100 ScenePresence sp = null; 107 ScenePresence sp = null;
101 foreach (Scene s in m_Scenes) 108 foreach (Scene s in m_Scenes)
102 { 109 {
103 s.TryGetAvatar(clientID, out sp); 110 s.TryGetScenePresence(clientID, out sp);
104 if ((sp != null) && !sp.IsChildAgent && (s != scene)) 111 if ((sp != null) && !sp.IsChildAgent && (s != scene))
105 { 112 {
106 m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping system folders in cache", 113 m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping system folders in cache",
@@ -113,6 +120,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
113 "[INVENTORY CACHE]: OnClientClosed in {0}, user {1} out of sim. Dropping system folders", 120 "[INVENTORY CACHE]: OnClientClosed in {0}, user {1} out of sim. Dropping system folders",
114 scene.RegionInfo.RegionName, clientID); 121 scene.RegionInfo.RegionName, clientID);
115 DropCachedSystemFolders(clientID); 122 DropCachedSystemFolders(clientID);
123 DropInventoryServiceURL(clientID);
116 } 124 }
117 } 125 }
118 126
@@ -174,5 +182,49 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
174 182
175 return null; 183 return null;
176 } 184 }
185
186 /// <summary>
187 /// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
188 /// and sticks it in the cache
189 /// </summary>
190 /// <param name="userID"></param>
191 private void CacheInventoryServiceURL(Scene scene, UUID userID)
192 {
193 if (scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID) == null)
194 {
195 // The user does not have a local account; let's cache its service URL
196 string inventoryURL = string.Empty;
197 ScenePresence sp = null;
198 scene.TryGetScenePresence(userID, out sp);
199 if (sp != null)
200 {
201 AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
202 if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
203 {
204 inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
205 if (inventoryURL != null && inventoryURL != string.Empty)
206 {
207 inventoryURL = inventoryURL.Trim(new char[] { '/' });
208 m_InventoryURLs.Add(userID, inventoryURL);
209 }
210 }
211 }
212 }
213 }
214
215 private void DropInventoryServiceURL(UUID userID)
216 {
217 lock (m_InventoryURLs)
218 if (m_InventoryURLs.ContainsKey(userID))
219 m_InventoryURLs.Remove(userID);
220 }
221
222 public string GetInventoryServiceURL(UUID userID)
223 {
224 if (m_InventoryURLs.ContainsKey(userID))
225 return m_InventoryURLs[userID];
226
227 return null;
228 }
177 } 229 }
178} 230}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs
index 191e859..22bd04c 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs
@@ -41,7 +41,7 @@ using OpenMetaverse;
41 41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory 42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
43{ 43{
44 public class LocalInventoryServicesConnector : BaseInventoryConnector, ISharedRegionModule, IInventoryService 44 public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService
45 { 45 {
46 private static readonly ILog m_log = 46 private static readonly ILog m_log =
47 LogManager.GetLogger( 47 LogManager.GetLogger(
@@ -50,7 +50,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
50 private IInventoryService m_InventoryService; 50 private IInventoryService m_InventoryService;
51 51
52 private bool m_Enabled = false; 52 private bool m_Enabled = false;
53 private bool m_Initialized = false;
54 53
55 public Type ReplaceableInterface 54 public Type ReplaceableInterface
56 { 55 {
@@ -93,23 +92,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
93 if (m_InventoryService == null) 92 if (m_InventoryService == null)
94 { 93 {
95 m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service"); 94 m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service");
96 //return;
97 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); 95 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
98 } 96 }
99 97
100 //List<IInventoryDataPlugin> plugins
101 // = DataPluginFactory.LoadDataPlugins<IInventoryDataPlugin>(
102 // configSettings.StandaloneInventoryPlugin,
103 // configSettings.StandaloneInventorySource);
104
105 //foreach (IInventoryDataPlugin plugin in plugins)
106 //{
107 // // Using the OSP wrapper plugin for database plugins should be made configurable at some point
108 // m_InventoryService.AddPlugin(new OspInventoryWrapperPlugin(plugin, this));
109 //}
110
111 Init(source);
112
113 m_Enabled = true; 98 m_Enabled = true;
114 m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled"); 99 m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled");
115 } 100 }
@@ -128,102 +113,60 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
128 { 113 {
129 if (!m_Enabled) 114 if (!m_Enabled)
130 return; 115 return;
131
132 if (!m_Initialized)
133 {
134 // ugh!
135 scene.CommsManager.UserProfileCacheService.SetInventoryService(this);
136 scene.CommsManager.UserService.SetInventoryService(this);
137 m_Initialized = true;
138 }
139
140// m_log.DebugFormat(
141// "[LOCAL INVENTORY SERVICES CONNECTOR]: Registering IInventoryService to scene {0}", scene.RegionInfo.RegionName);
142 116
143 scene.RegisterModuleInterface<IInventoryService>(this); 117 scene.RegisterModuleInterface<IInventoryService>(this);
144 m_cache.AddRegion(scene);
145 } 118 }
146 119
147 public void RemoveRegion(Scene scene) 120 public void RemoveRegion(Scene scene)
148 { 121 {
149 if (!m_Enabled) 122 if (!m_Enabled)
150 return; 123 return;
151
152 m_cache.RemoveRegion(scene);
153 } 124 }
154 125
155 public void RegionLoaded(Scene scene) 126 public void RegionLoaded(Scene scene)
156 { 127 {
157 if (!m_Enabled) 128 if (!m_Enabled)
158 return; 129 return;
159
160 m_log.InfoFormat(
161 "[LOCAL INVENTORY SERVICES CONNECTOR]: Enabled local inventory for region {0}", scene.RegionInfo.RegionName);
162 } 130 }
163 131
164 #region IInventoryService 132 #region IInventoryService
165 133
166 public override bool CreateUserInventory(UUID user) 134 public bool CreateUserInventory(UUID user)
167 { 135 {
168 return m_InventoryService.CreateUserInventory(user); 136 return m_InventoryService.CreateUserInventory(user);
169 } 137 }
170 138
171 public override List<InventoryFolderBase> GetInventorySkeleton(UUID userId) 139 public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
172 { 140 {
173 return m_InventoryService.GetInventorySkeleton(userId); 141 return m_InventoryService.GetInventorySkeleton(userId);
174 } 142 }
175 143
176 public override InventoryCollection GetUserInventory(UUID id) 144 public InventoryCollection GetUserInventory(UUID id)
177 { 145 {
178 return m_InventoryService.GetUserInventory(id); 146 return m_InventoryService.GetUserInventory(id);
179 } 147 }
180 148
181 public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback) 149 public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
182 { 150 {
183 m_InventoryService.GetUserInventory(userID, callback); 151 m_InventoryService.GetUserInventory(userID, callback);
184 } 152 }
185 153
186 // Inherited. See base 154 public InventoryFolderBase GetRootFolder(UUID userID)
187 //public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
188 //{
189 // return m_InventoryService.GetFolderForType(userID, type);
190 //}
191
192 public override Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
193 { 155 {
194 InventoryFolderBase root = m_InventoryService.GetRootFolder(userID); 156 return m_InventoryService.GetRootFolder(userID);
195 if (root != null) 157 }
196 {
197 InventoryCollection content = GetFolderContent(userID, root.ID);
198 if (content != null)
199 {
200 Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>();
201 foreach (InventoryFolderBase folder in content.Folders)
202 {
203 if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
204 {
205 //m_log.InfoFormat("[INVENTORY CONNECTOR]: folder type {0} ", folder.Type);
206 folders[(AssetType)folder.Type] = folder;
207 }
208 }
209 // Put the root folder there, as type Folder
210 folders[AssetType.Folder] = root;
211 //m_log.InfoFormat("[INVENTORY CONNECTOR]: root folder is type {0} ", root.Type);
212 158
213 return folders; 159 public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
214 } 160 {
215 } 161 return m_InventoryService.GetFolderForType(userID, type);
216 m_log.WarnFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: System folders for {0} not found", userID);
217 return new Dictionary<AssetType, InventoryFolderBase>();
218 } 162 }
219 163
220 public override InventoryCollection GetFolderContent(UUID userID, UUID folderID) 164 public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
221 { 165 {
222 return m_InventoryService.GetFolderContent(userID, folderID); 166 return m_InventoryService.GetFolderContent(userID, folderID);
223 } 167 }
224 168
225 169 public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
226 public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
227 { 170 {
228 return m_InventoryService.GetFolderItems(userID, folderID); 171 return m_InventoryService.GetFolderItems(userID, folderID);
229 } 172 }
@@ -233,7 +176,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
233 /// </summary> 176 /// </summary>
234 /// <param name="folder"></param> 177 /// <param name="folder"></param>
235 /// <returns>true if the folder was successfully added</returns> 178 /// <returns>true if the folder was successfully added</returns>
236 public override bool AddFolder(InventoryFolderBase folder) 179 public bool AddFolder(InventoryFolderBase folder)
237 { 180 {
238 return m_InventoryService.AddFolder(folder); 181 return m_InventoryService.AddFolder(folder);
239 } 182 }
@@ -243,7 +186,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
243 /// </summary> 186 /// </summary>
244 /// <param name="folder"></param> 187 /// <param name="folder"></param>
245 /// <returns>true if the folder was successfully updated</returns> 188 /// <returns>true if the folder was successfully updated</returns>
246 public override bool UpdateFolder(InventoryFolderBase folder) 189 public bool UpdateFolder(InventoryFolderBase folder)
247 { 190 {
248 return m_InventoryService.UpdateFolder(folder); 191 return m_InventoryService.UpdateFolder(folder);
249 } 192 }
@@ -253,12 +196,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
253 /// </summary> 196 /// </summary>
254 /// <param name="folder">A folder containing the details of the new location</param> 197 /// <param name="folder">A folder containing the details of the new location</param>
255 /// <returns>true if the folder was successfully moved</returns> 198 /// <returns>true if the folder was successfully moved</returns>
256 public override bool MoveFolder(InventoryFolderBase folder) 199 public bool MoveFolder(InventoryFolderBase folder)
257 { 200 {
258 return m_InventoryService.MoveFolder(folder); 201 return m_InventoryService.MoveFolder(folder);
259 } 202 }
260 203
261 public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) 204 public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
262 { 205 {
263 return m_InventoryService.DeleteFolders(ownerID, folderIDs); 206 return m_InventoryService.DeleteFolders(ownerID, folderIDs);
264 } 207 }
@@ -268,18 +211,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
268 /// </summary> 211 /// </summary>
269 /// <param name="folder"></param> 212 /// <param name="folder"></param>
270 /// <returns>true if the folder was successfully purged</returns> 213 /// <returns>true if the folder was successfully purged</returns>
271 public override bool PurgeFolder(InventoryFolderBase folder) 214 public bool PurgeFolder(InventoryFolderBase folder)
272 { 215 {
273 return m_InventoryService.PurgeFolder(folder); 216 return m_InventoryService.PurgeFolder(folder);
274 } 217 }
275 218
276 /// <summary> 219 /// <summary>
277 /// Add a new item to the user's inventory, plain 220 /// Add a new item to the user's inventory
278 /// Called by base class AddItem
279 /// </summary> 221 /// </summary>
280 /// <param name="item"></param> 222 /// <param name="item"></param>
281 /// <returns>true if the item was successfully added</returns> 223 /// <returns>true if the item was successfully added</returns>
282 protected override bool AddItemPlain(InventoryItemBase item) 224 public bool AddItem(InventoryItemBase item)
283 { 225 {
284 return m_InventoryService.AddItem(item); 226 return m_InventoryService.AddItem(item);
285 } 227 }
@@ -289,13 +231,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
289 /// </summary> 231 /// </summary>
290 /// <param name="item"></param> 232 /// <param name="item"></param>
291 /// <returns>true if the item was successfully updated</returns> 233 /// <returns>true if the item was successfully updated</returns>
292 public override bool UpdateItem(InventoryItemBase item) 234 public bool UpdateItem(InventoryItemBase item)
293 { 235 {
294 return m_InventoryService.UpdateItem(item); 236 return m_InventoryService.UpdateItem(item);
295 } 237 }
296 238
297 239
298 public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items) 240 public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
299 { 241 {
300 return m_InventoryService.MoveItems(ownerID, items); 242 return m_InventoryService.MoveItems(ownerID, items);
301 } 243 }
@@ -305,24 +247,27 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
305 /// </summary> 247 /// </summary>
306 /// <param name="item"></param> 248 /// <param name="item"></param>
307 /// <returns>true if the item was successfully deleted</returns> 249 /// <returns>true if the item was successfully deleted</returns>
308 public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs) 250 public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
309 { 251 {
310 return m_InventoryService.DeleteItems(ownerID, itemIDs); 252 return m_InventoryService.DeleteItems(ownerID, itemIDs);
311 } 253 }
312 254
313 public override InventoryItemBase GetItem(InventoryItemBase item) 255 public InventoryItemBase GetItem(InventoryItemBase item)
314 { 256 {
315// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID); 257// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID);
316 258
259 UUID requestedItemId = item.ID;
260
317 item = m_InventoryService.GetItem(item); 261 item = m_InventoryService.GetItem(item);
318 262
319 if (null == item) 263 if (null == item)
320 m_log.ErrorFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", item.ID); 264 m_log.ErrorFormat(
265 "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId);
321 266
322 return item; 267 return item;
323 } 268 }
324 269
325 public override InventoryFolderBase GetFolder(InventoryFolderBase folder) 270 public InventoryFolderBase GetFolder(InventoryFolderBase folder)
326 { 271 {
327 return m_InventoryService.GetFolder(folder); 272 return m_InventoryService.GetFolder(folder);
328 } 273 }
@@ -332,17 +277,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
332 /// </summary> 277 /// </summary>
333 /// <param name="userID"></param> 278 /// <param name="userID"></param>
334 /// <returns></returns> 279 /// <returns></returns>
335 public override bool HasInventoryForUser(UUID userID) 280 public bool HasInventoryForUser(UUID userID)
336 { 281 {
337 return m_InventoryService.HasInventoryForUser(userID); 282 return m_InventoryService.HasInventoryForUser(userID);
338 } 283 }
339 284
340 public override List<InventoryItemBase> GetActiveGestures(UUID userId) 285 public List<InventoryItemBase> GetActiveGestures(UUID userId)
341 { 286 {
342 return m_InventoryService.GetActiveGestures(userId); 287 return m_InventoryService.GetActiveGestures(userId);
343 } 288 }
344 289
345 public override int GetAssetPermissions(UUID userID, UUID assetID) 290 public int GetAssetPermissions(UUID userID, UUID assetID)
346 { 291 {
347 return m_InventoryService.GetAssetPermissions(userID, assetID); 292 return m_InventoryService.GetAssetPermissions(userID, assetID);
348 } 293 }
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs
index 69504df..aa3b30d 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs
@@ -32,7 +32,7 @@ using System.Reflection;
32using Nini.Config; 32using Nini.Config;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Statistics; 34using OpenSim.Framework.Statistics;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Services.Connectors; 36using OpenSim.Services.Connectors;
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 38using OpenSim.Region.Framework.Scenes;
@@ -49,7 +49,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
49 private bool m_Enabled = false; 49 private bool m_Enabled = false;
50 private bool m_Initialized = false; 50 private bool m_Initialized = false;
51 private Scene m_Scene; 51 private Scene m_Scene;
52 private UserProfileCacheService m_UserProfileService;
53 private InventoryServicesConnector m_RemoteConnector; 52 private InventoryServicesConnector m_RemoteConnector;
54 53
55 public Type ReplaceableInterface 54 public Type ReplaceableInterface
@@ -114,9 +113,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
114 113
115 if (!m_Initialized) 114 if (!m_Initialized)
116 { 115 {
117 // ugh!
118 scene.CommsManager.UserProfileCacheService.SetInventoryService(this);
119 scene.CommsManager.UserService.SetInventoryService(this);
120 m_Initialized = true; 116 m_Initialized = true;
121 } 117 }
122 118
@@ -134,10 +130,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
134 130
135 public void RegionLoaded(Scene scene) 131 public void RegionLoaded(Scene scene)
136 { 132 {
137 m_UserProfileService = m_Scene.CommsManager.UserProfileCacheService;
138 if (m_UserProfileService != null)
139 m_log.Debug("[XXXX] Set m_UserProfileService in " + m_Scene.RegionInfo.RegionName);
140
141 if (!m_Enabled) 133 if (!m_Enabled)
142 return; 134 return;
143 135
@@ -345,23 +337,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
345 337
346 private UUID GetSessionID(UUID userID) 338 private UUID GetSessionID(UUID userID)
347 { 339 {
348 //if (m_Scene == null)
349 //{
350 // m_log.Debug("[INVENTORY CONNECTOR]: OOPS! scene is null");
351 //}
352
353 if (m_UserProfileService == null)
354 {
355 //m_log.Debug("[INVENTORY CONNECTOR]: OOPS! UserProfileCacheService is null");
356 return UUID.Zero;
357 }
358
359 CachedUserInfo uinfo = m_UserProfileService.GetUserDetails(userID);
360 if (uinfo != null)
361 return uinfo.SessionID;
362 m_log.DebugFormat("[INVENTORY CONNECTOR]: user profile for {0} not found", userID);
363 return UUID.Zero; 340 return UUID.Zero;
364
365 } 341 }
366 342
367 } 343 }
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs
new file mode 100644
index 0000000..277060d
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs
@@ -0,0 +1,303 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using log4net;
29using System;
30using System.Collections.Generic;
31using System.Reflection;
32using Nini.Config;
33using OpenSim.Framework;
34using OpenSim.Framework.Statistics;
35
36using OpenSim.Services.Connectors;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Services.Interfaces;
40using OpenMetaverse;
41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
43{
44 public class RemoteXInventoryServicesConnector : ISharedRegionModule, IInventoryService
45 {
46 private static readonly ILog m_log =
47 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48
49 private bool m_Enabled = false;
50 private bool m_Initialized = false;
51 private Scene m_Scene;
52 private XInventoryServicesConnector m_RemoteConnector;
53
54 public Type ReplaceableInterface
55 {
56 get { return null; }
57 }
58
59 public string Name
60 {
61 get { return "RemoteXInventoryServicesConnector"; }
62 }
63
64 public RemoteXInventoryServicesConnector()
65 {
66 }
67
68 public RemoteXInventoryServicesConnector(string url)
69 {
70 m_RemoteConnector = new XInventoryServicesConnector(url);
71 }
72
73 public RemoteXInventoryServicesConnector(IConfigSource source)
74 {
75 Init(source);
76 }
77
78 protected void Init(IConfigSource source)
79 {
80 m_RemoteConnector = new XInventoryServicesConnector(source);
81 }
82
83
84 #region ISharedRegionModule
85
86 public void Initialise(IConfigSource source)
87 {
88 IConfig moduleConfig = source.Configs["Modules"];
89 if (moduleConfig != null)
90 {
91 string name = moduleConfig.GetString("InventoryServices", "");
92 if (name == Name)
93 {
94 Init(source);
95 m_Enabled = true;
96
97 m_log.Info("[XINVENTORY CONNECTOR]: Remote XInventory enabled");
98 }
99 }
100 }
101
102 public void PostInitialise()
103 {
104 }
105
106 public void Close()
107 {
108 }
109
110 public void AddRegion(Scene scene)
111 {
112 m_Scene = scene;
113 //m_log.Debug("[XXXX] Adding scene " + m_Scene.RegionInfo.RegionName);
114
115 if (!m_Enabled)
116 return;
117
118 if (!m_Initialized)
119 {
120 m_Initialized = true;
121 }
122
123 scene.RegisterModuleInterface<IInventoryService>(this);
124 }
125
126 public void RemoveRegion(Scene scene)
127 {
128 if (!m_Enabled)
129 return;
130
131 }
132
133 public void RegionLoaded(Scene scene)
134 {
135 if (!m_Enabled)
136 return;
137
138 m_log.InfoFormat("[XINVENTORY CONNECTOR]: Enabled remote XInventory for region {0}", scene.RegionInfo.RegionName);
139
140 }
141
142 #endregion ISharedRegionModule
143
144 #region IInventoryService
145
146 public bool CreateUserInventory(UUID user)
147 {
148 return false;
149 }
150
151 public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
152 {
153 return new List<InventoryFolderBase>();
154 }
155
156 public InventoryCollection GetUserInventory(UUID userID)
157 {
158 return null;
159 }
160
161 public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
162 {
163 }
164
165 public InventoryFolderBase GetRootFolder(UUID userID)
166 {
167 return m_RemoteConnector.GetRootFolder(userID);
168 }
169
170 public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
171 {
172 return m_RemoteConnector.GetFolderForType(userID, type);
173 }
174
175 public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
176 {
177 return m_RemoteConnector.GetFolderContent(userID, folderID);
178 }
179
180 public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
181 {
182 return m_RemoteConnector.GetFolderItems(userID, folderID);
183 }
184
185 public bool AddFolder(InventoryFolderBase folder)
186 {
187 if (folder == null)
188 return false;
189
190 return m_RemoteConnector.AddFolder(folder);
191 }
192
193 public bool UpdateFolder(InventoryFolderBase folder)
194 {
195 if (folder == null)
196 return false;
197
198 return m_RemoteConnector.UpdateFolder(folder);
199 }
200
201 public bool MoveFolder(InventoryFolderBase folder)
202 {
203 if (folder == null)
204 return false;
205
206 return m_RemoteConnector.MoveFolder(folder);
207 }
208
209 public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
210 {
211 if (folderIDs == null)
212 return false;
213 if (folderIDs.Count == 0)
214 return false;
215
216 return m_RemoteConnector.DeleteFolders(ownerID, folderIDs);
217 }
218
219
220 public bool PurgeFolder(InventoryFolderBase folder)
221 {
222 if (folder == null)
223 return false;
224
225 return m_RemoteConnector.PurgeFolder(folder);
226 }
227
228 public bool AddItem(InventoryItemBase item)
229 {
230 if (item == null)
231 return false;
232
233 return m_RemoteConnector.AddItem(item);
234 }
235
236 public bool UpdateItem(InventoryItemBase item)
237 {
238 if (item == null)
239 return false;
240
241 return m_RemoteConnector.UpdateItem(item);
242 }
243
244 public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
245 {
246 if (items == null)
247 return false;
248
249 return m_RemoteConnector.MoveItems(ownerID, items);
250 }
251
252
253 public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
254 {
255 if (itemIDs == null)
256 return false;
257 if (itemIDs.Count == 0)
258 return true;
259
260 return m_RemoteConnector.DeleteItems(ownerID, itemIDs);
261 }
262
263 public InventoryItemBase GetItem(InventoryItemBase item)
264 {
265 m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetItem {0}", item.ID);
266 if (item == null)
267 return null;
268
269 if (m_RemoteConnector == null)
270 m_log.DebugFormat("[XINVENTORY CONNECTOR]: connector stub is null!!!");
271 return m_RemoteConnector.GetItem(item);
272 }
273
274 public InventoryFolderBase GetFolder(InventoryFolderBase folder)
275 {
276 m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetFolder {0}", folder.ID);
277 if (folder == null)
278 return null;
279
280 return m_RemoteConnector.GetFolder(folder);
281 }
282
283 public bool HasInventoryForUser(UUID userID)
284 {
285 return false;
286 }
287
288 public List<InventoryItemBase> GetActiveGestures(UUID userId)
289 {
290 return new List<InventoryItemBase>();
291 }
292
293 public int GetAssetPermissions(UUID userID, UUID assetID)
294 {
295 return m_RemoteConnector.GetAssetPermissions(userID, assetID);
296 }
297
298
299 #endregion
300
301
302 }
303}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs
new file mode 100644
index 0000000..49dd633
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs
@@ -0,0 +1,199 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.Reflection;
30
31using OpenSim.Region.Framework.Interfaces;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Server.Base;
34using OpenSim.Services.Interfaces;
35using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
36
37using OpenMetaverse;
38using log4net;
39using Nini.Config;
40
41namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence
42{
43 public class LocalPresenceServicesConnector : ISharedRegionModule, IPresenceService
44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 private bool m_Enabled = false;
48
49 private PresenceDetector m_PresenceDetector;
50
51 /// <summary>
52 /// Underlying presence service. Do not use directly.
53 /// </summary>
54 public IPresenceService m_PresenceService;
55
56 public LocalPresenceServicesConnector()
57 {
58 }
59
60 public LocalPresenceServicesConnector(IConfigSource source)
61 {
62 Initialise(source);
63 }
64
65 #region ISharedRegionModule
66
67 public Type ReplaceableInterface
68 {
69 get { return null; }
70 }
71
72 public string Name
73 {
74 get { return "LocalPresenceServicesConnector"; }
75 }
76
77 public void Initialise(IConfigSource source)
78 {
79 IConfig moduleConfig = source.Configs["Modules"];
80 if (moduleConfig != null)
81 {
82 string name = moduleConfig.GetString("PresenceServices", "");
83 if (name == Name)
84 {
85 IConfig inventoryConfig = source.Configs["PresenceService"];
86 if (inventoryConfig == null)
87 {
88 m_log.Error("[LOCAL PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini");
89 return;
90 }
91
92 string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
93
94 if (serviceDll == String.Empty)
95 {
96 m_log.Error("[LOCAL PRESENCE CONNECTOR]: No LocalServiceModule named in section PresenceService");
97 return;
98 }
99
100 Object[] args = new Object[] { source };
101 m_log.DebugFormat("[LOCAL PRESENCE CONNECTOR]: Service dll = {0}", serviceDll);
102
103 m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(serviceDll, args);
104
105 if (m_PresenceService == null)
106 {
107 m_log.Error("[LOCAL PRESENCE CONNECTOR]: Can't load presence service");
108 //return;
109 throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
110 }
111
112 //Init(source);
113
114 m_PresenceDetector = new PresenceDetector(this);
115
116 m_Enabled = true;
117 m_log.Info("[LOCAL PRESENCE CONNECTOR]: Local presence connector enabled");
118 }
119 }
120 }
121
122 public void PostInitialise()
123 {
124 }
125
126 public void Close()
127 {
128 }
129
130 public void AddRegion(Scene scene)
131 {
132 if (!m_Enabled)
133 return;
134
135 // m_log.DebugFormat(
136 // "[LOCAL PRESENCE CONNECTOR]: Registering IPresenceService to scene {0}", scene.RegionInfo.RegionName);
137
138 scene.RegisterModuleInterface<IPresenceService>(this);
139 m_PresenceDetector.AddRegion(scene);
140
141 m_log.InfoFormat("[LOCAL PRESENCE CONNECTOR]: Enabled local presence for region {0}", scene.RegionInfo.RegionName);
142
143 }
144
145 public void RemoveRegion(Scene scene)
146 {
147 if (!m_Enabled)
148 return;
149
150 m_PresenceDetector.RemoveRegion(scene);
151 }
152
153 public void RegionLoaded(Scene scene)
154 {
155 if (!m_Enabled)
156 return;
157
158 }
159
160 #endregion
161
162 #region IPresenceService
163
164 public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
165 {
166 m_log.Warn("[LOCAL PRESENCE CONNECTOR]: LoginAgent connector not implemented at the simulators");
167 return false;
168 }
169
170 public bool LogoutAgent(UUID sessionID)
171 {
172 return m_PresenceService.LogoutAgent(sessionID);
173 }
174
175
176 public bool LogoutRegionAgents(UUID regionID)
177 {
178 return m_PresenceService.LogoutRegionAgents(regionID);
179 }
180
181 public bool ReportAgent(UUID sessionID, UUID regionID)
182 {
183 return m_PresenceService.ReportAgent(sessionID, regionID);
184 }
185
186 public PresenceInfo GetAgent(UUID sessionID)
187 {
188 return m_PresenceService.GetAgent(sessionID);
189 }
190
191 public PresenceInfo[] GetAgents(string[] userIDs)
192 {
193 return m_PresenceService.GetAgents(userIDs);
194 }
195
196 #endregion
197
198 }
199}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs
new file mode 100644
index 0000000..62b8278
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs
@@ -0,0 +1,103 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.Reflection;
30
31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Services.Interfaces;
34
35using OpenMetaverse;
36using log4net;
37
38namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence
39{
40 public class PresenceDetector
41 {
42 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43
44 private IPresenceService m_PresenceService;
45 private Scene m_aScene;
46
47 public PresenceDetector(IPresenceService presenceservice)
48 {
49 m_PresenceService = presenceservice;
50 }
51
52 public void AddRegion(Scene scene)
53 {
54 scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
55 scene.EventManager.OnNewClient += OnNewClient;
56
57 m_PresenceService.LogoutRegionAgents(scene.RegionInfo.RegionID);
58
59 if (m_aScene == null)
60 m_aScene = scene;
61 }
62
63 public void RemoveRegion(Scene scene)
64 {
65 scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent;
66 scene.EventManager.OnNewClient -= OnNewClient;
67
68 m_PresenceService.LogoutRegionAgents(scene.RegionInfo.RegionID);
69
70 }
71
72 public void OnMakeRootAgent(ScenePresence sp)
73 {
74 m_log.DebugFormat("[PRESENCE DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName);
75 m_PresenceService.ReportAgent(sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID);
76 }
77
78 public void OnNewClient(IClientAPI client)
79 {
80 client.OnConnectionClosed += OnConnectionClose;
81 }
82
83 public void OnConnectionClose(IClientAPI client)
84 {
85 if (client.IsLoggingOut)
86 {
87 object sp = null;
88 if (client.Scene.TryGetScenePresence(client.AgentId, out sp))
89 {
90 if (sp is ScenePresence)
91 {
92 if (((ScenePresence)sp).IsChildAgent)
93 return;
94 }
95 }
96
97 m_log.DebugFormat("[PRESENCE DETECTOR]: Detected client logout {0} in {1}", client.AgentId, client.Scene.RegionInfo.RegionName);
98 m_PresenceService.LogoutAgent(client.SessionId);
99 }
100
101 }
102 }
103}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs
new file mode 100644
index 0000000..bf4e9ab
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs
@@ -0,0 +1,159 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Collections.Generic;
29using System.Reflection;
30
31using OpenSim.Region.Framework.Interfaces;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Server.Base;
34using OpenSim.Services.Interfaces;
35using OpenSim.Services.Connectors;
36using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
37
38using OpenMetaverse;
39using log4net;
40using Nini.Config;
41
42namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence
43{
44 public class RemotePresenceServicesConnector : ISharedRegionModule, IPresenceService
45 {
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47
48 #region ISharedRegionModule
49
50 private bool m_Enabled = false;
51
52 private PresenceDetector m_PresenceDetector;
53 private IPresenceService m_RemoteConnector;
54
55 public Type ReplaceableInterface
56 {
57 get { return null; }
58 }
59
60 public string Name
61 {
62 get { return "RemotePresenceServicesConnector"; }
63 }
64
65 public void Initialise(IConfigSource source)
66 {
67 IConfig moduleConfig = source.Configs["Modules"];
68 if (moduleConfig != null)
69 {
70 string name = moduleConfig.GetString("PresenceServices", "");
71 if (name == Name)
72 {
73 m_RemoteConnector = new PresenceServicesConnector(source);
74
75 m_Enabled = true;
76
77 m_PresenceDetector = new PresenceDetector(this);
78
79 m_log.Info("[REMOTE PRESENCE CONNECTOR]: Remote presence enabled");
80 }
81 }
82
83 }
84
85 public void PostInitialise()
86 {
87 }
88
89 public void Close()
90 {
91 }
92
93 public void AddRegion(Scene scene)
94 {
95 if (!m_Enabled)
96 return;
97
98 scene.RegisterModuleInterface<IPresenceService>(this);
99 m_PresenceDetector.AddRegion(scene);
100
101 m_log.InfoFormat("[REMOTE PRESENCE CONNECTOR]: Enabled remote presence for region {0}", scene.RegionInfo.RegionName);
102
103 }
104
105 public void RemoveRegion(Scene scene)
106 {
107 if (!m_Enabled)
108 return;
109
110 m_PresenceDetector.RemoveRegion(scene);
111 }
112
113 public void RegionLoaded(Scene scene)
114 {
115 if (!m_Enabled)
116 return;
117
118 }
119
120 #endregion
121
122 #region IPresenceService
123
124 public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
125 {
126 m_log.Warn("[REMOTE PRESENCE CONNECTOR]: LoginAgent connector not implemented at the simulators");
127 return false;
128 }
129
130 public bool LogoutAgent(UUID sessionID)
131 {
132 return m_RemoteConnector.LogoutAgent(sessionID);
133 }
134
135
136 public bool LogoutRegionAgents(UUID regionID)
137 {
138 return m_RemoteConnector.LogoutRegionAgents(regionID);
139 }
140
141 public bool ReportAgent(UUID sessionID, UUID regionID)
142 {
143 return m_RemoteConnector.ReportAgent(sessionID, regionID);
144 }
145
146 public PresenceInfo GetAgent(UUID sessionID)
147 {
148 return m_RemoteConnector.GetAgent(sessionID);
149 }
150
151 public PresenceInfo[] GetAgents(string[] userIDs)
152 {
153 return m_RemoteConnector.GetAgents(userIDs);
154 }
155
156 #endregion
157
158 }
159}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs
new file mode 100644
index 0000000..ef910f4
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs
@@ -0,0 +1,115 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Reflection;
32using System.Threading;
33using log4net.Config;
34using NUnit.Framework;
35using NUnit.Framework.SyntaxHelpers;
36using OpenMetaverse;
37using OpenSim.Framework;
38using Nini.Config;
39
40using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence;
41using OpenSim.Region.Framework.Scenes;
42using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
43using OpenSim.Tests.Common;
44using OpenSim.Tests.Common.Setup;
45
46namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence.Tests
47{
48 [TestFixture]
49 public class PresenceConnectorsTests
50 {
51 LocalPresenceServicesConnector m_LocalConnector;
52 private void SetUp()
53 {
54 IConfigSource config = new IniConfigSource();
55 config.AddConfig("Modules");
56 config.AddConfig("PresenceService");
57 config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector");
58 config.Configs["PresenceService"].Set("LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService");
59 config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
60
61 m_LocalConnector = new LocalPresenceServicesConnector(config);
62
63 // Let's stick in a test presence
64 m_LocalConnector.m_PresenceService.LoginAgent(UUID.Zero.ToString(), UUID.Zero, UUID.Zero);
65 }
66
67 /// <summary>
68 /// Test OpenSim Presence.
69 /// </summary>
70 [Test]
71 public void TestPresenceV0_1()
72 {
73 SetUp();
74
75 // Let's stick in a test presence
76 /*
77 PresenceData p = new PresenceData();
78 p.SessionID = UUID.Zero;
79 p.UserID = UUID.Zero.ToString();
80 p.Data = new Dictionary<string, string>();
81 p.Data["Online"] = true.ToString();
82 m_presenceData.Add(UUID.Zero, p);
83 */
84
85 string user1 = UUID.Zero.ToString();
86 UUID session1 = UUID.Zero;
87
88 // this is not implemented by this connector
89 //m_LocalConnector.LoginAgent(user1, session1, UUID.Zero);
90 PresenceInfo result = m_LocalConnector.GetAgent(session1);
91 Assert.IsNotNull(result, "Retrieved GetAgent is null");
92 Assert.That(result.UserID, Is.EqualTo(user1), "Retrieved userID does not match");
93
94 UUID region1 = UUID.Random();
95 bool r = m_LocalConnector.ReportAgent(session1, region1);
96 Assert.IsTrue(r, "First ReportAgent returned false");
97 result = m_LocalConnector.GetAgent(session1);
98 Assert.That(result.RegionID, Is.EqualTo(region1), "Agent is not in the right region (region1)");
99
100 UUID region2 = UUID.Random();
101 r = m_LocalConnector.ReportAgent(session1, region2);
102 Assert.IsTrue(r, "Second ReportAgent returned false");
103 result = m_LocalConnector.GetAgent(session1);
104 Assert.That(result.RegionID, Is.EqualTo(region2), "Agent is not in the right region (region2)");
105
106 r = m_LocalConnector.LogoutAgent(session1);
107 Assert.IsTrue(r, "LogoutAgent returned false");
108 result = m_LocalConnector.GetAgent(session1);
109 Assert.IsNull(result, "Agent session is still stored after logout");
110
111 r = m_LocalConnector.ReportAgent(session1, region1);
112 Assert.IsFalse(r, "ReportAgent of non-logged in user returned true");
113 }
114 }
115}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/LocalInterregionComms.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs
index d68c683..e32dbb3 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Interregion/LocalInterregionComms.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs
@@ -33,33 +33,49 @@ using OpenMetaverse;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Region.Framework.Interfaces; 34using OpenSim.Region.Framework.Interfaces;
35using OpenSim.Region.Framework.Scenes; 35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Services.Interfaces;
37using GridRegion = OpenSim.Services.Interfaces.GridRegion;
36 38
37namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion 39namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
38{ 40{
39 public class LocalInterregionComms : ISharedRegionModule, IInterregionCommsOut, IInterregionCommsIn 41 public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService
40 { 42 {
41 private bool m_enabled = false;
42
43 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 43 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
44 private List<Scene> m_sceneList = new List<Scene>(); 44 private List<Scene> m_sceneList = new List<Scene>();
45 45
46 #region Events 46 private IEntityTransferModule m_AgentTransferModule;
47 public event ChildAgentUpdateReceived OnChildAgentUpdate; 47 protected IEntityTransferModule AgentTransferModule
48 {
49 get
50 {
51 if (m_AgentTransferModule == null)
52 m_AgentTransferModule = m_sceneList[0].RequestModuleInterface<IEntityTransferModule>();
53 return m_AgentTransferModule;
54 }
55 }
48 56
49 #endregion /* Events */ 57 private bool m_ModuleEnabled = false;
50 58
51 #region IRegionModule 59 #region IRegionModule
52 60
53 public void Initialise(IConfigSource config) 61 public void Initialise(IConfigSource config)
54 { 62 {
55 if (m_sceneList.Count == 0) 63 IConfig moduleConfig = config.Configs["Modules"];
64 if (moduleConfig != null)
56 { 65 {
57 IConfig startupConfig = config.Configs["Communications"]; 66 string name = moduleConfig.GetString("SimulationServices", "");
58 67 if (name == Name)
59 if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTComms") == "LocalComms"))
60 { 68 {
61 m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module"); 69 //IConfig userConfig = config.Configs["SimulationService"];
62 m_enabled = true; 70 //if (userConfig == null)
71 //{
72 // m_log.Error("[AVATAR CONNECTOR]: SimulationService missing from OpenSim.ini");
73 // return;
74 //}
75
76 m_ModuleEnabled = true;
77
78 m_log.Info("[SIMULATION CONNECTOR]: Local simulation enabled");
63 } 79 }
64 } 80 }
65 } 81 }
@@ -70,22 +86,24 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
70 86
71 public void AddRegion(Scene scene) 87 public void AddRegion(Scene scene)
72 { 88 {
89 if (!m_ModuleEnabled)
90 return;
91
92 Init(scene);
93 scene.RegisterModuleInterface<ISimulationService>(this);
73 } 94 }
74 95
75 public void RemoveRegion(Scene scene) 96 public void RemoveRegion(Scene scene)
76 { 97 {
77 if (m_enabled) 98 if (!m_ModuleEnabled)
78 { 99 return;
79 RemoveScene(scene); 100
80 } 101 RemoveScene(scene);
102 scene.UnregisterModuleInterface<ISimulationService>(this);
81 } 103 }
82 104
83 public void RegionLoaded(Scene scene) 105 public void RegionLoaded(Scene scene)
84 { 106 {
85 if (m_enabled)
86 {
87 Init(scene);
88 }
89 } 107 }
90 108
91 public void Close() 109 public void Close()
@@ -99,7 +117,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
99 117
100 public string Name 118 public string Name
101 { 119 {
102 get { return "LocalInterregionCommsModule"; } 120 get { return "LocalSimulationConnectorModule"; }
103 } 121 }
104 122
105 /// <summary> 123 /// <summary>
@@ -128,9 +146,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
128 lock (m_sceneList) 146 lock (m_sceneList)
129 { 147 {
130 m_sceneList.Add(scene); 148 m_sceneList.Add(scene);
131 if (m_enabled)
132 scene.RegisterModuleInterface<IInterregionCommsOut>(this);
133 scene.RegisterModuleInterface<IInterregionCommsIn>(this);
134 } 149 }
135 150
136 } 151 }
@@ -138,40 +153,63 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
138 153
139 #endregion /* IRegionModule */ 154 #endregion /* IRegionModule */
140 155
141 #region IInterregionComms 156 #region ISimulation
157
158 public IScene GetScene(ulong regionhandle)
159 {
160 foreach (Scene s in m_sceneList)
161 {
162 if (s.RegionInfo.RegionHandle == regionhandle)
163 return s;
164 }
165 // ? weird. should not happen
166 return m_sceneList[0];
167 }
168
169 public ISimulationService GetInnerService()
170 {
171 return this;
172 }
142 173
143 /** 174 /**
144 * Agent-related communications 175 * Agent-related communications
145 */ 176 */
146 177
147 public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, uint teleportFlags, out string reason) 178 public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
148 { 179 {
180 if (destination == null)
181 {
182 reason = "Given destination was null";
183 m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination");
184 return false;
185 }
149 186
150 foreach (Scene s in m_sceneList) 187 foreach (Scene s in m_sceneList)
151 { 188 {
152 if (s.RegionInfo.RegionHandle == regionHandle) 189 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
153 { 190 {
154// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle); 191 m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
155 return s.NewUserConnection(aCircuit, teleportFlags, out reason); 192 return s.NewUserConnection(aCircuit, teleportFlags, out reason);
156 } 193 }
157 } 194 }
158 195
159// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle); 196 m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Did not find region {0} for SendCreateChildAgent", destination.RegionName);
160 uint x = 0, y = 0; 197 reason = "Did not find region " + destination.RegionName;
161 Utils.LongToUInts(regionHandle, out x, out y);
162 reason = "Did not find region " + x + "-" + y;
163 return false; 198 return false;
164 } 199 }
165 200
166 public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData) 201 public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
167 { 202 {
203 if (destination == null)
204 return false;
205
168 foreach (Scene s in m_sceneList) 206 foreach (Scene s in m_sceneList)
169 { 207 {
170 if (s.RegionInfo.RegionHandle == regionHandle) 208 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
171 { 209 {
172 //m_log.DebugFormat( 210 m_log.DebugFormat(
173 // "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate", 211 "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
174 // s.RegionInfo.RegionName, regionHandle); 212 s.RegionInfo.RegionName, destination.RegionHandle);
175 213
176 s.IncomingChildAgentDataUpdate(cAgentData); 214 s.IncomingChildAgentDataUpdate(cAgentData);
177 return true; 215 return true;
@@ -182,11 +220,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
182 return false; 220 return false;
183 } 221 }
184 222
185 public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData) 223 public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
186 { 224 {
225 if (destination == null)
226 return false;
227
187 foreach (Scene s in m_sceneList) 228 foreach (Scene s in m_sceneList)
188 { 229 {
189 if (s.RegionInfo.RegionHandle == regionHandle) 230 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
190 { 231 {
191 //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); 232 //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
192 s.IncomingChildAgentDataUpdate(cAgentData); 233 s.IncomingChildAgentDataUpdate(cAgentData);
@@ -197,12 +238,16 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
197 return false; 238 return false;
198 } 239 }
199 240
200 public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent) 241 public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
201 { 242 {
202 agent = null; 243 agent = null;
244
245 if (destination == null)
246 return false;
247
203 foreach (Scene s in m_sceneList) 248 foreach (Scene s in m_sceneList)
204 { 249 {
205 if (s.RegionInfo.RegionHandle == regionHandle) 250 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
206 { 251 {
207 //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); 252 //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
208 return s.IncomingRetrieveRootAgent(id, out agent); 253 return s.IncomingRetrieveRootAgent(id, out agent);
@@ -212,35 +257,30 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
212 return false; 257 return false;
213 } 258 }
214 259
215 public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri) 260 public bool ReleaseAgent(UUID origin, UUID id, string uri)
216 { 261 {
217 //uint x, y;
218 //Utils.LongToUInts(regionHandle, out x, out y);
219 //x = x / Constants.RegionSize;
220 //y = y / Constants.RegionSize;
221 //m_log.Debug("\n >>> Local SendReleaseAgent " + x + "-" + y);
222 foreach (Scene s in m_sceneList) 262 foreach (Scene s in m_sceneList)
223 { 263 {
224 if (s.RegionInfo.RegionHandle == regionHandle) 264 if (s.RegionInfo.RegionID == origin)
225 { 265 {
226 //m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent"); 266 m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
227 return s.IncomingReleaseAgent(id); 267 AgentTransferModule.AgentArrivedAtDestination(id);
268 return true;
269// return s.IncomingReleaseAgent(id);
228 } 270 }
229 } 271 }
230 //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent"); 272 //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin);
231 return false; 273 return false;
232 } 274 }
233 275
234 public bool SendCloseAgent(ulong regionHandle, UUID id) 276 public bool CloseAgent(GridRegion destination, UUID id)
235 { 277 {
236 //uint x, y; 278 if (destination == null)
237 //Utils.LongToUInts(regionHandle, out x, out y); 279 return false;
238 //x = x / Constants.RegionSize; 280
239 //y = y / Constants.RegionSize;
240 //m_log.Debug("\n >>> Local SendCloseAgent " + x + "-" + y);
241 foreach (Scene s in m_sceneList) 281 foreach (Scene s in m_sceneList)
242 { 282 {
243 if (s.RegionInfo.RegionHandle == regionHandle) 283 if (s.RegionInfo.RegionID == destination.RegionID)
244 { 284 {
245 //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); 285 //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
246 return s.IncomingCloseAgent(id); 286 return s.IncomingCloseAgent(id);
@@ -254,11 +294,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
254 * Object-related communications 294 * Object-related communications
255 */ 295 */
256 296
257 public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall) 297 public bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall)
258 { 298 {
299 if (destination == null)
300 return false;
301
259 foreach (Scene s in m_sceneList) 302 foreach (Scene s in m_sceneList)
260 { 303 {
261 if (s.RegionInfo.RegionHandle == regionHandle) 304 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
262 { 305 {
263 //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject"); 306 //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
264 if (isLocalCall) 307 if (isLocalCall)
@@ -278,11 +321,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
278 return false; 321 return false;
279 } 322 }
280 323
281 public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID) 324 public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
282 { 325 {
326 if (destination == null)
327 return false;
328
283 foreach (Scene s in m_sceneList) 329 foreach (Scene s in m_sceneList)
284 { 330 {
285 if (s.RegionInfo.RegionHandle == regionHandle) 331 if (s.RegionInfo.RegionHandle == destination.RegionHandle)
286 { 332 {
287 return s.IncomingCreateObject(userID, itemID); 333 return s.IncomingCreateObject(userID, itemID);
288 } 334 }
@@ -295,21 +341,18 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
295 341
296 #region Misc 342 #region Misc
297 343
298 public Scene GetScene(ulong regionhandle) 344 public bool IsLocalRegion(ulong regionhandle)
299 { 345 {
300 foreach (Scene s in m_sceneList) 346 foreach (Scene s in m_sceneList)
301 {
302 if (s.RegionInfo.RegionHandle == regionhandle) 347 if (s.RegionInfo.RegionHandle == regionhandle)
303 return s; 348 return true;
304 } 349 return false;
305 // ? weird. should not happen
306 return m_sceneList[0];
307 } 350 }
308 351
309 public bool IsLocalRegion(ulong regionhandle) 352 public bool IsLocalRegion(UUID id)
310 { 353 {
311 foreach (Scene s in m_sceneList) 354 foreach (Scene s in m_sceneList)
312 if (s.RegionInfo.RegionHandle == regionhandle) 355 if (s.RegionInfo.RegionID == id)
313 return true; 356 return true;
314 return false; 357 return false;
315 } 358 }
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs
new file mode 100644
index 0000000..9e8454f
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs
@@ -0,0 +1,305 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34using log4net;
35using Nini.Config;
36using OpenMetaverse;
37using OpenMetaverse.StructuredData;
38using OpenSim.Framework;
39using OpenSim.Framework.Communications;
40using OpenSim.Region.Framework.Interfaces;
41using OpenSim.Region.Framework.Scenes;
42using OpenSim.Region.Framework.Scenes.Serialization;
43using OpenSim.Services.Interfaces;
44using OpenSim.Services.Connectors.Simulation;
45using GridRegion = OpenSim.Services.Interfaces.GridRegion;
46
47namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
48{
49 public class RemoteSimulationConnectorModule : ISharedRegionModule, ISimulationService
50 {
51 private bool initialized = false;
52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
53
54 protected bool m_enabled = false;
55 protected Scene m_aScene;
56 // RemoteSimulationConnector does not care about local regions; it delegates that to the Local module
57 protected LocalSimulationConnectorModule m_localBackend;
58 protected SimulationServiceConnector m_remoteConnector;
59
60 protected bool m_safemode;
61 protected IPAddress m_thisIP;
62
63 #region IRegionModule
64
65 public virtual void Initialise(IConfigSource config)
66 {
67
68 IConfig moduleConfig = config.Configs["Modules"];
69 if (moduleConfig != null)
70 {
71 string name = moduleConfig.GetString("SimulationServices", "");
72 if (name == Name)
73 {
74 //IConfig userConfig = config.Configs["SimulationService"];
75 //if (userConfig == null)
76 //{
77 // m_log.Error("[AVATAR CONNECTOR]: SimulationService missing from OpenSim.ini");
78 // return;
79 //}
80
81 m_remoteConnector = new SimulationServiceConnector();
82
83 m_enabled = true;
84
85 m_log.Info("[SIMULATION CONNECTOR]: Remote simulation enabled");
86 }
87 }
88 }
89
90 public virtual void PostInitialise()
91 {
92 }
93
94 public virtual void Close()
95 {
96 }
97
98 public void AddRegion(Scene scene)
99 {
100 if (!m_enabled)
101 return;
102
103 if (!initialized)
104 {
105 InitOnce(scene);
106 initialized = true;
107 }
108 InitEach(scene);
109 }
110
111 public void RemoveRegion(Scene scene)
112 {
113 if (m_enabled)
114 {
115 m_localBackend.RemoveScene(scene);
116 scene.UnregisterModuleInterface<ISimulationService>(this);
117 }
118 }
119
120 public void RegionLoaded(Scene scene)
121 {
122 if (!m_enabled)
123 return;
124 }
125
126 public Type ReplaceableInterface
127 {
128 get { return null; }
129 }
130
131 public virtual string Name
132 {
133 get { return "RemoteSimulationConnectorModule"; }
134 }
135
136 protected virtual void InitEach(Scene scene)
137 {
138 m_localBackend.Init(scene);
139 scene.RegisterModuleInterface<ISimulationService>(this);
140 }
141
142 protected virtual void InitOnce(Scene scene)
143 {
144 m_localBackend = new LocalSimulationConnectorModule();
145 m_aScene = scene;
146 //m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService);
147 m_thisIP = Util.GetHostFromDNS(scene.RegionInfo.ExternalHostName);
148 }
149
150 #endregion /* IRegionModule */
151
152 #region IInterregionComms
153
154 public IScene GetScene(ulong handle)
155 {
156 return m_localBackend.GetScene(handle);
157 }
158
159 public ISimulationService GetInnerService()
160 {
161 return m_localBackend;
162 }
163
164 /**
165 * Agent-related communications
166 */
167
168 public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
169 {
170 if (destination == null)
171 {
172 reason = "Given destination was null";
173 m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent was given a null destination");
174 return false;
175 }
176
177 // Try local first
178 if (m_localBackend.CreateAgent(destination, aCircuit, teleportFlags, out reason))
179 return true;
180
181 // else do the remote thing
182 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
183 {
184 //m_regionClient.SendUserInformation(regInfo, aCircuit);
185 return m_remoteConnector.CreateAgent(destination, aCircuit, teleportFlags, out reason);
186 }
187 return false;
188 }
189
190 public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
191 {
192 if (destination == null)
193 return false;
194
195 // Try local first
196 if (m_localBackend.UpdateAgent(destination, cAgentData))
197 return true;
198
199 // else do the remote thing
200 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
201 return m_remoteConnector.UpdateAgent(destination, cAgentData);
202
203 return false;
204
205 }
206
207 public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
208 {
209 if (destination == null)
210 return false;
211
212 // Try local first
213 if (m_localBackend.UpdateAgent(destination, cAgentData))
214 return true;
215
216 // else do the remote thing
217 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
218 return m_remoteConnector.UpdateAgent(destination, cAgentData);
219
220 return false;
221
222 }
223
224 public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
225 {
226 agent = null;
227
228 if (destination == null)
229 return false;
230
231 // Try local first
232 if (m_localBackend.RetrieveAgent(destination, id, out agent))
233 return true;
234
235 // else do the remote thing
236 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
237 return m_remoteConnector.RetrieveAgent(destination, id, out agent);
238
239 return false;
240
241 }
242
243 public bool ReleaseAgent(UUID origin, UUID id, string uri)
244 {
245 // Try local first
246 if (m_localBackend.ReleaseAgent(origin, id, uri))
247 return true;
248
249 // else do the remote thing
250 if (!m_localBackend.IsLocalRegion(origin))
251 return m_remoteConnector.ReleaseAgent(origin, id, uri);
252
253 return false;
254 }
255
256
257 public bool CloseAgent(GridRegion destination, UUID id)
258 {
259 if (destination == null)
260 return false;
261
262 // Try local first
263 if (m_localBackend.CloseAgent(destination, id))
264 return true;
265
266 // else do the remote thing
267 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
268 return m_remoteConnector.CloseAgent(destination, id);
269
270 return false;
271 }
272
273 /**
274 * Object-related communications
275 */
276
277 public bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall)
278 {
279 if (destination == null)
280 return false;
281
282 // Try local first
283 if (m_localBackend.CreateObject(destination, sog, isLocalCall))
284 {
285 //m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
286 return true;
287 }
288
289 // else do the remote thing
290 if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
291 return m_remoteConnector.CreateObject(destination, sog, isLocalCall);
292
293 return false;
294 }
295
296 public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
297 {
298 // Not Implemented
299 return false;
300 }
301
302 #endregion /* IInterregionComms */
303
304 }
305}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/LocalUserAccountServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/LocalUserAccountServiceConnector.cs
new file mode 100644
index 0000000..30ebb21
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/LocalUserAccountServiceConnector.cs
@@ -0,0 +1,190 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Server.Base;
36using OpenSim.Services.Interfaces;
37
38using OpenMetaverse;
39
40namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
41{
42 public class LocalUserAccountServicesConnector : ISharedRegionModule, IUserAccountService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 private IUserAccountService m_UserService;
49 private UserAccountCache m_Cache;
50
51 private bool m_Enabled = false;
52
53 #region ISharedRegionModule
54
55 public Type ReplaceableInterface
56 {
57 get { return null; }
58 }
59
60 public string Name
61 {
62 get { return "LocalUserAccountServicesConnector"; }
63 }
64
65 public void Initialise(IConfigSource source)
66 {
67 IConfig moduleConfig = source.Configs["Modules"];
68 if (moduleConfig != null)
69 {
70 string name = moduleConfig.GetString("UserAccountServices", "");
71 if (name == Name)
72 {
73 IConfig userConfig = source.Configs["UserAccountService"];
74 if (userConfig == null)
75 {
76 m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: UserAccountService missing from OpenSim.ini");
77 return;
78 }
79
80 string serviceDll = userConfig.GetString("LocalServiceModule", String.Empty);
81
82 if (serviceDll == String.Empty)
83 {
84 m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: No LocalServiceModule named in section UserService");
85 return;
86 }
87
88 Object[] args = new Object[] { source };
89 m_UserService = ServerUtils.LoadPlugin<IUserAccountService>(serviceDll, args);
90
91 if (m_UserService == null)
92 {
93 m_log.ErrorFormat(
94 "[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll);
95 return;
96 }
97 m_Enabled = true;
98 m_Cache = new UserAccountCache();
99
100 m_log.Info("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Local user connector enabled");
101 }
102 }
103 }
104
105 public void PostInitialise()
106 {
107 if (!m_Enabled)
108 return;
109 }
110
111 public void Close()
112 {
113 if (!m_Enabled)
114 return;
115 }
116
117 public void AddRegion(Scene scene)
118 {
119 if (!m_Enabled)
120 return;
121
122 scene.RegisterModuleInterface<IUserAccountService>(m_UserService);
123 }
124
125 public void RemoveRegion(Scene scene)
126 {
127 if (!m_Enabled)
128 return;
129 }
130
131 public void RegionLoaded(Scene scene)
132 {
133 if (!m_Enabled)
134 return;
135
136 m_log.InfoFormat("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Enabled local user accounts for region {0}", scene.RegionInfo.RegionName);
137 }
138
139 #endregion
140
141 #region IUserAccountService
142
143 public UserAccount GetUserAccount(UUID scopeID, UUID userID)
144 {
145 bool inCache = false;
146 UserAccount account = m_Cache.Get(userID, out inCache);
147 if (inCache)
148 return account;
149
150 account = m_UserService.GetUserAccount(scopeID, userID);
151 m_Cache.Cache(userID, account);
152
153 return account;
154 }
155
156 public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
157 {
158 bool inCache = false;
159 UserAccount account = m_Cache.Get(firstName + " " + lastName, out inCache);
160 if (inCache)
161 return account;
162
163 account = m_UserService.GetUserAccount(scopeID, firstName, lastName);
164 if (account != null)
165 m_Cache.Cache(account.PrincipalID, account);
166
167 return account;
168 }
169
170 public UserAccount GetUserAccount(UUID scopeID, string Email)
171 {
172 return m_UserService.GetUserAccount(scopeID, Email);
173 }
174
175 public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
176 {
177 return m_UserService.GetUserAccounts(scopeID, query);
178 }
179
180 // Update all updatable fields
181 //
182 public bool StoreUserAccount(UserAccount data)
183 {
184 return m_UserService.StoreUserAccount(data);
185 }
186
187 #endregion
188
189 }
190}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/RemoteUserAccountServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/RemoteUserAccountServiceConnector.cs
new file mode 100644
index 0000000..3321b38
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/RemoteUserAccountServiceConnector.cs
@@ -0,0 +1,155 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using Nini.Config;
30using log4net;
31using System.Reflection;
32using OpenSim.Region.Framework.Interfaces;
33using OpenSim.Region.Framework.Scenes;
34using OpenSim.Services.Interfaces;
35using OpenSim.Services.Connectors;
36
37using OpenMetaverse;
38
39namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
40{
41 public class RemoteUserAccountServicesConnector : UserAccountServicesConnector,
42 ISharedRegionModule, IUserAccountService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 private bool m_Enabled = false;
49 private UserAccountCache m_Cache;
50
51 public Type ReplaceableInterface
52 {
53 get { return null; }
54 }
55
56 public string Name
57 {
58 get { return "RemoteUserAccountServicesConnector"; }
59 }
60
61 public override void Initialise(IConfigSource source)
62 {
63 IConfig moduleConfig = source.Configs["Modules"];
64 if (moduleConfig != null)
65 {
66 string name = moduleConfig.GetString("UserAccountServices", "");
67 if (name == Name)
68 {
69 IConfig userConfig = source.Configs["UserAccountService"];
70 if (userConfig == null)
71 {
72 m_log.Error("[USER CONNECTOR]: UserAccountService missing from OpenSim.ini");
73 return;
74 }
75
76 m_Enabled = true;
77
78 base.Initialise(source);
79 m_Cache = new UserAccountCache();
80
81 m_log.Info("[USER CONNECTOR]: Remote users enabled");
82 }
83 }
84 }
85
86 public void PostInitialise()
87 {
88 if (!m_Enabled)
89 return;
90 }
91
92 public void Close()
93 {
94 if (!m_Enabled)
95 return;
96 }
97
98 public void AddRegion(Scene scene)
99 {
100 if (!m_Enabled)
101 return;
102
103 scene.RegisterModuleInterface<IUserAccountService>(this);
104 }
105
106 public void RemoveRegion(Scene scene)
107 {
108 if (!m_Enabled)
109 return;
110 }
111
112 public void RegionLoaded(Scene scene)
113 {
114 if (!m_Enabled)
115 return;
116 }
117
118 #region Overwritten methods from IUserAccountService
119
120 public override UserAccount GetUserAccount(UUID scopeID, UUID userID)
121 {
122 bool inCache = false;
123 UserAccount account = m_Cache.Get(userID, out inCache);
124 if (inCache)
125 return account;
126
127 account = base.GetUserAccount(scopeID, userID);
128 m_Cache.Cache(userID, account);
129
130 return account;
131 }
132
133 public override UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
134 {
135 bool inCache = false;
136 UserAccount account = m_Cache.Get(firstName + " " + lastName, out inCache);
137 if (inCache)
138 return account;
139
140 account = base.GetUserAccount(scopeID, firstName, lastName);
141 if (account != null)
142 m_Cache.Cache(account.PrincipalID, account);
143
144 return account;
145 }
146
147 public override bool StoreUserAccount(UserAccount data)
148 {
149 // This remote connector refuses to serve this method
150 return false;
151 }
152
153 #endregion
154 }
155}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/UserAccountCache.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/UserAccountCache.cs
new file mode 100644
index 0000000..a355661
--- /dev/null
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/UserAccounts/UserAccountCache.cs
@@ -0,0 +1,95 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using System;
28using System.Reflection;
29using System.Collections.Generic;
30using OpenSim.Framework;
31using OpenSim.Services.Interfaces;
32using OpenMetaverse;
33using log4net;
34
35namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
36{
37 public class UserAccountCache
38 {
39 private static readonly ILog m_log =
40 LogManager.GetLogger(
41 MethodBase.GetCurrentMethod().DeclaringType);
42 private ExpiringCache<UUID, UserAccount> m_UUIDCache;
43 private ExpiringCache<string, UUID> m_NameCache;
44
45 public UserAccountCache()
46 {
47 // Warning: the size values are a bit fuzzy. What matters
48 // most for this cache is the count value (128 entries).
49 m_UUIDCache = new ExpiringCache<UUID, UserAccount>();
50 m_NameCache = new ExpiringCache<string, UUID>(); // this one is unbound
51 }
52
53 public void Cache(UUID userID, UserAccount account)
54 {
55 // Cache even null accounts
56 m_UUIDCache.AddOrUpdate(userID, account, DateTime.Now + TimeSpan.FromMinutes(2.0d));
57 if (account != null)
58 m_NameCache.AddOrUpdate(account.Name, account.PrincipalID, DateTime.Now + TimeSpan.FromMinutes(2.0d));
59
60 m_log.DebugFormat("[USER CACHE]: cached user {0}", userID);
61 }
62
63 public UserAccount Get(UUID userID, out bool inCache)
64 {
65 UserAccount account = null;
66 inCache = false;
67 if (m_UUIDCache.TryGetValue(userID, out account))
68 {
69 //m_log.DebugFormat("[USER CACHE]: Account {0} {1} found in cache", account.FirstName, account.LastName);
70 inCache = true;
71 return account;
72 }
73
74 return null;
75 }
76
77 public UserAccount Get(string name, out bool inCache)
78 {
79 inCache = false;
80 if (!m_NameCache.Contains(name))
81 return null;
82
83 UserAccount account = null;
84 UUID uuid = UUID.Zero;
85 if (m_NameCache.TryGetValue(name, out uuid))
86 if (m_UUIDCache.TryGetValue(uuid, out account))
87 {
88 inCache = true;
89 return account;
90 }
91
92 return null;
93 }
94 }
95}
diff --git a/OpenSim/Region/CoreModules/World/Access/AccessModule.cs b/OpenSim/Region/CoreModules/World/Access/AccessModule.cs
index e4fe352..c355b13 100644
--- a/OpenSim/Region/CoreModules/World/Access/AccessModule.cs
+++ b/OpenSim/Region/CoreModules/World/Access/AccessModule.cs
@@ -33,7 +33,6 @@ using Nini.Config;
33using OpenMetaverse; 33using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Console; 35using OpenSim.Framework.Console;
36using OpenSim.Framework.Communications.Cache;
37using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
39using OpenSim.Services.Interfaces; 38using OpenSim.Services.Interfaces;
diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
index e6d4549..b37beab 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
@@ -38,10 +38,11 @@ using OpenMetaverse;
38using OpenSim.Framework; 38using OpenSim.Framework;
39using OpenSim.Framework.Serialization; 39using OpenSim.Framework.Serialization;
40using OpenSim.Framework.Serialization.External; 40using OpenSim.Framework.Serialization.External;
41using OpenSim.Framework.Communications.Cache; 41
42using OpenSim.Region.CoreModules.World.Terrain; 42using OpenSim.Region.CoreModules.World.Terrain;
43using OpenSim.Region.Framework.Interfaces; 43using OpenSim.Region.Framework.Interfaces;
44using OpenSim.Region.Framework.Scenes; 44using OpenSim.Region.Framework.Scenes;
45using OpenSim.Services.Interfaces;
45 46
46namespace OpenSim.Region.CoreModules.World.Archiver 47namespace OpenSim.Region.CoreModules.World.Archiver
47{ 48{
@@ -52,25 +53,27 @@ namespace OpenSim.Region.CoreModules.World.Archiver
52 { 53 {
53 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 54 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
54 55
55 private static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding(); 56 protected Scene m_scene;
56 private static UTF8Encoding m_utf8Encoding = new UTF8Encoding(); 57 protected Stream m_loadStream;
57 58 protected Guid m_requestId;
58 private Scene m_scene; 59 protected string m_errorMessage;
59 private Stream m_loadStream;
60 private Guid m_requestId;
61 private string m_errorMessage;
62 60
63 /// <value> 61 /// <value>
64 /// Should the archive being loaded be merged with what is already on the region? 62 /// Should the archive being loaded be merged with what is already on the region?
65 /// </value> 63 /// </value>
66 private bool m_merge; 64 protected bool m_merge;
65
66 /// <value>
67 /// Should we ignore any assets when reloading the archive?
68 /// </value>
69 protected bool m_skipAssets;
67 70
68 /// <summary> 71 /// <summary>
69 /// Used to cache lookups for valid uuids. 72 /// Used to cache lookups for valid uuids.
70 /// </summary> 73 /// </summary>
71 private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>(); 74 private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
72 75
73 public ArchiveReadRequest(Scene scene, string loadPath, bool merge, Guid requestId) 76 public ArchiveReadRequest(Scene scene, string loadPath, bool merge, bool skipAssets, Guid requestId)
74 { 77 {
75 m_scene = scene; 78 m_scene = scene;
76 79
@@ -88,14 +91,16 @@ namespace OpenSim.Region.CoreModules.World.Archiver
88 91
89 m_errorMessage = String.Empty; 92 m_errorMessage = String.Empty;
90 m_merge = merge; 93 m_merge = merge;
94 m_skipAssets = skipAssets;
91 m_requestId = requestId; 95 m_requestId = requestId;
92 } 96 }
93 97
94 public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, Guid requestId) 98 public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, bool skipAssets, Guid requestId)
95 { 99 {
96 m_scene = scene; 100 m_scene = scene;
97 m_loadStream = loadStream; 101 m_loadStream = loadStream;
98 m_merge = merge; 102 m_merge = merge;
103 m_skipAssets = skipAssets;
99 m_requestId = requestId; 104 m_requestId = requestId;
100 } 105 }
101 106
@@ -132,9 +137,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver
132 137
133 if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) 138 if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
134 { 139 {
135 serialisedSceneObjects.Add(m_utf8Encoding.GetString(data)); 140 serialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
136 } 141 }
137 else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) 142 else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
138 { 143 {
139 if (LoadAsset(filePath, data)) 144 if (LoadAsset(filePath, data))
140 successfulAssetRestores++; 145 successfulAssetRestores++;
@@ -154,7 +159,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
154 } 159 }
155 else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH)) 160 else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
156 { 161 {
157 serialisedParcels.Add(m_utf8Encoding.GetString(data)); 162 serialisedParcels.Add(Encoding.UTF8.GetString(data));
158 } 163 }
159 else if (filePath == ArchiveConstants.CONTROL_FILE_PATH) 164 else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
160 { 165 {
@@ -177,12 +182,15 @@ namespace OpenSim.Region.CoreModules.World.Archiver
177 archive.Close(); 182 archive.Close();
178 } 183 }
179 184
180 m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores); 185 if (!m_skipAssets)
181
182 if (failedAssetRestores > 0)
183 { 186 {
184 m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores); 187 m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
185 m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores); 188
189 if (failedAssetRestores > 0)
190 {
191 m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
192 m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
193 }
186 } 194 }
187 195
188 if (!m_merge) 196 if (!m_merge)
@@ -193,10 +201,6 @@ namespace OpenSim.Region.CoreModules.World.Archiver
193 201
194 // Try to retain the original creator/owner/lastowner if their uuid is present on this grid 202 // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
195 // otherwise, use the master avatar uuid instead 203 // otherwise, use the master avatar uuid instead
196 UUID masterAvatarId = m_scene.RegionInfo.MasterAvatarAssignedUUID;
197
198 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
199 masterAvatarId = m_scene.RegionInfo.EstateSettings.EstateOwner;
200 204
201 // Reload serialized parcels 205 // Reload serialized parcels
202 m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count); 206 m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
@@ -205,7 +209,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
205 { 209 {
206 LandData parcel = LandDataSerializer.Deserialize(serialisedParcel); 210 LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
207 if (!ResolveUserUuid(parcel.OwnerID)) 211 if (!ResolveUserUuid(parcel.OwnerID))
208 parcel.OwnerID = masterAvatarId; 212 parcel.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
209 landData.Add(parcel); 213 landData.Add(parcel);
210 } 214 }
211 m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData); 215 m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
@@ -244,13 +248,13 @@ namespace OpenSim.Region.CoreModules.World.Archiver
244 foreach (SceneObjectPart part in sceneObject.Children.Values) 248 foreach (SceneObjectPart part in sceneObject.Children.Values)
245 { 249 {
246 if (!ResolveUserUuid(part.CreatorID)) 250 if (!ResolveUserUuid(part.CreatorID))
247 part.CreatorID = masterAvatarId; 251 part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
248 252
249 if (!ResolveUserUuid(part.OwnerID)) 253 if (!ResolveUserUuid(part.OwnerID))
250 part.OwnerID = masterAvatarId; 254 part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
251 255
252 if (!ResolveUserUuid(part.LastOwnerID)) 256 if (!ResolveUserUuid(part.LastOwnerID))
253 part.LastOwnerID = masterAvatarId; 257 part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
254 258
255 // And zap any troublesome sit target information 259 // And zap any troublesome sit target information
256 part.SitTargetOrientation = new Quaternion(0, 0, 0, 1); 260 part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
@@ -265,11 +269,14 @@ namespace OpenSim.Region.CoreModules.World.Archiver
265 { 269 {
266 if (!ResolveUserUuid(kvp.Value.OwnerID)) 270 if (!ResolveUserUuid(kvp.Value.OwnerID))
267 { 271 {
268 kvp.Value.OwnerID = masterAvatarId; 272 if (!ResolveUserUuid(kvp.Value.OwnerID))
269 } 273 {
270 if (!ResolveUserUuid(kvp.Value.CreatorID)) 274 kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
271 { 275 }
272 kvp.Value.CreatorID = masterAvatarId; 276 if (!ResolveUserUuid(kvp.Value.CreatorID))
277 {
278 kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
279 }
273 } 280 }
274 } 281 }
275 part.TaskInventory.LockItemsForRead(false); 282 part.TaskInventory.LockItemsForRead(false);
@@ -279,6 +286,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
279 { 286 {
280 sceneObjectsLoadedCount++; 287 sceneObjectsLoadedCount++;
281 sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0); 288 sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0);
289 sceneObject.ResumeScripts();
282 } 290 }
283 } 291 }
284 292
@@ -303,8 +311,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver
303 { 311 {
304 if (!m_validUserUuids.ContainsKey(uuid)) 312 if (!m_validUserUuids.ContainsKey(uuid))
305 { 313 {
306 CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(uuid); 314 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
307 if (profile != null && profile.UserProfile != null) 315 if (account != null)
308 m_validUserUuids.Add(uuid, true); 316 m_validUserUuids.Add(uuid, true);
309 else 317 else
310 m_validUserUuids.Add(uuid, false); 318 m_validUserUuids.Add(uuid, false);
@@ -349,7 +357,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
349 357
350 //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); 358 //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
351 359
352 AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType); 360 AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
353 asset.Data = data; 361 asset.Data = data;
354 362
355 // We're relying on the asset service to do the sensible thing and not store the asset if it already 363 // We're relying on the asset service to do the sensible thing and not store the asset if it already
@@ -543,7 +551,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
543 XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); 551 XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
544 552
545 XmlTextReader xtr 553 XmlTextReader xtr
546 = new XmlTextReader(m_asciiEncoding.GetString(data), XmlNodeType.Document, context); 554 = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
547 555
548 RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings; 556 RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
549 557
diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs
index b61b341..b25636f 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs
@@ -100,7 +100,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
100 /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception> 100 /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
101 public void ArchiveRegion() 101 public void ArchiveRegion()
102 { 102 {
103 Dictionary<UUID, int> assetUuids = new Dictionary<UUID, int>(); 103 Dictionary<UUID, AssetType> assetUuids = new Dictionary<UUID, AssetType>();
104 104
105 List<EntityBase> entities = m_scene.GetEntities(); 105 List<EntityBase> entities = m_scene.GetEntities();
106 List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); 106 List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
@@ -142,18 +142,18 @@ namespace OpenSim.Region.CoreModules.World.Archiver
142 142
143 // Make sure that we also request terrain texture assets 143 // Make sure that we also request terrain texture assets
144 RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings; 144 RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings;
145 145
146 if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1) 146 if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
147 assetUuids[regionSettings.TerrainTexture1] = 1; 147 assetUuids[regionSettings.TerrainTexture1] = AssetType.Texture;
148 148
149 if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2) 149 if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
150 assetUuids[regionSettings.TerrainTexture2] = 1; 150 assetUuids[regionSettings.TerrainTexture2] = AssetType.Texture;
151 151
152 if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3) 152 if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
153 assetUuids[regionSettings.TerrainTexture3] = 1; 153 assetUuids[regionSettings.TerrainTexture3] = AssetType.Texture;
154 154
155 if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4) 155 if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
156 assetUuids[regionSettings.TerrainTexture4] = 1; 156 assetUuids[regionSettings.TerrainTexture4] = AssetType.Texture;
157 157
158 TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream); 158 TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream);
159 159
@@ -168,7 +168,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
168 m_requestId); 168 m_requestId);
169 169
170 new AssetsRequest( 170 new AssetsRequest(
171 new AssetsArchiver(archiveWriter), assetUuids.Keys, 171 new AssetsArchiver(archiveWriter), assetUuids,
172 m_scene.AssetService, awre.ReceivedAllAssets).Execute(); 172 m_scene.AssetService, awre.ReceivedAllAssets).Execute();
173 } 173 }
174 } 174 }
diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiverModule.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiverModule.cs
index fc8d4e1..82ede01 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/ArchiverModule.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiverModule.cs
@@ -94,8 +94,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver
94 public void HandleLoadOarConsoleCommand(string module, string[] cmdparams) 94 public void HandleLoadOarConsoleCommand(string module, string[] cmdparams)
95 { 95 {
96 bool mergeOar = false; 96 bool mergeOar = false;
97 bool skipAssets = false;
97 98
98 OptionSet options = new OptionSet().Add("m|merge", delegate (string v) { mergeOar = v != null; }); 99 OptionSet options = new OptionSet().Add("m|merge", delegate (string v) { mergeOar = v != null; });
100 options.Add("s|skip-assets", delegate (string v) { skipAssets = v != null; });
101
99 List<string> mainParams = options.Parse(cmdparams); 102 List<string> mainParams = options.Parse(cmdparams);
100 103
101// m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar); 104// m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar);
@@ -105,11 +108,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver
105 108
106 if (mainParams.Count > 2) 109 if (mainParams.Count > 2)
107 { 110 {
108 DearchiveRegion(mainParams[2], mergeOar, Guid.Empty); 111 DearchiveRegion(mainParams[2], mergeOar, skipAssets, Guid.Empty);
109 } 112 }
110 else 113 else
111 { 114 {
112 DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, mergeOar, Guid.Empty); 115 DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, mergeOar, skipAssets, Guid.Empty);
113 } 116 }
114 } 117 }
115 118
@@ -154,25 +157,25 @@ namespace OpenSim.Region.CoreModules.World.Archiver
154 157
155 public void DearchiveRegion(string loadPath) 158 public void DearchiveRegion(string loadPath)
156 { 159 {
157 DearchiveRegion(loadPath, false, Guid.Empty); 160 DearchiveRegion(loadPath, false, false, Guid.Empty);
158 } 161 }
159 162
160 public void DearchiveRegion(string loadPath, bool merge, Guid requestId) 163 public void DearchiveRegion(string loadPath, bool merge, bool skipAssets, Guid requestId)
161 { 164 {
162 m_log.InfoFormat( 165 m_log.InfoFormat(
163 "[ARCHIVER]: Loading archive to region {0} from {1}", m_scene.RegionInfo.RegionName, loadPath); 166 "[ARCHIVER]: Loading archive to region {0} from {1}", m_scene.RegionInfo.RegionName, loadPath);
164 167
165 new ArchiveReadRequest(m_scene, loadPath, merge, requestId).DearchiveRegion(); 168 new ArchiveReadRequest(m_scene, loadPath, merge, skipAssets, requestId).DearchiveRegion();
166 } 169 }
167 170
168 public void DearchiveRegion(Stream loadStream) 171 public void DearchiveRegion(Stream loadStream)
169 { 172 {
170 DearchiveRegion(loadStream, false, Guid.Empty); 173 DearchiveRegion(loadStream, false, false, Guid.Empty);
171 } 174 }
172 175
173 public void DearchiveRegion(Stream loadStream, bool merge, Guid requestId) 176 public void DearchiveRegion(Stream loadStream, bool merge, bool skipAssets, Guid requestId)
174 { 177 {
175 new ArchiveReadRequest(m_scene, loadStream, merge, requestId).DearchiveRegion(); 178 new ArchiveReadRequest(m_scene, loadStream, merge, skipAssets, requestId).DearchiveRegion();
176 } 179 }
177 } 180 }
178} 181}
diff --git a/OpenSim/Region/CoreModules/World/Archiver/AssetsDearchiver.cs b/OpenSim/Region/CoreModules/World/Archiver/AssetsDearchiver.cs
index 2d2c570..2c04008 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/AssetsDearchiver.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/AssetsDearchiver.cs
@@ -158,7 +158,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
158 158
159 m_log.DebugFormat("[ARCHIVER]: Importing asset {0}", filename); 159 m_log.DebugFormat("[ARCHIVER]: Importing asset {0}", filename);
160 160
161 AssetBase asset = new AssetBase(new UUID(filename), metadata.Name, metadata.AssetType); 161 AssetBase asset = new AssetBase(new UUID(filename), metadata.Name, metadata.AssetType, UUID.Zero.ToString());
162 asset.Description = metadata.Description; 162 asset.Description = metadata.Description;
163 asset.Data = data; 163 asset.Data = data;
164 164
diff --git a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
index c9fce91..4215f97 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
@@ -74,7 +74,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
74 /// <value> 74 /// <value>
75 /// uuids to request 75 /// uuids to request
76 /// </value> 76 /// </value>
77 protected ICollection<UUID> m_uuids; 77 protected IDictionary<UUID, AssetType> m_uuids;
78 78
79 /// <value> 79 /// <value>
80 /// Callback used when all the assets requested have been received. 80 /// Callback used when all the assets requested have been received.
@@ -104,7 +104,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
104 protected AssetsArchiver m_assetsArchiver; 104 protected AssetsArchiver m_assetsArchiver;
105 105
106 protected internal AssetsRequest( 106 protected internal AssetsRequest(
107 AssetsArchiver assetsArchiver, ICollection<UUID> uuids, 107 AssetsArchiver assetsArchiver, IDictionary<UUID, AssetType> uuids,
108 IAssetService assetService, AssetsRequestCallback assetsRequestCallback) 108 IAssetService assetService, AssetsRequestCallback assetsRequestCallback)
109 { 109 {
110 m_assetsArchiver = assetsArchiver; 110 m_assetsArchiver = assetsArchiver;
@@ -132,9 +132,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver
132 return; 132 return;
133 } 133 }
134 134
135 foreach (UUID uuid in m_uuids) 135 foreach (KeyValuePair<UUID, AssetType> kvp in m_uuids)
136 { 136 {
137 m_assetService.Get(uuid.ToString(), this, AssetRequestCallback); 137 m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);
138 } 138 }
139 139
140 m_requestCallbackTimer.Enabled = true; 140 m_requestCallbackTimer.Enabled = true;
@@ -157,7 +157,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
157 // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure 157 // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure
158 // case anyway. 158 // case anyway.
159 List<UUID> uuids = new List<UUID>(); 159 List<UUID> uuids = new List<UUID>();
160 foreach (UUID uuid in m_uuids) 160 foreach (UUID uuid in m_uuids.Keys)
161 { 161 {
162 uuids.Add(uuid); 162 uuids.Add(uuid);
163 } 163 }
@@ -200,6 +200,19 @@ namespace OpenSim.Region.CoreModules.World.Archiver
200 } 200 }
201 } 201 }
202 202
203 protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
204 {
205 // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
206 if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
207 {
208 AssetType type = (AssetType)assetType;
209 m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, type);
210 fetchedAsset.Type = (sbyte)type;
211 }
212
213 AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
214 }
215
203 /// <summary> 216 /// <summary>
204 /// Called back by the asset cache when it has the asset 217 /// Called back by the asset cache when it has the asset
205 /// </summary> 218 /// </summary>
diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs
index e77a23b..624dc22 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs
@@ -34,7 +34,7 @@ using NUnit.Framework;
34using NUnit.Framework.SyntaxHelpers; 34using NUnit.Framework.SyntaxHelpers;
35using OpenMetaverse; 35using OpenMetaverse;
36using OpenSim.Framework; 36using OpenSim.Framework;
37using OpenSim.Framework.Communications.Cache; 37
38using OpenSim.Framework.Serialization; 38using OpenSim.Framework.Serialization;
39using OpenSim.Framework.Serialization.External; 39using OpenSim.Framework.Serialization.External;
40using OpenSim.Region.CoreModules.World.Serialiser; 40using OpenSim.Region.CoreModules.World.Serialiser;
@@ -63,7 +63,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests
63 SerialiserModule serialiserModule = new SerialiserModule(); 63 SerialiserModule serialiserModule = new SerialiserModule();
64 TerrainModule terrainModule = new TerrainModule(); 64 TerrainModule terrainModule = new TerrainModule();
65 65
66 m_scene = SceneSetupHelpers.SetupScene("scene1"); 66 m_scene = SceneSetupHelpers.SetupScene("useraccounts");
67 SceneSetupHelpers.SetupSceneModules(m_scene, m_archiverModule, serialiserModule, terrainModule); 67 SceneSetupHelpers.SetupSceneModules(m_scene, m_archiverModule, serialiserModule, terrainModule);
68 } 68 }
69 69
@@ -442,7 +442,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests
442 byte[] archive = archiveWriteStream.ToArray(); 442 byte[] archive = archiveWriteStream.ToArray();
443 MemoryStream archiveReadStream = new MemoryStream(archive); 443 MemoryStream archiveReadStream = new MemoryStream(archive);
444 444
445 m_archiverModule.DearchiveRegion(archiveReadStream, true, Guid.Empty); 445 m_archiverModule.DearchiveRegion(archiveReadStream, true, false, Guid.Empty);
446 446
447 SceneObjectPart object1Existing = m_scene.GetSceneObjectPart(part1.Name); 447 SceneObjectPart object1Existing = m_scene.GetSceneObjectPart(part1.Name);
448 Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge"); 448 Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge");
diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs
index 03da269..940b535 100644
--- a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs
+++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs
@@ -48,6 +48,10 @@ namespace OpenSim.Region.CoreModules.World.Estate
48 48
49 private EstateTerrainXferHandler TerrainUploader; 49 private EstateTerrainXferHandler TerrainUploader;
50 50
51 public event ChangeDelegate OnRegionInfoChange;
52 public event ChangeDelegate OnEstateInfoChange;
53 public event MessageDelegate OnEstateMessage;
54
51 #region Packet Data Responders 55 #region Packet Data Responders
52 56
53 private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice) 57 private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
@@ -57,10 +61,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
57 if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime) 61 if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime)
58 sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800; 62 sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800;
59 UUID estateOwner; 63 UUID estateOwner;
60 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 64 estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
61 estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
62 else
63 estateOwner = m_scene.RegionInfo.MasterAvatarAssignedUUID;
64 65
65 if (m_scene.Permissions.IsGod(remote_client.AgentId)) 66 if (m_scene.Permissions.IsGod(remote_client.AgentId))
66 estateOwner = remote_client.AgentId; 67 estateOwner = remote_client.AgentId;
@@ -140,6 +141,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
140 m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; 141 m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false;
141 142
142 m_scene.RegionInfo.RegionSettings.Save(); 143 m_scene.RegionInfo.RegionSettings.Save();
144 TriggerRegionInfoChange();
143 145
144 sendRegionInfoPacketToAll(); 146 sendRegionInfoPacketToAll();
145 } 147 }
@@ -165,6 +167,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
165 break; 167 break;
166 } 168 }
167 m_scene.RegionInfo.RegionSettings.Save(); 169 m_scene.RegionInfo.RegionSettings.Save();
170 TriggerRegionInfoChange();
168 sendRegionInfoPacketToAll(); 171 sendRegionInfoPacketToAll();
169 } 172 }
170 173
@@ -190,6 +193,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
190 break; 193 break;
191 } 194 }
192 m_scene.RegionInfo.RegionSettings.Save(); 195 m_scene.RegionInfo.RegionSettings.Save();
196 TriggerRegionInfoChange();
193 sendRegionInfoPacketToAll(); 197 sendRegionInfoPacketToAll();
194 } 198 }
195 199
@@ -215,13 +219,14 @@ namespace OpenSim.Region.CoreModules.World.Estate
215 m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; 219 m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
216 m_scene.RegionInfo.RegionSettings.SunPosition = SunHour; 220 m_scene.RegionInfo.RegionSettings.SunPosition = SunHour;
217 221
218 TriggerEstateToolsSunUpdate(); 222 m_scene.TriggerEstateSunUpdate();
219 223
220 //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString()); 224 //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
221 //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString()); 225 //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
222 226
223 sendRegionInfoPacketToAll(); 227 sendRegionInfoPacketToAll();
224 m_scene.RegionInfo.RegionSettings.Save(); 228 m_scene.RegionInfo.RegionSettings.Save();
229 TriggerRegionInfoChange();
225 } 230 }
226 231
227 private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds) 232 private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
@@ -233,6 +238,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
233 { 238 {
234 m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; 239 m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
235 m_scene.RegionInfo.RegionSettings.Save(); 240 m_scene.RegionInfo.RegionSettings.Save();
241 TriggerRegionInfoChange();
236 } 242 }
237 243
238 private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user) 244 private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
@@ -241,8 +247,6 @@ namespace OpenSim.Region.CoreModules.World.Estate
241 247
242 if (user == m_scene.RegionInfo.EstateSettings.EstateOwner) 248 if (user == m_scene.RegionInfo.EstateSettings.EstateOwner)
243 return; // never process EO 249 return; // never process EO
244 if (user == m_scene.RegionInfo.MasterAvatarAssignedUUID)
245 return; // never process owner
246 250
247 if ((estateAccessType & 4) != 0) // User add 251 if ((estateAccessType & 4) != 0) // User add
248 { 252 {
@@ -250,6 +254,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
250 { 254 {
251 m_scene.RegionInfo.EstateSettings.AddEstateUser(user); 255 m_scene.RegionInfo.EstateSettings.AddEstateUser(user);
252 m_scene.RegionInfo.EstateSettings.Save(); 256 m_scene.RegionInfo.EstateSettings.Save();
257 TriggerEstateInfoChange();
253 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); 258 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID);
254 } 259 }
255 else 260 else
@@ -264,6 +269,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
264 { 269 {
265 m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user); 270 m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user);
266 m_scene.RegionInfo.EstateSettings.Save(); 271 m_scene.RegionInfo.EstateSettings.Save();
272 TriggerEstateInfoChange();
267 273
268 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); 274 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID);
269 } 275 }
@@ -278,6 +284,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
278 { 284 {
279 m_scene.RegionInfo.EstateSettings.AddEstateGroup(user); 285 m_scene.RegionInfo.EstateSettings.AddEstateGroup(user);
280 m_scene.RegionInfo.EstateSettings.Save(); 286 m_scene.RegionInfo.EstateSettings.Save();
287 TriggerEstateInfoChange();
281 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); 288 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID);
282 } 289 }
283 else 290 else
@@ -291,6 +298,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
291 { 298 {
292 m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); 299 m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user);
293 m_scene.RegionInfo.EstateSettings.Save(); 300 m_scene.RegionInfo.EstateSettings.Save();
301 TriggerEstateInfoChange();
294 302
295 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); 303 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID);
296 } 304 }
@@ -328,6 +336,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
328 336
329 m_scene.RegionInfo.EstateSettings.AddBan(item); 337 m_scene.RegionInfo.EstateSettings.AddBan(item);
330 m_scene.RegionInfo.EstateSettings.Save(); 338 m_scene.RegionInfo.EstateSettings.Save();
339 TriggerEstateInfoChange();
331 340
332 ScenePresence s = m_scene.GetScenePresence(user); 341 ScenePresence s = m_scene.GetScenePresence(user);
333 if (s != null) 342 if (s != null)
@@ -375,6 +384,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
375 { 384 {
376 m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); 385 m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
377 m_scene.RegionInfo.EstateSettings.Save(); 386 m_scene.RegionInfo.EstateSettings.Save();
387 TriggerEstateInfoChange();
378 } 388 }
379 else 389 else
380 { 390 {
@@ -394,6 +404,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
394 { 404 {
395 m_scene.RegionInfo.EstateSettings.AddEstateManager(user); 405 m_scene.RegionInfo.EstateSettings.AddEstateManager(user);
396 m_scene.RegionInfo.EstateSettings.Save(); 406 m_scene.RegionInfo.EstateSettings.Save();
407 TriggerEstateInfoChange();
397 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); 408 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
398 } 409 }
399 else 410 else
@@ -407,6 +418,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
407 { 418 {
408 m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user); 419 m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
409 m_scene.RegionInfo.EstateSettings.Save(); 420 m_scene.RegionInfo.EstateSettings.Save();
421 TriggerEstateInfoChange();
410 422
411 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); 423 remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
412 } 424 }
@@ -429,10 +441,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
429 private void SendEstateBlueBoxMessage( 441 private void SendEstateBlueBoxMessage(
430 IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) 442 IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
431 { 443 {
432 IDialogModule dm = m_scene.RequestModuleInterface<IDialogModule>(); 444 TriggerEstateMessage(senderID, senderName, message);
433
434 if (dm != null)
435 dm.SendNotificationToUsersInEstate(senderID, senderName, message);
436 } 445 }
437 446
438 private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics) 447 private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics)
@@ -454,12 +463,16 @@ namespace OpenSim.Region.CoreModules.World.Estate
454 463
455 464
456 m_scene.RegionInfo.RegionSettings.Save(); 465 m_scene.RegionInfo.RegionSettings.Save();
466 TriggerRegionInfoChange();
457 467
458 m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics); 468 m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics);
459 } 469 }
460 470
461 private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey) 471 private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
462 { 472 {
473 if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
474 return;
475
463 if (prey != UUID.Zero) 476 if (prey != UUID.Zero)
464 { 477 {
465 ScenePresence s = m_scene.GetScenePresence(prey); 478 ScenePresence s = m_scene.GetScenePresence(prey);
@@ -473,28 +486,23 @@ namespace OpenSim.Region.CoreModules.World.Estate
473 486
474 private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID) 487 private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
475 { 488 {
476 // Get a fresh list that will not change as people get teleported away 489 if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
477 ScenePresence[] presences = m_scene.GetScenePresences(); 490 return;
478 491
479 for (int i = 0; i < presences.Length; i++) 492 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
480 { 493 {
481 ScenePresence p = presences[i]; 494 if (sp.UUID != senderID)
482
483 if (p.UUID != senderID)
484 { 495 {
496 ScenePresence p = m_scene.GetScenePresence(sp.UUID);
485 // make sure they are still there, we could be working down a long list 497 // make sure they are still there, we could be working down a long list
486 ScenePresence s = m_scene.GetScenePresence(p.UUID); 498 // Also make sure they are actually in the region
487 if (s != null) 499 if (p != null && !p.IsChildAgent)
488 { 500 {
489 // Also make sure they are actually in the region 501 p.ControllingClient.SendTeleportLocationStart();
490 if (!s.IsChildAgent) 502 m_scene.TeleportClientHome(p.UUID, p.ControllingClient);
491 {
492 s.ControllingClient.SendTeleportLocationStart();
493 m_scene.TeleportClientHome(s.UUID, s.ControllingClient);
494 }
495 } 503 }
496 } 504 }
497 } 505 });
498 } 506 }
499 private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID) 507 private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
500 { 508 {
@@ -709,16 +717,9 @@ namespace OpenSim.Region.CoreModules.World.Estate
709 lsri.TaskID = sog.UUID; 717 lsri.TaskID = sog.UUID;
710 lsri.TaskLocalID = sog.LocalId; 718 lsri.TaskLocalID = sog.LocalId;
711 lsri.TaskName = sog.GetPartName(obj); 719 lsri.TaskName = sog.GetPartName(obj);
712 if (m_scene.CommsManager.UUIDNameCachedTest(sog.OwnerID)) 720 lsri.OwnerName = "waiting";
713 { 721 lock (uuidNameLookupList)
714 lsri.OwnerName = m_scene.CommsManager.UUIDNameRequestString(sog.OwnerID); 722 uuidNameLookupList.Add(sog.OwnerID);
715 }
716 else
717 {
718 lsri.OwnerName = "waiting";
719 lock (uuidNameLookupList)
720 uuidNameLookupList.Add(sog.OwnerID);
721 }
722 723
723 if (filter.Length != 0) 724 if (filter.Length != 0)
724 { 725 {
@@ -769,7 +770,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
769 for (int i = 0; i < uuidarr.Length; i++) 770 for (int i = 0; i < uuidarr.Length; i++)
770 { 771 {
771 // string lookupname = m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]); 772 // string lookupname = m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]);
772 m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]); 773 m_scene.GetUserName(uuidarr[i]);
773 // we drop it. It gets cached though... so we're ready for the next request. 774 // we drop it. It gets cached though... so we're ready for the next request.
774 } 775 }
775 } 776 }
@@ -779,12 +780,11 @@ namespace OpenSim.Region.CoreModules.World.Estate
779 780
780 public void sendRegionInfoPacketToAll() 781 public void sendRegionInfoPacketToAll()
781 { 782 {
782 List<ScenePresence> avatars = m_scene.GetAvatars(); 783 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
783
784 for (int i = 0; i < avatars.Count; i++)
785 { 784 {
786 HandleRegionInfoRequest(avatars[i].ControllingClient); 785 if (!sp.IsChildAgent)
787 } 786 HandleRegionInfoRequest(sp.ControllingClient);
787 });
788 } 788 }
789 789
790 public void sendRegionHandshake(IClientAPI remoteClient) 790 public void sendRegionHandshake(IClientAPI remoteClient)
@@ -808,14 +808,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
808 args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; 808 args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
809 args.regionFlags = GetRegionFlags(); 809 args.regionFlags = GetRegionFlags();
810 args.regionName = m_scene.RegionInfo.RegionName; 810 args.regionName = m_scene.RegionInfo.RegionName;
811 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 811 args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
812 args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
813 else
814 args.SimOwner = m_scene.RegionInfo.MasterAvatarAssignedUUID;
815
816 // Fudge estate owner
817 //if (m_scene.Permissions.IsGod(remoteClient.AgentId))
818 // args.SimOwner = remoteClient.AgentId;
819 812
820 args.terrainBase0 = UUID.Zero; 813 args.terrainBase0 = UUID.Zero;
821 args.terrainBase1 = UUID.Zero; 814 args.terrainBase1 = UUID.Zero;
@@ -888,8 +881,9 @@ namespace OpenSim.Region.CoreModules.World.Estate
888 m_scene.RegionInfo.EstateSettings.DenyMinors = false; 881 m_scene.RegionInfo.EstateSettings.DenyMinors = false;
889 882
890 m_scene.RegionInfo.EstateSettings.Save(); 883 m_scene.RegionInfo.EstateSettings.Save();
884 TriggerEstateInfoChange();
891 885
892 TriggerEstateToolsSunUpdate(); 886 m_scene.TriggerEstateSunUpdate();
893 887
894 sendDetailedEstateData(remoteClient, invoice); 888 sendDetailedEstateData(remoteClient, invoice);
895 } 889 }
@@ -955,6 +949,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
955 break; 949 break;
956 } 950 }
957 m_scene.RegionInfo.RegionSettings.Save(); 951 m_scene.RegionInfo.RegionSettings.Save();
952 TriggerRegionInfoChange();
958 sendRegionInfoPacketToAll(); 953 sendRegionInfoPacketToAll();
959 954
960 } 955 }
@@ -1000,6 +995,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
1000 break; 995 break;
1001 } 996 }
1002 m_scene.RegionInfo.RegionSettings.Save(); 997 m_scene.RegionInfo.RegionSettings.Save();
998 TriggerRegionInfoChange();
1003 sendRegionHandshakeToAll(); 999 sendRegionHandshakeToAll();
1004 } 1000 }
1005 } 1001 }
@@ -1011,7 +1007,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
1011 { 1007 {
1012 // Sets up the sun module based no the saved Estate and Region Settings 1008 // Sets up the sun module based no the saved Estate and Region Settings
1013 // DO NOT REMOVE or the sun will stop working 1009 // DO NOT REMOVE or the sun will stop working
1014 TriggerEstateToolsSunUpdate(); 1010 m_scene.TriggerEstateSunUpdate();
1015 } 1011 }
1016 1012
1017 public void Close() 1013 public void Close()
@@ -1032,40 +1028,6 @@ namespace OpenSim.Region.CoreModules.World.Estate
1032 1028
1033 #region Other Functions 1029 #region Other Functions
1034 1030
1035 private void TriggerEstateToolsSunUpdate()
1036 {
1037 float sun;
1038 if (m_scene.RegionInfo.RegionSettings.UseEstateSun)
1039 {
1040 sun = (float)m_scene.RegionInfo.EstateSettings.SunPosition;
1041 if (m_scene.RegionInfo.EstateSettings.UseGlobalTime)
1042 {
1043 sun = m_scene.EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f;
1044 }
1045
1046 //
1047 m_scene.EventManager.TriggerEstateToolsSunUpdate(
1048 m_scene.RegionInfo.RegionHandle,
1049 m_scene.RegionInfo.EstateSettings.FixedSun,
1050 m_scene.RegionInfo.RegionSettings.UseEstateSun,
1051 sun);
1052 }
1053 else
1054 {
1055 // Use the Sun Position from the Region Settings
1056 sun = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f;
1057
1058 m_scene.EventManager.TriggerEstateToolsSunUpdate(
1059 m_scene.RegionInfo.RegionHandle,
1060 m_scene.RegionInfo.RegionSettings.FixedSun,
1061 m_scene.RegionInfo.RegionSettings.UseEstateSun,
1062 sun);
1063 }
1064
1065
1066 }
1067
1068
1069 public void changeWaterHeight(float height) 1031 public void changeWaterHeight(float height)
1070 { 1032 {
1071 setRegionTerrainSettings(height, 1033 setRegionTerrainSettings(height,
@@ -1194,8 +1156,6 @@ namespace OpenSim.Region.CoreModules.World.Estate
1194 1156
1195 public bool IsManager(UUID avatarID) 1157 public bool IsManager(UUID avatarID)
1196 { 1158 {
1197 if (avatarID == m_scene.RegionInfo.MasterAvatarAssignedUUID)
1198 return true;
1199 if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner) 1159 if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner)
1200 return true; 1160 return true;
1201 1161
@@ -1205,5 +1165,29 @@ namespace OpenSim.Region.CoreModules.World.Estate
1205 1165
1206 return false; 1166 return false;
1207 } 1167 }
1168
1169 protected void TriggerRegionInfoChange()
1170 {
1171 ChangeDelegate change = OnRegionInfoChange;
1172
1173 if (change != null)
1174 change(m_scene.RegionInfo.RegionID);
1175 }
1176
1177 protected void TriggerEstateInfoChange()
1178 {
1179 ChangeDelegate change = OnEstateInfoChange;
1180
1181 if (change != null)
1182 change(m_scene.RegionInfo.RegionID);
1183 }
1184
1185 protected void TriggerEstateMessage(UUID fromID, string fromName, string message)
1186 {
1187 MessageDelegate onmessage = OnEstateMessage;
1188
1189 if (onmessage != null)
1190 onmessage(m_scene.RegionInfo.RegionID, fromID, fromName, message);
1191 }
1208 } 1192 }
1209} 1193}
diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateTerrainXferHandler.cs b/OpenSim/Region/CoreModules/World/Estate/EstateTerrainXferHandler.cs
index 2ff635b..b8d8b10 100644
--- a/OpenSim/Region/CoreModules/World/Estate/EstateTerrainXferHandler.cs
+++ b/OpenSim/Region/CoreModules/World/Estate/EstateTerrainXferHandler.cs
@@ -52,7 +52,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
52 52
53 public EstateTerrainXferHandler(IClientAPI pRemoteClient, string pClientFilename) 53 public EstateTerrainXferHandler(IClientAPI pRemoteClient, string pClientFilename)
54 { 54 {
55 m_asset = new AssetBase(UUID.Zero, pClientFilename, type); 55 m_asset = new AssetBase(UUID.Zero, pClientFilename, type, pRemoteClient.AgentId.ToString());
56 m_asset.Data = new byte[0]; 56 m_asset.Data = new byte[0];
57 m_asset.Description = "empty"; 57 m_asset.Description = "empty";
58 m_asset.Local = true; 58 m_asset.Local = true;
diff --git a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
index 8039558..d05235e 100644
--- a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
+++ b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
@@ -28,6 +28,7 @@
28using System; 28using System;
29using System.Collections; 29using System.Collections;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Diagnostics;
31using System.Reflection; 32using System.Reflection;
32using log4net; 33using log4net;
33using Nini.Config; 34using Nini.Config;
@@ -86,6 +87,7 @@ namespace OpenSim.Region.CoreModules.World.Land
86 87
87 // caches ExtendedLandData 88 // caches ExtendedLandData
88 private Cache parcelInfoCache; 89 private Cache parcelInfoCache;
90 private Vector3? forcedPosition = null;
89 91
90 #region INonSharedRegionModule Members 92 #region INonSharedRegionModule Members
91 93
@@ -144,6 +146,13 @@ namespace OpenSim.Region.CoreModules.World.Land
144 { 146 {
145 } 147 }
146 148
149 private bool OnVerifyUserConnection(ScenePresence scenePresence, out string reason)
150 {
151 ILandObject nearestParcel = m_scene.GetNearestAllowedParcel(scenePresence.UUID, scenePresence.AbsolutePosition.X, scenePresence.AbsolutePosition.Y);
152 reason = "You are not allowed to enter this sim.";
153 return nearestParcel != null;
154 }
155
147 void EventManagerOnNewClient(IClientAPI client) 156 void EventManagerOnNewClient(IClientAPI client)
148 { 157 {
149 //Register some client events 158 //Register some client events
@@ -161,10 +170,7 @@ namespace OpenSim.Region.CoreModules.World.Land
161 client.OnParcelInfoRequest += ClientOnParcelInfoRequest; 170 client.OnParcelInfoRequest += ClientOnParcelInfoRequest;
162 client.OnParcelDwellRequest += ClientOnParcelDwellRequest; 171 client.OnParcelDwellRequest += ClientOnParcelDwellRequest;
163 client.OnParcelDeedToGroup += ClientOnParcelDeedToGroup; 172 client.OnParcelDeedToGroup += ClientOnParcelDeedToGroup;
164 client.OnParcelGodMark += ClientOnParcelGodMark; 173 client.OnPreAgentUpdate += ClientOnPreAgentUpdate;
165 client.OnSimWideDeletes += ClientOnSimWideDeletes;
166 client.OnParcelFreezeUser += ClientOnParcelFreezeUser;
167 client.OnParcelEjectUser += ClientOnParcelEjectUser;
168 174
169 EntityBase presenceEntity; 175 EntityBase presenceEntity;
170 if (m_scene.Entities.TryGetValue(client.AgentId, out presenceEntity) && presenceEntity is ScenePresence) 176 if (m_scene.Entities.TryGetValue(client.AgentId, out presenceEntity) && presenceEntity is ScenePresence)
@@ -174,6 +180,40 @@ namespace OpenSim.Region.CoreModules.World.Land
174 } 180 }
175 } 181 }
176 182
183 void ClientOnPreAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
184 {
185 //If we are forcing a position for them to go
186 if (forcedPosition != null)
187 {
188 ScenePresence clientAvatar = m_scene.GetScenePresence(remoteClient.AgentId);
189
190 //Putting the user into flying, both keeps the avatar in fligth when it bumps into something and stopped from going another direction AND
191 //When the avatar walks into a ban line on the ground, it prevents getting stuck
192 agentData.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
193
194
195 //Make sure we stop if they get about to the right place to prevent yoyo and prevents getting stuck on banlines
196 if (Vector3.Distance(clientAvatar.AbsolutePosition, forcedPosition.Value) < .2)
197 {
198 Debug.WriteLine(string.Format("Stopping force position because {0} is close enough to position {1}", forcedPosition.Value, clientAvatar.AbsolutePosition));
199 forcedPosition = null;
200 }
201 //if we are far away, teleport
202 else if (Vector3.Distance(clientAvatar.AbsolutePosition, forcedPosition.Value) > 3)
203 {
204 Debug.WriteLine(string.Format("Teleporting out because {0} is too far from avatar position {1}", forcedPosition.Value, clientAvatar.AbsolutePosition));
205 clientAvatar.Teleport(forcedPosition.Value);
206 forcedPosition = null;
207 }
208 else
209 {
210 //Forces them toward the forced position we want if they aren't there yet
211 agentData.UseClientAgentPosition = true;
212 agentData.ClientAgentPosition = forcedPosition.Value;
213 }
214 }
215 }
216
177 217
178 public void PostInitialise() 218 public void PostInitialise()
179 { 219 {
@@ -239,10 +279,7 @@ namespace OpenSim.Region.CoreModules.World.Land
239 ILandObject fullSimParcel = new LandObject(UUID.Zero, false, m_scene); 279 ILandObject fullSimParcel = new LandObject(UUID.Zero, false, m_scene);
240 280
241 fullSimParcel.SetLandBitmap(fullSimParcel.GetSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); 281 fullSimParcel.SetLandBitmap(fullSimParcel.GetSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize));
242 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 282 fullSimParcel.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
243 fullSimParcel.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
244 else
245 fullSimParcel.LandData.OwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
246 fullSimParcel.LandData.ClaimDate = Util.UnixTimeSinceEpoch(); 283 fullSimParcel.LandData.ClaimDate = Util.UnixTimeSinceEpoch();
247 AddLandObject(fullSimParcel); 284 AddLandObject(fullSimParcel);
248 } 285 }
@@ -276,106 +313,38 @@ namespace OpenSim.Region.CoreModules.World.Land
276 return parcelsNear; 313 return parcelsNear;
277 } 314 }
278 315
279 316 public void SendYouAreBannedNotice(ScenePresence avatar)
280 public void MoveUserOutOfParcel(ScenePresence avatar)
281 { 317 {
282 if (avatar.GodLevel == 0) 318 if (AllowedForcefulBans)
283 { 319 {
284 ILandObject land = m_scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 320 avatar.ControllingClient.SendAlertMessage(
285 List<ILandObject> parcelsNear = new List<ILandObject>(); 321 "You are not allowed on this parcel because you are banned. Please go away.");
322 }
323 else
324 {
325 avatar.ControllingClient.SendAlertMessage(
326 "You are not allowed on this parcel because you are banned; however, the grid administrator has disabled ban lines globally. Please obey the land owner's requests or you can be banned from the entire sim!");
327 }
328 }
286 329
287 for (int x = -2; x <= 2; x += 2) 330
288 { 331
289 ILandObject check = GetLandObject(avatar.AbsolutePosition.X + x, avatar.AbsolutePosition.Y); 332 private void ForceAvatarToPosition(ScenePresence avatar, Vector3? position)
290 if (check != null) 333 {
291 { 334 if (m_scene.Permissions.IsGod(avatar.UUID)) return;
292 if (check.IsEitherBannedOrRestricted(avatar.UUID) != true) 335 if (position.HasValue)
293 { 336 {
294 Vector3 target = new Vector3(avatar.AbsolutePosition.X + x, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); 337 forcedPosition = position;
295 avatar.TeleportWithMomentum(target);
296 return;
297 }
298 }
299 }
300 for (int y = -2; y <= 2; y += 2)
301 {
302 ILandObject check = GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y + y);
303 if (check != null)
304 {
305 if (check.IsEitherBannedOrRestricted(avatar.UUID) != true)
306 {
307 Vector3 target = new Vector3(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y + y, avatar.AbsolutePosition.Z);
308 avatar.TeleportWithMomentum(target);
309 return;
310 }
311 }
312 }
313 List<ILandObject> allParcels = new List<ILandObject>();
314 allParcels = AllParcels();
315 if (allParcels.Count != 1)
316 {
317 foreach (ILandObject parcel in allParcels)
318 {
319 if (parcel.IsEitherBannedOrRestricted(avatar.UUID) != true)
320 {
321 Vector3 temptarget = parcel.LandData.UserLocation;
322 if (parcel.ContainsPoint((int)parcel.LandData.UserLocation.X, (int)parcel.LandData.UserLocation.Y))
323 {
324 avatar.TeleportWithMomentum(temptarget);
325 return;
326 }
327 else
328 {
329 for (int x = 0; x <= Constants.RegionSize / 3; x += 3)
330 {
331 for (int y = 0; y <= Constants.RegionSize / 3; y += 3)
332 {
333 if (parcel.ContainsPoint(x, y))
334 {
335 temptarget = new Vector3(x, y, avatar.AbsolutePosition.Z);
336 avatar.TeleportWithMomentum(temptarget);
337 return;
338 }
339 }
340 }
341 }
342 }
343 }
344 }
345 //Move to region side
346 if (avatar.AbsolutePosition.X > avatar.AbsolutePosition.Y)
347 {
348 if (avatar.AbsolutePosition.X > .5 * Constants.RegionSize)
349 {
350 Vector3 target = new Vector3(Constants.RegionSize, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); ;
351 avatar.TeleportWithMomentum(target);
352 return;
353 }
354 else
355 {
356 Vector3 target = new Vector3(0, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); ;
357 avatar.TeleportWithMomentum(target);
358 return;
359 }
360 }
361 else
362 {
363 if (avatar.AbsolutePosition.Y > .5 * Constants.RegionSize)
364 {
365 Vector3 target = new Vector3(avatar.AbsolutePosition.X, Constants.RegionSize, avatar.AbsolutePosition.Z); ;
366 avatar.TeleportWithMomentum(target);
367 return;
368 }
369 else
370 {
371 Vector3 target = new Vector3(avatar.AbsolutePosition.X, 0, avatar.AbsolutePosition.Z); ;
372 avatar.TeleportWithMomentum(target);
373 return;
374 }
375 }
376 } 338 }
377 } 339 }
378 340
341 public void SendYouAreRestrictedNotice(ScenePresence avatar)
342 {
343 avatar.ControllingClient.SendAlertMessage(
344 "You are not allowed on this parcel because the land owner has restricted access.");
345
346 }
347
379 public void EventManagerOnAvatarEnteringNewParcel(ScenePresence avatar, int localLandID, UUID regionID) 348 public void EventManagerOnAvatarEnteringNewParcel(ScenePresence avatar, int localLandID, UUID regionID)
380 { 349 {
381 if (m_scene.RegionInfo.RegionID == regionID) 350 if (m_scene.RegionInfo.RegionID == regionID)
@@ -392,7 +361,17 @@ namespace OpenSim.Region.CoreModules.World.Land
392 { 361 {
393 if (parcelAvatarIsEntering.IsEitherBannedOrRestricted(avatar.UUID)) 362 if (parcelAvatarIsEntering.IsEitherBannedOrRestricted(avatar.UUID))
394 { 363 {
395 MoveUserOutOfParcel(avatar); 364 SendYouAreBannedNotice(avatar);
365 ForceAvatarToPosition(avatar, m_scene.GetNearestAllowedPosition(avatar));
366 }
367 else if (parcelAvatarIsEntering.IsRestrictedFromLand(avatar.UUID))
368 {
369 SendYouAreRestrictedNotice(avatar);
370 ForceAvatarToPosition(avatar, m_scene.GetNearestAllowedPosition(avatar));
371 }
372 else
373 {
374 avatar.sentMessageAboutRestrictedParcelFlyingDown = true;
396 } 375 }
397 } 376 }
398 else 377 else
@@ -403,49 +382,27 @@ namespace OpenSim.Region.CoreModules.World.Land
403 } 382 }
404 } 383 }
405 384
406 public void SendOutNearestBanLine(ScenePresence avatar) 385 public void SendOutNearestBanLine(IClientAPI client)
407 { 386 {
408 ILandObject checkBan = null; 387 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
409 for (int x = -2; x <= 2; x += 2) 388 if (sp == null || sp.IsChildAgent)
389 return;
390
391 List<ILandObject> checkLandParcels = ParcelsNearPoint(sp.AbsolutePosition);
392 foreach (ILandObject checkBan in checkLandParcels)
410 { 393 {
411 checkBan = GetLandObject(avatar.AbsolutePosition.X + x, avatar.AbsolutePosition.Y); 394 if (checkBan.IsBannedFromLand(client.AgentId))
412 if (checkBan != null)
413 { 395 {
414 if (avatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT) 396 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionBanned, false, (int)ParcelResult.Single, client);
415 { 397 return; //Only send one
416 if (checkBan.IsRestrictedFromLand(avatar.ControllingClient.AgentId))
417 {
418 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionNotOnAccessList, true, (int)ParcelResult.Multiple, avatar.ControllingClient);
419 return;
420 }
421 if (checkBan.IsBannedFromLand(avatar.ControllingClient.AgentId))
422 {
423 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionBanned, true, (int)ParcelResult.Multiple, avatar.ControllingClient);
424 return;
425 }
426 }
427 } 398 }
428 } 399 if (checkBan.IsRestrictedFromLand(client.AgentId))
429 for (int y = -2; y <= 2; y += 2)
430 {
431 checkBan = GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y + y);
432 if (checkBan != null)
433 { 400 {
434 if (avatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT) 401 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionNotOnAccessList, false, (int)ParcelResult.Single, client);
435 { 402 return; //Only send one
436 if (checkBan.IsRestrictedFromLand(avatar.ControllingClient.AgentId))
437 {
438 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionNotOnAccessList, true, (int)ParcelResult.Multiple, avatar.ControllingClient);
439 return;
440 }
441 if (checkBan.IsBannedFromLand(avatar.ControllingClient.AgentId))
442 {
443 checkBan.SendLandProperties((int)ParcelPropertiesStatus.CollisionBanned, true, (int)ParcelResult.Multiple, avatar.ControllingClient);
444 return;
445 }
446 }
447 } 403 }
448 } 404 }
405 return;
449 } 406 }
450 407
451 public void SendLandUpdate(ScenePresence avatar, bool force) 408 public void SendLandUpdate(ScenePresence avatar, bool force)
@@ -490,14 +447,44 @@ namespace OpenSim.Region.CoreModules.World.Land
490 if (clientAvatar != null) 447 if (clientAvatar != null)
491 { 448 {
492 SendLandUpdate(clientAvatar); 449 SendLandUpdate(clientAvatar);
493 SendOutNearestBanLine(clientAvatar); 450 SendOutNearestBanLine(remote_client);
494 ILandObject parcel = GetLandObject(clientAvatar.AbsolutePosition.X, clientAvatar.AbsolutePosition.Y); 451 ILandObject parcel = GetLandObject(clientAvatar.AbsolutePosition.X, clientAvatar.AbsolutePosition.Y);
495 if (parcel != null) 452 if (parcel != null)
496 { 453 {
497 if (clientAvatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT && 454 if (clientAvatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT &&
455 clientAvatar.sentMessageAboutRestrictedParcelFlyingDown)
456 {
457 EventManagerOnAvatarEnteringNewParcel(clientAvatar, parcel.LandData.LocalID,
458 m_scene.RegionInfo.RegionID);
459 //They are going under the safety line!
460 if (!parcel.IsBannedFromLand(clientAvatar.UUID))
461 {
462 clientAvatar.sentMessageAboutRestrictedParcelFlyingDown = false;
463 }
464 }
465 else if (clientAvatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT &&
498 parcel.IsBannedFromLand(clientAvatar.UUID)) 466 parcel.IsBannedFromLand(clientAvatar.UUID))
499 { 467 {
500 MoveUserOutOfParcel(clientAvatar); 468 //once we've sent the message once, keep going toward the target until we are done
469 if (forcedPosition == null)
470 {
471 SendYouAreBannedNotice(clientAvatar);
472 ForceAvatarToPosition(clientAvatar, m_scene.GetNearestAllowedPosition(clientAvatar));
473 }
474 }
475 else if (parcel.IsRestrictedFromLand(clientAvatar.UUID))
476 {
477 //once we've sent the message once, keep going toward the target until we are done
478 if (forcedPosition == null)
479 {
480 SendYouAreRestrictedNotice(clientAvatar);
481 ForceAvatarToPosition(clientAvatar, m_scene.GetNearestAllowedPosition(clientAvatar));
482 }
483 }
484 else
485 {
486 //when we are finally in a safe place, lets release the forced position lock
487 forcedPosition = null;
501 } 488 }
502 } 489 }
503 } 490 }
@@ -509,7 +496,7 @@ namespace OpenSim.Region.CoreModules.World.Land
509 ILandObject over = GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 496 ILandObject over = GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
510 if (over != null) 497 if (over != null)
511 { 498 {
512 if (!over.IsBannedFromLand(avatar.UUID) || avatar.AbsolutePosition.Z >= LandChannel.BAN_LINE_SAFETY_HIEGHT) 499 if (!over.IsRestrictedFromLand(avatar.UUID) && (!over.IsBannedFromLand(avatar.UUID) || avatar.AbsolutePosition.Z >= LandChannel.BAN_LINE_SAFETY_HIEGHT))
513 { 500 {
514 avatar.lastKnownAllowedPosition = 501 avatar.lastKnownAllowedPosition =
515 new Vector3(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); 502 new Vector3(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
@@ -545,21 +532,9 @@ namespace OpenSim.Region.CoreModules.World.Land
545 532
546 if (land != null) 533 if (land != null)
547 { 534 {
548 if (m_scene.Permissions.CanEditParcel(agentID, land)) 535 if (agentID == land.LandData.OwnerID)
549 { 536 {
550 land.UpdateAccessList(flags, entries, remote_client); 537 land.UpdateAccessList(flags, entries, remote_client);
551 List<ScenePresence> presences = ((Scene)remote_client.Scene).GetAvatars();
552 foreach (ScenePresence presence in presences)
553 {
554 land = GetLandObject(presence.AbsolutePosition.X, presence.AbsolutePosition.Y);
555 if (land != null)
556 {
557 if (land.IsEitherBannedOrRestricted(presence.UUID))
558 {
559 MoveUserOutOfParcel(presence);
560 }
561 }
562 }
563 } 538 }
564 } 539 }
565 else 540 else
@@ -1129,25 +1104,7 @@ namespace OpenSim.Region.CoreModules.World.Land
1129 m_landList.TryGetValue(localID, out land); 1104 m_landList.TryGetValue(localID, out land);
1130 } 1105 }
1131 1106
1132 if (land != null) 1107 if (land != null) land.UpdateLandProperties(args, remote_client);
1133 {
1134 land.UpdateLandProperties(args, remote_client);
1135 if ((args.ParcelFlags & (uint)(ParcelFlags.UseBanList | ParcelFlags.UseAccessList | ParcelFlags.UseAccessGroup | ParcelFlags.UsePassList)) != 0)
1136 {
1137 List<ScenePresence> presences = ((Scene)remote_client.Scene).GetAvatars();
1138 foreach (ScenePresence presence in presences)
1139 {
1140 land = GetLandObject(presence.AbsolutePosition.X, presence.AbsolutePosition.Y);
1141 if (land != null)
1142 {
1143 if (land.IsEitherBannedOrRestricted(presence.UUID))
1144 {
1145 MoveUserOutOfParcel(presence);
1146 }
1147 }
1148 }
1149 }
1150 }
1151 } 1108 }
1152 1109
1153 public void ClientOnParcelDivideRequest(int west, int south, int east, int north, IClientAPI remote_client) 1110 public void ClientOnParcelDivideRequest(int west, int south, int east, int north, IClientAPI remote_client)
@@ -1199,6 +1156,7 @@ namespace OpenSim.Region.CoreModules.World.Land
1199 land.LandData.OwnerID = ownerID; 1156 land.LandData.OwnerID = ownerID;
1200 land.LandData.GroupID = UUID.Zero; 1157 land.LandData.GroupID = UUID.Zero;
1201 land.LandData.IsGroupOwned = false; 1158 land.LandData.IsGroupOwned = false;
1159 land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory);
1202 1160
1203 m_scene.ForEachClient(SendParcelOverlay); 1161 m_scene.ForEachClient(SendParcelOverlay);
1204 land.SendLandUpdateToClient(true, remote_client); 1162 land.SendLandUpdateToClient(true, remote_client);
@@ -1218,12 +1176,10 @@ namespace OpenSim.Region.CoreModules.World.Land
1218 { 1176 {
1219 if (m_scene.Permissions.CanAbandonParcel(remote_client.AgentId, land)) 1177 if (m_scene.Permissions.CanAbandonParcel(remote_client.AgentId, land))
1220 { 1178 {
1221 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 1179 land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
1222 land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
1223 else
1224 land.LandData.OwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
1225 land.LandData.GroupID = UUID.Zero; 1180 land.LandData.GroupID = UUID.Zero;
1226 land.LandData.IsGroupOwned = false; 1181 land.LandData.IsGroupOwned = false;
1182 land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory);
1227 m_scene.ForEachClient(SendParcelOverlay); 1183 m_scene.ForEachClient(SendParcelOverlay);
1228 land.SendLandUpdateToClient(true, remote_client); 1184 land.SendLandUpdateToClient(true, remote_client);
1229 } 1185 }
@@ -1242,13 +1198,14 @@ namespace OpenSim.Region.CoreModules.World.Land
1242 { 1198 {
1243 if (m_scene.Permissions.CanReclaimParcel(remote_client.AgentId, land)) 1199 if (m_scene.Permissions.CanReclaimParcel(remote_client.AgentId, land))
1244 { 1200 {
1245 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 1201 land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
1246 land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
1247 else
1248 land.LandData.OwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
1249 land.LandData.ClaimDate = Util.UnixTimeSinceEpoch(); 1202 land.LandData.ClaimDate = Util.UnixTimeSinceEpoch();
1250 land.LandData.GroupID = UUID.Zero; 1203 land.LandData.GroupID = UUID.Zero;
1251 land.LandData.IsGroupOwned = false; 1204 land.LandData.IsGroupOwned = false;
1205 land.LandData.SalePrice = 0;
1206 land.LandData.AuthBuyerID = UUID.Zero;
1207 land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory);
1208
1252 m_scene.ForEachClient(SendParcelOverlay); 1209 m_scene.ForEachClient(SendParcelOverlay);
1253 land.SendLandUpdateToClient(true, remote_client); 1210 land.SendLandUpdateToClient(true, remote_client);
1254 } 1211 }
@@ -1565,6 +1522,7 @@ namespace OpenSim.Region.CoreModules.World.Land
1565 1522
1566 UpdateLandObject(localID, land.LandData); 1523 UpdateLandObject(localID, land.LandData);
1567 } 1524 }
1525
1568 public void ClientOnParcelGodMark(IClientAPI client, UUID god, int landID) 1526 public void ClientOnParcelGodMark(IClientAPI client, UUID god, int landID)
1569 { 1527 {
1570 ILandObject land = null; 1528 ILandObject land = null;
@@ -1580,10 +1538,11 @@ namespace OpenSim.Region.CoreModules.World.Land
1580 land.LandData.Name = DefaultGodParcelName; 1538 land.LandData.Name = DefaultGodParcelName;
1581 land.SendLandUpdateToAvatarsOverMe(); 1539 land.SendLandUpdateToAvatarsOverMe();
1582 } 1540 }
1541
1583 private void ClientOnSimWideDeletes(IClientAPI client, UUID agentID, int flags, UUID targetID) 1542 private void ClientOnSimWideDeletes(IClientAPI client, UUID agentID, int flags, UUID targetID)
1584 { 1543 {
1585 ScenePresence SP; 1544 ScenePresence SP;
1586 ((Scene)client.Scene).TryGetAvatar(client.AgentId, out SP); 1545 ((Scene)client.Scene).TryGetScenePresence(client.AgentId, out SP);
1587 List<SceneObjectGroup> returns = new List<SceneObjectGroup>(); 1546 List<SceneObjectGroup> returns = new List<SceneObjectGroup>();
1588 if (SP.GodLevel != 0) 1547 if (SP.GodLevel != 0)
1589 { 1548 {
@@ -1648,9 +1607,9 @@ namespace OpenSim.Region.CoreModules.World.Land
1648 public void ClientOnParcelFreezeUser(IClientAPI client, UUID parcelowner, uint flags, UUID target) 1607 public void ClientOnParcelFreezeUser(IClientAPI client, UUID parcelowner, uint flags, UUID target)
1649 { 1608 {
1650 ScenePresence targetAvatar = null; 1609 ScenePresence targetAvatar = null;
1651 ((Scene)client.Scene).TryGetAvatar(target, out targetAvatar); 1610 ((Scene)client.Scene).TryGetScenePresence(target, out targetAvatar);
1652 ScenePresence parcelManager = null; 1611 ScenePresence parcelManager = null;
1653 ((Scene)client.Scene).TryGetAvatar(client.AgentId, out parcelManager); 1612 ((Scene)client.Scene).TryGetScenePresence(client.AgentId, out parcelManager);
1654 System.Threading.Timer Timer; 1613 System.Threading.Timer Timer;
1655 1614
1656 if (targetAvatar.GodLevel == 0) 1615 if (targetAvatar.GodLevel == 0)
@@ -1692,9 +1651,9 @@ namespace OpenSim.Region.CoreModules.World.Land
1692 public void ClientOnParcelEjectUser(IClientAPI client, UUID parcelowner, uint flags, UUID target) 1651 public void ClientOnParcelEjectUser(IClientAPI client, UUID parcelowner, uint flags, UUID target)
1693 { 1652 {
1694 ScenePresence targetAvatar = null; 1653 ScenePresence targetAvatar = null;
1695 ((Scene)client.Scene).TryGetAvatar(target, out targetAvatar); 1654 ((Scene)client.Scene).TryGetScenePresence(target, out targetAvatar);
1696 ScenePresence parcelManager = null; 1655 ScenePresence parcelManager = null;
1697 ((Scene)client.Scene).TryGetAvatar(client.AgentId, out parcelManager); 1656 ((Scene)client.Scene).TryGetScenePresence(client.AgentId, out parcelManager);
1698 //Just eject 1657 //Just eject
1699 if (flags == 0) 1658 if (flags == 0)
1700 { 1659 {
diff --git a/OpenSim/Region/CoreModules/World/Land/LandObject.cs b/OpenSim/Region/CoreModules/World/Land/LandObject.cs
index b8c35f7..3945142 100644
--- a/OpenSim/Region/CoreModules/World/Land/LandObject.cs
+++ b/OpenSim/Region/CoreModules/World/Land/LandObject.cs
@@ -104,7 +104,7 @@ namespace OpenSim.Region.CoreModules.World.Land
104 /// <returns>Returns true if the piece of land contains the specified point</returns> 104 /// <returns>Returns true if the piece of land contains the specified point</returns>
105 public bool ContainsPoint(int x, int y) 105 public bool ContainsPoint(int x, int y)
106 { 106 {
107 if (x >= 0 && y >= 0 && x <= Constants.RegionSize && x <= Constants.RegionSize) 107 if (x >= 0 && y >= 0 && x <= Constants.RegionSize && y <= Constants.RegionSize)
108 { 108 {
109 return (LandBitmap[x / 4, y / 4] == true); 109 return (LandBitmap[x / 4, y / 4] == true);
110 } 110 }
@@ -247,7 +247,7 @@ namespace OpenSim.Region.CoreModules.World.Land
247 newData.ClaimPrice = claimprice; 247 newData.ClaimPrice = claimprice;
248 newData.SalePrice = 0; 248 newData.SalePrice = 0;
249 newData.AuthBuyerID = UUID.Zero; 249 newData.AuthBuyerID = UUID.Zero;
250 newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects); 250 newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory);
251 m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); 251 m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
252 252
253 SendLandUpdateToAvatarsOverMe(true); 253 SendLandUpdateToAvatarsOverMe(true);
@@ -260,6 +260,9 @@ namespace OpenSim.Region.CoreModules.World.Land
260 newData.GroupID = groupID; 260 newData.GroupID = groupID;
261 newData.IsGroupOwned = true; 261 newData.IsGroupOwned = true;
262 262
263 // Reset show in directory flag on deed
264 newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory);
265
263 m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); 266 m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
264 267
265 SendLandUpdateToAvatarsOverMe(true); 268 SendLandUpdateToAvatarsOverMe(true);
@@ -267,7 +270,11 @@ namespace OpenSim.Region.CoreModules.World.Land
267 270
268 public bool IsEitherBannedOrRestricted(UUID avatar) 271 public bool IsEitherBannedOrRestricted(UUID avatar)
269 { 272 {
270 if (IsRestrictedFromLand(avatar) || IsBannedFromLand(avatar)) 273 if (IsBannedFromLand(avatar))
274 {
275 return true;
276 }
277 else if (IsRestrictedFromLand(avatar))
271 { 278 {
272 return true; 279 return true;
273 } 280 }
@@ -276,31 +283,17 @@ namespace OpenSim.Region.CoreModules.World.Land
276 283
277 public bool IsBannedFromLand(UUID avatar) 284 public bool IsBannedFromLand(UUID avatar)
278 { 285 {
279 ScenePresence SP = m_scene.GetScenePresence(avatar); 286 if ((LandData.Flags & (uint) ParcelFlags.UseBanList) > 0)
280 if ((LandData.Flags & (uint)ParcelFlags.UseBanList) > 0)
281 { 287 {
282 ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); 288 ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
283 entry.AgentID = avatar; 289 entry.AgentID = avatar;
284 entry.Flags = AccessList.Ban; 290 entry.Flags = AccessList.Ban;
285 entry.Time = new DateTime(); 291 entry.Time = new DateTime();
286 if (LandData.ParcelAccessList.Contains(entry)) 292 //See if they are on the list, but make sure the owner isn't banned
293 if (LandData.ParcelAccessList.Contains(entry) && LandData.OwnerID != avatar)
287 { 294 {
288 if ((LandData.Flags & (uint)ParcelFlags.UseAccessGroup) > 0) 295 //They are banned, so lets send them a notice about this parcel
289 { 296 return true;
290 if (LandData.GroupID == SP.ControllingClient.ActiveGroupId)
291 {
292 return false;
293 }
294 else
295 {
296 //They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel
297 return true;
298 }
299 }
300 else
301 {
302 return true;
303 }
304 } 297 }
305 } 298 }
306 return false; 299 return false;
@@ -308,31 +301,18 @@ namespace OpenSim.Region.CoreModules.World.Land
308 301
309 public bool IsRestrictedFromLand(UUID avatar) 302 public bool IsRestrictedFromLand(UUID avatar)
310 { 303 {
311 ScenePresence SP = m_scene.GetScenePresence(avatar); 304 if ((LandData.Flags & (uint) ParcelFlags.UseAccessList) > 0)
312 if ((LandData.Flags & (uint)ParcelFlags.UseAccessList) > 0)
313 { 305 {
314 ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); 306 ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
315 entry.AgentID = avatar; 307 entry.AgentID = avatar;
316 entry.Flags = AccessList.Access; 308 entry.Flags = AccessList.Access;
317 entry.Time = new DateTime(); 309 entry.Time = new DateTime();
318 if (!LandData.ParcelAccessList.Contains(entry)) 310
311 //If they are not on the access list and are not the owner
312 if (!LandData.ParcelAccessList.Contains(entry) && LandData.OwnerID != avatar)
319 { 313 {
320 if ((LandData.Flags & (uint)ParcelFlags.UseAccessGroup) > 0) 314 //They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel
321 { 315 return true;
322 if (LandData.GroupID == SP.ControllingClient.ActiveGroupId)
323 {
324 return false;
325 }
326 else
327 {
328 //They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel
329 return true;
330 }
331 }
332 else
333 {
334 return true;
335 }
336 } 316 }
337 } 317 }
338 return false; 318 return false;
@@ -355,36 +335,38 @@ namespace OpenSim.Region.CoreModules.World.Land
355 335
356 public void SendLandUpdateToAvatarsOverMe(bool snap_selection) 336 public void SendLandUpdateToAvatarsOverMe(bool snap_selection)
357 { 337 {
358 List<ScenePresence> avatars = m_scene.GetAvatars(); 338 m_scene.ForEachScenePresence(delegate(ScenePresence avatar)
359 ILandObject over = null;
360 for (int i = 0; i < avatars.Count; i++)
361 { 339 {
340 if (avatar.IsChildAgent)
341 return;
342
343 ILandObject over = null;
362 try 344 try
363 { 345 {
364 over = 346 over =
365 m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.X), 0, ((int)Constants.RegionSize - 1)), 347 m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.X), 0, ((int)Constants.RegionSize - 1)),
366 Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.Y), 0, ((int)Constants.RegionSize - 1))); 348 Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.Y), 0, ((int)Constants.RegionSize - 1)));
367 } 349 }
368 catch (Exception) 350 catch (Exception)
369 { 351 {
370 m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatars[i].AbsolutePosition.X) + " y: " + 352 m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatar.AbsolutePosition.X) + " y: " +
371 Math.Round(avatars[i].AbsolutePosition.Y)); 353 Math.Round(avatar.AbsolutePosition.Y));
372 } 354 }
373 355
374 if (over != null) 356 if (over != null)
375 { 357 {
376 if (over.LandData.LocalID == LandData.LocalID) 358 if (over.LandData.LocalID == LandData.LocalID)
377 { 359 {
378 if (((over.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0) && 360 if (((over.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0) &&
379 m_scene.RegionInfo.RegionSettings.AllowDamage) 361 m_scene.RegionInfo.RegionSettings.AllowDamage)
380 avatars[i].Invulnerable = false; 362 avatar.Invulnerable = false;
381 else 363 else
382 avatars[i].Invulnerable = true; 364 avatar.Invulnerable = true;
383 365
384 SendLandUpdateToClient(snap_selection, avatars[i].ControllingClient); 366 SendLandUpdateToClient(snap_selection, avatar.ControllingClient);
385 } 367 }
386 } 368 }
387 } 369 });
388 } 370 }
389 371
390 #endregion 372 #endregion
diff --git a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
index 212cfee..69b247c 100644
--- a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
+++ b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
@@ -32,7 +32,7 @@ using log4net;
32using Nini.Config; 32using Nini.Config;
33using OpenMetaverse; 33using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.Framework.Scenes; 37using OpenSim.Region.Framework.Scenes;
38using OpenSim.Services.Interfaces; 38using OpenSim.Services.Interfaces;
@@ -95,6 +95,23 @@ namespace OpenSim.Region.CoreModules.World.Permissions
95 95
96 protected Scene m_scene; 96 protected Scene m_scene;
97 97
98 private InventoryFolderImpl m_libraryRootFolder;
99 protected InventoryFolderImpl LibraryRootFolder
100 {
101 get
102 {
103 if (m_libraryRootFolder != null)
104 return m_libraryRootFolder;
105
106 ILibraryService lib = m_scene.RequestModuleInterface<ILibraryService>();
107 if (lib != null)
108 {
109 m_libraryRootFolder = lib.LibraryRootFolder;
110 }
111 return m_libraryRootFolder;
112 }
113 }
114
98 #region Constants 115 #region Constants
99 // These are here for testing. They will be taken out 116 // These are here for testing. They will be taken out
100 117
@@ -145,7 +162,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
145 private Dictionary<string, bool> GrantVB = new Dictionary<string, bool>(); 162 private Dictionary<string, bool> GrantVB = new Dictionary<string, bool>();
146 private Dictionary<string, bool> GrantJS = new Dictionary<string, bool>(); 163 private Dictionary<string, bool> GrantJS = new Dictionary<string, bool>();
147 private Dictionary<string, bool> GrantYP = new Dictionary<string, bool>(); 164 private Dictionary<string, bool> GrantYP = new Dictionary<string, bool>();
148 private IFriendsModule m_friendsModule = null; 165 private IFriendsModule m_friendsModule;
166 private IGroupsModule m_groupsModule;
149 167
150 #endregion 168 #endregion
151 169
@@ -369,9 +387,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
369 m_friendsModule = m_scene.RequestModuleInterface<IFriendsModule>(); 387 m_friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
370 388
371 if (m_friendsModule == null) 389 if (m_friendsModule == null)
372 m_log.Error("[PERMISSIONS]: Friends module not found, friend permissions will not work"); 390 m_log.Warn("[PERMISSIONS]: Friends module not found, friend permissions will not work");
373 else 391
374 m_log.Info("[PERMISSIONS]: Friends module found, friend permissions enabled"); 392 m_groupsModule = m_scene.RequestModuleInterface<IGroupsModule>();
393
394 if (m_groupsModule == null)
395 m_log.Warn("[PERMISSIONS]: Groups module not found, group permissions will not work");
375 } 396 }
376 397
377 public void Close() 398 public void Close()
@@ -406,14 +427,17 @@ namespace OpenSim.Region.CoreModules.World.Permissions
406 // with the powers requested (powers = 0 for no powers check) 427 // with the powers requested (powers = 0 for no powers check)
407 protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers) 428 protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers)
408 { 429 {
409 ScenePresence sp = m_scene.GetScenePresence(userID); 430 if (null == m_groupsModule)
410 if (sp != null) 431 return false;
411 { 432
412 IClientAPI client = sp.ControllingClient; 433 GroupMembershipData gmd = m_groupsModule.GetMembershipData(groupID, userID);
413 434
414 return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) && 435 if (gmd != null)
415 ((powers == 0) || ((client.ActiveGroupPowers & powers) == powers))); 436 {
437 if (((gmd.GroupPowers != 0) && powers == 0) || (gmd.GroupPowers & powers) == powers)
438 return true;
416 } 439 }
440
417 return false; 441 return false;
418 } 442 }
419 443
@@ -461,12 +485,6 @@ namespace OpenSim.Region.CoreModules.World.Permissions
461 { 485 {
462 if (user == UUID.Zero) return false; 486 if (user == UUID.Zero) return false;
463 487
464 if (m_scene.RegionInfo.MasterAvatarAssignedUUID != UUID.Zero)
465 {
466 if (m_RegionOwnerIsGod && (m_scene.RegionInfo.MasterAvatarAssignedUUID == user))
467 return true;
468 }
469
470 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) 488 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
471 { 489 {
472 if (m_scene.RegionInfo.EstateSettings.EstateOwner == user && m_RegionOwnerIsGod) 490 if (m_scene.RegionInfo.EstateSettings.EstateOwner == user && m_RegionOwnerIsGod)
@@ -478,10 +496,18 @@ namespace OpenSim.Region.CoreModules.World.Permissions
478 496
479 if (m_allowGridGods) 497 if (m_allowGridGods)
480 { 498 {
481 CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(user); 499 ScenePresence sp = m_scene.GetScenePresence(user);
482 if (profile != null && profile.UserProfile != null) 500 if (sp != null)
501 {
502 if (sp.UserLevel >= 200)
503 return true;
504 return false;
505 }
506
507 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, user);
508 if (account != null)
483 { 509 {
484 if (profile.UserProfile.GodLevel >= 200) 510 if (account.UserLevel >= 200)
485 return true; 511 return true;
486 } 512 }
487 } 513 }
@@ -498,13 +524,10 @@ namespace OpenSim.Region.CoreModules.World.Permissions
498 if (m_friendsModule == null) 524 if (m_friendsModule == null)
499 return false; 525 return false;
500 526
501 List<FriendListItem> profile = m_friendsModule.GetUserFriends(user); 527 uint friendPerms = m_friendsModule.GetFriendPerms(user, objectOwner);
528 if ((friendPerms & (uint)FriendRights.CanModifyObjects) != 0)
529 return true;
502 530
503 foreach (FriendListItem item in profile)
504 {
505 if (item.Friend == objectOwner && (item.FriendPerms & (uint)FriendRights.CanModifyObjects) != 0)
506 return true;
507 }
508 return false; 531 return false;
509 } 532 }
510 533
@@ -600,16 +623,17 @@ namespace OpenSim.Region.CoreModules.World.Permissions
600 if (IsFriendWithPerms(user, objectOwner)) 623 if (IsFriendWithPerms(user, objectOwner))
601 return objectOwnerMask; 624 return objectOwnerMask;
602 625
603 // Estate users should be able to edit anything in the sim 626 // Estate users should be able to edit anything in the sim if RegionOwnerIsGod is set
604 if (IsEstateManager(user) && m_RegionOwnerIsGod && (!IsAdministrator(objectOwner)) || objectOwner == user) 627 if (m_RegionOwnerIsGod && IsEstateManager(user) && !IsAdministrator(objectOwner))
605 return objectOwnerMask; 628 return objectOwnerMask;
606 629
607 // Admin should be able to edit anything in the sim (including admin objects) 630 // Admin should be able to edit anything in the sim (including admin objects)
608 if (IsAdministrator(user)) 631 if (IsAdministrator(user))
609 return objectOwnerMask; 632 return objectOwnerMask;
610 633
611 // Users should be able to edit what is over their land. 634 // Users should be able to edit what is over their land.
612 ILandObject parcel = m_scene.LandChannel.GetLandObject(task.AbsolutePosition.X, task.AbsolutePosition.Y); 635 Vector3 taskPos = task.AbsolutePosition;
636 ILandObject parcel = m_scene.LandChannel.GetLandObject(taskPos.X, taskPos.Y);
613 if (parcel != null && parcel.LandData.OwnerID == user && m_ParcelOwnerIsGod) 637 if (parcel != null && parcel.LandData.OwnerID == user && m_ParcelOwnerIsGod)
614 { 638 {
615 // Admin objects should not be editable by the above 639 // Admin objects should not be editable by the above
@@ -704,8 +728,17 @@ namespace OpenSim.Region.CoreModules.World.Permissions
704 permission = false; 728 permission = false;
705 } 729 }
706 730
731// m_log.DebugFormat(
732// "[PERMISSIONS]: group.GroupID = {0}, part.GroupMask = {1}, isGroupMember = {2} for {3}",
733// group.GroupID,
734// m_scene.GetSceneObjectPart(objId).GroupMask,
735// IsGroupMember(group.GroupID, currentUser, 0),
736// currentUser);
737
707 // Group members should be able to edit group objects 738 // Group members should be able to edit group objects
708 if ((group.GroupID != UUID.Zero) && ((m_scene.GetSceneObjectPart(objId).GroupMask & (uint)PermissionMask.Modify) != 0) && IsGroupMember(group.GroupID, currentUser, 0)) 739 if ((group.GroupID != UUID.Zero)
740 && ((m_scene.GetSceneObjectPart(objId).GroupMask & (uint)PermissionMask.Modify) != 0)
741 && IsGroupMember(group.GroupID, currentUser, 0))
709 { 742 {
710 // Return immediately, so that the administrator can shares group objects 743 // Return immediately, so that the administrator can shares group objects
711 return true; 744 return true;
@@ -940,7 +973,6 @@ namespace OpenSim.Region.CoreModules.World.Permissions
940 DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name); 973 DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
941 if (m_bypassPermissions) return m_bypassPermissionsValue; 974 if (m_bypassPermissions) return m_bypassPermissionsValue;
942 975
943
944 return GenericObjectPermission(editorID, objectID, false); 976 return GenericObjectPermission(editorID, objectID, false);
945 } 977 }
946 978
@@ -1010,9 +1042,9 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1010 IInventoryService invService = m_scene.InventoryService; 1042 IInventoryService invService = m_scene.InventoryService;
1011 InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user); 1043 InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user);
1012 assetRequestItem = invService.GetItem(assetRequestItem); 1044 assetRequestItem = invService.GetItem(assetRequestItem);
1013 if (assetRequestItem == null) // Library item 1045 if (assetRequestItem == null && LibraryRootFolder != null) // Library item
1014 { 1046 {
1015 assetRequestItem = scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard); 1047 assetRequestItem = LibraryRootFolder.FindItem(notecard);
1016 1048
1017 if (assetRequestItem != null) // Implicitly readable 1049 if (assetRequestItem != null) // Implicitly readable
1018 return true; 1050 return true;
@@ -1047,7 +1079,9 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1047 1079
1048 if ((part.GroupMask & (uint)PermissionMask.Modify) == 0) 1080 if ((part.GroupMask & (uint)PermissionMask.Modify) == 0)
1049 return false; 1081 return false;
1050 } else { 1082 }
1083 else
1084 {
1051 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0) 1085 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
1052 return false; 1086 return false;
1053 } 1087 }
@@ -1063,7 +1097,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1063 return false; 1097 return false;
1064 1098
1065 if (!IsGroupMember(ti.GroupID, user, 0)) 1099 if (!IsGroupMember(ti.GroupID, user, 0))
1066 return false; 1100 return false;
1067 } 1101 }
1068 1102
1069 // Require full perms 1103 // Require full perms
@@ -1259,13 +1293,104 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1259 1293
1260 private bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene) 1294 private bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene)
1261 { 1295 {
1262 if (objects.Count == 0)
1263 return false;
1264
1265 DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name); 1296 DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
1266 if (m_bypassPermissions) return m_bypassPermissionsValue; 1297 if (m_bypassPermissions) return m_bypassPermissionsValue;
1267 1298
1268 return GenericObjectPermission(user, objects[0].UUID, false); 1299 GroupPowers powers;
1300 ILandObject l;
1301
1302 ScenePresence sp = scene.GetScenePresence(user);
1303 if (sp == null)
1304 return false;
1305
1306 IClientAPI client = sp.ControllingClient;
1307
1308 foreach (SceneObjectGroup g in new List<SceneObjectGroup>(objects))
1309 {
1310 // Any user can return their own objects at any time
1311 //
1312 if (GenericObjectPermission(user, g.UUID, false))
1313 continue;
1314
1315 // This is a short cut for efficiency. If land is non-null,
1316 // then all objects are on that parcel and we can save
1317 // ourselves the checking for each prim. Much faster.
1318 //
1319 if (land != null)
1320 {
1321 l = land;
1322 }
1323 else
1324 {
1325 Vector3 pos = g.AbsolutePosition;
1326
1327 l = scene.LandChannel.GetLandObject(pos.X, pos.Y);
1328 }
1329
1330 // If it's not over any land, then we can't do a thing
1331 if (l == null)
1332 {
1333 objects.Remove(g);
1334 continue;
1335 }
1336
1337 // If we own the land outright, then allow
1338 //
1339 if (l.LandData.OwnerID == user)
1340 continue;
1341
1342 // Group voodoo
1343 //
1344 if (l.LandData.IsGroupOwned)
1345 {
1346 powers = (GroupPowers)client.GetGroupPowers(l.LandData.GroupID);
1347 // Not a group member, or no rights at all
1348 //
1349 if (powers == (GroupPowers)0)
1350 {
1351 objects.Remove(g);
1352 continue;
1353 }
1354
1355 // Group deeded object?
1356 //
1357 if (g.OwnerID == l.LandData.GroupID &&
1358 (powers & GroupPowers.ReturnGroupOwned) == (GroupPowers)0)
1359 {
1360 objects.Remove(g);
1361 continue;
1362 }
1363
1364 // Group set object?
1365 //
1366 if (g.GroupID == l.LandData.GroupID &&
1367 (powers & GroupPowers.ReturnGroupSet) == (GroupPowers)0)
1368 {
1369 objects.Remove(g);
1370 continue;
1371 }
1372
1373 if ((powers & GroupPowers.ReturnNonGroup) == (GroupPowers)0)
1374 {
1375 objects.Remove(g);
1376 continue;
1377 }
1378
1379 // So we can remove all objects from this group land.
1380 // Fine.
1381 //
1382 continue;
1383 }
1384
1385 // By default, we can't remove
1386 //
1387 objects.Remove(g);
1388 }
1389
1390 if (objects.Count == 0)
1391 return false;
1392
1393 return true;
1269 } 1394 }
1270 1395
1271 private bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition, Scene scene) 1396 private bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition, Scene scene)
@@ -1433,9 +1558,9 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1433 IInventoryService invService = m_scene.InventoryService; 1558 IInventoryService invService = m_scene.InventoryService;
1434 InventoryItemBase assetRequestItem = new InventoryItemBase(script, user); 1559 InventoryItemBase assetRequestItem = new InventoryItemBase(script, user);
1435 assetRequestItem = invService.GetItem(assetRequestItem); 1560 assetRequestItem = invService.GetItem(assetRequestItem);
1436 if (assetRequestItem == null) // Library item 1561 if (assetRequestItem == null && LibraryRootFolder != null) // Library item
1437 { 1562 {
1438 assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(script); 1563 assetRequestItem = LibraryRootFolder.FindItem(script);
1439 1564
1440 if (assetRequestItem != null) // Implicitly readable 1565 if (assetRequestItem != null) // Implicitly readable
1441 return true; 1566 return true;
@@ -1470,14 +1595,16 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1470 if (part.OwnerID != user) 1595 if (part.OwnerID != user)
1471 { 1596 {
1472 if (part.GroupID == UUID.Zero) 1597 if (part.GroupID == UUID.Zero)
1473 return false; 1598 return false;
1474 1599
1475 if (!IsGroupMember(part.GroupID, user, 0)) 1600 if (!IsGroupMember(part.GroupID, user, 0))
1476 return false; 1601 return false;
1477 1602
1478 if ((part.GroupMask & (uint)PermissionMask.Modify) == 0) 1603 if ((part.GroupMask & (uint)PermissionMask.Modify) == 0)
1479 return false; 1604 return false;
1480 } else { 1605 }
1606 else
1607 {
1481 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0) 1608 if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
1482 return false; 1609 return false;
1483 } 1610 }
@@ -1528,9 +1655,9 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1528 IInventoryService invService = m_scene.InventoryService; 1655 IInventoryService invService = m_scene.InventoryService;
1529 InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user); 1656 InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user);
1530 assetRequestItem = invService.GetItem(assetRequestItem); 1657 assetRequestItem = invService.GetItem(assetRequestItem);
1531 if (assetRequestItem == null) // Library item 1658 if (assetRequestItem == null && LibraryRootFolder != null) // Library item
1532 { 1659 {
1533 assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard); 1660 assetRequestItem = LibraryRootFolder.FindItem(notecard);
1534 1661
1535 if (assetRequestItem != null) // Implicitly readable 1662 if (assetRequestItem != null) // Implicitly readable
1536 return true; 1663 return true;
@@ -1732,7 +1859,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
1732 return GenericObjectPermission(agentID, prim, false); 1859 return GenericObjectPermission(agentID, prim, false);
1733 } 1860 }
1734 1861
1735 private bool CanCompileScript(UUID ownerUUID, int scriptType, Scene scene) { 1862 private bool CanCompileScript(UUID ownerUUID, int scriptType, Scene scene)
1863 {
1736 //m_log.DebugFormat("check if {0} is allowed to compile {1}", ownerUUID, scriptType); 1864 //m_log.DebugFormat("check if {0} is allowed to compile {1}", ownerUUID, scriptType);
1737 switch (scriptType) { 1865 switch (scriptType) {
1738 case 0: 1866 case 0:
diff --git a/OpenSim/Region/CoreModules/World/Sound/SoundModule.cs b/OpenSim/Region/CoreModules/World/Sound/SoundModule.cs
index 1f5a4ff..a52fea4 100644
--- a/OpenSim/Region/CoreModules/World/Sound/SoundModule.cs
+++ b/OpenSim/Region/CoreModules/World/Sound/SoundModule.cs
@@ -62,40 +62,46 @@ namespace OpenSim.Region.CoreModules.World.Sound
62 public virtual void PlayAttachedSound( 62 public virtual void PlayAttachedSound(
63 UUID soundID, UUID ownerID, UUID objectID, double gain, Vector3 position, byte flags, float radius) 63 UUID soundID, UUID ownerID, UUID objectID, double gain, Vector3 position, byte flags, float radius)
64 { 64 {
65 foreach (ScenePresence p in m_scene.GetAvatars()) 65 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
66 { 66 {
67 double dis = Util.GetDistanceTo(p.AbsolutePosition, position); 67 if (sp.IsChildAgent)
68 return;
69
70 double dis = Util.GetDistanceTo(sp.AbsolutePosition, position);
68 if (dis > 100.0) // Max audio distance 71 if (dis > 100.0) // Max audio distance
69 continue; 72 return;
70 73
71 // Scale by distance 74 // Scale by distance
72 if (radius == 0) 75 if (radius == 0)
73 gain = (float)((double)gain * ((100.0 - dis) / 100.0)); 76 gain = (float)((double)gain * ((100.0 - dis) / 100.0));
74 else 77 else
75 gain = (float)((double)gain * ((radius - dis) / radius)); 78 gain = (float)((double)gain * ((radius - dis) / radius));
76 79
77 p.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID, (float)gain, flags); 80 sp.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID, (float)gain, flags);
78 } 81 });
79 } 82 }
80 83
81 public virtual void TriggerSound( 84 public virtual void TriggerSound(
82 UUID soundId, UUID ownerID, UUID objectID, UUID parentID, double gain, Vector3 position, UInt64 handle, float radius) 85 UUID soundId, UUID ownerID, UUID objectID, UUID parentID, double gain, Vector3 position, UInt64 handle, float radius)
83 { 86 {
84 foreach (ScenePresence p in m_scene.GetAvatars()) 87 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
85 { 88 {
86 double dis = Util.GetDistanceTo(p.AbsolutePosition, position); 89 if (sp.IsChildAgent)
90 return;
91
92 double dis = Util.GetDistanceTo(sp.AbsolutePosition, position);
87 if (dis > 100.0) // Max audio distance 93 if (dis > 100.0) // Max audio distance
88 continue; 94 return;
89 95
90 // Scale by distance 96 // Scale by distance
91 if (radius == 0) 97 if (radius == 0)
92 gain = (float)((double)gain * ((100.0 - dis) / 100.0)); 98 gain = (float)((double)gain * ((100.0 - dis) / 100.0));
93 else 99 else
94 gain = (float)((double)gain * ((radius - dis) / radius)); 100 gain = (float)((double)gain * ((radius - dis) / radius));
95 101
96 p.ControllingClient.SendTriggeredSound( 102 sp.ControllingClient.SendTriggeredSound(
97 soundId, ownerID, objectID, parentID, handle, position, (float)gain); 103 soundId, ownerID, objectID, parentID, handle, position, (float)gain);
98 } 104 });
99 } 105 }
100 } 106 }
101} 107}
diff --git a/OpenSim/Region/CoreModules/World/Sun/SunModule.cs b/OpenSim/Region/CoreModules/World/Sun/SunModule.cs
index 0712a7f..a6dc2ec 100644
--- a/OpenSim/Region/CoreModules/World/Sun/SunModule.cs
+++ b/OpenSim/Region/CoreModules/World/Sun/SunModule.cs
@@ -509,14 +509,13 @@ namespace OpenSim.Region.CoreModules
509 509
510 private void SunUpdateToAllClients() 510 private void SunUpdateToAllClients()
511 { 511 {
512 List<ScenePresence> avatars = m_scene.GetAvatars(); 512 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
513 foreach (ScenePresence avatar in avatars)
514 { 513 {
515 if (!avatar.IsChildAgent) 514 if (!sp.IsChildAgent)
516 { 515 {
517 SunToClient(avatar.ControllingClient); 516 SunToClient(sp.ControllingClient);
518 } 517 }
519 } 518 });
520 } 519 }
521 520
522 #region ISunModule Members 521 #region ISunModule Members
diff --git a/OpenSim/Region/CoreModules/World/Wind/WindModule.cs b/OpenSim/Region/CoreModules/World/Wind/WindModule.cs
index 3283c1f..9736b73 100644
--- a/OpenSim/Region/CoreModules/World/Wind/WindModule.cs
+++ b/OpenSim/Region/CoreModules/World/Wind/WindModule.cs
@@ -425,9 +425,7 @@ namespace OpenSim.Region.CoreModules
425 { 425 {
426 if (m_ready) 426 if (m_ready)
427 { 427 {
428 List<ScenePresence> avatars = m_scene.GetAvatars(); 428 if(m_scene.GetRootAgentCount() > 0)
429
430 if (avatars.Count > 0)
431 { 429 {
432 // Ask wind plugin to generate a LL wind array to be cached locally 430 // Ask wind plugin to generate a LL wind array to be cached locally
433 // Try not to update this too often, as it may involve array copies 431 // Try not to update this too often, as it may involve array copies
@@ -437,11 +435,11 @@ namespace OpenSim.Region.CoreModules
437 m_frameLastUpdateClientArray = m_frame; 435 m_frameLastUpdateClientArray = m_frame;
438 } 436 }
439 437
440 foreach (ScenePresence avatar in avatars) 438 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
441 { 439 {
442 if (!avatar.IsChildAgent) 440 if (!sp.IsChildAgent)
443 avatar.ControllingClient.SendWindData(windSpeeds); 441 sp.ControllingClient.SendWindData(windSpeeds);
444 } 442 });
445 } 443 }
446 } 444 }
447 } 445 }
diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs
index 285d36a..b71b5f6 100644
--- a/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs
+++ b/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs
@@ -251,13 +251,12 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
251 // if you want tree blocks on the map comment the above line and uncomment the below line 251 // if you want tree blocks on the map comment the above line and uncomment the below line
252 //mapdotspot = Color.PaleGreen; 252 //mapdotspot = Color.PaleGreen;
253 253
254 if (part.Shape.Textures == null) 254 Primitive.TextureEntry textureEntry = part.Shape.Textures;
255 continue;
256 255
257 if (part.Shape.Textures.DefaultTexture == null) 256 if (textureEntry == null || textureEntry.DefaultTexture == null)
258 continue; 257 continue;
259 258
260 Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA; 259 Color4 texcolor = textureEntry.DefaultTexture.RGBA;
261 260
262 // Not sure why some of these are null, oh well. 261 // Not sure why some of these are null, oh well.
263 262
diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs
index be46fa5..a1a4f9e 100644
--- a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs
+++ b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs
@@ -32,7 +32,6 @@ using OpenMetaverse;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Region.Framework.Interfaces; 33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes; 34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Region.Framework.Scenes.Hypergrid;
36using OpenSim.Services.Interfaces; 35using OpenSim.Services.Interfaces;
37using GridRegion = OpenSim.Services.Interfaces.GridRegion; 36using GridRegion = OpenSim.Services.Interfaces.GridRegion;
38 37
@@ -104,25 +103,6 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
104 if (info != null) regionInfos.Add(info); 103 if (info != null) regionInfos.Add(info);
105 } 104 }
106 105
107 if ((regionInfos.Count == 0) && IsHypergridOn())
108 {
109 // OK, we tried but there are no regions matching that name.
110 // Let's check quickly if this is a domain name, and if so link to it
111 if (mapName.Contains("."))
112 {
113 // It probably is a domain name. Try to link to it.
114 GridRegion regInfo;
115 Scene cScene = GetClientScene(remoteClient);
116 IHyperlinkService hyperService = cScene.RequestModuleInterface<IHyperlinkService>();
117 if (hyperService != null)
118 {
119 regInfo = hyperService.TryLinkRegion(remoteClient, mapName);
120 if (regInfo != null)
121 regionInfos.Add(regInfo);
122 }
123 }
124 }
125
126 List<MapBlockData> blocks = new List<MapBlockData>(); 106 List<MapBlockData> blocks = new List<MapBlockData>();
127 107
128 MapBlockData data; 108 MapBlockData data;
@@ -155,12 +135,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
155 data.Y = 0; 135 data.Y = 0;
156 blocks.Add(data); 136 blocks.Add(data);
157 137
158 remoteClient.SendMapBlock(blocks, 0); 138 remoteClient.SendMapBlock(blocks, 2);
159 }
160
161 private bool IsHypergridOn()
162 {
163 return (m_scene.SceneGridService is HGSceneCommunicationService);
164 } 139 }
165 140
166 private Scene GetClientScene(IClientAPI client) 141 private Scene GetClientScene(IClientAPI client)
diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
index 44a651f..2b0e83f 100644
--- a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
+++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
@@ -210,7 +210,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
210 // this is here because CAPS map requests work even beyond the 10,000 limit. 210 // this is here because CAPS map requests work even beyond the 10,000 limit.
211 ScenePresence avatarPresence = null; 211 ScenePresence avatarPresence = null;
212 212
213 m_scene.TryGetAvatar(agentID, out avatarPresence); 213 m_scene.TryGetScenePresence(agentID, out avatarPresence);
214 214
215 if (avatarPresence != null) 215 if (avatarPresence != null)
216 { 216 {
@@ -304,25 +304,11 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
304 /// <param name="AgentId">AgentID that logged out</param> 304 /// <param name="AgentId">AgentID that logged out</param>
305 private void ClientLoggedOut(UUID AgentId, Scene scene) 305 private void ClientLoggedOut(UUID AgentId, Scene scene)
306 { 306 {
307 List<ScenePresence> presences = m_scene.GetAvatars();
308 int rootcount = 0;
309 for (int i=0;i<presences.Count;i++)
310 {
311 if (presences[i] != null)
312 {
313 if (!presences[i].IsChildAgent)
314 rootcount++;
315 }
316 }
317 if (rootcount <= 1)
318 StopThread();
319
320 lock (m_rootAgents) 307 lock (m_rootAgents)
321 { 308 {
322 if (m_rootAgents.Contains(AgentId)) 309 m_rootAgents.Remove(AgentId);
323 { 310 if(m_rootAgents.Count == 0)
324 m_rootAgents.Remove(AgentId); 311 StopThread();
325 }
326 } 312 }
327 } 313 }
328 #endregion 314 #endregion
@@ -375,11 +361,10 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
375 if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) 361 if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
376 { 362 {
377 // Local Map Item Request 363 // Local Map Item Request
378 List<ScenePresence> avatars = m_scene.GetAvatars();
379 int tc = Environment.TickCount; 364 int tc = Environment.TickCount;
380 List<mapItemReply> mapitems = new List<mapItemReply>(); 365 List<mapItemReply> mapitems = new List<mapItemReply>();
381 mapItemReply mapitem = new mapItemReply(); 366 mapItemReply mapitem = new mapItemReply();
382 if (avatars.Count == 0 || avatars.Count == 1) 367 if (m_scene.GetRootAgentCount() <= 1)
383 { 368 {
384 mapitem = new mapItemReply(); 369 mapitem = new mapItemReply();
385 mapitem.x = (uint)(xstart + 1); 370 mapitem.x = (uint)(xstart + 1);
@@ -392,21 +377,21 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
392 } 377 }
393 else 378 else
394 { 379 {
395 foreach (ScenePresence av in avatars) 380 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
396 { 381 {
397 // Don't send a green dot for yourself 382 // Don't send a green dot for yourself
398 if (av.UUID != remoteClient.AgentId) 383 if (!sp.IsChildAgent && sp.UUID != remoteClient.AgentId)
399 { 384 {
400 mapitem = new mapItemReply(); 385 mapitem = new mapItemReply();
401 mapitem.x = (uint)(xstart + av.AbsolutePosition.X); 386 mapitem.x = (uint)(xstart + sp.AbsolutePosition.X);
402 mapitem.y = (uint)(ystart + av.AbsolutePosition.Y); 387 mapitem.y = (uint)(ystart + sp.AbsolutePosition.Y);
403 mapitem.id = UUID.Zero; 388 mapitem.id = UUID.Zero;
404 mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); 389 mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
405 mapitem.Extra = 1; 390 mapitem.Extra = 1;
406 mapitem.Extra2 = 0; 391 mapitem.Extra2 = 0;
407 mapitems.Add(mapitem); 392 mapitems.Add(mapitem);
408 } 393 }
409 } 394 });
410 } 395 }
411 remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); 396 remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
412 } 397 }
@@ -504,7 +489,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
504 if (mrs.agentID != UUID.Zero) 489 if (mrs.agentID != UUID.Zero)
505 { 490 {
506 ScenePresence av = null; 491 ScenePresence av = null;
507 m_scene.TryGetAvatar(mrs.agentID, out av); 492 m_scene.TryGetScenePresence(mrs.agentID, out av);
508 if (av != null) 493 if (av != null)
509 { 494 {
510 if (response.ContainsKey(mrs.itemtype.ToString())) 495 if (response.ContainsKey(mrs.itemtype.ToString()))
@@ -981,51 +966,35 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
981 Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart); 966 Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart);
982 967
983 OSDMap responsemap = new OSDMap(); 968 OSDMap responsemap = new OSDMap();
984 List<ScenePresence> avatars = m_scene.GetAvatars();
985 OSDArray responsearr = new OSDArray(avatars.Count);
986 OSDMap responsemapdata = new OSDMap();
987 int tc = Environment.TickCount; 969 int tc = Environment.TickCount;
988 /* 970 if (m_scene.GetRootAgentCount() == 0)
989 foreach (ScenePresence av in avatars)
990 {
991 responsemapdata = new OSDMap();
992 responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X));
993 responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y));
994 responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
995 responsemapdata["Name"] = OSD.FromString("TH");
996 responsemapdata["Extra"] = OSD.FromInteger(0);
997 responsemapdata["Extra2"] = OSD.FromInteger(0);
998 responsearr.Add(responsemapdata);
999 }
1000 responsemap["1"] = responsearr;
1001 */
1002 if (avatars.Count == 0)
1003 { 971 {
1004 responsemapdata = new OSDMap(); 972 OSDMap responsemapdata = new OSDMap();
1005 responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); 973 responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
1006 responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); 974 responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
1007 responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); 975 responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
1008 responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); 976 responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
1009 responsemapdata["Extra"] = OSD.FromInteger(0); 977 responsemapdata["Extra"] = OSD.FromInteger(0);
1010 responsemapdata["Extra2"] = OSD.FromInteger(0); 978 responsemapdata["Extra2"] = OSD.FromInteger(0);
979 OSDArray responsearr = new OSDArray();
1011 responsearr.Add(responsemapdata); 980 responsearr.Add(responsemapdata);
1012 981
1013 responsemap["6"] = responsearr; 982 responsemap["6"] = responsearr;
1014 } 983 }
1015 else 984 else
1016 { 985 {
1017 responsearr = new OSDArray(avatars.Count); 986 OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount());
1018 foreach (ScenePresence av in avatars) 987 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
1019 { 988 {
1020 responsemapdata = new OSDMap(); 989 OSDMap responsemapdata = new OSDMap();
1021 responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X)); 990 responsemapdata["X"] = OSD.FromInteger((int)(xstart + sp.AbsolutePosition.X));
1022 responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y)); 991 responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sp.AbsolutePosition.Y));
1023 responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); 992 responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
1024 responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); 993 responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
1025 responsemapdata["Extra"] = OSD.FromInteger(1); 994 responsemapdata["Extra"] = OSD.FromInteger(1);
1026 responsemapdata["Extra2"] = OSD.FromInteger(0); 995 responsemapdata["Extra2"] = OSD.FromInteger(0);
1027 responsearr.Add(responsemapdata); 996 responsearr.Add(responsemapdata);
1028 } 997 });
1029 responsemap["6"] = responsearr; 998 responsemap["6"] = responsearr;
1030 } 999 }
1031 return responsemap; 1000 return responsemap;
@@ -1080,7 +1049,8 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
1080 AssetBase asset = new AssetBase( 1049 AssetBase asset = new AssetBase(
1081 m_scene.RegionInfo.RegionSettings.TerrainImageID, 1050 m_scene.RegionInfo.RegionSettings.TerrainImageID,
1082 "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString(), 1051 "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString(),
1083 (sbyte)AssetType.Texture); 1052 (sbyte)AssetType.Texture,
1053 m_scene.RegionInfo.RegionID.ToString());
1084 asset.Data = data; 1054 asset.Data = data;
1085 asset.Description = m_scene.RegionInfo.RegionName; 1055 asset.Description = m_scene.RegionInfo.RegionName;
1086 asset.Temporary = temporary; 1056 asset.Temporary = temporary;
@@ -1106,25 +1076,11 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
1106 1076
1107 private void MakeChildAgent(ScenePresence avatar) 1077 private void MakeChildAgent(ScenePresence avatar)
1108 { 1078 {
1109 List<ScenePresence> presences = m_scene.GetAvatars();
1110 int rootcount = 0;
1111 for (int i = 0; i < presences.Count; i++)
1112 {
1113 if (presences[i] != null)
1114 {
1115 if (!presences[i].IsChildAgent)
1116 rootcount++;
1117 }
1118 }
1119 if (rootcount <= 1)
1120 StopThread();
1121
1122 lock (m_rootAgents) 1079 lock (m_rootAgents)
1123 { 1080 {
1124 if (m_rootAgents.Contains(avatar.UUID)) 1081 m_rootAgents.Remove(avatar.UUID);
1125 { 1082 if (m_rootAgents.Count == 0)
1126 m_rootAgents.Remove(avatar.UUID); 1083 StopThread();
1127 }
1128 } 1084 }
1129 } 1085 }
1130 1086
diff --git a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
index 4df9094..9fc002b 100644
--- a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
+++ b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
@@ -94,28 +94,16 @@ namespace OpenSim.Region.DataSnapshot
94 if (!m_configLoaded) 94 if (!m_configLoaded)
95 { 95 {
96 m_configLoaded = true; 96 m_configLoaded = true;
97 m_log.Info("[DATASNAPSHOT]: Loading configuration"); 97 //m_log.Debug("[DATASNAPSHOT]: Loading configuration");
98 //Read from the config for options 98 //Read from the config for options
99 lock (m_syncInit) 99 lock (m_syncInit)
100 { 100 {
101 try 101 try
102 { 102 {
103 m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled); 103 m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled);
104 if (config.Configs["Startup"].GetBoolean("gridmode", false)) 104 IConfig conf = config.Configs["GridService"];
105 { 105 if (conf != null)
106 m_gridinfo.Add( 106 m_gridinfo.Add("gridserverURL", conf.GetString("GridServerURI", "http://127.0.0.1:8003"));
107 "gridserverURL",
108 config.Configs["Network"].GetString(
109 "grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString()));
110 m_gridinfo.Add(
111 "userserverURL",
112 config.Configs["Network"].GetString(
113 "user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString()));
114 m_gridinfo.Add(
115 "assetserverURL",
116 config.Configs["Network"].GetString(
117 "asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString()));
118 }
119 107
120 m_gridinfo.Add( 108 m_gridinfo.Add(
121 "Name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo")); 109 "Name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo"));
@@ -135,7 +123,7 @@ namespace OpenSim.Region.DataSnapshot
135 } 123 }
136 catch (Exception) 124 catch (Exception)
137 { 125 {
138 m_log.Info("[DATASNAPSHOT]: Could not load configuration. DataSnapshot will be disabled."); 126 m_log.Warn("[DATASNAPSHOT]: Could not load configuration. DataSnapshot will be disabled.");
139 m_enabled = false; 127 m_enabled = false;
140 return; 128 return;
141 } 129 }
@@ -191,7 +179,7 @@ namespace OpenSim.Region.DataSnapshot
191 } 179 }
192 else 180 else
193 { 181 {
194 m_log.Warn("[DATASNAPSHOT]: Data snapshot disabled, not adding scene to module (or anything else)."); 182 //m_log.Debug("[DATASNAPSHOT]: Data snapshot disabled, not adding scene to module (or anything else).");
195 } 183 }
196 } 184 }
197 185
diff --git a/OpenSim/Region/DataSnapshot/EstateSnapshot.cs b/OpenSim/Region/DataSnapshot/EstateSnapshot.cs
index 5fff89f..8da9e8c 100644
--- a/OpenSim/Region/DataSnapshot/EstateSnapshot.cs
+++ b/OpenSim/Region/DataSnapshot/EstateSnapshot.cs
@@ -29,9 +29,10 @@ using System;
29using System.Xml; 29using System.Xml;
30using OpenMetaverse; 30using OpenMetaverse;
31using OpenSim.Framework; 31using OpenSim.Framework;
32using OpenSim.Framework.Communications.Cache; 32
33using OpenSim.Region.DataSnapshot.Interfaces; 33using OpenSim.Region.DataSnapshot.Interfaces;
34using OpenSim.Region.Framework.Scenes; 34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Services.Interfaces;
35 36
36namespace OpenSim.Region.DataSnapshot.Providers 37namespace OpenSim.Region.DataSnapshot.Providers
37{ 38{
@@ -55,21 +56,17 @@ namespace OpenSim.Region.DataSnapshot.Providers
55 //Now in DataSnapshotProvider module form! 56 //Now in DataSnapshotProvider module form!
56 XmlNode estatedata = factory.CreateNode(XmlNodeType.Element, "estate", ""); 57 XmlNode estatedata = factory.CreateNode(XmlNodeType.Element, "estate", "");
57 58
58 UUID ownerid = m_scene.RegionInfo.MasterAvatarAssignedUUID; 59 UUID ownerid = m_scene.RegionInfo.EstateSettings.EstateOwner;
59 if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
60 ownerid = m_scene.RegionInfo.EstateSettings.EstateOwner;
61
62 CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(ownerid);
63 60
61 UserAccount userInfo = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid);
64 //TODO: Change to query userserver about the master avatar UUID ? 62 //TODO: Change to query userserver about the master avatar UUID ?
65 String firstname; 63 String firstname;
66 String lastname; 64 String lastname;
67 65
68 if (userInfo != null) 66 if (userInfo != null)
69 { 67 {
70 UserProfileData userProfile = userInfo.UserProfile; 68 firstname = userInfo.FirstName;
71 firstname = userProfile.FirstName; 69 lastname = userInfo.LastName;
72 lastname = userProfile.SurName;
73 70
74 //TODO: Fix the marshalling system to have less copypasta gruntwork 71 //TODO: Fix the marshalling system to have less copypasta gruntwork
75 XmlNode user = factory.CreateNode(XmlNodeType.Element, "user", ""); 72 XmlNode user = factory.CreateNode(XmlNodeType.Element, "user", "");
diff --git a/OpenSim/Region/DataSnapshot/LandSnapshot.cs b/OpenSim/Region/DataSnapshot/LandSnapshot.cs
index 51eacef..64d29f2 100644
--- a/OpenSim/Region/DataSnapshot/LandSnapshot.cs
+++ b/OpenSim/Region/DataSnapshot/LandSnapshot.cs
@@ -32,11 +32,12 @@ using System.Xml;
32using log4net; 32using log4net;
33using OpenMetaverse; 33using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Region.CoreModules.World.Land; 36using OpenSim.Region.CoreModules.World.Land;
37using OpenSim.Region.DataSnapshot.Interfaces; 37using OpenSim.Region.DataSnapshot.Interfaces;
38using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
40using OpenSim.Services.Interfaces;
40 41
41namespace OpenSim.Region.DataSnapshot.Providers 42namespace OpenSim.Region.DataSnapshot.Providers
42{ 43{
@@ -258,8 +259,8 @@ namespace OpenSim.Region.DataSnapshot.Providers
258 try 259 try
259 { 260 {
260 XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", ""); 261 XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", "");
261 CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userOwnerUUID); 262 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, userOwnerUUID);
262 username.InnerText = profile.UserProfile.FirstName + " " + profile.UserProfile.SurName; 263 username.InnerText = account.FirstName + " " + account.LastName;
263 userblock.AppendChild(username); 264 userblock.AppendChild(username);
264 } 265 }
265 catch (Exception) 266 catch (Exception)
diff --git a/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs b/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs
index 62666a4..6e69902 100644
--- a/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs
+++ b/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs
@@ -203,44 +203,54 @@ namespace OpenSim.Region.DataSnapshot.Providers
203 { 203 {
204 string bestguess = string.Empty; 204 string bestguess = string.Empty;
205 Dictionary<UUID, int> counts = new Dictionary<UUID, int>(); 205 Dictionary<UUID, int> counts = new Dictionary<UUID, int>();
206 if (sog.RootPart.Shape != null && sog.RootPart.Shape.ProfileShape == ProfileShape.Square && 206
207 sog.RootPart.Shape.Textures != null && sog.RootPart.Shape.Textures.FaceTextures != null) 207 PrimitiveBaseShape shape = sog.RootPart.Shape;
208 if (shape != null && shape.ProfileShape == ProfileShape.Square)
208 { 209 {
209 if (sog.RootPart.Shape.Textures.DefaultTexture.TextureID != UUID.Zero && 210 Primitive.TextureEntry textures = shape.Textures;
210 sog.RootPart.Shape.Textures.DefaultTexture.TextureID != m_DefaultImage && 211 if (textures != null)
211 sog.RootPart.Shape.Textures.DefaultTexture.TextureID != m_BlankImage &&
212 sog.RootPart.Shape.Textures.DefaultTexture.RGBA.A < 50)
213 { 212 {
214 counts[sog.RootPart.Shape.Textures.DefaultTexture.TextureID] = 8; 213 if (textures.DefaultTexture != null &&
215 } 214 textures.DefaultTexture.TextureID != UUID.Zero &&
215 textures.DefaultTexture.TextureID != m_DefaultImage &&
216 textures.DefaultTexture.TextureID != m_BlankImage &&
217 textures.DefaultTexture.RGBA.A < 50f)
218 {
219 counts[textures.DefaultTexture.TextureID] = 8;
220 }
216 221
217 foreach (Primitive.TextureEntryFace tentry in sog.RootPart.Shape.Textures.FaceTextures) 222 if (textures.FaceTextures != null)
218 {
219 if (tentry != null)
220 { 223 {
221 if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50) 224 foreach (Primitive.TextureEntryFace tentry in textures.FaceTextures)
222 { 225 {
223 int c = 0; 226 if (tentry != null)
224 counts.TryGetValue(tentry.TextureID, out c); 227 {
225 counts[tentry.TextureID] = c + 1; 228 if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50)
226 // decrease the default texture count 229 {
227 if (counts.ContainsKey(sog.RootPart.Shape.Textures.DefaultTexture.TextureID)) 230 int c = 0;
228 counts[sog.RootPart.Shape.Textures.DefaultTexture.TextureID] = counts[sog.RootPart.Shape.Textures.DefaultTexture.TextureID] - 1; 231 counts.TryGetValue(tentry.TextureID, out c);
232 counts[tentry.TextureID] = c + 1;
233 // decrease the default texture count
234 if (counts.ContainsKey(textures.DefaultTexture.TextureID))
235 counts[textures.DefaultTexture.TextureID] = counts[textures.DefaultTexture.TextureID] - 1;
236 }
237 }
229 } 238 }
230 } 239 }
231 }
232 240
233 // Let's pick the most unique texture 241 // Let's pick the most unique texture
234 int min = 9999; 242 int min = 9999;
235 foreach (KeyValuePair<UUID, int> kv in counts) 243 foreach (KeyValuePair<UUID, int> kv in counts)
236 {
237 if (kv.Value < min && kv.Value >= 1)
238 { 244 {
239 bestguess = kv.Key.ToString(); 245 if (kv.Value < min && kv.Value >= 1)
240 min = kv.Value; 246 {
247 bestguess = kv.Key.ToString();
248 min = kv.Value;
249 }
241 } 250 }
242 } 251 }
243 } 252 }
253
244 return bestguess; 254 return bestguess;
245 } 255 }
246 } 256 }
diff --git a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs
index d2b0161..09611af 100644
--- a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs
+++ b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs
@@ -83,7 +83,8 @@ namespace OpenSim.Region.Examples.SimpleModule
83 public event DeRezObject OnDeRezObject; 83 public event DeRezObject OnDeRezObject;
84 public event Action<IClientAPI> OnRegionHandShakeReply; 84 public event Action<IClientAPI> OnRegionHandShakeReply;
85 public event GenericCall2 OnRequestWearables; 85 public event GenericCall2 OnRequestWearables;
86 public event GenericCall2 OnCompleteMovementToRegion; 86 public event GenericCall1 OnCompleteMovementToRegion;
87 public event UpdateAgent OnPreAgentUpdate;
87 public event UpdateAgent OnAgentUpdate; 88 public event UpdateAgent OnAgentUpdate;
88 public event AgentRequestSit OnAgentRequestSit; 89 public event AgentRequestSit OnAgentRequestSit;
89 public event AgentSit OnAgentSit; 90 public event AgentSit OnAgentSit;
@@ -128,6 +129,7 @@ namespace OpenSim.Region.Examples.SimpleModule
128 public event Action<UUID> OnRemoveAvatar; 129 public event Action<UUID> OnRemoveAvatar;
129 130
130 public event CreateNewInventoryItem OnCreateNewInventoryItem; 131 public event CreateNewInventoryItem OnCreateNewInventoryItem;
132 public event LinkInventoryItem OnLinkInventoryItem;
131 public event CreateInventoryFolder OnCreateNewInventoryFolder; 133 public event CreateInventoryFolder OnCreateNewInventoryFolder;
132 public event UpdateInventoryFolder OnUpdateInventoryFolder; 134 public event UpdateInventoryFolder OnUpdateInventoryFolder;
133 public event MoveInventoryFolder OnMoveInventoryFolder; 135 public event MoveInventoryFolder OnMoveInventoryFolder;
@@ -353,7 +355,11 @@ namespace OpenSim.Region.Examples.SimpleModule
353 get { return true; } 355 get { return true; }
354 set { } 356 set { }
355 } 357 }
356 358 public bool IsLoggingOut
359 {
360 get { return false; }
361 set { }
362 }
357 public UUID ActiveGroupId 363 public UUID ActiveGroupId
358 { 364 {
359 get { return UUID.Zero; } 365 get { return UUID.Zero; }
@@ -655,7 +661,7 @@ namespace OpenSim.Region.Examples.SimpleModule
655 661
656 if (OnCompleteMovementToRegion != null) 662 if (OnCompleteMovementToRegion != null)
657 { 663 {
658 OnCompleteMovementToRegion(); 664 OnCompleteMovementToRegion(this);
659 } 665 }
660 } 666 }
661 public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) 667 public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
@@ -1145,5 +1151,13 @@ namespace OpenSim.Region.Examples.SimpleModule
1145 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) 1151 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
1146 { 1152 {
1147 } 1153 }
1154
1155 public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
1156 {
1157 }
1158
1159 public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
1160 {
1161 }
1148 } 1162 }
1149} 1163}
diff --git a/OpenSim/Region/Examples/SimpleModule/RegionModule.cs b/OpenSim/Region/Examples/SimpleModule/RegionModule.cs
index e1d5bdc..6da41db 100644
--- a/OpenSim/Region/Examples/SimpleModule/RegionModule.cs
+++ b/OpenSim/Region/Examples/SimpleModule/RegionModule.cs
@@ -88,12 +88,12 @@ namespace OpenSim.Region.Examples.SimpleModule
88 m_scene.AgentCrossing(m_character.AgentId, Vector3.Zero, false); 88 m_scene.AgentCrossing(m_character.AgentId, Vector3.Zero, false);
89 } 89 }
90 90
91 List<ScenePresence> avatars = m_scene.GetAvatars(); 91 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
92 foreach (ScenePresence avatar in avatars)
93 { 92 {
94 avatar.AbsolutePosition = 93 if (!sp.IsChildAgent)
95 new Vector3((float)Util.RandomClass.Next(100, 200), (float)Util.RandomClass.Next(30, 200), 2); 94 sp.AbsolutePosition =
96 } 95 new Vector3((float)Util.RandomClass.Next(100, 200), (float)Util.RandomClass.Next(30, 200), 2);
96 });
97 } 97 }
98 98
99 // private void AddComplexObjects(RegionInfo regionInfo, Vector3 pos) 99 // private void AddComplexObjects(RegionInfo regionInfo, Vector3 pos)
diff --git a/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs b/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs
new file mode 100644
index 0000000..958847b
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs
@@ -0,0 +1,140 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSim Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Xml;
30using OpenMetaverse;
31using OpenMetaverse.Packets;
32using OpenSim.Framework;
33using OpenSim.Region.Framework.Scenes;
34
35namespace OpenSim.Region.Framework.Interfaces
36{
37 public interface IAttachmentsModule
38 {
39 /// <summary>
40 /// Attach an object to an avatar from the world.
41 /// </summary>
42 /// <param name="controllingClient"></param>
43 /// <param name="localID"></param>
44 /// <param name="attachPoint"></param>
45 /// <param name="rot"></param>
46 /// <param name="silent"></param>
47 void AttachObject(
48 IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent);
49
50 /// <summary>
51 /// Attach an object to an avatar.
52 /// </summary>
53 /// <param name="controllingClient"></param>
54 /// <param name="localID"></param>
55 /// <param name="attachPoint"></param>
56 /// <param name="rot"></param>
57 /// <param name="attachPos"></param>
58 /// <param name="silent"></param>
59 /// <returns>true if the object was successfully attached, false otherwise</returns>
60 bool AttachObject(
61 IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent);
62
63 /// <summary>
64 /// Rez an attachment from user inventory and change inventory status to match.
65 /// </summary>
66 /// <param name="remoteClient"></param>
67 /// <param name="itemID"></param>
68 /// <param name="AttachmentPt"></param>
69 /// <returns>The scene object that was attached. Null if the scene object could not be found</returns>
70 UUID RezSingleAttachmentFromInventory(IClientAPI remoteClient, UUID itemID, uint AttachmentPt);
71
72 /// <summary>
73 /// Rez an attachment from user inventory
74 /// </summary>
75 /// <param name="remoteClient"></param>
76 /// <param name="itemID"></param>
77 /// <param name="AttachmentPt"></param>
78 /// <param name="updateinventoryStatus">
79 /// If true, we also update the user's inventory to show that the attachment is set. If false, we do not.
80 /// False is required so that we don't attempt to update information when a user enters a scene with the
81 /// attachment already correctly set up in inventory.
82 /// <returns>The uuid of the scene object that was attached. Null if the scene object could not be found</returns>
83 UUID RezSingleAttachmentFromInventory(
84 IClientAPI remoteClient, UUID itemID, uint AttachmentPt, bool updateInventoryStatus);
85
86 // Same as above, but also load script states from a separate doc
87 UUID RezSingleAttachmentFromInventory(
88 IClientAPI remoteClient, UUID itemID, uint AttachmentPt, bool updateInventoryStatus, XmlDocument doc);
89
90 /// <summary>
91 /// Rez multiple attachments from a user's inventory
92 /// </summary>
93 /// <param name="remoteClient"></param>
94 /// <param name="header"></param>
95 /// <param name="objects"></param>
96 void RezMultipleAttachmentsFromInventory(
97 IClientAPI remoteClient,
98 RezMultipleAttachmentsFromInvPacket.HeaderDataBlock header,
99 RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects);
100
101 /// <summary>
102 /// Detach an object from the avatar.
103 /// </summary>
104 ///
105 /// This method is called in response to a client's detach request, so we only update the information in
106 /// inventory
107 /// <param name="objectLocalID"></param>
108 /// <param name="remoteClient"></param>
109 void DetachObject(uint objectLocalID, IClientAPI remoteClient);
110
111 /// <summary>
112 /// Detach the given item to the ground.
113 /// </summary>
114 /// <param name="itemID"></param>
115 /// <param name="remoteClient"></param>
116 void DetachSingleAttachmentToGround(UUID itemID, IClientAPI remoteClient);
117
118 /// <summary>
119 /// Update the user inventory to the attachment of an item
120 /// </summary>
121 /// <param name="att"></param>
122 /// <param name="remoteClient"></param>
123 /// <param name="itemID"></param>
124 /// <param name="AttachmentPt"></param>
125 /// <returns></returns>
126 UUID SetAttachmentInventoryStatus(
127 SceneObjectGroup att, IClientAPI remoteClient, UUID itemID, uint AttachmentPt);
128
129 /// <summary>
130 /// Update the user inventory to show a detach.
131 /// </summary>
132 /// <param name="itemID">
133 /// A <see cref="UUID"/>
134 /// </param>
135 /// <param name="remoteClient">
136 /// A <see cref="IClientAPI"/>
137 /// </param>
138 void ShowDetachInUserInventory(UUID itemID, IClientAPI remoteClient);
139 }
140}
diff --git a/OpenSim/Region/Framework/Interfaces/IDialogModule.cs b/OpenSim/Region/Framework/Interfaces/IDialogModule.cs
index ce57c44..be9764a 100644
--- a/OpenSim/Region/Framework/Interfaces/IDialogModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IDialogModule.cs
@@ -120,16 +120,8 @@ namespace OpenSim.Region.Framework.Interfaces
120 void SendNotificationToUsersInRegion(UUID fromAvatarID, string fromAvatarName, string message); 120 void SendNotificationToUsersInRegion(UUID fromAvatarID, string fromAvatarName, string message);
121 121
122 /// <summary> 122 /// <summary>
123 /// Send a notification to all users in the estate. This notification should remain around until the 123 /// Send a textbox entry for the client to respond to
124 /// user explicitly dismisses it.
125 /// </summary> 124 /// </summary>
126 /// 125 void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid);
127 /// On the Linden Labs Second Client (as of 1.21), this is a big blue box message on the upper right of the
128 /// screen.
129 ///
130 /// <param name="fromAvatarID">The user sending the message</param>
131 /// <param name="fromAvatarName">The name of the user doing the sending</param>
132 /// <param name="message">The message being sent to the user</param>
133 void SendNotificationToUsersInEstate(UUID fromAvatarID, string fromAvatarName, string message);
134 } 126 }
135} 127}
diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
index 16ca3f9..1e2f60b 100644
--- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
@@ -73,6 +73,9 @@ namespace OpenSim.Region.Framework.Interfaces
73 /// </summary> 73 /// </summary>
74 void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource); 74 void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource);
75 75
76 ArrayList GetScriptErrors(UUID itemID);
77 void ResumeScripts();
78
76 /// <summary> 79 /// <summary>
77 /// Stop all the scripts in this entity. 80 /// Stop all the scripts in this entity.
78 /// </summary> 81 /// </summary>
@@ -160,6 +163,7 @@ namespace OpenSim.Region.Framework.Interfaces
160 /// in this prim's inventory.</param> 163 /// in this prim's inventory.</param>
161 /// <returns>false if the item did not exist, true if the update occurred successfully</returns> 164 /// <returns>false if the item did not exist, true if the update occurred successfully</returns>
162 bool UpdateInventoryItem(TaskInventoryItem item); 165 bool UpdateInventoryItem(TaskInventoryItem item);
166 bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents);
163 167
164 /// <summary> 168 /// <summary>
165 /// Remove an item from this entity's inventory 169 /// Remove an item from this entity's inventory
@@ -212,5 +216,6 @@ namespace OpenSim.Region.Framework.Interfaces
212 /// A <see cref="Dictionary`2"/> 216 /// A <see cref="Dictionary`2"/>
213 /// </returns> 217 /// </returns>
214 Dictionary<UUID, string> GetScriptStates(); 218 Dictionary<UUID, string> GetScriptStates();
219 Dictionary<UUID, string> GetScriptStates(bool oldIDs);
215 } 220 }
216} 221}
diff --git a/OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
index 94e4ed2..e8738c4 100644
--- a/OpenSim/Region/Communications/OGS1/CommunicationsOGS1.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
@@ -25,30 +25,36 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System;
29using OpenSim.Services.Interfaces;
30using GridRegion = OpenSim.Services.Interfaces.GridRegion;
31
32using OpenMetaverse;
28using OpenSim.Framework; 33using OpenSim.Framework;
29using OpenSim.Framework.Communications; 34using OpenSim.Region.Framework.Scenes;
30using OpenSim.Framework.Communications.Cache;
31using OpenSim.Framework.Servers.HttpServer;
32 35
33namespace OpenSim.Region.Communications.OGS1 36namespace OpenSim.Region.Framework.Interfaces
34{ 37{
35 public class CommunicationsOGS1 : CommunicationsManager 38 public interface IEntityTransferModule
36 { 39 {
37 public CommunicationsOGS1( 40 void Teleport(ScenePresence agent, ulong regionHandle, Vector3 position,
38 NetworkServersInfo serversInfo, 41 Vector3 lookAt, uint teleportFlags);
39 LibraryRootFolder libraryRootFolder) 42
40 : base(serversInfo, libraryRootFolder) 43 void TeleportHome(UUID id, IClientAPI client);
41 { 44
42 45 void Cross(ScenePresence agent, bool isFlying);
43 // This plugin arrangement could eventually be configurable rather than hardcoded here. 46
44 OGS1UserServices userServices = new OGS1UserServices(this); 47 void AgentArrivedAtDestination(UUID agent);
45 userServices.AddPlugin(new TemporaryUserProfilePlugin()); 48
46 userServices.AddPlugin(new OGS1UserDataPlugin(this)); 49 void EnableChildAgents(ScenePresence agent);
47
48 m_userService = userServices;
49 m_messageService = userServices;
50 m_avatarService = (IAvatarService)m_userService;
51 }
52 50
51 void EnableChildAgent(ScenePresence agent, GridRegion region);
52
53 void Cross(SceneObjectGroup sog, Vector3 position, bool silent);
54 }
55
56 public interface IUserAgentVerificationModule
57 {
58 bool VerifyClient(AgentCircuitData aCircuit, string token);
53 } 59 }
54} 60}
diff --git a/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs b/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs
index 668ff98..87c7a05 100644
--- a/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs
@@ -25,6 +25,7 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System.Collections.Generic;
28using OpenMetaverse; 29using OpenMetaverse;
29using OpenSim.Framework; 30using OpenSim.Framework;
30 31
@@ -34,7 +35,12 @@ namespace OpenSim.Region.Framework.Interfaces
34 { 35 {
35 void Initialise(string connectstring); 36 void Initialise(string connectstring);
36 37
37 EstateSettings LoadEstateSettings(UUID regionID); 38 EstateSettings LoadEstateSettings(UUID regionID, bool create);
39 EstateSettings LoadEstateSettings(int estateID);
38 void StoreEstateSettings(EstateSettings es); 40 void StoreEstateSettings(EstateSettings es);
41 List<int> GetEstates(string search);
42 bool LinkRegion(UUID regionID, int estateID);
43 List<UUID> GetRegions(int estateID);
44 bool DeleteEstate(int estateID);
39 } 45 }
40} 46}
diff --git a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
index 890fa31..c850f7f 100644
--- a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
@@ -29,8 +29,15 @@ using OpenMetaverse;
29 29
30namespace OpenSim.Region.Framework.Interfaces 30namespace OpenSim.Region.Framework.Interfaces
31{ 31{
32 public delegate void ChangeDelegate(UUID regionID);
33 public delegate void MessageDelegate(UUID regionID, UUID fromID, string fromName, string message);
34
32 public interface IEstateModule : IRegionModule 35 public interface IEstateModule : IRegionModule
33 { 36 {
37 event ChangeDelegate OnRegionInfoChange;
38 event ChangeDelegate OnEstateInfoChange;
39 event MessageDelegate OnEstateMessage;
40
34 uint GetRegionFlags(); 41 uint GetRegionFlags();
35 bool IsManager(UUID avatarID); 42 bool IsManager(UUID avatarID);
36 43
diff --git a/OpenSim/Region/Framework/Interfaces/IFriendsModule.cs b/OpenSim/Region/Framework/Interfaces/IFriendsModule.cs
index 8386030..0ff7dee 100644
--- a/OpenSim/Region/Framework/Interfaces/IFriendsModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IFriendsModule.cs
@@ -33,19 +33,7 @@ namespace OpenSim.Region.Framework.Interfaces
33{ 33{
34 public interface IFriendsModule 34 public interface IFriendsModule
35 { 35 {
36 /// <summary> 36 uint GetFriendPerms(UUID PrincipalID, UUID FriendID);
37 /// Offer a friendship to a user from the server end rather than by direct initiation from a client. 37 void SendFriendsOnlineIfNeeded(IClientAPI client);
38 /// </summary>
39 /// <param name="fromUserId">
40 /// A user with this id must existing in the user data store, but need not be logged on.
41 /// </param>
42 /// <param name="toUserClient">
43 /// An actually logged in client to which the offer is being made.
44 /// FIXME: This is somewhat too tightly coupled - it should arguably be possible to offer friendships even if the
45 /// receiving user is not currently online.
46 /// </param>
47 /// <param name="offerMessage"></param>
48 void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage);
49 List<FriendListItem> GetUserFriends(UUID agentID);
50 } 38 }
51} 39}
diff --git a/OpenSim/Region/Framework/Interfaces/IGroupsMessagingModule.cs b/OpenSim/Region/Framework/Interfaces/IGroupsMessagingModule.cs
new file mode 100644
index 0000000..f158236
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/IGroupsMessagingModule.cs
@@ -0,0 +1,73 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using OpenMetaverse;
29using OpenSim.Framework;
30
31namespace OpenSim.Region.Framework.Interfaces
32{
33 /// <summary>
34 /// Provide mechanisms for messaging groups.
35 /// </summary>
36 ///
37 /// TODO: Provide a mechanism for receiving group messages as well as sending them
38 ///
39 public interface IGroupsMessagingModule
40 {
41 /// <summary>
42 /// Start a group chat session.
43 /// </summary>
44 /// You must call this before calling SendMessageToGroup(). If a chat session for this group is already taking
45 /// place then the agent will added to that session.
46 /// <param name="agentID">
47 /// A UUID that represents the agent being added. If you are agentless (e.g. you are
48 /// a region module), then you can use any random ID.
49 /// </param>
50 /// <param name="groupID">
51 /// The ID for the group to join. Currently, the session ID used is identical to the
52 /// group ID.
53 /// </param>
54 /// <returns>
55 /// True if the chat session was started successfully, false otherwise.
56 /// </returns>
57 bool StartGroupChatSession(UUID agentID, UUID groupID);
58
59 /// <summary>
60 /// Send a message to an entire group.
61 /// </summary>
62 /// <param name="im">
63 /// The message itself. The fields that must be populated are
64 ///
65 /// imSessionID - Populate this with the group ID (session ID and group ID are currently identical)
66 /// fromAgentName - Populate this with whatever arbitrary name you want to show up in the chat dialog
67 /// message - The message itself
68 /// dialog - This must be (byte)InstantMessageDialog.SessionSend
69 /// </param>
70 /// <param name="groupID"></param>
71 void SendMessageToGroup(GridInstantMessage im, UUID groupID);
72 }
73} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Interfaces/IGroupsModule.cs b/OpenSim/Region/Framework/Interfaces/IGroupsModule.cs
index 8980b2d..2c091e7 100644
--- a/OpenSim/Region/Framework/Interfaces/IGroupsModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IGroupsModule.cs
@@ -37,21 +37,51 @@ namespace OpenSim.Region.Framework.Interfaces
37 { 37 {
38 event NewGroupNotice OnNewGroupNotice; 38 event NewGroupNotice OnNewGroupNotice;
39 39
40 /// <summary>
41 /// Create a group
42 /// </summary>
43 /// <param name="remoteClient"></param>
44 /// <param name="name"></param>
45 /// <param name="charter"></param>
46 /// <param name="showInList"></param>
47 /// <param name="insigniaID"></param>
48 /// <param name="membershipFee"></param>
49 /// <param name="openEnrollment"></param>
50 /// <param name="allowPublish"></param>
51 /// <param name="maturePublish"></param>
52 /// <returns>The UUID of the created group</returns>
53 UUID CreateGroup(
54 IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee,
55 bool openEnrollment, bool allowPublish, bool maturePublish);
56
57 /// <summary>
58 /// Get a group
59 /// </summary>
60 /// <param name="name">Name of the group</param>
61 /// <returns>The group's data. Null if there is no such group.</returns>
62 GroupRecord GetGroupRecord(string name);
63
64 /// <summary>
65 /// Get a group
66 /// </summary>
67 /// <param name="GroupID">ID of the group</param>
68 /// <returns>The group's data. Null if there is no such group.</returns>
69 GroupRecord GetGroupRecord(UUID GroupID);
70
40 void ActivateGroup(IClientAPI remoteClient, UUID groupID); 71 void ActivateGroup(IClientAPI remoteClient, UUID groupID);
41 List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID); 72 List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID);
42 List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID); 73 List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID);
43 List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID); 74 List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID);
44 List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID); 75 List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID);
45 GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID); 76 GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID);
46 GroupMembershipData[] GetMembershipData(UUID UserID); 77 GroupMembershipData[] GetMembershipData(UUID UserID);
47 GroupMembershipData GetMembershipData(UUID GroupID, UUID UserID); 78 GroupMembershipData GetMembershipData(UUID GroupID, UUID UserID);
48 79
49 void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish); 80 void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish);
50 81
51 void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile); 82 void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile);
52 83
53 void GroupTitleUpdate(IClientAPI remoteClient, UUID GroupID, UUID TitleRoleID); 84 void GroupTitleUpdate(IClientAPI remoteClient, UUID GroupID, UUID TitleRoleID);
54 UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish);
55 85
56 GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID GroupID); 86 GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID GroupID);
57 string GetGroupTitle(UUID avatarID); 87 string GetGroupTitle(UUID avatarID);
@@ -64,7 +94,6 @@ namespace OpenSim.Region.Framework.Interfaces
64 void LeaveGroupRequest(IClientAPI remoteClient, UUID GroupID); 94 void LeaveGroupRequest(IClientAPI remoteClient, UUID GroupID);
65 void EjectGroupMemberRequest(IClientAPI remoteClient, UUID GroupID, UUID EjecteeID); 95 void EjectGroupMemberRequest(IClientAPI remoteClient, UUID GroupID, UUID EjecteeID);
66 void InviteGroupRequest(IClientAPI remoteClient, UUID GroupID, UUID InviteeID, UUID RoleID); 96 void InviteGroupRequest(IClientAPI remoteClient, UUID GroupID, UUID InviteeID, UUID RoleID);
67 GroupRecord GetGroupRecord(UUID GroupID);
68 void NotifyChange(UUID GroupID); 97 void NotifyChange(UUID GroupID);
69 } 98 }
70} 99} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Interfaces/ITeleportModule.cs b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs
index 5f9129d..8185258 100644
--- a/OpenSim/Region/Framework/Interfaces/ITeleportModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs
@@ -27,15 +27,21 @@
27 27
28using System; 28using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30using System.Text; 30
31using OpenMetaverse; 31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes; 32using OpenSim.Region.Framework.Scenes;
33 33
34using OpenMetaverse;
35
34namespace OpenSim.Region.Framework.Interfaces 36namespace OpenSim.Region.Framework.Interfaces
35{ 37{
36 public interface ITeleportModule 38 public interface IInventoryAccessModule
37 { 39 {
38 void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position, 40 UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data);
39 Vector3 lookAt, uint teleportFlags); 41 UUID DeleteToInventory(DeRezAction action, UUID folderID, SceneObjectGroup objectGroup, IClientAPI remoteClient);
42 SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
43 UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
44 bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment);
45 void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver);
40 } 46 }
41} 47}
diff --git a/OpenSim/Region/Framework/Interfaces/IInventoryArchiverModule.cs b/OpenSim/Region/Framework/Interfaces/IInventoryArchiverModule.cs
index 2d038ce..fbadd91 100644
--- a/OpenSim/Region/Framework/Interfaces/IInventoryArchiverModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IInventoryArchiverModule.cs
@@ -27,7 +27,7 @@
27 27
28using System; 28using System;
29using System.IO; 29using System.IO;
30using OpenSim.Framework.Communications.Cache; 30using OpenSim.Services.Interfaces;
31 31
32namespace OpenSim.Region.Framework.Interfaces 32namespace OpenSim.Region.Framework.Interfaces
33{ 33{
@@ -41,7 +41,7 @@ namespace OpenSim.Region.Framework.Interfaces
41 /// <param name="savePath">The stream to which the archive was saved</param> 41 /// <param name="savePath">The stream to which the archive was saved</param>
42 /// <param name="reportedException">Contains the exception generated if the save did not succeed</param> 42 /// <param name="reportedException">Contains the exception generated if the save did not succeed</param>
43 public delegate void InventoryArchiveSaved( 43 public delegate void InventoryArchiveSaved(
44 Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, Exception reportedException); 44 Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException);
45 45
46 public interface IInventoryArchiverModule 46 public interface IInventoryArchiverModule
47 { 47 {
diff --git a/OpenSim/Region/Framework/Interfaces/IPresenceModule.cs b/OpenSim/Region/Framework/Interfaces/IPresenceModule.cs
index 630c6a3..d44c1e1 100644
--- a/OpenSim/Region/Framework/Interfaces/IPresenceModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IPresenceModule.cs
@@ -31,13 +31,13 @@ namespace OpenSim.Region.Framework.Interfaces
31{ 31{
32 public struct PresenceInfo 32 public struct PresenceInfo
33 { 33 {
34 public UUID userID; 34 public string UserID;
35 public UUID regionID; 35 public UUID RegionID;
36 36
37 public PresenceInfo(UUID userID, UUID regionID) 37 public PresenceInfo(string userID, UUID regionID)
38 { 38 {
39 this.userID = userID; 39 UserID = userID;
40 this.regionID = regionID; 40 RegionID = regionID;
41 } 41 }
42 } 42 }
43 43
diff --git a/OpenSim/Region/Framework/Interfaces/IRegionArchiverModule.cs b/OpenSim/Region/Framework/Interfaces/IRegionArchiverModule.cs
index 991d60c..89e59d0 100644
--- a/OpenSim/Region/Framework/Interfaces/IRegionArchiverModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IRegionArchiverModule.cs
@@ -90,8 +90,12 @@ namespace OpenSim.Region.Framework.Interfaces
90 /// If true, the loaded region merges with the existing one rather than replacing it. Any terrain or region 90 /// If true, the loaded region merges with the existing one rather than replacing it. Any terrain or region
91 /// settings in the archive will be ignored. 91 /// settings in the archive will be ignored.
92 /// </param> 92 /// </param>
93 /// <param name="skipAssets">
94 /// If true, the archive is loaded without loading any assets contained within it. This is useful if the
95 /// assets are already known to be present in the grid's asset service.
96 /// </param>
93 /// <param name="requestId">If supplied, this request Id is later returned in the saved event</param> 97 /// <param name="requestId">If supplied, this request Id is later returned in the saved event</param>
94 void DearchiveRegion(string loadPath, bool merge, Guid requestId); 98 void DearchiveRegion(string loadPath, bool merge, bool skipAssets, Guid requestId);
95 99
96 /// <summary> 100 /// <summary>
97 /// Dearchive a region from a stream. This replaces the existing scene. 101 /// Dearchive a region from a stream. This replaces the existing scene.
@@ -113,7 +117,11 @@ namespace OpenSim.Region.Framework.Interfaces
113 /// If true, the loaded region merges with the existing one rather than replacing it. Any terrain or region 117 /// If true, the loaded region merges with the existing one rather than replacing it. Any terrain or region
114 /// settings in the archive will be ignored. 118 /// settings in the archive will be ignored.
115 /// </param> 119 /// </param>
120 /// <param name="skipAssets">
121 /// If true, the archive is loaded without loading any assets contained within it. This is useful if the
122 /// assets are already known to be present in the grid's asset service.
123 /// </param
116 /// <param name="requestId">If supplied, this request Id is later returned in the saved event</param> 124 /// <param name="requestId">If supplied, this request Id is later returned in the saved event</param>
117 void DearchiveRegion(Stream loadStream, bool merge, Guid requestId); 125 void DearchiveRegion(Stream loadStream, bool merge, bool skipAssets, Guid requestId);
118 } 126 }
119} 127}
diff --git a/OpenSim/Region/Framework/Interfaces/IRegionDataStore.cs b/OpenSim/Region/Framework/Interfaces/IRegionDataStore.cs
index 7312799..3e8e196 100644
--- a/OpenSim/Region/Framework/Interfaces/IRegionDataStore.cs
+++ b/OpenSim/Region/Framework/Interfaces/IRegionDataStore.cs
@@ -103,8 +103,8 @@ namespace OpenSim.Region.Framework.Interfaces
103 103
104 void StoreRegionSettings(RegionSettings rs); 104 void StoreRegionSettings(RegionSettings rs);
105 RegionSettings LoadRegionSettings(UUID regionUUID); 105 RegionSettings LoadRegionSettings(UUID regionUUID);
106 RegionMeta7WindlightData LoadRegionWindlightSettings(UUID regionUUID); 106 RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID);
107 void StoreRegionWindlightSettings(RegionMeta7WindlightData wl); 107 void StoreRegionWindlightSettings(RegionLightShareData wl);
108 108
109 void Shutdown(); 109 void Shutdown();
110 } 110 }
diff --git a/OpenSim/Region/Framework/Interfaces/IRegionModule.cs b/OpenSim/Region/Framework/Interfaces/IRegionModule.cs
index 8eb906c..e25a6e8 100644
--- a/OpenSim/Region/Framework/Interfaces/IRegionModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IRegionModule.cs
@@ -30,6 +30,9 @@ using OpenSim.Region.Framework.Scenes;
30 30
31namespace OpenSim.Region.Framework.Interfaces 31namespace OpenSim.Region.Framework.Interfaces
32{ 32{
33 /// <summary>
34 /// DEPRECATED! Use INonSharedRegionModule or ISharedRegionModule instead
35 /// </summary>
33 public interface IRegionModule 36 public interface IRegionModule
34 { 37 {
35 void Initialise(Scene scene, IConfigSource source); 38 void Initialise(Scene scene, IConfigSource source);
diff --git a/OpenSim/Region/Framework/Interfaces/IScriptModule.cs b/OpenSim/Region/Framework/Interfaces/IScriptModule.cs
index e90b300..fecdd1b 100644
--- a/OpenSim/Region/Framework/Interfaces/IScriptModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IScriptModule.cs
@@ -41,6 +41,14 @@ namespace OpenSim.Region.Framework.Interfaces
41 bool PostScriptEvent(UUID itemID, string name, Object[] args); 41 bool PostScriptEvent(UUID itemID, string name, Object[] args);
42 bool PostObjectEvent(UUID itemID, string name, Object[] args); 42 bool PostObjectEvent(UUID itemID, string name, Object[] args);
43 43
44 // Suspend ALL scripts in a given scene object. The item ID
45 // is the UUID of a SOG, and the method acts on all contained
46 // scripts. This is different from the suspend/resume that
47 // can be issued by a client.
48 //
49 void SuspendScript(UUID itemID);
50 void ResumeScript(UUID itemID);
51
44 ArrayList GetScriptErrors(UUID itemID); 52 ArrayList GetScriptErrors(UUID itemID);
45 } 53 }
46} 54}
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index b43caf2..702a1e2 100644
--- a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
+++ b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
@@ -378,7 +378,7 @@ namespace OpenSim.Region.Framework.Scenes.Animation
378 } 378 }
379 } 379 }
380 380
381 AssetBase Animasset = new AssetBase(UUID.Random(), "Random Animation", (sbyte)AssetType.Animation); 381 AssetBase Animasset = new AssetBase(UUID.Random(), "Random Animation", (sbyte)AssetType.Animation, m_scenePresence.UUID.ToString());
382 Animasset.Data = anim.ToBytes(); 382 Animasset.Data = anim.ToBytes();
383 Animasset.Temporary = true; 383 Animasset.Temporary = true;
384 Animasset.Local = true; 384 Animasset.Local = true;
@@ -413,11 +413,12 @@ namespace OpenSim.Region.Framework.Scenes.Animation
413 if (m_scenePresence.IsChildAgent) 413 if (m_scenePresence.IsChildAgent)
414 return; 414 return;
415 415
416 m_scenePresence.Scene.ForEachScenePresence( 416 UUID[] animIDs;
417 delegate(ScenePresence SP) 417 int[] sequenceNums;
418 { 418 UUID[] objectIDs;
419 SP.Animator.SendAnimPack(); 419
420 }); 420 m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs);
421 client.SendAnimations(animIDs, sequenceNums, m_scenePresence.ControllingClient.AgentId, objectIDs);
421 } 422 }
422 423
423 /// <summary> 424 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs
index 9a7863b..c08b961 100644
--- a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs
+++ b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs
@@ -32,6 +32,7 @@ using System.Timers;
32using log4net; 32using log4net;
33using OpenMetaverse; 33using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Region.Framework.Interfaces;
35 36
36namespace OpenSim.Region.Framework.Scenes 37namespace OpenSim.Region.Framework.Scenes
37{ 38{
@@ -137,7 +138,9 @@ namespace OpenSim.Region.Framework.Scenes
137 138
138 try 139 try
139 { 140 {
140 m_scene.DeleteToInventory(x.action, x.folderID, x.objectGroup, x.remoteClient); 141 IInventoryAccessModule invAccess = m_scene.RequestModuleInterface<IInventoryAccessModule>();
142 if (invAccess != null)
143 invAccess.DeleteToInventory(x.action, x.folderID, x.objectGroup, x.remoteClient);
141 if (x.permissionToDelete) 144 if (x.permissionToDelete)
142 m_scene.DeleteSceneObject(x.objectGroup, false); 145 m_scene.DeleteSceneObject(x.objectGroup, false);
143 } 146 }
diff --git a/OpenSim/Region/Framework/Scenes/EventManager.cs b/OpenSim/Region/Framework/Scenes/EventManager.cs
index 7fb1cd8..ef125cd 100644
--- a/OpenSim/Region/Framework/Scenes/EventManager.cs
+++ b/OpenSim/Region/Framework/Scenes/EventManager.cs
@@ -66,13 +66,16 @@ namespace OpenSim.Region.Framework.Scenes
66 public event OnClientConnectCoreDelegate OnClientConnect; 66 public event OnClientConnectCoreDelegate OnClientConnect;
67 67
68 public delegate void OnNewClientDelegate(IClientAPI client); 68 public delegate void OnNewClientDelegate(IClientAPI client);
69 69
70 /// <summary> 70 /// <summary>
71 /// Deprecated in favour of OnClientConnect. 71 /// Deprecated in favour of OnClientConnect.
72 /// Will be marked Obsolete after IClientCore has 100% of IClientAPI interfaces. 72 /// Will be marked Obsolete after IClientCore has 100% of IClientAPI interfaces.
73 /// </summary> 73 /// </summary>
74 public event OnNewClientDelegate OnNewClient; 74 public event OnNewClientDelegate OnNewClient;
75 75
76 public delegate void OnClientLoginDelegate(IClientAPI client);
77 public event OnClientLoginDelegate OnClientLogin;
78
76 public delegate void OnNewPresenceDelegate(ScenePresence presence); 79 public delegate void OnNewPresenceDelegate(ScenePresence presence);
77 80
78 public event OnNewPresenceDelegate OnNewPresence; 81 public event OnNewPresenceDelegate OnNewPresence;
@@ -107,12 +110,12 @@ namespace OpenSim.Region.Framework.Scenes
107 public event OnSetRootAgentSceneDelegate OnSetRootAgentScene; 110 public event OnSetRootAgentSceneDelegate OnSetRootAgentScene;
108 111
109 /// <summary> 112 /// <summary>
110 /// Called when an object is touched/grabbed. 113 /// Fired when an object is touched/grabbed.
111 /// </summary> 114 /// </summary>
112 /// The originalID is the local ID of the part that was actually touched. The localID itself is always that of 115 /// The originalID is the local ID of the part that was actually touched. The localID itself is always that of
113 /// the root part. 116 /// the root part.
114 public delegate void ObjectGrabDelegate(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs);
115 public event ObjectGrabDelegate OnObjectGrab; 117 public event ObjectGrabDelegate OnObjectGrab;
118 public delegate void ObjectGrabDelegate(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs);
116 119
117 public event ObjectGrabDelegate OnObjectGrabbing; 120 public event ObjectGrabDelegate OnObjectGrabbing;
118 public event ObjectDeGrabDelegate OnObjectDeGrab; 121 public event ObjectDeGrabDelegate OnObjectDeGrab;
@@ -120,8 +123,11 @@ namespace OpenSim.Region.Framework.Scenes
120 123
121 public event OnPermissionErrorDelegate OnPermissionError; 124 public event OnPermissionErrorDelegate OnPermissionError;
122 125
123 public delegate void NewRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource); 126 /// <summary>
127 /// Fired when a new script is created.
128 /// </summary>
124 public event NewRezScript OnRezScript; 129 public event NewRezScript OnRezScript;
130 public delegate void NewRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource);
125 131
126 public delegate void RemoveScript(uint localID, UUID itemID); 132 public delegate void RemoveScript(uint localID, UUID itemID);
127 public event RemoveScript OnRemoveScript; 133 public event RemoveScript OnRemoveScript;
@@ -165,36 +171,33 @@ namespace OpenSim.Region.Framework.Scenes
165 171
166 public event ClientClosed OnClientClosed; 172 public event ClientClosed OnClientClosed;
167 173
168 public delegate void ScriptChangedEvent(uint localID, uint change); 174 /// <summary>
169 175 /// This is fired when a scene object property that a script might be interested in (such as color, scale or
176 /// inventory) changes. Only enough information is sent for the LSL changed event
177 /// (see http://lslwiki.net/lslwiki/wakka.php?wakka=changed)
178 /// </summary>
170 public event ScriptChangedEvent OnScriptChangedEvent; 179 public event ScriptChangedEvent OnScriptChangedEvent;
180 public delegate void ScriptChangedEvent(uint localID, uint change);
171 181
172 public delegate void ScriptControlEvent(uint localID, UUID item, UUID avatarID, uint held, uint changed); 182 public delegate void ScriptControlEvent(uint localID, UUID item, UUID avatarID, uint held, uint changed);
173
174 public event ScriptControlEvent OnScriptControlEvent; 183 public event ScriptControlEvent OnScriptControlEvent;
175 184
176 public delegate void ScriptAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 atpos); 185 public delegate void ScriptAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 atpos);
177
178 public event ScriptAtTargetEvent OnScriptAtTargetEvent; 186 public event ScriptAtTargetEvent OnScriptAtTargetEvent;
179 187
180 public delegate void ScriptNotAtTargetEvent(uint localID); 188 public delegate void ScriptNotAtTargetEvent(uint localID);
181
182 public event ScriptNotAtTargetEvent OnScriptNotAtTargetEvent; 189 public event ScriptNotAtTargetEvent OnScriptNotAtTargetEvent;
183 190
184 public delegate void ScriptAtRotTargetEvent(uint localID, uint handle, Quaternion targetrot, Quaternion atrot); 191 public delegate void ScriptAtRotTargetEvent(uint localID, uint handle, Quaternion targetrot, Quaternion atrot);
185
186 public event ScriptAtRotTargetEvent OnScriptAtRotTargetEvent; 192 public event ScriptAtRotTargetEvent OnScriptAtRotTargetEvent;
187 193
188 public delegate void ScriptNotAtRotTargetEvent(uint localID); 194 public delegate void ScriptNotAtRotTargetEvent(uint localID);
189
190 public event ScriptNotAtRotTargetEvent OnScriptNotAtRotTargetEvent; 195 public event ScriptNotAtRotTargetEvent OnScriptNotAtRotTargetEvent;
191 196
192 public delegate void ScriptColliding(uint localID, ColliderArgs colliders); 197 public delegate void ScriptColliding(uint localID, ColliderArgs colliders);
193
194 public event ScriptColliding OnScriptColliderStart; 198 public event ScriptColliding OnScriptColliderStart;
195 public event ScriptColliding OnScriptColliding; 199 public event ScriptColliding OnScriptColliding;
196 public event ScriptColliding OnScriptCollidingEnd; 200 public event ScriptColliding OnScriptCollidingEnd;
197
198 public event ScriptColliding OnScriptLandColliderStart; 201 public event ScriptColliding OnScriptLandColliderStart;
199 public event ScriptColliding OnScriptLandColliding; 202 public event ScriptColliding OnScriptLandColliding;
200 public event ScriptColliding OnScriptLandColliderEnd; 203 public event ScriptColliding OnScriptLandColliderEnd;
@@ -204,7 +207,7 @@ namespace OpenSim.Region.Framework.Scenes
204 207
205 public delegate void OnMakeRootAgentDelegate(ScenePresence presence); 208 public delegate void OnMakeRootAgentDelegate(ScenePresence presence);
206 public delegate void OnSaveNewWindlightProfileDelegate(); 209 public delegate void OnSaveNewWindlightProfileDelegate();
207 public delegate void OnSendNewWindlightProfileTargetedDelegate(RegionMeta7WindlightData wl, UUID user); 210 public delegate void OnSendNewWindlightProfileTargetedDelegate(RegionLightShareData wl, UUID user);
208 public event OnMakeRootAgentDelegate OnMakeRootAgent; 211 public event OnMakeRootAgentDelegate OnMakeRootAgent;
209 public event OnSendNewWindlightProfileTargetedDelegate OnSendNewWindlightProfileTargeted; 212 public event OnSendNewWindlightProfileTargetedDelegate OnSendNewWindlightProfileTargeted;
210 public event OnSaveNewWindlightProfileDelegate OnSaveNewWindlightProfile; 213 public event OnSaveNewWindlightProfileDelegate OnSaveNewWindlightProfile;
@@ -587,6 +590,28 @@ namespace OpenSim.Region.Framework.Scenes
587 } 590 }
588 } 591 }
589 592
593 public void TriggerOnClientLogin(IClientAPI client)
594 {
595 OnClientLoginDelegate handlerClientLogin = OnClientLogin;
596 if (handlerClientLogin != null)
597 {
598 foreach (OnClientLoginDelegate d in handlerClientLogin.GetInvocationList())
599 {
600 try
601 {
602 d(client);
603 }
604 catch (Exception e)
605 {
606 m_log.ErrorFormat(
607 "[EVENT MANAGER]: Delegate for TriggerOnClientLogin failed - continuing. {0} {1}",
608 e.Message, e.StackTrace);
609 }
610 }
611 }
612
613 }
614
590 public void TriggerOnNewPresence(ScenePresence presence) 615 public void TriggerOnNewPresence(ScenePresence presence)
591 { 616 {
592 OnNewPresenceDelegate handlerNewPresence = OnNewPresence; 617 OnNewPresenceDelegate handlerNewPresence = OnNewPresence;
@@ -1195,7 +1220,7 @@ namespace OpenSim.Region.Framework.Scenes
1195 } 1220 }
1196 } 1221 }
1197 1222
1198 public void TriggerOnSendNewWindlightProfileTargeted(RegionMeta7WindlightData wl, UUID user) 1223 public void TriggerOnSendNewWindlightProfileTargeted(RegionLightShareData wl, UUID user)
1199 { 1224 {
1200 OnSendNewWindlightProfileTargetedDelegate handlerSendNewWindlightProfileTargeted = OnSendNewWindlightProfileTargeted; 1225 OnSendNewWindlightProfileTargetedDelegate handlerSendNewWindlightProfileTargeted = OnSendNewWindlightProfileTargeted;
1201 if (handlerSendNewWindlightProfileTargeted != null) 1226 if (handlerSendNewWindlightProfileTargeted != null)
diff --git a/OpenSim/Region/Framework/Scenes/Hypergrid/HGAssetMapper.cs b/OpenSim/Region/Framework/Scenes/Hypergrid/HGAssetMapper.cs
deleted file mode 100644
index ec50598..0000000
--- a/OpenSim/Region/Framework/Scenes/Hypergrid/HGAssetMapper.cs
+++ /dev/null
@@ -1,265 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using System.Threading;
32using log4net;
33using OpenMetaverse;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications.Cache;
36using OpenSim.Framework.Communications.Clients;
37using OpenSim.Region.Framework.Scenes.Serialization;
38using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Services.Interfaces;
40
41//using HyperGrid.Framework;
42//using OpenSim.Region.Communications.Hypergrid;
43
44namespace OpenSim.Region.Framework.Scenes.Hypergrid
45{
46 public class HGAssetMapper
47 {
48 #region Fields
49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 // This maps between inventory server urls and inventory server clients
52// private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
53
54 private Scene m_scene;
55
56 private IHyperAssetService m_hyper;
57 IHyperAssetService HyperlinkAssets
58 {
59 get
60 {
61 if (m_hyper == null)
62 m_hyper = m_scene.RequestModuleInterface<IHyperAssetService>();
63 return m_hyper;
64 }
65 }
66
67 #endregion
68
69 #region Constructor
70
71 public HGAssetMapper(Scene scene)
72 {
73 m_scene = scene;
74 }
75
76 #endregion
77
78 #region Internal functions
79
80// private string UserAssetURL(UUID userID)
81// {
82// CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
83// if (uinfo != null)
84// return (uinfo.UserProfile.UserAssetURI == "") ? null : uinfo.UserProfile.UserAssetURI;
85// return null;
86// }
87
88// private string UserInventoryURL(UUID userID)
89// {
90// CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
91// if (uinfo != null)
92// return (uinfo.UserProfile.UserInventoryURI == "") ? null : uinfo.UserProfile.UserInventoryURI;
93// return null;
94// }
95
96
97 public AssetBase FetchAsset(string url, UUID assetID)
98 {
99 AssetBase asset = m_scene.AssetService.Get(url + "/" + assetID.ToString());
100
101 if (asset != null)
102 {
103 m_log.DebugFormat("[HGScene]: Copied asset {0} from {1} to local asset server. ", asset.ID, url);
104 return asset;
105 }
106 return null;
107 }
108
109 public bool PostAsset(string url, AssetBase asset)
110 {
111 if (asset != null)
112 {
113 // See long comment in AssetCache.AddAsset
114 if (!asset.Temporary || asset.Local)
115 {
116 // We need to copy the asset into a new asset, because
117 // we need to set its ID to be URL+UUID, so that the
118 // HGAssetService dispatches it to the remote grid.
119 // It's not pretty, but the best that can be done while
120 // not having a global naming infrastructure
121 AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type);
122 Copy(asset, asset1);
123 try
124 {
125 asset1.ID = url + "/" + asset.ID;
126 }
127 catch
128 {
129 m_log.Warn("[HGScene]: Oops.");
130 }
131
132 m_scene.AssetService.Store(asset1);
133 m_log.DebugFormat("[HGScene]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
134 }
135 return true;
136 }
137 else
138 m_log.Warn("[HGScene]: Tried to post asset to remote server, but asset not in local cache.");
139
140 return false;
141 }
142
143 private void Copy(AssetBase from, AssetBase to)
144 {
145 to.Data = from.Data;
146 to.Description = from.Description;
147 to.FullID = from.FullID;
148 to.ID = from.ID;
149 to.Local = from.Local;
150 to.Name = from.Name;
151 to.Temporary = from.Temporary;
152 to.Type = from.Type;
153
154 }
155
156 // TODO: unused
157 // private void Dump(Dictionary<UUID, bool> lst)
158 // {
159 // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
160 // foreach (KeyValuePair<UUID, bool> kvp in lst)
161 // m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
162 // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
163 // }
164
165 #endregion
166
167
168 #region Public interface
169
170 public void Get(UUID assetID, UUID ownerID)
171 {
172 // Get the item from the remote asset server onto the local AssetCache
173 // and place an entry in m_assetMap
174
175 string userAssetURL = HyperlinkAssets.GetUserAssetServer(ownerID);
176 if ((userAssetURL != string.Empty) && (userAssetURL != HyperlinkAssets.GetSimAssetServer()))
177 {
178 m_log.Debug("[HGScene]: Fetching object " + assetID + " from asset server " + userAssetURL);
179 AssetBase asset = FetchAsset(userAssetURL, assetID);
180
181 if (asset != null)
182 {
183 // OK, now fetch the inside.
184 Dictionary<UUID, int> ids = new Dictionary<UUID, int>();
185 HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL);
186 uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
187 foreach (UUID uuid in ids.Keys)
188 FetchAsset(userAssetURL, uuid);
189
190 m_log.DebugFormat("[HGScene]: Successfully fetched asset {0} from asset server {1}", asset.ID, userAssetURL);
191
192 }
193 else
194 m_log.Warn("[HGScene]: Could not fetch asset from remote asset server " + userAssetURL);
195 }
196 else
197 m_log.Debug("[HGScene]: user's asset server is the local region's asset server");
198 }
199
200 //public InventoryItemBase Get(InventoryItemBase item, UUID rootFolder, CachedUserInfo userInfo)
201 //{
202 // InventoryClient invCli = null;
203 // string inventoryURL = UserInventoryURL(item.Owner);
204 // if (!m_inventoryServers.TryGetValue(inventoryURL, out invCli))
205 // {
206 // m_log.Debug("[HGScene]: Starting new InventorytClient for " + inventoryURL);
207 // invCli = new InventoryClient(inventoryURL);
208 // m_inventoryServers.Add(inventoryURL, invCli);
209 // }
210
211 // item = invCli.GetInventoryItem(item);
212 // if (item != null)
213 // {
214 // // Change the folder, stick it in root folder, all items flattened out here in this region cache
215 // item.Folder = rootFolder;
216 // //userInfo.AddItem(item); don't use this, it calls back to the inventory server
217 // lock (userInfo.RootFolder.Items)
218 // {
219 // userInfo.RootFolder.Items[item.ID] = item;
220 // }
221
222 // }
223 // return item;
224 //}
225
226 public void Post(UUID assetID, UUID ownerID)
227 {
228 // Post the item from the local AssetCache onto the remote asset server
229 // and place an entry in m_assetMap
230
231 string userAssetURL = HyperlinkAssets.GetUserAssetServer(ownerID);
232 if ((userAssetURL != string.Empty) && (userAssetURL != HyperlinkAssets.GetSimAssetServer()))
233 {
234 m_log.Debug("[HGScene]: Posting object " + assetID + " to asset server " + userAssetURL);
235 AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
236 if (asset != null)
237 {
238 Dictionary<UUID, int> ids = new Dictionary<UUID, int>();
239 HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, string.Empty);
240 uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
241 foreach (UUID uuid in ids.Keys)
242 {
243 asset = m_scene.AssetService.Get(uuid.ToString());
244 if (asset == null)
245 m_log.DebugFormat("[HGScene]: Could not find asset {0}", uuid);
246 else
247 PostAsset(userAssetURL, asset);
248 }
249
250 // maybe all pieces got there...
251 m_log.DebugFormat("[HGScene]: Successfully posted item {0} to asset server {1}", assetID, userAssetURL);
252
253 }
254 else
255 m_log.DebugFormat("[HGScene]: Something wrong with asset {0}, it could not be found", assetID);
256 }
257 else
258 m_log.Debug("[HGScene]: user's asset server is local region's asset server");
259
260 }
261
262 #endregion
263
264 }
265}
diff --git a/OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.cs b/OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.cs
deleted file mode 100644
index b1981b6..0000000
--- a/OpenSim/Region/Framework/Scenes/Hypergrid/HGScene.cs
+++ /dev/null
@@ -1,77 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using OpenMetaverse;
29using OpenSim.Framework;
30using OpenSim.Framework.Communications.Cache;
31using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
32using GridRegion = OpenSim.Services.Interfaces.GridRegion;
33
34namespace OpenSim.Region.Framework.Scenes.Hypergrid
35{
36 public partial class HGScene : Scene
37 {
38 /// <summary>
39 /// Teleport an avatar to their home region
40 /// </summary>
41 /// <param name="agentId"></param>
42 /// <param name="client"></param>
43 public override void TeleportClientHome(UUID agentId, IClientAPI client)
44 {
45 m_log.Debug("[HGScene]: TeleportClientHome " + client.FirstName + " " + client.LastName);
46
47 CachedUserInfo uinfo = CommsManager.UserProfileCacheService.GetUserDetails(agentId);
48 if (uinfo != null)
49 {
50 UserProfileData UserProfile = uinfo.UserProfile;
51
52 if (UserProfile != null)
53 {
54 GridRegion regionInfo = GridService.GetRegionByUUID(UUID.Zero, UserProfile.HomeRegionID);
55 //if (regionInfo != null)
56 //{
57 // UserProfile.HomeRegionID = regionInfo.RegionID;
58 // //CommsManager.UserService.UpdateUserProfile(UserProfile);
59 //}
60 if (regionInfo == null)
61 {
62 // can't find the Home region: Tell viewer and abort
63 client.SendTeleportFailed("Your home-region could not be found.");
64 return;
65 }
66 RequestTeleportLocation(
67 client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
68 (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
69 }
70 }
71 else
72 client.SendTeleportFailed("Sorry! I lost your home-region information.");
73
74 }
75
76 }
77}
diff --git a/OpenSim/Region/Framework/Scenes/Hypergrid/HGSceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/Hypergrid/HGSceneCommunicationService.cs
deleted file mode 100644
index 416826c..0000000
--- a/OpenSim/Region/Framework/Scenes/Hypergrid/HGSceneCommunicationService.cs
+++ /dev/null
@@ -1,391 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Reflection;
32using System.Threading;
33using log4net;
34using OpenMetaverse;
35using OpenSim.Framework;
36using OpenSim.Framework.Client;
37using OpenSim.Framework.Communications;
38using OpenSim.Framework.Communications.Cache;
39using OpenSim.Framework.Capabilities;
40using OpenSim.Region.Framework.Interfaces;
41using OpenSim.Services.Interfaces;
42using GridRegion = OpenSim.Services.Interfaces.GridRegion;
43
44namespace OpenSim.Region.Framework.Scenes.Hypergrid
45{
46 public class HGSceneCommunicationService : SceneCommunicationService
47 {
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49
50 private IHyperlinkService m_hg;
51 IHyperlinkService HyperlinkService
52 {
53 get
54 {
55 if (m_hg == null)
56 m_hg = m_scene.RequestModuleInterface<IHyperlinkService>();
57 return m_hg;
58 }
59 }
60
61 public HGSceneCommunicationService(CommunicationsManager commsMan) : base(commsMan)
62 {
63 }
64
65
66 /// <summary>
67 /// Try to teleport an agent to a new region.
68 /// </summary>
69 /// <param name="remoteClient"></param>
70 /// <param name="RegionHandle"></param>
71 /// <param name="position"></param>
72 /// <param name="lookAt"></param>
73 /// <param name="flags"></param>
74 public override void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
75 Vector3 lookAt, uint teleportFlags)
76 {
77 if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
78 return;
79
80 bool destRegionUp = true;
81
82 IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
83
84 // Reset animations; the viewer does that in teleports.
85 avatar.Animator.ResetAnimations();
86
87 if (regionHandle == m_regionInfo.RegionHandle)
88 {
89 // Teleport within the same region
90 if (IsOutsideRegion(avatar.Scene, position) || position.Z < 0)
91 {
92 Vector3 emergencyPos = new Vector3(128, 128, 128);
93
94 m_log.WarnFormat(
95 "[HGSceneCommService]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
96 position, avatar.Name, avatar.UUID, emergencyPos);
97 position = emergencyPos;
98 }
99 // TODO: Get proper AVG Height
100 float localAVHeight = 1.56f;
101
102 float posZLimit = 22;
103
104 if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
105 {
106 posZLimit = (float) avatar.Scene.Heightmap[(int) position.X, (int) position.Y];
107 }
108
109 float newPosZ = posZLimit + localAVHeight;
110 if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
111 {
112 position.Z = newPosZ;
113 }
114
115 // Only send this if the event queue is null
116 if (eq == null)
117 avatar.ControllingClient.SendTeleportLocationStart();
118
119
120 avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
121 avatar.Teleport(position);
122 }
123 else
124 {
125 uint x = 0, y = 0;
126 Utils.LongToUInts(regionHandle, out x, out y);
127 GridRegion reg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
128
129 if (reg != null)
130 {
131
132 uint newRegionX = (uint)(reg.RegionHandle >> 40);
133 uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
134 uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
135 uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
136
137 ///
138 /// Hypergrid mod start
139 ///
140 ///
141 bool isHyperLink = (HyperlinkService.GetHyperlinkRegion(reg.RegionHandle) != null);
142 bool isHomeUser = true;
143 ulong realHandle = regionHandle;
144 CachedUserInfo uinfo = m_commsProvider.UserProfileCacheService.GetUserDetails(avatar.UUID);
145 if (uinfo != null)
146 {
147 isHomeUser = HyperlinkService.IsLocalUser(uinfo.UserProfile.ID);
148 realHandle = m_hg.FindRegionHandle(regionHandle);
149 m_log.Debug("XXX ---- home user? " + isHomeUser + " --- hyperlink? " + isHyperLink + " --- real handle: " + realHandle.ToString());
150 }
151 ///
152 /// Hypergrid mod stop
153 ///
154 ///
155
156 if (eq == null)
157 avatar.ControllingClient.SendTeleportLocationStart();
158
159
160 // Let's do DNS resolution only once in this process, please!
161 // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
162 // it's actually doing a lot of work.
163 IPEndPoint endPoint = reg.ExternalEndPoint;
164 if (endPoint.Address == null)
165 {
166 // Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
167 destRegionUp = false;
168 }
169
170 if (destRegionUp)
171 {
172 // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
173 // both regions
174 if (avatar.ParentID != (uint)0)
175 avatar.StandUp();
176
177 if (!avatar.ValidateAttachments())
178 {
179 avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
180 return;
181 }
182
183 // the avatar.Close below will clear the child region list. We need this below for (possibly)
184 // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
185 //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
186 // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
187 // failure at this point (unlike a border crossing failure). So perhaps this can never fail
188 // once we reach here...
189 //avatar.Scene.RemoveCapsHandler(avatar.UUID);
190
191 string capsPath = String.Empty;
192 AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
193 agentCircuit.BaseFolder = UUID.Zero;
194 agentCircuit.InventoryFolder = UUID.Zero;
195 agentCircuit.startpos = position;
196 agentCircuit.child = true;
197 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
198 {
199 // brand new agent, let's create a new caps seed
200 agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
201 }
202
203 string reason = String.Empty;
204
205 //if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
206 if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, teleportFlags, out reason))
207 {
208 avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
209 reason));
210 return;
211 }
212
213 // Let's close some agents
214 if (isHyperLink) // close them all except this one
215 {
216 List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
217 regions.Remove(avatar.Scene.RegionInfo.RegionHandle);
218 SendCloseChildAgentConnections(avatar.UUID, regions);
219 }
220 else // close just a few
221 avatar.CloseChildAgents(newRegionX, newRegionY);
222
223 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY) || isHyperLink)
224 {
225 capsPath
226 = "http://"
227 + reg.ExternalHostName
228 + ":"
229 + reg.HttpPort
230 + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
231
232 if (eq != null)
233 {
234 #region IP Translation for NAT
235 IClientIPEndpoint ipepClient;
236 if (avatar.ClientView.TryGet(out ipepClient))
237 {
238 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
239 }
240 #endregion
241
242 eq.EnableSimulator(realHandle, endPoint, avatar.UUID);
243
244 // ES makes the client send a UseCircuitCode message to the destination,
245 // which triggers a bunch of things there.
246 // So let's wait
247 Thread.Sleep(2000);
248
249 eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
250 }
251 else
252 {
253 avatar.ControllingClient.InformClientOfNeighbour(realHandle, endPoint);
254 // TODO: make Event Queue disablable!
255 }
256 }
257 else
258 {
259 // child agent already there
260 agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
261 capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
262 + "/CAPS/" + agentCircuit.CapsPath + "0000/";
263 }
264
265 //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
266 // position, false);
267
268 //if (!m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
269 // position, false))
270 //{
271 // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
272 // // We should close that agent we just created over at destination...
273 // List<ulong> lst = new List<ulong>();
274 // lst.Add(realHandle);
275 // SendCloseChildAgentAsync(avatar.UUID, lst);
276 // return;
277 //}
278
279 SetInTransit(avatar.UUID);
280 // Let's send a full update of the agent. This is a synchronous call.
281 AgentData agent = new AgentData();
282 avatar.CopyTo(agent);
283 agent.Position = position;
284 agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
285 "/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
286
287 m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
288
289 m_log.DebugFormat(
290 "[CAPS]: Sending new CAPS seed url {0} to client {1}", agentCircuit.CapsPath, avatar.UUID);
291
292
293 ///
294 /// Hypergrid mod: realHandle instead of reg.RegionHandle
295 ///
296 ///
297 if (eq != null)
298 {
299 eq.TeleportFinishEvent(realHandle, 13, endPoint,
300 4, teleportFlags, capsPath, avatar.UUID);
301 }
302 else
303 {
304 avatar.ControllingClient.SendRegionTeleport(realHandle, 13, endPoint, 4,
305 teleportFlags, capsPath);
306 }
307 ///
308 /// Hypergrid mod stop
309 ///
310
311
312 // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
313 // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
314 // that the client contacted the destination before we send the attachments and close things here.
315 if (!WaitForCallback(avatar.UUID))
316 {
317 // Client never contacted destination. Let's restore everything back
318 avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
319
320 ResetFromTransit(avatar.UUID);
321 // Yikes! We should just have a ref to scene here.
322 avatar.Scene.InformClientOfNeighbours(avatar);
323
324 // Finally, kill the agent we just created at the destination.
325 m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
326
327 return;
328 }
329
330 // Can't go back from here
331 if (KiPrimitive != null)
332 {
333 KiPrimitive(avatar.LocalId);
334 }
335
336 avatar.MakeChildAgent();
337
338 // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
339 avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
340
341
342 // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
343 ///
344 /// Hypergrid mod: extra check for isHyperLink
345 ///
346 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY) || isHyperLink)
347 {
348 Thread.Sleep(5000);
349 avatar.Close();
350 CloseConnection(avatar.UUID);
351 }
352 // if (teleport success) // seems to be always success here
353 // the user may change their profile information in other region,
354 // so the userinfo in UserProfileCache is not reliable any more, delete it
355 if (avatar.Scene.NeedSceneCacheClear(avatar.UUID) || isHyperLink)
356 {
357 m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
358 m_log.DebugFormat(
359 "[HGSceneCommService]: User {0} is going to another region, profile cache removed",
360 avatar.UUID);
361 }
362 }
363 else
364 {
365 avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
366 }
367 }
368 else
369 {
370 // TP to a place that doesn't exist (anymore)
371 // Inform the viewer about that
372 avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
373
374 // and set the map-tile to '(Offline)'
375 uint regX, regY;
376 Utils.LongToUInts(regionHandle, out regX, out regY);
377
378 MapBlockData block = new MapBlockData();
379 block.X = (ushort)(regX / Constants.RegionSize);
380 block.Y = (ushort)(regY / Constants.RegionSize);
381 block.Access = 254; // == not there
382
383 List<MapBlockData> blocks = new List<MapBlockData>();
384 blocks.Add(block);
385 avatar.ControllingClient.SendMapBlock(blocks, 0);
386 }
387 }
388 }
389
390 }
391}
diff --git a/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs b/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
index e9660b1..d25d5dd 100644
--- a/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
+++ b/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
@@ -36,8 +36,7 @@ using OpenMetaverse;
36using OpenMetaverse.StructuredData; 36using OpenMetaverse.StructuredData;
37using OpenSim.Framework; 37using OpenSim.Framework;
38using OpenSim.Framework.Communications; 38using OpenSim.Framework.Communications;
39using OpenSim.Framework.Communications.Services; 39
40using OpenSim.Framework.Communications.Cache;
41using OpenSim.Framework.Console; 40using OpenSim.Framework.Console;
42using OpenSim.Framework.Servers; 41using OpenSim.Framework.Servers;
43using OpenSim.Framework.Servers.HttpServer; 42using OpenSim.Framework.Servers.HttpServer;
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
index e031ebc..386aab4 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
@@ -35,7 +35,6 @@ using OpenMetaverse;
35using OpenMetaverse.Packets; 35using OpenMetaverse.Packets;
36using log4net; 36using log4net;
37using OpenSim.Framework; 37using OpenSim.Framework;
38using OpenSim.Framework.Communications.Cache;
39using OpenSim.Region.Framework; 38using OpenSim.Region.Framework;
40using OpenSim.Region.Framework.Interfaces; 39using OpenSim.Region.Framework.Interfaces;
41using OpenSim.Region.Framework.Scenes.Serialization; 40using OpenSim.Region.Framework.Scenes.Serialization;
@@ -64,6 +63,7 @@ namespace OpenSim.Region.Framework.Scenes
64 if (group is SceneObjectGroup) 63 if (group is SceneObjectGroup)
65 { 64 {
66 ((SceneObjectGroup) group).CreateScriptInstances(0, false, DefaultScriptEngine, 0); 65 ((SceneObjectGroup) group).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
66 ((SceneObjectGroup) group).ResumeScripts();
67 } 67 }
68 } 68 }
69 } 69 }
@@ -94,6 +94,22 @@ namespace OpenSim.Region.Framework.Scenes
94 94
95 public void AddInventoryItem(UUID AgentID, InventoryItemBase item) 95 public void AddInventoryItem(UUID AgentID, InventoryItemBase item)
96 { 96 {
97 InventoryFolderBase folder;
98
99 if (item.Folder == UUID.Zero)
100 {
101 folder = InventoryService.GetFolderForType(AgentID, (AssetType)item.AssetType);
102 if (folder == null)
103 {
104 folder = InventoryService.GetRootFolder(AgentID);
105
106 if (folder == null)
107 return;
108 }
109
110 item.Folder = folder.ID;
111 }
112
97 if (InventoryService.AddItem(item)) 113 if (InventoryService.AddItem(item))
98 { 114 {
99 int userlevel = 0; 115 int userlevel = 0;
@@ -101,12 +117,6 @@ namespace OpenSim.Region.Framework.Scenes
101 { 117 {
102 userlevel = 1; 118 userlevel = 1;
103 } 119 }
104 // TODO: remove this cruft once MasterAvatar is fully deprecated
105 //
106 if (m_regInfo.MasterAvatarAssignedUUID == AgentID)
107 {
108 userlevel = 2;
109 }
110 EventManager.TriggerOnNewInventoryItemUploadComplete(AgentID, item.AssetID, item.Name, userlevel); 120 EventManager.TriggerOnNewInventoryItemUploadComplete(AgentID, item.AssetID, item.Name, userlevel);
111 } 121 }
112 else 122 else
@@ -132,70 +142,17 @@ namespace OpenSim.Region.Framework.Scenes
132 } 142 }
133 143
134 /// <summary> 144 /// <summary>
135 /// Capability originating call to update the asset of an item in an agent's inventory
136 /// </summary>
137 /// <param name="remoteClient"></param>
138 /// <param name="itemID"></param>
139 /// <param name="data"></param>
140 /// <returns></returns>
141 public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
142 {
143 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
144 item = InventoryService.GetItem(item);
145
146 if (item != null)
147 {
148 if ((InventoryType)item.InvType == InventoryType.Notecard)
149 {
150 if (!Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
151 {
152 remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
153 return UUID.Zero;
154 }
155
156 remoteClient.SendAgentAlertMessage("Notecard saved", false);
157 }
158 else if ((InventoryType)item.InvType == InventoryType.LSL)
159 {
160 if (!Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
161 {
162 remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
163 return UUID.Zero;
164 }
165
166 remoteClient.SendAgentAlertMessage("Script saved", false);
167 }
168
169 AssetBase asset =
170 CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data);
171 item.AssetID = asset.FullID;
172 AssetService.Store(asset);
173
174 InventoryService.UpdateItem(item);
175
176 // remoteClient.SendInventoryItemCreateUpdate(item);
177 return (asset.FullID);
178 }
179 else
180 {
181 m_log.ErrorFormat(
182 "[AGENT INVENTORY]: Could not find item {0} for caps inventory update",
183 itemID);
184 }
185
186 return UUID.Zero;
187 }
188
189 /// <summary>
190 /// <see>CapsUpdatedInventoryItemAsset(IClientAPI, UUID, byte[])</see> 145 /// <see>CapsUpdatedInventoryItemAsset(IClientAPI, UUID, byte[])</see>
191 /// </summary> 146 /// </summary>
192 public UUID CapsUpdateInventoryItemAsset(UUID avatarId, UUID itemID, byte[] data) 147 public UUID CapsUpdateInventoryItemAsset(UUID avatarId, UUID itemID, byte[] data)
193 { 148 {
194 ScenePresence avatar; 149 ScenePresence avatar;
195 150
196 if (TryGetAvatar(avatarId, out avatar)) 151 if (TryGetScenePresence(avatarId, out avatar))
197 { 152 {
198 return CapsUpdateInventoryItemAsset(avatar.ControllingClient, itemID, data); 153 IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
154 if (invAccess != null)
155 return invAccess.CapsUpdateInventoryItemAsset(avatar.ControllingClient, itemID, data);
199 } 156 }
200 else 157 else
201 { 158 {
@@ -251,7 +208,7 @@ namespace OpenSim.Region.Framework.Scenes
251 return new ArrayList(); 208 return new ArrayList();
252 } 209 }
253 210
254 AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)AssetType.LSLText, data); 211 AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)AssetType.LSLText, data, remoteClient.AgentId);
255 AssetService.Store(asset); 212 AssetService.Store(asset);
256 213
257 if (isScriptRunning) 214 if (isScriptRunning)
@@ -261,7 +218,9 @@ namespace OpenSim.Region.Framework.Scenes
261 218
262 // Update item with new asset 219 // Update item with new asset
263 item.AssetID = asset.FullID; 220 item.AssetID = asset.FullID;
264 group.UpdateInventoryItem(item); 221 if (group.UpdateInventoryItem(item))
222 remoteClient.SendAgentAlertMessage("Notecard saved", false);
223
265 part.GetProperties(remoteClient); 224 part.GetProperties(remoteClient);
266 225
267 // Trigger rerunning of script (use TriggerRezScript event, see RezScript) 226 // Trigger rerunning of script (use TriggerRezScript event, see RezScript)
@@ -277,6 +236,7 @@ namespace OpenSim.Region.Framework.Scenes
277 { 236 {
278 remoteClient.SendAgentAlertMessage("Script saved", false); 237 remoteClient.SendAgentAlertMessage("Script saved", false);
279 } 238 }
239 part.ParentGroup.ResumeScripts();
280 return errors; 240 return errors;
281 } 241 }
282 242
@@ -288,7 +248,7 @@ namespace OpenSim.Region.Framework.Scenes
288 { 248 {
289 ScenePresence avatar; 249 ScenePresence avatar;
290 250
291 if (TryGetAvatar(avatarId, out avatar)) 251 if (TryGetScenePresence(avatarId, out avatar))
292 { 252 {
293 return CapsUpdateTaskInventoryScriptAsset( 253 return CapsUpdateTaskInventoryScriptAsset(
294 avatar.ControllingClient, itemId, primId, isScriptRunning, data); 254 avatar.ControllingClient, itemId, primId, isScriptRunning, data);
@@ -470,6 +430,25 @@ namespace OpenSim.Region.Framework.Scenes
470 itemCopy.BasePermissions = item.BasePermissions; 430 itemCopy.BasePermissions = item.BasePermissions;
471 } 431 }
472 432
433 if (itemCopy.Folder == UUID.Zero)
434 {
435 InventoryFolderBase folder = InventoryService.GetFolderForType(recipient, (AssetType)itemCopy.AssetType);
436
437 if (folder != null)
438 {
439 itemCopy.Folder = folder.ID;
440 }
441 else
442 {
443 InventoryFolderBase root = InventoryService.GetRootFolder(recipient);
444
445 if (root != null)
446 itemCopy.Folder = root.ID;
447 else
448 return null; // No destination
449 }
450 }
451
473 itemCopy.GroupID = UUID.Zero; 452 itemCopy.GroupID = UUID.Zero;
474 itemCopy.GroupOwned = false; 453 itemCopy.GroupOwned = false;
475 itemCopy.Flags = item.Flags; 454 itemCopy.Flags = item.Flags;
@@ -477,7 +456,11 @@ namespace OpenSim.Region.Framework.Scenes
477 itemCopy.SaleType = item.SaleType; 456 itemCopy.SaleType = item.SaleType;
478 457
479 if (InventoryService.AddItem(itemCopy)) 458 if (InventoryService.AddItem(itemCopy))
480 TransferInventoryAssets(itemCopy, senderId, recipient); 459 {
460 IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
461 if (invAccess != null)
462 invAccess.TransferInventoryAssets(itemCopy, senderId, recipient);
463 }
481 464
482 if (!Permissions.BypassPermissions()) 465 if (!Permissions.BypassPermissions())
483 { 466 {
@@ -499,10 +482,6 @@ namespace OpenSim.Region.Framework.Scenes
499 482
500 } 483 }
501 484
502 protected virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
503 {
504 }
505
506 /// <summary> 485 /// <summary>
507 /// Give an entire inventory folder from one user to another. The entire contents (including all descendent 486 /// Give an entire inventory folder from one user to another. The entire contents (including all descendent
508 /// folders) is given. 487 /// folders) is given.
@@ -530,7 +509,6 @@ namespace OpenSim.Region.Framework.Scenes
530 return null; 509 return null;
531 } 510 }
532 511
533
534 if (recipientParentFolderId == UUID.Zero) 512 if (recipientParentFolderId == UUID.Zero)
535 { 513 {
536 InventoryFolderBase recipientRootFolder = InventoryService.GetRootFolder(recipientId); 514 InventoryFolderBase recipientRootFolder = InventoryService.GetRootFolder(recipientId);
@@ -572,7 +550,9 @@ namespace OpenSim.Region.Framework.Scenes
572 "[AGENT INVENTORY]: CopyInventoryItem received by {0} with oldAgentID {1}, oldItemID {2}, new FolderID {3}, newName {4}", 550 "[AGENT INVENTORY]: CopyInventoryItem received by {0} with oldAgentID {1}, oldItemID {2}, new FolderID {3}, newName {4}",
573 remoteClient.AgentId, oldAgentID, oldItemID, newFolderID, newName); 551 remoteClient.AgentId, oldAgentID, oldItemID, newFolderID, newName);
574 552
575 InventoryItemBase item = CommsManager.UserProfileCacheService.LibraryRoot.FindItem(oldItemID); 553 InventoryItemBase item = null;
554 if (LibraryService != null && LibraryService.LibraryRootFolder != null)
555 item = LibraryService.LibraryRootFolder.FindItem(oldItemID);
576 556
577 if (item == null) 557 if (item == null)
578 { 558 {
@@ -626,15 +606,9 @@ namespace OpenSim.Region.Framework.Scenes
626 /// <summary> 606 /// <summary>
627 /// Create a new asset data structure. 607 /// Create a new asset data structure.
628 /// </summary> 608 /// </summary>
629 /// <param name="name"></param> 609 private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, UUID creatorID)
630 /// <param name="description"></param>
631 /// <param name="invType"></param>
632 /// <param name="assetType"></param>
633 /// <param name="data"></param>
634 /// <returns></returns>
635 private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data)
636 { 610 {
637 AssetBase asset = new AssetBase(UUID.Random(), name, assetType); 611 AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID.ToString());
638 asset.Description = description; 612 asset.Description = description;
639 asset.Data = (data == null) ? new byte[1] : data; 613 asset.Data = (data == null) ? new byte[1] : data;
640 614
@@ -744,13 +718,9 @@ namespace OpenSim.Region.Framework.Scenes
744 718
745 if (transactionID == UUID.Zero) 719 if (transactionID == UUID.Zero)
746 { 720 {
747 CachedUserInfo userInfo 721 ScenePresence presence;
748 = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); 722 if (TryGetScenePresence(remoteClient.AgentId, out presence))
749
750 if (userInfo != null)
751 { 723 {
752 ScenePresence presence;
753 TryGetAvatar(remoteClient.AgentId, out presence);
754 byte[] data = null; 724 byte[] data = null;
755 725
756 if (invType == (sbyte)InventoryType.Landmark && presence != null) 726 if (invType == (sbyte)InventoryType.Landmark && presence != null)
@@ -764,7 +734,7 @@ namespace OpenSim.Region.Framework.Scenes
764 data = Encoding.ASCII.GetBytes(strdata); 734 data = Encoding.ASCII.GetBytes(strdata);
765 } 735 }
766 736
767 AssetBase asset = CreateAsset(name, description, assetType, data); 737 AssetBase asset = CreateAsset(name, description, assetType, data, remoteClient.AgentId);
768 AssetService.Store(asset); 738 AssetService.Store(asset);
769 739
770 CreateNewInventoryItem(remoteClient, remoteClient.AgentId.ToString(), folderID, asset.Name, 0, callbackID, asset, invType, nextOwnerMask, creationDate); 740 CreateNewInventoryItem(remoteClient, remoteClient.AgentId.ToString(), folderID, asset.Name, 0, callbackID, asset, invType, nextOwnerMask, creationDate);
@@ -772,7 +742,7 @@ namespace OpenSim.Region.Framework.Scenes
772 else 742 else
773 { 743 {
774 m_log.ErrorFormat( 744 m_log.ErrorFormat(
775 "userInfo for agent uuid {0} unexpectedly null in CreateNewInventoryItem", 745 "ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem",
776 remoteClient.AgentId); 746 remoteClient.AgentId);
777 } 747 }
778 } 748 }
@@ -788,6 +758,37 @@ namespace OpenSim.Region.Framework.Scenes
788 } 758 }
789 } 759 }
790 760
761 private void HandleLinkInventoryItem(IClientAPI remoteClient, UUID transActionID, UUID folderID,
762 uint callbackID, string description, string name,
763 sbyte invType, sbyte type, UUID olditemID)
764 {
765 m_log.DebugFormat("[AGENT INVENTORY]: Received request to create inventory item link {0} in folder {1} pointing to {2}", name, folderID, olditemID);
766
767 if (!Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
768 return;
769
770 ScenePresence presence;
771 if (TryGetScenePresence(remoteClient.AgentId, out presence))
772 {
773 byte[] data = null;
774
775 AssetBase asset = new AssetBase();
776 asset.FullID = olditemID;
777 asset.Type = type;
778 asset.Name = name;
779 asset.Description = description;
780
781 CreateNewInventoryItem(remoteClient, remoteClient.AgentId.ToString(), folderID, name, 0, callbackID, asset, invType, (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, Util.UnixTimeSinceEpoch());
782
783 }
784 else
785 {
786 m_log.ErrorFormat(
787 "ScenePresence for agent uuid {0} unexpectedly not found in HandleLinkInventoryItem",
788 remoteClient.AgentId);
789 }
790 }
791
791 /// <summary> 792 /// <summary>
792 /// Remove an inventory item for the client's inventory 793 /// Remove an inventory item for the client's inventory
793 /// </summary> 794 /// </summary>
@@ -1011,7 +1012,7 @@ namespace OpenSim.Region.Framework.Scenes
1011 { 1012 {
1012 ScenePresence avatar; 1013 ScenePresence avatar;
1013 1014
1014 if (TryGetAvatar(avatarId, out avatar)) 1015 if (TryGetScenePresence(avatarId, out avatar))
1015 { 1016 {
1016 return MoveTaskInventoryItem(avatar.ControllingClient, folderId, part, itemId); 1017 return MoveTaskInventoryItem(avatar.ControllingClient, folderId, part, itemId);
1017 } 1018 }
@@ -1125,7 +1126,7 @@ namespace OpenSim.Region.Framework.Scenes
1125 1126
1126 ScenePresence avatar; 1127 ScenePresence avatar;
1127 1128
1128 if (TryGetAvatar(srcTaskItem.OwnerID, out avatar)) 1129 if (TryGetScenePresence(srcTaskItem.OwnerID, out avatar))
1129 { 1130 {
1130 destPart.GetProperties(avatar.ControllingClient); 1131 destPart.GetProperties(avatar.ControllingClient);
1131 } 1132 }
@@ -1153,7 +1154,7 @@ namespace OpenSim.Region.Framework.Scenes
1153 } 1154 }
1154 1155
1155 ScenePresence avatar = null; 1156 ScenePresence avatar = null;
1156 if (TryGetAvatar(destID, out avatar)) 1157 if (TryGetScenePresence(destID, out avatar))
1157 { 1158 {
1158 //profile.SendInventoryDecendents(avatar.ControllingClient, 1159 //profile.SendInventoryDecendents(avatar.ControllingClient,
1159 // profile.RootFolder.ID, true, false); 1160 // profile.RootFolder.ID, true, false);
@@ -1169,15 +1170,36 @@ namespace OpenSim.Region.Framework.Scenes
1169 1170
1170 private void SendInventoryUpdate(IClientAPI client, InventoryFolderBase folder, bool fetchFolders, bool fetchItems) 1171 private void SendInventoryUpdate(IClientAPI client, InventoryFolderBase folder, bool fetchFolders, bool fetchItems)
1171 { 1172 {
1172 m_log.DebugFormat("[AGENT INVENTORY]: Send Inventory Folder {0} Update to {1} {2}", folder.Name, client.FirstName, client.LastName); 1173 if (folder == null)
1174 return;
1175
1176 // TODO: This code for looking in the folder for the library should be folded somewhere else
1177 // so that this class doesn't have to know the details (and so that multiple libraries, etc.
1178 // can be handled transparently).
1179 InventoryFolderImpl fold = null;
1180 if (LibraryService != null && LibraryService.LibraryRootFolder != null)
1181 {
1182 if ((fold = LibraryService.LibraryRootFolder.FindFolder(folder.ID)) != null)
1183 {
1184 client.SendInventoryFolderDetails(
1185 fold.Owner, folder.ID, fold.RequestListOfItems(),
1186 fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
1187 return;
1188 }
1189 }
1190
1191 // Fetch the folder contents
1173 InventoryCollection contents = InventoryService.GetFolderContent(client.AgentId, folder.ID); 1192 InventoryCollection contents = InventoryService.GetFolderContent(client.AgentId, folder.ID);
1174 InventoryFolderBase containingFolder = new InventoryFolderBase(); 1193
1175 containingFolder.ID = folder.ID; 1194 // Fetch the folder itself to get its current version
1176 containingFolder.Owner = client.AgentId; 1195 InventoryFolderBase containingFolder = new InventoryFolderBase(folder.ID, client.AgentId);
1177 containingFolder = InventoryService.GetFolder(containingFolder); 1196 containingFolder = InventoryService.GetFolder(containingFolder);
1178 int version = containingFolder.Version;
1179 1197
1180 client.SendInventoryFolderDetails(client.AgentId, folder.ID, contents.Items, contents.Folders, version, fetchFolders, fetchItems); 1198 //m_log.DebugFormat("[AGENT INVENTORY]: Sending inventory folder contents ({0} nodes) for \"{1}\" to {2} {3}",
1199 // contents.Folders.Count + contents.Items.Count, containingFolder.Name, client.FirstName, client.LastName);
1200
1201 if (containingFolder != null && containingFolder != null)
1202 client.SendInventoryFolderDetails(client.AgentId, folder.ID, contents.Items, contents.Folders, containingFolder.Version, fetchFolders, fetchItems);
1181 } 1203 }
1182 1204
1183 /// <summary> 1205 /// <summary>
@@ -1219,11 +1241,12 @@ namespace OpenSim.Region.Framework.Scenes
1219 item = InventoryService.GetItem(item); 1241 item = InventoryService.GetItem(item);
1220 1242
1221 // Try library 1243 // Try library
1222 if (null == item) 1244 if (null == item && LibraryService != null && LibraryService.LibraryRootFolder != null)
1223 { 1245 {
1224 item = CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID); 1246 item = LibraryService.LibraryRootFolder.FindItem(itemID);
1225 } 1247 }
1226 1248
1249 // If we've found the item in the user's inventory or in the library
1227 if (item != null) 1250 if (item != null)
1228 { 1251 {
1229 part.ParentGroup.AddInventoryItem(remoteClient, primLocalID, item, copyID); 1252 part.ParentGroup.AddInventoryItem(remoteClient, primLocalID, item, copyID);
@@ -1258,7 +1281,10 @@ namespace OpenSim.Region.Framework.Scenes
1258 remoteClient, part, transactionID, currentItem); 1281 remoteClient, part, transactionID, currentItem);
1259 } 1282 }
1260 if (part.Inventory.UpdateInventoryItem(itemInfo)) 1283 if (part.Inventory.UpdateInventoryItem(itemInfo))
1284 {
1285 remoteClient.SendAgentAlertMessage("Notecard saved", false);
1261 part.GetProperties(remoteClient); 1286 part.GetProperties(remoteClient);
1287 }
1262 } 1288 }
1263 } 1289 }
1264 else 1290 else
@@ -1288,9 +1314,9 @@ namespace OpenSim.Region.Framework.Scenes
1288 1314
1289 // Try library 1315 // Try library
1290 // XXX clumsy, possibly should be one call 1316 // XXX clumsy, possibly should be one call
1291 if (null == item) 1317 if (null == item && LibraryService != null && LibraryService.LibraryRootFolder != null)
1292 { 1318 {
1293 item = CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID); 1319 item = LibraryService.LibraryRootFolder.FindItem(itemID);
1294 } 1320 }
1295 1321
1296 if (item != null) 1322 if (item != null)
@@ -1310,6 +1336,7 @@ namespace OpenSim.Region.Framework.Scenes
1310 // "Rezzed script {0} into prim local ID {1} for user {2}", 1336 // "Rezzed script {0} into prim local ID {1} for user {2}",
1311 // item.inventoryName, localID, remoteClient.Name); 1337 // item.inventoryName, localID, remoteClient.Name);
1312 part.GetProperties(remoteClient); 1338 part.GetProperties(remoteClient);
1339 part.ParentGroup.ResumeScripts();
1313 } 1340 }
1314 else 1341 else
1315 { 1342 {
@@ -1347,7 +1374,9 @@ namespace OpenSim.Region.Framework.Scenes
1347 itemBase.InvType, part.UUID, remoteClient.AgentId)) 1374 itemBase.InvType, part.UUID, remoteClient.AgentId))
1348 return; 1375 return;
1349 1376
1350 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType, Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n}")); 1377 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType,
1378 Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n}"),
1379 remoteClient.AgentId);
1351 AssetService.Store(asset); 1380 AssetService.Store(asset);
1352 1381
1353 TaskInventoryItem taskItem = new TaskInventoryItem(); 1382 TaskInventoryItem taskItem = new TaskInventoryItem();
@@ -1377,6 +1406,7 @@ namespace OpenSim.Region.Framework.Scenes
1377 part.GetProperties(remoteClient); 1406 part.GetProperties(remoteClient);
1378 1407
1379 part.Inventory.CreateScriptInstance(taskItem, 0, false, DefaultScriptEngine, 0); 1408 part.Inventory.CreateScriptInstance(taskItem, 0, false, DefaultScriptEngine, 0);
1409 part.ParentGroup.ResumeScripts();
1380 } 1410 }
1381 } 1411 }
1382 1412
@@ -1480,9 +1510,11 @@ namespace OpenSim.Region.Framework.Scenes
1480 destPart.Inventory.CreateScriptInstance(destTaskItem, start_param, false, DefaultScriptEngine, 0); 1510 destPart.Inventory.CreateScriptInstance(destTaskItem, start_param, false, DefaultScriptEngine, 0);
1481 } 1511 }
1482 1512
1513 destPart.ParentGroup.ResumeScripts();
1514
1483 ScenePresence avatar; 1515 ScenePresence avatar;
1484 1516
1485 if (TryGetAvatar(srcTaskItem.OwnerID, out avatar)) 1517 if (TryGetScenePresence(srcTaskItem.OwnerID, out avatar))
1486 { 1518 {
1487 destPart.GetProperties(avatar.ControllingClient); 1519 destPart.GetProperties(avatar.ControllingClient);
1488 } 1520 }
@@ -1616,237 +1648,6 @@ namespace OpenSim.Region.Framework.Scenes
1616 } 1648 }
1617 } 1649 }
1618 1650
1619 /// <summary>
1620 /// Delete a scene object from a scene and place in the given avatar's inventory.
1621 /// Returns the UUID of the newly created asset.
1622 /// </summary>
1623 /// <param name="action"></param>
1624 /// <param name="folderID"></param>
1625 /// <param name="objectGroup"></param>
1626 /// <param name="remoteClient"> </param>
1627 public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID,
1628 SceneObjectGroup objectGroup, IClientAPI remoteClient)
1629 {
1630 UUID assetID = UUID.Zero;
1631
1632 Vector3 inventoryStoredPosition = new Vector3
1633 (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
1634 ? 250
1635 : objectGroup.AbsolutePosition.X)
1636 ,
1637 (objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
1638 ? 250
1639 : objectGroup.AbsolutePosition.X,
1640 objectGroup.AbsolutePosition.Z);
1641
1642 Vector3 originalPosition = objectGroup.AbsolutePosition;
1643
1644 objectGroup.AbsolutePosition = inventoryStoredPosition;
1645
1646 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(objectGroup);
1647
1648 objectGroup.AbsolutePosition = originalPosition;
1649
1650 // Get the user info of the item destination
1651 //
1652 UUID userID = UUID.Zero;
1653
1654 if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
1655 action == DeRezAction.SaveToExistingUserInventoryItem)
1656 {
1657 // Take or take copy require a taker
1658 // Saving changes requires a local user
1659 //
1660 if (remoteClient == null)
1661 return UUID.Zero;
1662
1663 userID = remoteClient.AgentId;
1664 }
1665 else
1666 {
1667 // All returns / deletes go to the object owner
1668 //
1669
1670 userID = objectGroup.RootPart.OwnerID;
1671 }
1672
1673 if (userID == UUID.Zero) // Can't proceed
1674 {
1675 return UUID.Zero;
1676 }
1677
1678 // If we're returning someone's item, it goes back to the
1679 // owner's Lost And Found folder.
1680 // Delete is treated like return in this case
1681 // Deleting your own items makes them go to trash
1682 //
1683
1684 InventoryFolderBase folder = null;
1685 InventoryItemBase item = null;
1686
1687 if (DeRezAction.SaveToExistingUserInventoryItem == action)
1688 {
1689 item = new InventoryItemBase(objectGroup.RootPart.FromUserInventoryItemID, userID);
1690 item = InventoryService.GetItem(item);
1691
1692 //item = userInfo.RootFolder.FindItem(
1693 // objectGroup.RootPart.FromUserInventoryItemID);
1694
1695 if (null == item)
1696 {
1697 m_log.DebugFormat(
1698 "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.",
1699 objectGroup.Name, objectGroup.UUID);
1700 return UUID.Zero;
1701 }
1702 }
1703 else
1704 {
1705 // Folder magic
1706 //
1707 if (action == DeRezAction.Delete)
1708 {
1709 // Deleting someone else's item
1710 //
1711
1712
1713 if (remoteClient == null ||
1714 objectGroup.OwnerID != remoteClient.AgentId)
1715 {
1716 // Folder skeleton may not be loaded and we
1717 // have to wait for the inventory to find
1718 // the destination folder
1719 //
1720 folder = InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
1721 }
1722 else
1723 {
1724 // Assume inventory skeleton was loaded during login
1725 // and all folders can be found
1726 //
1727 folder = InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
1728 }
1729 }
1730 else if (action == DeRezAction.Return)
1731 {
1732
1733 // Dump to lost + found unconditionally
1734 //
1735 folder = InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
1736 }
1737
1738 if (folderID == UUID.Zero && folder == null)
1739 {
1740 if (action == DeRezAction.Delete)
1741 {
1742 // Deletes go to trash by default
1743 //
1744 folder = InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
1745 }
1746 else
1747 {
1748 // Catch all. Use lost & found
1749 //
1750
1751 folder = InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
1752 }
1753 }
1754
1755 if (folder == null) // None of the above
1756 {
1757 //folder = userInfo.RootFolder.FindFolder(folderID);
1758 folder = new InventoryFolderBase(folderID);
1759
1760 if (folder == null) // Nowhere to put it
1761 {
1762 return UUID.Zero;
1763 }
1764 }
1765
1766 item = new InventoryItemBase();
1767 item.CreatorId = objectGroup.RootPart.CreatorID.ToString();
1768 item.ID = UUID.Random();
1769 item.InvType = (int)InventoryType.Object;
1770 item.Folder = folder.ID;
1771 item.Owner = userID;
1772 }
1773
1774 AssetBase asset = CreateAsset(
1775 objectGroup.GetPartName(objectGroup.RootPart.LocalId),
1776 objectGroup.GetPartDescription(objectGroup.RootPart.LocalId),
1777 (sbyte)AssetType.Object,
1778 Utils.StringToBytes(sceneObjectXml));
1779 AssetService.Store(asset);
1780 assetID = asset.FullID;
1781
1782 if (DeRezAction.SaveToExistingUserInventoryItem == action)
1783 {
1784 item.AssetID = asset.FullID;
1785 InventoryService.UpdateItem(item);
1786 }
1787 else
1788 {
1789 item.AssetID = asset.FullID;
1790
1791 if (remoteClient != null && (remoteClient.AgentId != objectGroup.RootPart.OwnerID) && Permissions.PropagatePermissions())
1792 {
1793 uint perms=objectGroup.GetEffectivePermissions();
1794 uint nextPerms=(perms & 7) << 13;
1795 if ((nextPerms & (uint)PermissionMask.Copy) == 0)
1796 perms &= ~(uint)PermissionMask.Copy;
1797 if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
1798 perms &= ~(uint)PermissionMask.Transfer;
1799 if ((nextPerms & (uint)PermissionMask.Modify) == 0)
1800 perms &= ~(uint)PermissionMask.Modify;
1801
1802 item.BasePermissions = perms & objectGroup.RootPart.NextOwnerMask;
1803 item.CurrentPermissions = item.BasePermissions;
1804 item.NextPermissions = objectGroup.RootPart.NextOwnerMask;
1805 item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask & objectGroup.RootPart.NextOwnerMask;
1806 item.GroupPermissions = objectGroup.RootPart.GroupMask & objectGroup.RootPart.NextOwnerMask;
1807 item.CurrentPermissions |= 8; // Slam!
1808 }
1809 else
1810 {
1811 uint ownerPerms = objectGroup.GetEffectivePermissions();
1812 if ((objectGroup.RootPart.OwnerMask & (uint)PermissionMask.Modify) != 0)
1813 ownerPerms |= (uint)PermissionMask.Modify;
1814
1815 item.BasePermissions = ownerPerms;
1816 item.CurrentPermissions = ownerPerms;
1817
1818 item.NextPermissions = objectGroup.RootPart.NextOwnerMask;
1819 item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask;
1820 item.GroupPermissions = objectGroup.RootPart.GroupMask;
1821
1822 item.CurrentPermissions |= 8; // Slam!
1823 }
1824
1825 // TODO: add the new fields (Flags, Sale info, etc)
1826 item.CreationDate = Util.UnixTimeSinceEpoch();
1827 item.Description = asset.Description;
1828 item.Name = asset.Name;
1829 item.AssetType = asset.Type;
1830
1831 InventoryService.AddItem(item);
1832
1833 if (remoteClient != null && item.Owner == remoteClient.AgentId)
1834 {
1835 remoteClient.SendInventoryItemCreateUpdate(item, 0);
1836 }
1837 else
1838 {
1839 ScenePresence notifyUser = GetScenePresence(item.Owner);
1840 if (notifyUser != null)
1841 {
1842 notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
1843 }
1844 }
1845 }
1846
1847 return assetID;
1848 }
1849
1850 public void UpdateKnownItem(IClientAPI remoteClient, SceneObjectGroup grp, UUID itemID, UUID agentID) 1651 public void UpdateKnownItem(IClientAPI remoteClient, SceneObjectGroup grp, UUID itemID, UUID agentID)
1851 { 1652 {
1852 SceneObjectGroup objectGroup = grp; 1653 SceneObjectGroup objectGroup = grp;
@@ -1873,7 +1674,8 @@ namespace OpenSim.Region.Framework.Scenes
1873 objectGroup.GetPartName(objectGroup.LocalId), 1674 objectGroup.GetPartName(objectGroup.LocalId),
1874 objectGroup.GetPartDescription(objectGroup.LocalId), 1675 objectGroup.GetPartDescription(objectGroup.LocalId),
1875 (sbyte)AssetType.Object, 1676 (sbyte)AssetType.Object,
1876 Utils.StringToBytes(sceneObjectXml)); 1677 Utils.StringToBytes(sceneObjectXml),
1678 remoteClient.AgentId);
1877 AssetService.Store(asset); 1679 AssetService.Store(asset);
1878 1680
1879 item.AssetID = asset.FullID; 1681 item.AssetID = asset.FullID;
@@ -1920,7 +1722,8 @@ namespace OpenSim.Region.Framework.Scenes
1920 grp.GetPartName(grp.LocalId), 1722 grp.GetPartName(grp.LocalId),
1921 grp.GetPartDescription(grp.LocalId), 1723 grp.GetPartDescription(grp.LocalId),
1922 (sbyte)AssetType.Object, 1724 (sbyte)AssetType.Object,
1923 Utils.StringToBytes(sceneObjectXml)); 1725 Utils.StringToBytes(sceneObjectXml),
1726 remoteClient.AgentId);
1924 AssetService.Store(asset); 1727 AssetService.Store(asset);
1925 1728
1926 InventoryItemBase item = new InventoryItemBase(); 1729 InventoryItemBase item = new InventoryItemBase();
@@ -1987,225 +1790,11 @@ namespace OpenSim.Region.Framework.Scenes
1987 UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, 1790 UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
1988 bool RezSelected, bool RemoveItem, UUID fromTaskID) 1791 bool RezSelected, bool RemoveItem, UUID fromTaskID)
1989 { 1792 {
1990 RezObject( 1793 IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
1991 remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, 1794 if (invAccess != null)
1992 RezSelected, RemoveItem, fromTaskID, false); 1795 invAccess.RezObject(
1993 } 1796 remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
1994 1797 RezSelected, RemoveItem, fromTaskID, false);
1995 /// <summary>
1996 /// Rez an object into the scene from the user's inventory
1997 /// </summary>
1998 /// <param name="remoteClient"></param>
1999 /// <param name="itemID"></param>
2000 /// <param name="RayEnd"></param>
2001 /// <param name="RayStart"></param>
2002 /// <param name="RayTargetID"></param>
2003 /// <param name="BypassRayCast"></param>
2004 /// <param name="RayEndIsIntersection"></param>
2005 /// <param name="RezSelected"></param>
2006 /// <param name="RemoveItem"></param>
2007 /// <param name="fromTaskID"></param>
2008 /// <param name="attachment"></param>
2009 /// <returns>The SceneObjectGroup rezzed or null if rez was unsuccessful.</returns>
2010 public virtual SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
2011 UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
2012 bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
2013 {
2014 // Work out position details
2015 byte bRayEndIsIntersection = (byte)0;
2016
2017 if (RayEndIsIntersection)
2018 {
2019 bRayEndIsIntersection = (byte)1;
2020 }
2021 else
2022 {
2023 bRayEndIsIntersection = (byte)0;
2024 }
2025
2026 Vector3 scale = new Vector3(0.5f, 0.5f, 0.5f);
2027
2028
2029 Vector3 pos = GetNewRezLocation(
2030 RayStart, RayEnd, RayTargetID, Quaternion.Identity,
2031 BypassRayCast, bRayEndIsIntersection,true,scale, false);
2032
2033 // Rez object
2034 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
2035 item = InventoryService.GetItem(item);
2036
2037 if (item != null)
2038 {
2039 AssetBase rezAsset = AssetService.Get(item.AssetID.ToString());
2040
2041 if (rezAsset != null)
2042 {
2043 UUID itemId = UUID.Zero;
2044
2045 // If we have permission to copy then link the rezzed object back to the user inventory
2046 // item that it came from. This allows us to enable 'save object to inventory'
2047 if (!Permissions.BypassPermissions())
2048 {
2049 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy)
2050 {
2051 itemId = item.ID;
2052 }
2053 }
2054 else
2055 {
2056 // Brave new fullperm world
2057 //
2058 itemId = item.ID;
2059 }
2060
2061 string xmlData = Utils.BytesToString(rezAsset.Data);
2062 SceneObjectGroup group
2063 = SceneObjectSerializer.FromOriginalXmlFormat(itemId, xmlData);
2064
2065 if (!Permissions.CanRezObject(
2066 group.Children.Count, remoteClient.AgentId, pos)
2067 && !attachment)
2068 {
2069 // The client operates in no fail mode. It will
2070 // have already removed the item from the folder
2071 // if it's no copy.
2072 // Put it back if it's not an attachment
2073 //
2074 if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!attachment))
2075 remoteClient.SendBulkUpdateInventory(item);
2076 return null;
2077 }
2078
2079 group.ResetIDs();
2080
2081 if (attachment)
2082 {
2083 group.RootPart.ObjectFlags |= (uint)PrimFlags.Phantom;
2084 group.RootPart.IsAttachment = true;
2085 }
2086
2087 AddNewSceneObject(group, true);
2088
2089 // m_log.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z);
2090 // if attachment we set it's asset id so object updates can reflect that
2091 // if not, we set it's position in world.
2092 if (!attachment)
2093 {
2094 float offsetHeight = 0;
2095 pos = GetNewRezLocation(
2096 RayStart, RayEnd, RayTargetID, Quaternion.Identity,
2097 BypassRayCast, bRayEndIsIntersection, true, group.GetAxisAlignedBoundingBox(out offsetHeight), false);
2098 pos.Z += offsetHeight;
2099 group.AbsolutePosition = pos;
2100 // m_log.InfoFormat("rezx point for inventory rezz is {0} {1} {2} and offsetheight was {3}", pos.X, pos.Y, pos.Z, offsetHeight);
2101
2102 }
2103 else
2104 {
2105 group.SetFromItemID(itemID);
2106 }
2107
2108 SceneObjectPart rootPart = null;
2109 try
2110 {
2111 rootPart = group.GetChildPart(group.UUID);
2112 }
2113 catch (NullReferenceException)
2114 {
2115 string isAttachment = "";
2116
2117 if (attachment)
2118 isAttachment = " Object was an attachment";
2119
2120 m_log.Error("[AGENT INVENTORY]: Error rezzing ItemID: " + itemID + " object has no rootpart." + isAttachment);
2121 }
2122
2123 // Since renaming the item in the inventory does not affect the name stored
2124 // in the serialization, transfer the correct name from the inventory to the
2125 // object itself before we rez.
2126 rootPart.Name = item.Name;
2127 rootPart.Description = item.Description;
2128
2129 List<SceneObjectPart> partList = new List<SceneObjectPart>(group.Children.Values);
2130
2131 group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
2132 if (rootPart.OwnerID != item.Owner)
2133 {
2134 //Need to kill the for sale here
2135 rootPart.ObjectSaleType = 0;
2136 rootPart.SalePrice = 10;
2137
2138 if (Permissions.PropagatePermissions())
2139 {
2140 if ((item.CurrentPermissions & 8) != 0)
2141 {
2142 foreach (SceneObjectPart part in partList)
2143 {
2144 part.EveryoneMask = item.EveryOnePermissions;
2145 part.NextOwnerMask = item.NextPermissions;
2146 part.GroupMask = 0; // DO NOT propagate here
2147 }
2148 }
2149 group.ApplyNextOwnerPermissions();
2150 }
2151 }
2152
2153 foreach (SceneObjectPart part in partList)
2154 {
2155 if (part.OwnerID != item.Owner)
2156 {
2157 part.LastOwnerID = part.OwnerID;
2158 part.OwnerID = item.Owner;
2159 part.Inventory.ChangeInventoryOwner(item.Owner);
2160 }
2161 else if (((item.CurrentPermissions & 8) != 0) && (!attachment)) // Slam!
2162 {
2163 part.EveryoneMask = item.EveryOnePermissions;
2164 part.NextOwnerMask = item.NextPermissions;
2165
2166 part.GroupMask = 0; // DO NOT propagate here
2167 }
2168 }
2169
2170 rootPart.TrimPermissions();
2171
2172 if (!attachment)
2173 {
2174 if (group.RootPart.Shape.PCode == (byte)PCode.Prim)
2175 {
2176 group.ClearPartAttachmentData();
2177 }
2178 }
2179
2180 if (!attachment)
2181 {
2182 // Fire on_rez
2183 group.CreateScriptInstances(0, true, DefaultScriptEngine, 0);
2184
2185 rootPart.ScheduleFullUpdate();
2186 }
2187
2188 if (!Permissions.BypassPermissions())
2189 {
2190 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
2191 {
2192 // If this is done on attachments, no
2193 // copy ones will be lost, so avoid it
2194 //
2195 if (!attachment)
2196 {
2197 List<UUID> uuids = new List<UUID>();
2198 uuids.Add(item.ID);
2199 InventoryService.DeleteItems(item.Owner, uuids);
2200 }
2201 }
2202 }
2203
2204 return rootPart.ParentGroup;
2205 }
2206 }
2207
2208 return null;
2209 } 1798 }
2210 1799
2211 /// <summary> 1800 /// <summary>
@@ -2343,178 +1932,6 @@ namespace OpenSim.Region.Framework.Scenes
2343 EventManager.TriggerStopScript(part.LocalId, itemID); 1932 EventManager.TriggerStopScript(part.LocalId, itemID);
2344 } 1933 }
2345 1934
2346 internal void SendAttachEvent(uint localID, UUID itemID, UUID avatarID)
2347 {
2348 EventManager.TriggerOnAttach(localID, itemID, avatarID);
2349 }
2350
2351 /// <summary>
2352 /// Called when the client receives a request to rez a single attachment on to the avatar from inventory
2353 /// (RezSingleAttachmentFromInv packet).
2354 /// </summary>
2355 /// <param name="remoteClient"></param>
2356 /// <param name="itemID"></param>
2357 /// <param name="AttachmentPt"></param>
2358 /// <returns></returns>
2359 public UUID RezSingleAttachment(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
2360 {
2361 m_log.DebugFormat("[USER INVENTORY]: Rezzing single attachment from item {0} for {1}", itemID, remoteClient.Name);
2362
2363 SceneObjectGroup att = m_sceneGraph.RezSingleAttachment(remoteClient, itemID, AttachmentPt);
2364
2365 if (att == null)
2366 {
2367 DetachSingleAttachmentToInv(itemID, remoteClient);
2368 return UUID.Zero;
2369 }
2370
2371 return RezSingleAttachment(att, remoteClient, itemID, AttachmentPt);
2372 }
2373
2374 /// <summary>
2375 /// Update the user inventory to reflect an attachment
2376 /// </summary>
2377 /// <param name="att"></param>
2378 /// <param name="remoteClient"></param>
2379 /// <param name="itemID"></param>
2380 /// <param name="AttachmentPt"></param>
2381 /// <returns></returns>
2382 public UUID RezSingleAttachment(SceneObjectGroup att, IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
2383 {
2384 m_log.DebugFormat(
2385 "[USER INVENTORY]: Updating inventory of {0} to show attachment of {1} (item ID {2})",
2386 remoteClient.Name, att.Name, itemID);
2387
2388 if (!att.IsDeleted)
2389 AttachmentPt = att.RootPart.AttachmentPoint;
2390
2391 ScenePresence presence;
2392 if (TryGetAvatar(remoteClient.AgentId, out presence))
2393 {
2394 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
2395 item = InventoryService.GetItem(item);
2396
2397 presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/);
2398 }
2399 return att.UUID;
2400 }
2401
2402 public void RezMultipleAttachments(IClientAPI remoteClient, RezMultipleAttachmentsFromInvPacket.HeaderDataBlock header,
2403 RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects)
2404 {
2405 foreach (RezMultipleAttachmentsFromInvPacket.ObjectDataBlock obj in objects)
2406 {
2407 RezSingleAttachment(remoteClient, obj.ItemID, obj.AttachmentPt);
2408 }
2409 }
2410
2411 /// <summary>
2412 /// Attach an object.
2413 /// </summary>
2414 /// <param name="controllingClient"></param>
2415 /// <param name="localID"></param>
2416 /// <param name="attachPoint"></param>
2417 /// <param name="rot"></param>
2418 /// <param name="pos"></param>
2419 /// <param name="silent"></param>
2420 /// <returns>true if the object was successfully attached, false otherwise</returns>
2421 public bool AttachObject(IClientAPI controllingClient, uint localID, uint attachPoint, Quaternion rot, Vector3 pos, bool silent)
2422 {
2423 return m_sceneGraph.AttachObject(controllingClient, localID, attachPoint, rot, pos, silent);
2424 }
2425
2426 /// <summary>
2427 /// This registers the item as attached in a user's inventory
2428 /// </summary>
2429 /// <param name="remoteClient"></param>
2430 /// <param name="AttachmentPt"></param>
2431 /// <param name="itemID"></param>
2432 /// <param name="att"></param>
2433 public void AttachObject(IClientAPI remoteClient, uint AttachmentPt, UUID itemID, SceneObjectGroup att)
2434 {
2435// m_log.DebugFormat(
2436// "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
2437// att.Name, remoteClient.Name, AttachmentPt, itemID);
2438
2439 if (UUID.Zero == itemID)
2440 {
2441 m_log.Error("[SCENE INVENTORY]: Unable to save attachment. Error inventory item ID.");
2442 return;
2443 }
2444
2445 if (0 == AttachmentPt)
2446 {
2447 m_log.Error("[SCENE INVENTORY]: Unable to save attachment. Error attachment point.");
2448 return;
2449 }
2450
2451 if (null == att.RootPart)
2452 {
2453 m_log.Error("[SCENE INVENTORY]: Unable to save attachment for a prim without the rootpart!");
2454 return;
2455 }
2456
2457 ScenePresence presence;
2458 if (TryGetAvatar(remoteClient.AgentId, out presence))
2459 {
2460 // XXYY!!
2461 InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
2462 item = InventoryService.GetItem(item);
2463 presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/);
2464
2465 if (m_AvatarFactory != null)
2466 m_AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
2467 }
2468 }
2469
2470 public void DetachSingleAttachmentToGround(UUID itemID, IClientAPI remoteClient)
2471 {
2472 SceneObjectPart part = GetSceneObjectPart(itemID);
2473 if (part == null || part.ParentGroup == null)
2474 return;
2475
2476 UUID inventoryID = part.ParentGroup.GetFromItemID();
2477
2478 ScenePresence presence;
2479 if (TryGetAvatar(remoteClient.AgentId, out presence))
2480 {
2481 if (!Permissions.CanRezObject(part.ParentGroup.Children.Count, remoteClient.AgentId, presence.AbsolutePosition))
2482 return;
2483
2484 presence.Appearance.DetachAttachment(itemID);
2485 IAvatarFactory ava = RequestModuleInterface<IAvatarFactory>();
2486 if (ava != null)
2487 {
2488 ava.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
2489 }
2490 part.ParentGroup.DetachToGround();
2491
2492 List<UUID> uuids = new List<UUID>();
2493 uuids.Add(inventoryID);
2494 InventoryService.DeleteItems(remoteClient.AgentId, uuids);
2495 remoteClient.SendRemoveInventoryItem(inventoryID);
2496 }
2497 SendAttachEvent(part.ParentGroup.LocalId, itemID, UUID.Zero);
2498 }
2499
2500 public void DetachSingleAttachmentToInv(UUID itemID, IClientAPI remoteClient)
2501 {
2502 ScenePresence presence;
2503 if (TryGetAvatar(remoteClient.AgentId, out presence))
2504 {
2505 presence.Appearance.DetachAttachment(itemID);
2506
2507 // Save avatar attachment information
2508 if (m_AvatarFactory != null)
2509 {
2510 m_log.Info("[SCENE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId + ", ItemID: " + itemID);
2511 m_AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
2512 }
2513 }
2514
2515 m_sceneGraph.DetachSingleAttachmentToInv(itemID, remoteClient);
2516 }
2517
2518 public void GetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID) 1935 public void GetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
2519 { 1936 {
2520 EventManager.TriggerGetScriptRunning(controllingClient, objectID, itemID); 1937 EventManager.TriggerGetScriptRunning(controllingClient, objectID, itemID);
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index ac04dc7..e25b1f1 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
@@ -32,7 +32,7 @@ using OpenMetaverse;
32using OpenMetaverse.Packets; 32using OpenMetaverse.Packets;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications; 34using OpenSim.Framework.Communications;
35using OpenSim.Framework.Communications.Cache; 35using OpenSim.Services.Interfaces;
36 36
37namespace OpenSim.Region.Framework.Scenes 37namespace OpenSim.Region.Framework.Scenes
38{ 38{
@@ -371,14 +371,16 @@ namespace OpenSim.Region.Framework.Scenes
371 { 371 {
372 //EventManager.TriggerAvatarPickerRequest(); 372 //EventManager.TriggerAvatarPickerRequest();
373 373
374 List<AvatarPickerAvatar> AvatarResponses = new List<AvatarPickerAvatar>(); 374 List<UserAccount> accounts = UserAccountService.GetUserAccounts(RegionInfo.ScopeID, query);
375 AvatarResponses = m_sceneGridService.GenerateAgentPickerRequestResponse(RequestID, query); 375
376 if (accounts == null)
377 return;
376 378
377 AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); 379 AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
378 // TODO: don't create new blocks if recycling an old packet 380 // TODO: don't create new blocks if recycling an old packet
379 381
380 AvatarPickerReplyPacket.DataBlock[] searchData = 382 AvatarPickerReplyPacket.DataBlock[] searchData =
381 new AvatarPickerReplyPacket.DataBlock[AvatarResponses.Count]; 383 new AvatarPickerReplyPacket.DataBlock[accounts.Count];
382 AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock(); 384 AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
383 385
384 agentData.AgentID = avatarID; 386 agentData.AgentID = avatarID;
@@ -387,16 +389,16 @@ namespace OpenSim.Region.Framework.Scenes
387 //byte[] bytes = new byte[AvatarResponses.Count*32]; 389 //byte[] bytes = new byte[AvatarResponses.Count*32];
388 390
389 int i = 0; 391 int i = 0;
390 foreach (AvatarPickerAvatar item in AvatarResponses) 392 foreach (UserAccount item in accounts)
391 { 393 {
392 UUID translatedIDtem = item.AvatarID; 394 UUID translatedIDtem = item.PrincipalID;
393 searchData[i] = new AvatarPickerReplyPacket.DataBlock(); 395 searchData[i] = new AvatarPickerReplyPacket.DataBlock();
394 searchData[i].AvatarID = translatedIDtem; 396 searchData[i].AvatarID = translatedIDtem;
395 searchData[i].FirstName = Utils.StringToBytes((string) item.firstName); 397 searchData[i].FirstName = Utils.StringToBytes((string) item.FirstName);
396 searchData[i].LastName = Utils.StringToBytes((string) item.lastName); 398 searchData[i].LastName = Utils.StringToBytes((string) item.LastName);
397 i++; 399 i++;
398 } 400 }
399 if (AvatarResponses.Count == 0) 401 if (accounts.Count == 0)
400 { 402 {
401 searchData = new AvatarPickerReplyPacket.DataBlock[0]; 403 searchData = new AvatarPickerReplyPacket.DataBlock[0];
402 } 404 }
@@ -455,7 +457,24 @@ namespace OpenSim.Region.Framework.Scenes
455 } 457 }
456 ); 458 );
457 } 459 }
458 460
461 public void HandleUUIDNameRequest(UUID uuid, IClientAPI remote_client)
462 {
463 if (LibraryService != null && (LibraryService.LibraryRootFolder.Owner == uuid))
464 {
465 remote_client.SendNameReply(uuid, "Mr", "OpenSim");
466 }
467 else
468 {
469 string[] names = GetUserNames(uuid);
470 if (names.Length == 2)
471 {
472 remote_client.SendNameReply(uuid, names[0], names[1]);
473 }
474
475 }
476 }
477
459 /// <summary> 478 /// <summary>
460 /// Handle a fetch inventory request from the client 479 /// Handle a fetch inventory request from the client
461 /// </summary> 480 /// </summary>
@@ -464,7 +483,7 @@ namespace OpenSim.Region.Framework.Scenes
464 /// <param name="ownerID"></param> 483 /// <param name="ownerID"></param>
465 public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID) 484 public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID)
466 { 485 {
467 if (ownerID == CommsManager.UserProfileCacheService.LibraryRoot.Owner) 486 if (LibraryService != null && LibraryService.LibraryRootFolder != null && ownerID == LibraryService.LibraryRootFolder.Owner)
468 { 487 {
469 //m_log.Debug("request info for library item"); 488 //m_log.Debug("request info for library item");
470 return; 489 return;
@@ -494,17 +513,18 @@ namespace OpenSim.Region.Framework.Scenes
494 { 513 {
495 // FIXME MAYBE: We're not handling sortOrder! 514 // FIXME MAYBE: We're not handling sortOrder!
496 515
497 // TODO: This code for looking in the folder for the library should be folded back into the 516 // TODO: This code for looking in the folder for the library should be folded somewhere else
498 // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc. 517 // so that this class doesn't have to know the details (and so that multiple libraries, etc.
499 // can be handled transparently). 518 // can be handled transparently).
500 InventoryFolderImpl fold = null; 519 InventoryFolderImpl fold = null;
501 if ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null) 520 if (LibraryService != null && LibraryService.LibraryRootFolder != null)
502 { 521 if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
503 remoteClient.SendInventoryFolderDetails( 522 {
504 fold.Owner, folderID, fold.RequestListOfItems(), 523 remoteClient.SendInventoryFolderDetails(
505 fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems); 524 fold.Owner, folderID, fold.RequestListOfItems(),
506 return; 525 fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
507 } 526 return;
527 }
508 528
509 // We're going to send the reply async, because there may be 529 // We're going to send the reply async, because there may be
510 // an enormous quantity of packets -- basically the entire inventory! 530 // an enormous quantity of packets -- basically the entire inventory!
@@ -552,15 +572,16 @@ namespace OpenSim.Region.Framework.Scenes
552 // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc. 572 // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc.
553 // can be handled transparently). 573 // can be handled transparently).
554 InventoryFolderImpl fold; 574 InventoryFolderImpl fold;
555 if ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null) 575 if (LibraryService != null && LibraryService.LibraryRootFolder != null)
556 { 576 if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
557 version = 0; 577 {
558 InventoryCollection ret = new InventoryCollection(); 578 version = 0;
559 ret.Folders = new List<InventoryFolderBase>(); 579 InventoryCollection ret = new InventoryCollection();
560 ret.Items = fold.RequestListOfItems(); 580 ret.Folders = new List<InventoryFolderBase>();
581 ret.Items = fold.RequestListOfItems();
561 582
562 return ret; 583 return ret;
563 } 584 }
564 585
565 InventoryCollection contents = new InventoryCollection(); 586 InventoryCollection contents = new InventoryCollection();
566 587
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index ee097bc..122ed02 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -27,6 +27,7 @@
27 27
28using System; 28using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30using System.Diagnostics;
30using System.Drawing; 31using System.Drawing;
31using System.Drawing.Imaging; 32using System.Drawing.Imaging;
32using System.IO; 33using System.IO;
@@ -41,8 +42,7 @@ using OpenMetaverse.Imaging;
41using OpenSim.Framework; 42using OpenSim.Framework;
42using OpenSim.Services.Interfaces; 43using OpenSim.Services.Interfaces;
43using OpenSim.Framework.Communications; 44using OpenSim.Framework.Communications;
44using OpenSim.Framework.Communications.Cache; 45
45using OpenSim.Framework.Communications.Clients;
46using OpenSim.Framework.Console; 46using OpenSim.Framework.Console;
47using OpenSim.Region.Framework.Interfaces; 47using OpenSim.Region.Framework.Interfaces;
48using OpenSim.Region.Framework.Scenes.Scripting; 48using OpenSim.Region.Framework.Scenes.Scripting;
@@ -131,7 +131,6 @@ namespace OpenSim.Region.Framework.Scenes
131 private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing 131 private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
132 private int m_incrementsof15seconds; 132 private int m_incrementsof15seconds;
133 private volatile bool m_backingup; 133 private volatile bool m_backingup;
134 private bool m_useAsyncWhenPossible;
135 134
136 private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>(); 135 private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
137 private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>(); 136 private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>();
@@ -141,7 +140,6 @@ namespace OpenSim.Region.Framework.Scenes
141 protected ModuleLoader m_moduleLoader; 140 protected ModuleLoader m_moduleLoader;
142 protected StorageManager m_storageManager; 141 protected StorageManager m_storageManager;
143 protected AgentCircuitManager m_authenticateHandler; 142 protected AgentCircuitManager m_authenticateHandler;
144 public CommunicationsManager CommsManager;
145 143
146 protected SceneCommunicationService m_sceneGridService; 144 protected SceneCommunicationService m_sceneGridService;
147 public bool LoginsDisabled = true; 145 public bool LoginsDisabled = true;
@@ -203,11 +201,11 @@ namespace OpenSim.Region.Framework.Scenes
203 { 201 {
204 m_AuthorizationService = RequestModuleInterface<IAuthorizationService>(); 202 m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
205 203
206 if (m_AuthorizationService == null) 204 //if (m_AuthorizationService == null)
207 { 205 //{
208 // don't throw an exception if no authorization service is set for the time being 206 // // don't throw an exception if no authorization service is set for the time being
209 m_log.InfoFormat("[SCENE]: No Authorization service is configured"); 207 // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
210 } 208 //}
211 } 209 }
212 210
213 return m_AuthorizationService; 211 return m_AuthorizationService;
@@ -254,8 +252,87 @@ namespace OpenSim.Region.Framework.Scenes
254 } 252 }
255 } 253 }
256 254
255 protected ILibraryService m_LibraryService;
256
257 public ILibraryService LibraryService
258 {
259 get
260 {
261 if (m_LibraryService == null)
262 m_LibraryService = RequestModuleInterface<ILibraryService>();
263
264 return m_LibraryService;
265 }
266 }
267
268 protected ISimulationService m_simulationService;
269 public ISimulationService SimulationService
270 {
271 get
272 {
273 if (m_simulationService == null)
274 m_simulationService = RequestModuleInterface<ISimulationService>();
275 return m_simulationService;
276 }
277 }
278
279 protected IAuthenticationService m_AuthenticationService;
280 public IAuthenticationService AuthenticationService
281 {
282 get
283 {
284 if (m_AuthenticationService == null)
285 m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
286 return m_AuthenticationService;
287 }
288 }
289
290 protected IPresenceService m_PresenceService;
291 public IPresenceService PresenceService
292 {
293 get
294 {
295 if (m_PresenceService == null)
296 m_PresenceService = RequestModuleInterface<IPresenceService>();
297 return m_PresenceService;
298 }
299 }
300 protected IUserAccountService m_UserAccountService;
301 public IUserAccountService UserAccountService
302 {
303 get
304 {
305 if (m_UserAccountService == null)
306 m_UserAccountService = RequestModuleInterface<IUserAccountService>();
307 return m_UserAccountService;
308 }
309 }
310
311 protected OpenSim.Services.Interfaces.IAvatarService m_AvatarService;
312 public OpenSim.Services.Interfaces.IAvatarService AvatarService
313 {
314 get
315 {
316 if (m_AvatarService == null)
317 m_AvatarService = RequestModuleInterface<IAvatarService>();
318 return m_AvatarService;
319 }
320 }
321
322 protected IGridUserService m_GridUserService;
323 public IGridUserService GridUserService
324 {
325 get
326 {
327 if (m_GridUserService == null)
328 m_GridUserService = RequestModuleInterface<IGridUserService>();
329 return m_GridUserService;
330 }
331 }
332
257 protected IXMLRPC m_xmlrpcModule; 333 protected IXMLRPC m_xmlrpcModule;
258 protected IWorldComm m_worldCommModule; 334 protected IWorldComm m_worldCommModule;
335 public IAttachmentsModule AttachmentsModule { get; set; }
259 protected IAvatarFactory m_AvatarFactory; 336 protected IAvatarFactory m_AvatarFactory;
260 public IAvatarFactory AvatarFactory 337 public IAvatarFactory AvatarFactory
261 { 338 {
@@ -263,10 +340,8 @@ namespace OpenSim.Region.Framework.Scenes
263 } 340 }
264 protected IConfigSource m_config; 341 protected IConfigSource m_config;
265 protected IRegionSerialiserModule m_serialiser; 342 protected IRegionSerialiserModule m_serialiser;
266 protected IInterregionCommsOut m_interregionCommsOut;
267 protected IInterregionCommsIn m_interregionCommsIn;
268 protected IDialogModule m_dialogModule; 343 protected IDialogModule m_dialogModule;
269 protected ITeleportModule m_teleportModule; 344 protected IEntityTransferModule m_teleportModule;
270 345
271 protected ICapabilitiesModule m_capsModule; 346 protected ICapabilitiesModule m_capsModule;
272 public ICapabilitiesModule CapsModule 347 public ICapabilitiesModule CapsModule
@@ -497,7 +572,7 @@ namespace OpenSim.Region.Framework.Scenes
497 #region Constructors 572 #region Constructors
498 573
499 public Scene(RegionInfo regInfo, AgentCircuitManager authen, 574 public Scene(RegionInfo regInfo, AgentCircuitManager authen,
500 CommunicationsManager commsMan, SceneCommunicationService sceneGridService, 575 SceneCommunicationService sceneGridService,
501 StorageManager storeManager, 576 StorageManager storeManager,
502 ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, 577 ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
503 bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion) 578 bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
@@ -533,7 +608,6 @@ namespace OpenSim.Region.Framework.Scenes
533 m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4); 608 m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
534 m_moduleLoader = moduleLoader; 609 m_moduleLoader = moduleLoader;
535 m_authenticateHandler = authen; 610 m_authenticateHandler = authen;
536 CommsManager = commsMan;
537 m_sceneGridService = sceneGridService; 611 m_sceneGridService = sceneGridService;
538 m_storageManager = storeManager; 612 m_storageManager = storeManager;
539 m_regInfo = regInfo; 613 m_regInfo = regInfo;
@@ -557,9 +631,52 @@ namespace OpenSim.Region.Framework.Scenes
557 631
558 if (m_storageManager.EstateDataStore != null) 632 if (m_storageManager.EstateDataStore != null)
559 { 633 {
560 m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID); 634 m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false);
635 if (m_regInfo.EstateSettings.EstateID == 0) // No record at all
636 {
637 MainConsole.Instance.Output("Your region is not part of an estate.");
638 while (true)
639 {
640 string response = MainConsole.Instance.CmdPrompt("Do you wish to join an existing estate?", "no", new List<string>() {"yes", "no"});
641 if (response == "no")
642 {
643 // Create a new estate
644 m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, true);
645
646 m_regInfo.EstateSettings.EstateName = MainConsole.Instance.CmdPrompt("New estate name", m_regInfo.EstateSettings.EstateName);
647 m_regInfo.EstateSettings.Save();
648 break;
649 }
650 else
651 {
652 response = MainConsole.Instance.CmdPrompt("Estate name to join", "None");
653 if (response == "None")
654 continue;
655
656 List<int> estateIDs = m_storageManager.EstateDataStore.GetEstates(response);
657 if (estateIDs.Count < 1)
658 {
659 MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again");
660 continue;
661 }
662
663 int estateID = estateIDs[0];
664
665 m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(estateID);
666
667 if (m_storageManager.EstateDataStore.LinkRegion(m_regInfo.RegionID, estateID))
668 break;
669
670 MainConsole.Instance.Output("Joining the estate failed. Please try again.");
671 }
672 }
673 }
561 } 674 }
562 675
676 MainConsole.Instance.Commands.AddCommand("region", false, "reload estate",
677 "reload estate",
678 "Reload the estate data", HandleReloadEstate);
679
563 //Bind Storage Manager functions to some land manager functions for this scene 680 //Bind Storage Manager functions to some land manager functions for this scene
564 EventManager.OnLandObjectAdded += 681 EventManager.OnLandObjectAdded +=
565 new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject); 682 new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
@@ -606,9 +723,6 @@ namespace OpenSim.Region.Framework.Scenes
606 // 723 //
607 IConfig startupConfig = m_config.Configs["Startup"]; 724 IConfig startupConfig = m_config.Configs["Startup"];
608 725
609 // Should we try to run loops synchronously or asynchronously?
610 m_useAsyncWhenPossible = startupConfig.GetBoolean("use_async_when_possible", false);
611
612 //Animation states 726 //Animation states
613 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false); 727 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
614 // TODO: Change default to true once the feature is supported 728 // TODO: Change default to true once the feature is supported
@@ -792,6 +906,36 @@ namespace OpenSim.Region.Framework.Scenes
792 return m_simulatorVersion; 906 return m_simulatorVersion;
793 } 907 }
794 908
909 public string[] GetUserNames(UUID uuid)
910 {
911 string[] returnstring = new string[0];
912
913 UserAccount account = UserAccountService.GetUserAccount(RegionInfo.ScopeID, uuid);
914
915 if (account != null)
916 {
917 returnstring = new string[2];
918 returnstring[0] = account.FirstName;
919 returnstring[1] = account.LastName;
920 }
921
922 return returnstring;
923 }
924
925 public string GetUserName(UUID uuid)
926 {
927 string[] names = GetUserNames(uuid);
928 if (names.Length == 2)
929 {
930 string firstname = names[0];
931 string lastname = names[1];
932
933 return firstname + " " + lastname;
934
935 }
936 return "(hippos)";
937 }
938
795 /// <summary> 939 /// <summary>
796 /// Another region is up. 940 /// Another region is up.
797 /// 941 ///
@@ -825,7 +969,7 @@ namespace OpenSim.Region.Framework.Scenes
825 regInfo.RegionName = otherRegion.RegionName; 969 regInfo.RegionName = otherRegion.RegionName;
826 regInfo.ScopeID = otherRegion.ScopeID; 970 regInfo.ScopeID = otherRegion.ScopeID;
827 regInfo.ExternalHostName = otherRegion.ExternalHostName; 971 regInfo.ExternalHostName = otherRegion.ExternalHostName;
828 972 GridRegion r = new GridRegion(regInfo);
829 try 973 try
830 { 974 {
831 ForEachScenePresence(delegate(ScenePresence agent) 975 ForEachScenePresence(delegate(ScenePresence agent)
@@ -839,7 +983,8 @@ namespace OpenSim.Region.Framework.Scenes
839 List<ulong> old = new List<ulong>(); 983 List<ulong> old = new List<ulong>();
840 old.Add(otherRegion.RegionHandle); 984 old.Add(otherRegion.RegionHandle);
841 agent.DropOldNeighbours(old); 985 agent.DropOldNeighbours(old);
842 InformClientOfNeighbor(agent, regInfo); 986 if (m_teleportModule != null)
987 m_teleportModule.EnableChildAgent(agent, r);
843 } 988 }
844 } 989 }
845 ); 990 );
@@ -999,6 +1144,7 @@ namespace OpenSim.Region.Framework.Scenes
999 { 1144 {
1000 foreach (RegionInfo region in m_regionRestartNotifyList) 1145 foreach (RegionInfo region in m_regionRestartNotifyList)
1001 { 1146 {
1147 GridRegion r = new GridRegion(region);
1002 try 1148 try
1003 { 1149 {
1004 ForEachScenePresence(delegate(ScenePresence agent) 1150 ForEachScenePresence(delegate(ScenePresence agent)
@@ -1006,9 +1152,8 @@ namespace OpenSim.Region.Framework.Scenes
1006 // If agent is a root agent. 1152 // If agent is a root agent.
1007 if (!agent.IsChildAgent) 1153 if (!agent.IsChildAgent)
1008 { 1154 {
1009 //agent.ControllingClient.new 1155 if (m_teleportModule != null)
1010 //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo()); 1156 m_teleportModule.EnableChildAgent(agent, r);
1011 InformClientOfNeighbor(agent, region);
1012 } 1157 }
1013 } 1158 }
1014 ); 1159 );
@@ -1029,7 +1174,6 @@ namespace OpenSim.Region.Framework.Scenes
1029 { 1174 {
1030 if (m_scripts_enabled != !ScriptEngine) 1175 if (m_scripts_enabled != !ScriptEngine)
1031 { 1176 {
1032 // Tedd! Here's the method to disable the scripting engine!
1033 if (ScriptEngine) 1177 if (ScriptEngine)
1034 { 1178 {
1035 m_log.Info("Stopping all Scripts in Scene"); 1179 m_log.Info("Stopping all Scripts in Scene");
@@ -1051,6 +1195,7 @@ namespace OpenSim.Region.Framework.Scenes
1051 if (ent is SceneObjectGroup) 1195 if (ent is SceneObjectGroup)
1052 { 1196 {
1053 ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0); 1197 ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
1198 ((SceneObjectGroup)ent).ResumeScripts();
1054 } 1199 }
1055 } 1200 }
1056 } 1201 }
@@ -1067,10 +1212,7 @@ namespace OpenSim.Region.Framework.Scenes
1067 1212
1068 public int GetInaccurateNeighborCount() 1213 public int GetInaccurateNeighborCount()
1069 { 1214 {
1070 lock (m_neighbours) 1215 return m_neighbours.Count;
1071 {
1072 return m_neighbours.Count;
1073 }
1074 } 1216 }
1075 1217
1076 // This is the method that shuts down the scene. 1218 // This is the method that shuts down the scene.
@@ -1150,12 +1292,89 @@ namespace OpenSim.Region.Framework.Scenes
1150 m_worldCommModule = RequestModuleInterface<IWorldComm>(); 1292 m_worldCommModule = RequestModuleInterface<IWorldComm>();
1151 XferManager = RequestModuleInterface<IXfer>(); 1293 XferManager = RequestModuleInterface<IXfer>();
1152 m_AvatarFactory = RequestModuleInterface<IAvatarFactory>(); 1294 m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
1295 AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
1153 m_serialiser = RequestModuleInterface<IRegionSerialiserModule>(); 1296 m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
1154 m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
1155 m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
1156 m_dialogModule = RequestModuleInterface<IDialogModule>(); 1297 m_dialogModule = RequestModuleInterface<IDialogModule>();
1157 m_capsModule = RequestModuleInterface<ICapabilitiesModule>(); 1298 m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
1158 m_teleportModule = RequestModuleInterface<ITeleportModule>(); 1299 m_teleportModule = RequestModuleInterface<IEntityTransferModule>();
1300
1301 // Shoving this in here for now, because we have the needed
1302 // interfaces at this point
1303 //
1304 // TODO: Find a better place for this
1305 //
1306 while (m_regInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
1307 {
1308 MainConsole.Instance.Output("The current estate has no owner set.");
1309 string first = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test");
1310 string last = MainConsole.Instance.CmdPrompt("Estate owner last name", "User");
1311
1312 UserAccount account = UserAccountService.GetUserAccount(m_regInfo.ScopeID, first, last);
1313
1314 if (account == null)
1315 {
1316 // Create a new account
1317 account = new UserAccount(m_regInfo.ScopeID, first, last, String.Empty);
1318 if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
1319 {
1320 account.ServiceURLs = new Dictionary<string, object>();
1321 account.ServiceURLs["HomeURI"] = string.Empty;
1322 account.ServiceURLs["GatekeeperURI"] = string.Empty;
1323 account.ServiceURLs["InventoryServerURI"] = string.Empty;
1324 account.ServiceURLs["AssetServerURI"] = string.Empty;
1325 }
1326
1327 if (UserAccountService.StoreUserAccount(account))
1328 {
1329 string password = MainConsole.Instance.PasswdPrompt("Password");
1330 string email = MainConsole.Instance.CmdPrompt("Email", "");
1331
1332 account.Email = email;
1333 UserAccountService.StoreUserAccount(account);
1334
1335 bool success = false;
1336 success = AuthenticationService.SetPassword(account.PrincipalID, password);
1337 if (!success)
1338 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
1339 first, last);
1340
1341 GridRegion home = null;
1342 if (GridService != null)
1343 {
1344 List<GridRegion> defaultRegions = GridService.GetDefaultRegions(UUID.Zero);
1345 if (defaultRegions != null && defaultRegions.Count >= 1)
1346 home = defaultRegions[0];
1347
1348 if (GridUserService != null && home != null)
1349 GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
1350 else
1351 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
1352 first, last);
1353
1354 }
1355 else
1356 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
1357 first, last);
1358
1359 if (InventoryService != null)
1360 success = InventoryService.CreateUserInventory(account.PrincipalID);
1361 if (!success)
1362 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
1363 first, last);
1364
1365
1366 m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", first, last);
1367
1368 m_regInfo.EstateSettings.EstateOwner = account.PrincipalID;
1369 m_regInfo.EstateSettings.Save();
1370 }
1371 }
1372 else
1373 {
1374 m_regInfo.EstateSettings.EstateOwner = account.PrincipalID;
1375 m_regInfo.EstateSettings.Save();
1376 }
1377 }
1159 } 1378 }
1160 1379
1161 #endregion 1380 #endregion
@@ -1539,7 +1758,7 @@ namespace OpenSim.Region.Framework.Scenes
1539 m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID); 1758 m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
1540 } 1759 }
1541 1760
1542 public void StoreWindlightProfile(RegionMeta7WindlightData wl) 1761 public void StoreWindlightProfile(RegionLightShareData wl)
1543 { 1762 {
1544 m_regInfo.WindlightSettings = wl; 1763 m_regInfo.WindlightSettings = wl;
1545 m_storageManager.DataStore.StoreRegionWindlightSettings(wl); 1764 m_storageManager.DataStore.StoreRegionWindlightSettings(wl);
@@ -1605,7 +1824,9 @@ namespace OpenSim.Region.Framework.Scenes
1605 GridRegion region = new GridRegion(RegionInfo); 1824 GridRegion region = new GridRegion(RegionInfo);
1606 string error = GridService.RegisterRegion(RegionInfo.ScopeID, region); 1825 string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
1607 if (error != String.Empty) 1826 if (error != String.Empty)
1827 {
1608 throw new Exception(error); 1828 throw new Exception(error);
1829 }
1609 1830
1610 m_sceneGridService.SetScene(this); 1831 m_sceneGridService.SetScene(this);
1611 m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo); 1832 m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
@@ -2017,7 +2238,6 @@ namespace OpenSim.Region.Framework.Scenes
2017 /// Move the given scene object into a new region depending on which region its absolute position has moved 2238 /// Move the given scene object into a new region depending on which region its absolute position has moved
2018 /// into. 2239 /// into.
2019 /// 2240 ///
2020 /// This method locates the new region handle and offsets the prim position for the new region
2021 /// </summary> 2241 /// </summary>
2022 /// <param name="attemptedPosition">the attempted out of region position of the scene object</param> 2242 /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
2023 /// <param name="grp">the scene object that we're crossing</param> 2243 /// <param name="grp">the scene object that we're crossing</param>
@@ -2059,191 +2279,8 @@ namespace OpenSim.Region.Framework.Scenes
2059 return; 2279 return;
2060 } 2280 }
2061 2281
2062 int thisx = (int)RegionInfo.RegionLocX; 2282 if (m_teleportModule != null)
2063 int thisy = (int)RegionInfo.RegionLocY; 2283 m_teleportModule.Cross(grp, attemptedPosition, silent);
2064 Vector3 EastCross = new Vector3(0.1f,0,0);
2065 Vector3 WestCross = new Vector3(-0.1f, 0, 0);
2066 Vector3 NorthCross = new Vector3(0, 0.1f, 0);
2067 Vector3 SouthCross = new Vector3(0, -0.1f, 0);
2068
2069
2070 // use this if no borders were crossed!
2071 ulong newRegionHandle
2072 = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
2073 (uint)((thisy) * Constants.RegionSize));
2074
2075 Vector3 pos = attemptedPosition;
2076
2077 int changeX = 1;
2078 int changeY = 1;
2079
2080 if (TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
2081 {
2082 if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2083 {
2084
2085 Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2086
2087 if (crossedBorderx.BorderLine.Z > 0)
2088 {
2089 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2090 changeX = (int)(crossedBorderx.BorderLine.Z /(int) Constants.RegionSize);
2091 }
2092 else
2093 pos.X = ((pos.X + Constants.RegionSize));
2094
2095 Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2096 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2097
2098 if (crossedBordery.BorderLine.Z > 0)
2099 {
2100 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2101 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2102 }
2103 else
2104 pos.Y = ((pos.Y + Constants.RegionSize));
2105
2106
2107
2108 newRegionHandle
2109 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2110 (uint)((thisy - changeY) * Constants.RegionSize));
2111 // x - 1
2112 // y - 1
2113 }
2114 else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2115 {
2116 Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2117
2118 if (crossedBorderx.BorderLine.Z > 0)
2119 {
2120 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2121 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
2122 }
2123 else
2124 pos.X = ((pos.X + Constants.RegionSize));
2125
2126
2127 Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2128 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2129
2130 try
2131 {
2132 if (crossedBordery.BorderLine.Z > 0)
2133 {
2134 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2135 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2136 }
2137 else
2138 pos.Y = ((pos.Y + Constants.RegionSize));
2139
2140 newRegionHandle
2141 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2142 (uint)((thisy + changeY) * Constants.RegionSize));
2143 // x - 1
2144 // y + 1
2145 }
2146 catch (Exception ex)
2147 {
2148 }
2149 }
2150 else
2151 {
2152 Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2153
2154 if (crossedBorderx.BorderLine.Z > 0)
2155 {
2156 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2157 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
2158 }
2159 else
2160 pos.X = ((pos.X + Constants.RegionSize));
2161
2162 newRegionHandle
2163 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2164 (uint) (thisy*Constants.RegionSize));
2165 // x - 1
2166 }
2167 }
2168 else if (TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
2169 {
2170 if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2171 {
2172
2173 pos.X = ((pos.X - Constants.RegionSize));
2174 Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2175 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2176
2177 if (crossedBordery.BorderLine.Z > 0)
2178 {
2179 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2180 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2181 }
2182 else
2183 pos.Y = ((pos.Y + Constants.RegionSize));
2184
2185
2186 newRegionHandle
2187 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2188 (uint)((thisy - changeY) * Constants.RegionSize));
2189 // x + 1
2190 // y - 1
2191 }
2192 else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2193 {
2194 pos.X = ((pos.X - Constants.RegionSize));
2195 pos.Y = ((pos.Y - Constants.RegionSize));
2196 newRegionHandle
2197 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2198 (uint)((thisy + changeY) * Constants.RegionSize));
2199 // x + 1
2200 // y + 1
2201 }
2202 else
2203 {
2204 pos.X = ((pos.X - Constants.RegionSize));
2205 newRegionHandle
2206 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2207 (uint) (thisy*Constants.RegionSize));
2208 // x + 1
2209 }
2210 }
2211 else if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2212 {
2213 Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2214 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2215
2216 if (crossedBordery.BorderLine.Z > 0)
2217 {
2218 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2219 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2220 }
2221 else
2222 pos.Y = ((pos.Y + Constants.RegionSize));
2223
2224 newRegionHandle
2225 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
2226 // y - 1
2227 }
2228 else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2229 {
2230
2231 pos.Y = ((pos.Y - Constants.RegionSize));
2232 newRegionHandle
2233 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
2234 // y + 1
2235 }
2236
2237 // Offset the positions for the new region across the border
2238 Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
2239 grp.OffsetForNewRegion(pos);
2240
2241 // If we fail to cross the border, then reset the position of the scene object on that border.
2242 if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
2243 {
2244 grp.OffsetForNewRegion(oldGroupPosition);
2245 grp.ScheduleGroupForFullUpdate();
2246 }
2247 } 2284 }
2248 2285
2249 public Border GetCrossedBorder(Vector3 position, Cardinals gridline) 2286 public Border GetCrossedBorder(Vector3 position, Cardinals gridline)
@@ -2427,75 +2464,6 @@ namespace OpenSim.Region.Framework.Scenes
2427 2464
2428 2465
2429 /// <summary> 2466 /// <summary>
2430 /// Move the given scene object into a new region
2431 /// </summary>
2432 /// <param name="newRegionHandle"></param>
2433 /// <param name="grp">Scene Object Group that we're crossing</param>
2434 /// <returns>
2435 /// true if the crossing itself was successful, false on failure
2436 /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
2437 /// </returns>
2438 public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
2439 {
2440 //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
2441
2442 bool successYN = false;
2443 grp.RootPart.UpdateFlag = 0;
2444 //int primcrossingXMLmethod = 0;
2445
2446 if (newRegionHandle != 0)
2447 {
2448 //string objectState = grp.GetStateSnapshot();
2449
2450 //successYN
2451 // = m_sceneGridService.PrimCrossToNeighboringRegion(
2452 // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
2453 //if (successYN && (objectState != "") && m_allowScriptCrossings)
2454 //{
2455 // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
2456 // newRegionHandle, grp.UUID, objectState, 100);
2457 //}
2458
2459 // And the new channel...
2460 if (m_interregionCommsOut != null)
2461 successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
2462
2463 if (successYN)
2464 {
2465 // We remove the object here
2466 try
2467 {
2468 DeleteSceneObject(grp, silent);
2469 }
2470 catch (Exception e)
2471 {
2472 m_log.ErrorFormat(
2473 "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
2474 grp, e);
2475 }
2476 }
2477 else
2478 {
2479 if (!grp.IsDeleted)
2480 {
2481 if (grp.RootPart.PhysActor != null)
2482 {
2483 grp.RootPart.PhysActor.CrossingFailure();
2484 }
2485 }
2486
2487 m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
2488 }
2489 }
2490 else
2491 {
2492 m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
2493 }
2494
2495 return successYN;
2496 }
2497
2498 /// <summary>
2499 /// Called when objects or attachments cross the border between regions. 2467 /// Called when objects or attachments cross the border between regions.
2500 /// </summary> 2468 /// </summary>
2501 /// <param name="sog"></param> 2469 /// <param name="sog"></param>
@@ -2539,10 +2507,10 @@ namespace OpenSim.Region.Framework.Scenes
2539 //m_log.DebugFormat(" >>> IncomingCreateObject(userID, itemID) <<< {0} {1}", userID, itemID); 2507 //m_log.DebugFormat(" >>> IncomingCreateObject(userID, itemID) <<< {0} {1}", userID, itemID);
2540 2508
2541 ScenePresence sp = GetScenePresence(userID); 2509 ScenePresence sp = GetScenePresence(userID);
2542 if (sp != null) 2510 if (sp != null && AttachmentsModule != null)
2543 { 2511 {
2544 uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID); 2512 uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID);
2545 m_sceneGraph.RezSingleAttachment(sp.ControllingClient, itemID, attPt); 2513 AttachmentsModule.RezSingleAttachmentFromInventory(sp.ControllingClient, itemID, attPt);
2546 } 2514 }
2547 2515
2548 return false; 2516 return false;
@@ -2567,6 +2535,9 @@ namespace OpenSim.Region.Framework.Scenes
2567 2535
2568 return false; 2536 return false;
2569 } 2537 }
2538
2539 sceneObject.SetScene(this);
2540
2570 // Force allocation of new LocalId 2541 // Force allocation of new LocalId
2571 // 2542 //
2572 foreach (SceneObjectPart p in sceneObject.Children.Values) 2543 foreach (SceneObjectPart p in sceneObject.Children.Values)
@@ -2603,9 +2574,11 @@ namespace OpenSim.Region.Framework.Scenes
2603 //grp.SetFromAssetID(grp.RootPart.LastOwnerID); 2574 //grp.SetFromAssetID(grp.RootPart.LastOwnerID);
2604 m_log.DebugFormat( 2575 m_log.DebugFormat(
2605 "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition); 2576 "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
2577
2578 if (AttachmentsModule != null)
2579 AttachmentsModule.AttachObject(
2580 sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false);
2606 2581
2607 AttachObject(
2608 sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false);
2609 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2582 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2610 grp.SendGroupFullUpdate(); 2583 grp.SendGroupFullUpdate();
2611 } 2584 }
@@ -2645,6 +2618,8 @@ namespace OpenSim.Region.Framework.Scenes
2645 /// <param name="client"></param> 2618 /// <param name="client"></param>
2646 public override void AddNewClient(IClientAPI client) 2619 public override void AddNewClient(IClientAPI client)
2647 { 2620 {
2621 bool vialogin = false;
2622
2648 m_clientManager.Add(client); 2623 m_clientManager.Add(client);
2649 2624
2650 CheckHeartbeat(); 2625 CheckHeartbeat();
@@ -2679,23 +2654,48 @@ namespace OpenSim.Region.Framework.Scenes
2679 { 2654 {
2680 AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode); 2655 AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
2681 2656
2682 m_log.Debug("[Scene] Adding new agent " + client.Name + " to scene " + RegionInfo.RegionName); 2657 // Do the verification here
2683 /* 2658 System.Net.EndPoint ep = client.GetClientEP();
2684 string logMsg = string.Format("[SCENE]: Adding new {0} agent for {1} in {2}", 2659 if (aCircuit != null)
2685 ((aCircuit.child == true) ? "child" : "root"), client.Name, 2660 {
2686 RegionInfo.RegionName); 2661 if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
2687 2662 {
2688 m_log.Debug(logMsg); 2663 m_log.DebugFormat("[Scene]: Incoming client {0} {1} in region {2} via Login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
2689 */ 2664 vialogin = true;
2665 IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
2666 if (userVerification != null && ep != null)
2667 {
2668 if (!userVerification.VerifyClient(aCircuit, ep.ToString()))
2669 {
2670 // uh-oh, this is fishy
2671 m_log.WarnFormat("[Scene]: Agent {0} with session {1} connecting with unidentified end point {2}. Refusing service.",
2672 client.AgentId, client.SessionId, ep.ToString());
2673 try
2674 {
2675 client.Close();
2676 }
2677 catch (Exception e)
2678 {
2679 m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace);
2680 }
2681 return;
2682 }
2683 else
2684 m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} returned true", aCircuit.firstname, aCircuit.lastname);
2685 }
2686 }
2687 }
2690 2688
2691 CommsManager.UserProfileCacheService.AddNewUser(client.AgentId); 2689 m_log.Debug("[Scene] Adding new agent " + client.Name + " to scene " + RegionInfo.RegionName);
2692 2690
2693 ScenePresence sp = CreateAndAddScenePresence(client); 2691 ScenePresence sp = CreateAndAddScenePresence(client);
2692 if (aCircuit != null)
2693 sp.Appearance = aCircuit.Appearance;
2694 2694
2695 // HERE!!! Do the initial attachments right here 2695 // HERE!!! Do the initial attachments right here
2696 // first agent upon login is a root agent by design. 2696 // first agent upon login is a root agent by design.
2697 // All other AddNewClient calls find aCircuit.child to be true 2697 // All other AddNewClient calls find aCircuit.child to be true
2698 if (aCircuit == null || aCircuit.child == false) 2698 if (aCircuit == null || (aCircuit != null && aCircuit.child == false))
2699 { 2699 {
2700 sp.IsChildAgent = false; 2700 sp.IsChildAgent = false;
2701 Util.FireAndForget(delegate(object o) { sp.RezAttachments(); }); 2701 Util.FireAndForget(delegate(object o) { sp.RezAttachments(); });
@@ -2704,6 +2704,8 @@ namespace OpenSim.Region.Framework.Scenes
2704 2704
2705 m_LastLogin = Util.EnvironmentTickCount(); 2705 m_LastLogin = Util.EnvironmentTickCount();
2706 EventManager.TriggerOnNewClient(client); 2706 EventManager.TriggerOnNewClient(client);
2707 if (vialogin)
2708 EventManager.TriggerOnClientLogin(client);
2707 } 2709 }
2708 2710
2709 2711
@@ -2790,6 +2792,7 @@ namespace OpenSim.Region.Framework.Scenes
2790 public virtual void SubscribeToClientInventoryEvents(IClientAPI client) 2792 public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
2791 { 2793 {
2792 client.OnCreateNewInventoryItem += CreateNewInventoryItem; 2794 client.OnCreateNewInventoryItem += CreateNewInventoryItem;
2795 client.OnLinkInventoryItem += HandleLinkInventoryItem;
2793 client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder; 2796 client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
2794 client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder; 2797 client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
2795 client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!! 2798 client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
@@ -2809,19 +2812,21 @@ namespace OpenSim.Region.Framework.Scenes
2809 } 2812 }
2810 2813
2811 public virtual void SubscribeToClientAttachmentEvents(IClientAPI client) 2814 public virtual void SubscribeToClientAttachmentEvents(IClientAPI client)
2812 { 2815 {
2813 client.OnRezSingleAttachmentFromInv += RezSingleAttachment; 2816 if (AttachmentsModule != null)
2814 client.OnRezMultipleAttachmentsFromInv += RezMultipleAttachments; 2817 {
2815 client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv; 2818 client.OnRezSingleAttachmentFromInv += AttachmentsModule.RezSingleAttachmentFromInventory;
2816 client.OnObjectAttach += m_sceneGraph.AttachObject; 2819 client.OnRezMultipleAttachmentsFromInv += AttachmentsModule.RezMultipleAttachmentsFromInventory;
2817 client.OnObjectDetach += m_sceneGraph.DetachObject; 2820 client.OnObjectAttach += AttachmentsModule.AttachObject;
2821 client.OnObjectDetach += AttachmentsModule.DetachObject;
2822 client.OnDetachAttachmentIntoInv += AttachmentsModule.ShowDetachInUserInventory;
2823 }
2818 } 2824 }
2819 2825
2820 public virtual void SubscribeToClientTeleportEvents(IClientAPI client) 2826 public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
2821 { 2827 {
2822 client.OnTeleportLocationRequest += RequestTeleportLocation; 2828 client.OnTeleportLocationRequest += RequestTeleportLocation;
2823 client.OnTeleportLandmarkRequest += RequestTeleportLandmark; 2829 client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
2824 client.OnTeleportHomeRequest += TeleportClientHome;
2825 } 2830 }
2826 2831
2827 public virtual void SubscribeToClientScriptEvents(IClientAPI client) 2832 public virtual void SubscribeToClientScriptEvents(IClientAPI client)
@@ -2841,7 +2846,7 @@ namespace OpenSim.Region.Framework.Scenes
2841 2846
2842 public virtual void SubscribeToClientGridEvents(IClientAPI client) 2847 public virtual void SubscribeToClientGridEvents(IClientAPI client)
2843 { 2848 {
2844 client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest; 2849 client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
2845 client.OnMoneyTransferRequest += ProcessMoneyTransferRequest; 2850 client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
2846 client.OnAvatarPickerRequest += ProcessAvatarPickerRequest; 2851 client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
2847 client.OnSetStartLocationRequest += SetHomeRezPoint; 2852 client.OnSetStartLocationRequest += SetHomeRezPoint;
@@ -2863,7 +2868,6 @@ namespace OpenSim.Region.Framework.Scenes
2863 2868
2864 protected virtual void UnsubscribeToClientEvents(IClientAPI client) 2869 protected virtual void UnsubscribeToClientEvents(IClientAPI client)
2865 { 2870 {
2866
2867 } 2871 }
2868 2872
2869 /// <summary> 2873 /// <summary>
@@ -2885,7 +2889,6 @@ namespace OpenSim.Region.Framework.Scenes
2885 2889
2886 UnSubscribeToClientNetworkEvents(client); 2890 UnSubscribeToClientNetworkEvents(client);
2887 2891
2888
2889 // EventManager.TriggerOnNewClient(client); 2892 // EventManager.TriggerOnNewClient(client);
2890 } 2893 }
2891 2894
@@ -2942,7 +2945,6 @@ namespace OpenSim.Region.Framework.Scenes
2942 client.OnRezObject -= RezObject; 2945 client.OnRezObject -= RezObject;
2943 } 2946 }
2944 2947
2945
2946 public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client) 2948 public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
2947 { 2949 {
2948 client.OnCreateNewInventoryItem -= CreateNewInventoryItem; 2950 client.OnCreateNewInventoryItem -= CreateNewInventoryItem;
@@ -2965,19 +2967,22 @@ namespace OpenSim.Region.Framework.Scenes
2965 } 2967 }
2966 2968
2967 public virtual void UnSubscribeToClientAttachmentEvents(IClientAPI client) 2969 public virtual void UnSubscribeToClientAttachmentEvents(IClientAPI client)
2968 { 2970 {
2969 client.OnRezSingleAttachmentFromInv -= RezSingleAttachment; 2971 if (AttachmentsModule != null)
2970 client.OnRezMultipleAttachmentsFromInv -= RezMultipleAttachments; 2972 {
2971 client.OnDetachAttachmentIntoInv -= DetachSingleAttachmentToInv; 2973 client.OnRezSingleAttachmentFromInv -= AttachmentsModule.RezSingleAttachmentFromInventory;
2972 client.OnObjectAttach -= m_sceneGraph.AttachObject; 2974 client.OnRezMultipleAttachmentsFromInv -= AttachmentsModule.RezMultipleAttachmentsFromInventory;
2973 client.OnObjectDetach -= m_sceneGraph.DetachObject; 2975 client.OnObjectAttach -= AttachmentsModule.AttachObject;
2976 client.OnObjectDetach -= AttachmentsModule.DetachObject;
2977 client.OnDetachAttachmentIntoInv -= AttachmentsModule.ShowDetachInUserInventory;
2978 }
2974 } 2979 }
2975 2980
2976 public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client) 2981 public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
2977 { 2982 {
2978 client.OnTeleportLocationRequest -= RequestTeleportLocation; 2983 client.OnTeleportLocationRequest -= RequestTeleportLocation;
2979 client.OnTeleportLandmarkRequest -= RequestTeleportLandmark; 2984 client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
2980 client.OnTeleportHomeRequest -= TeleportClientHome; 2985 //client.OnTeleportHomeRequest -= TeleportClientHome;
2981 } 2986 }
2982 2987
2983 public virtual void UnSubscribeToClientScriptEvents(IClientAPI client) 2988 public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
@@ -2997,7 +3002,7 @@ namespace OpenSim.Region.Framework.Scenes
2997 3002
2998 public virtual void UnSubscribeToClientGridEvents(IClientAPI client) 3003 public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
2999 { 3004 {
3000 client.OnNameFromUUIDRequest -= CommsManager.HandleUUIDNameRequest; 3005 client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
3001 client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest; 3006 client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
3002 client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest; 3007 client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest;
3003 client.OnSetStartLocationRequest -= SetHomeRezPoint; 3008 client.OnSetStartLocationRequest -= SetHomeRezPoint;
@@ -3024,30 +3029,12 @@ namespace OpenSim.Region.Framework.Scenes
3024 /// <param name="client">The IClientAPI for the client</param> 3029 /// <param name="client">The IClientAPI for the client</param>
3025 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3030 public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
3026 { 3031 {
3027 UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId); 3032 if (m_teleportModule != null)
3028 if (UserProfile != null) 3033 m_teleportModule.TeleportHome(agentId, client);
3034 else
3029 { 3035 {
3030 GridRegion regionInfo = GridService.GetRegionByUUID(UUID.Zero, UserProfile.HomeRegionID); 3036 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3031 if (regionInfo == null) 3037 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3032 {
3033 uint x = 0, y = 0;
3034 Utils.LongToUInts(UserProfile.HomeRegion, out x, out y);
3035 regionInfo = GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
3036 if (regionInfo != null) // home region can be away temporarily, too
3037 {
3038 UserProfile.HomeRegionID = regionInfo.RegionID;
3039 CommsManager.UserService.UpdateUserProfile(UserProfile);
3040 }
3041 }
3042 if (regionInfo == null)
3043 {
3044 // can't find the Home region: Tell viewer and abort
3045 client.SendTeleportFailed("Your home-region could not be found.");
3046 return;
3047 }
3048 RequestTeleportLocation(
3049 client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
3050 (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
3051 } 3038 }
3052 } 3039 }
3053 3040
@@ -3138,7 +3125,7 @@ namespace OpenSim.Region.Framework.Scenes
3138 } 3125 }
3139 3126
3140 /// <summary> 3127 /// <summary>
3141 /// Sets the Home Point. The GridService uses this to know where to put a user when they log-in 3128 /// Sets the Home Point. The LoginService uses this to know where to put a user when they log-in
3142 /// </summary> 3129 /// </summary>
3143 /// <param name="remoteClient"></param> 3130 /// <param name="remoteClient"></param>
3144 /// <param name="regionHandle"></param> 3131 /// <param name="regionHandle"></param>
@@ -3147,27 +3134,11 @@ namespace OpenSim.Region.Framework.Scenes
3147 /// <param name="flags"></param> 3134 /// <param name="flags"></param>
3148 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3135 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3149 { 3136 {
3150 UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId); 3137 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3151 if (UserProfile != null)
3152 {
3153 // I know I'm ignoring the regionHandle provided by the teleport location request.
3154 // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
3155 UserProfile.HomeRegionID = RegionInfo.RegionID;
3156 // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
3157 // TODO: The HomeRegion property can be removed then, too
3158 UserProfile.HomeRegion = RegionInfo.RegionHandle;
3159
3160 UserProfile.HomeLocation = position;
3161 UserProfile.HomeLookAt = lookAt;
3162 CommsManager.UserService.UpdateUserProfile(UserProfile);
3163
3164 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3138 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3165 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3139 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
3166 }
3167 else 3140 else
3168 {
3169 m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed."); 3141 m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
3170 }
3171 } 3142 }
3172 3143
3173 /// <summary> 3144 /// <summary>
@@ -3240,14 +3211,12 @@ namespace OpenSim.Region.Framework.Scenes
3240 m_sceneGraph.removeUserCount(!childagentYN); 3211 m_sceneGraph.removeUserCount(!childagentYN);
3241 CapsModule.RemoveCapsHandler(agentID); 3212 CapsModule.RemoveCapsHandler(agentID);
3242 3213
3243 if (avatar.Scene.NeedSceneCacheClear(avatar.UUID)) 3214 // REFACTORING PROBLEM -- well not really a problem, but just to point out that whatever
3244 { 3215 // this method is doing is HORRIBLE!!!
3245 CommsManager.UserProfileCacheService.RemoveUser(agentID); 3216 avatar.Scene.NeedSceneCacheClear(avatar.UUID);
3246 }
3247 3217
3248 if (!avatar.IsChildAgent) 3218 if (!avatar.IsChildAgent)
3249 { 3219 {
3250 m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
3251 //List<ulong> childknownRegions = new List<ulong>(); 3220 //List<ulong> childknownRegions = new List<ulong>();
3252 //List<ulong> ckn = avatar.KnownChildRegionHandles; 3221 //List<ulong> ckn = avatar.KnownChildRegionHandles;
3253 //for (int i = 0; i < ckn.Count; i++) 3222 //for (int i = 0; i < ckn.Count; i++)
@@ -3302,12 +3271,6 @@ namespace OpenSim.Region.Framework.Scenes
3302 m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString()); 3271 m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
3303 } 3272 }
3304 3273
3305 // Remove client agent from profile, so new logins will work
3306 if (!childagentYN)
3307 {
3308 m_sceneGridService.ClearUserAgent(agentID);
3309 }
3310
3311 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode); 3274 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
3312 3275
3313 //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false)); 3276 //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
@@ -3380,14 +3343,6 @@ namespace OpenSim.Region.Framework.Scenes
3380 m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid; 3343 m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
3381 m_sceneGridService.KiPrimitive += SendKillObject; 3344 m_sceneGridService.KiPrimitive += SendKillObject;
3382 m_sceneGridService.OnGetLandData += GetLandData; 3345 m_sceneGridService.OnGetLandData += GetLandData;
3383
3384 if (m_interregionCommsIn != null)
3385 {
3386 m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
3387 m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
3388 }
3389 else
3390 m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
3391 } 3346 }
3392 3347
3393 /// <summary> 3348 /// <summary>
@@ -3405,9 +3360,6 @@ namespace OpenSim.Region.Framework.Scenes
3405 m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent; 3360 m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
3406 m_sceneGridService.OnGetLandData -= GetLandData; 3361 m_sceneGridService.OnGetLandData -= GetLandData;
3407 3362
3408 if (m_interregionCommsIn != null)
3409 m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
3410
3411 // this does nothing; should be removed 3363 // this does nothing; should be removed
3412 m_sceneGridService.Close(); 3364 m_sceneGridService.Close();
3413 3365
@@ -3444,6 +3396,7 @@ namespace OpenSim.Region.Framework.Scenes
3444 /// also return a reason.</returns> 3396 /// also return a reason.</returns>
3445 public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason) 3397 public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason)
3446 { 3398 {
3399 TeleportFlags tp = (TeleportFlags)teleportFlags;
3447 //Teleport flags: 3400 //Teleport flags:
3448 // 3401 //
3449 // TeleportFlags.ViaGodlikeLure - Border Crossing 3402 // TeleportFlags.ViaGodlikeLure - Border Crossing
@@ -3464,7 +3417,7 @@ namespace OpenSim.Region.Framework.Scenes
3464 agent.AgentID, agent.circuitcode, teleportFlags); 3417 agent.AgentID, agent.circuitcode, teleportFlags);
3465 3418
3466 reason = String.Empty; 3419 reason = String.Empty;
3467 if (!AuthenticateUser(agent, out reason)) 3420 if (!VerifyUserPresence(agent, out reason))
3468 return false; 3421 return false;
3469 3422
3470 if (!AuthorizeUser(agent, out reason)) 3423 if (!AuthorizeUser(agent, out reason))
@@ -3477,7 +3430,18 @@ namespace OpenSim.Region.Framework.Scenes
3477 3430
3478 CapsModule.NewUserConnection(agent); 3431 CapsModule.NewUserConnection(agent);
3479 3432
3480 ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID); 3433 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3434
3435 //On login or border crossing test land permisions
3436 if (tp != TeleportFlags.Default)
3437 {
3438 if (land != null && !TestLandRestrictions(agent, land, out reason))
3439 {
3440 return false;
3441 }
3442 }
3443
3444 ScenePresence sp = GetScenePresence(agent.AgentID);
3481 if (sp != null) 3445 if (sp != null)
3482 { 3446 {
3483 m_log.DebugFormat( 3447 m_log.DebugFormat(
@@ -3564,40 +3528,73 @@ namespace OpenSim.Region.Framework.Scenes
3564 */// This is now handled properly in ScenePresence.MakeRootAgent 3528 */// This is now handled properly in ScenePresence.MakeRootAgent
3565 } 3529 }
3566 3530
3531 agent.teleportFlags = teleportFlags;
3567 m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent); 3532 m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
3568 3533
3569 // rewrite session_id 3534 return true;
3570 CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID); 3535 }
3571 if (userinfo != null) 3536
3572 { 3537 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason)
3573 userinfo.SessionID = agent.SessionID; 3538 {
3574 } 3539
3575 else 3540 bool banned = land.IsBannedFromLand(agent.AgentID);
3541 bool restricted = land.IsRestrictedFromLand(agent.AgentID);
3542
3543 if (banned || restricted)
3576 { 3544 {
3577 m_log.WarnFormat( 3545 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y);
3578 "[CONNECTION BEGIN]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID); 3546 if (nearestParcel != null)
3547 {
3548 //Move agent to nearest allowed
3549 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3550 agent.startpos.X = newPosition.X;
3551 agent.startpos.Y = newPosition.Y;
3552 }
3553 else
3554 {
3555 if (banned)
3556 {
3557 reason = "Cannot regioncross into banned parcel.";
3558 }
3559 else
3560 {
3561 reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
3562 RegionInfo.RegionName);
3563 }
3564 return false;
3565 }
3579 } 3566 }
3580 3567 reason = "";
3581 return true; 3568 return true;
3582 } 3569 }
3583 3570
3584 /// <summary> 3571 /// <summary>
3585 /// Verifies that the user has a session on the Grid 3572 /// Verifies that the user has a presence on the Grid
3586 /// </summary> 3573 /// </summary>
3587 /// <param name="agent">Circuit Data of the Agent we're verifying</param> 3574 /// <param name="agent">Circuit Data of the Agent we're verifying</param>
3588 /// <param name="reason">Outputs the reason for the false response on this string</param> 3575 /// <param name="reason">Outputs the reason for the false response on this string</param>
3589 /// <returns>True if the user has a session on the grid. False if it does not. False will 3576 /// <returns>True if the user has a session on the grid. False if it does not. False will
3590 /// also return a reason.</returns> 3577 /// also return a reason.</returns>
3591 public virtual bool AuthenticateUser(AgentCircuitData agent, out string reason) 3578 public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
3592 { 3579 {
3593 reason = String.Empty; 3580 reason = String.Empty;
3594 3581
3595 bool result = CommsManager.UserService.VerifySession(agent.AgentID, agent.SessionID); 3582 IPresenceService presence = RequestModuleInterface<IPresenceService>();
3596 m_log.Debug("[CONNECTION BEGIN]: User authentication returned " + result); 3583 if (presence == null)
3597 if (!result) 3584 {
3598 reason = String.Format("Failed to authenticate user {0} {1}, access denied.", agent.firstname, agent.lastname); 3585 reason = String.Format("Failed to verify user {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
3586 return false;
3587 }
3588
3589 OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
3590
3591 if (pinfo == null)
3592 {
3593 reason = String.Format("Failed to verify user {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
3594 return false;
3595 }
3599 3596
3600 return result; 3597 return true;
3601 } 3598 }
3602 3599
3603 /// <summary> 3600 /// <summary>
@@ -3702,6 +3699,18 @@ namespace OpenSim.Region.Framework.Scenes
3702 return true; 3699 return true;
3703 } 3700 }
3704 3701
3702 private ILandObject GetParcelAtPoint(float x, float y)
3703 {
3704 foreach (var parcel in AllParcels())
3705 {
3706 if (parcel.ContainsPoint((int)x,(int)y))
3707 {
3708 return parcel;
3709 }
3710 }
3711 return null;
3712 }
3713
3705 /// <summary> 3714 /// <summary>
3706 /// Update an AgentCircuitData object with new information 3715 /// Update an AgentCircuitData object with new information
3707 /// </summary> 3716 /// </summary>
@@ -3730,8 +3739,7 @@ namespace OpenSim.Region.Framework.Scenes
3730 /// <param name="message">message to display to the user. Reason for being logged off</param> 3739 /// <param name="message">message to display to the user. Reason for being logged off</param>
3731 public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message) 3740 public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
3732 { 3741 {
3733 ScenePresence loggingOffUser = null; 3742 ScenePresence loggingOffUser = GetScenePresence(AvatarID);
3734 loggingOffUser = GetScenePresence(AvatarID);
3735 if (loggingOffUser != null) 3743 if (loggingOffUser != null)
3736 { 3744 {
3737 UUID localRegionSecret = UUID.Zero; 3745 UUID localRegionSecret = UUID.Zero;
@@ -3767,10 +3775,8 @@ namespace OpenSim.Region.Framework.Scenes
3767 /// <param name="isFlying"></param> 3775 /// <param name="isFlying"></param>
3768 public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying) 3776 public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
3769 { 3777 {
3770 ScenePresence presence; 3778 ScenePresence presence = GetScenePresence(agentID);
3771 m_sceneGraph.TryGetAvatar(agentID, out presence); 3779 if(presence != null)
3772
3773 if (presence != null)
3774 { 3780 {
3775 try 3781 try
3776 { 3782 {
@@ -3798,8 +3804,8 @@ namespace OpenSim.Region.Framework.Scenes
3798 /// <returns>true if we handled it.</returns> 3804 /// <returns>true if we handled it.</returns>
3799 public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData) 3805 public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
3800 { 3806 {
3801// m_log.DebugFormat( 3807 m_log.DebugFormat(
3802// "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName); 3808 "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
3803 3809
3804 // We have to wait until the viewer contacts this region after receiving EAC. 3810 // We have to wait until the viewer contacts this region after receiving EAC.
3805 // That calls AddNewClient, which finally creates the ScenePresence 3811 // That calls AddNewClient, which finally creates the ScenePresence
@@ -3868,16 +3874,6 @@ namespace OpenSim.Region.Framework.Scenes
3868 return false; 3874 return false;
3869 } 3875 }
3870 3876
3871 public virtual bool IncomingReleaseAgent(UUID id)
3872 {
3873 return m_sceneGridService.ReleaseAgent(id);
3874 }
3875
3876 public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
3877 {
3878 m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
3879 }
3880
3881 /// <summary> 3877 /// <summary>
3882 /// Tell a single agent to disconnect from the region. 3878 /// Tell a single agent to disconnect from the region.
3883 /// </summary> 3879 /// </summary>
@@ -3922,30 +3918,6 @@ namespace OpenSim.Region.Framework.Scenes
3922 } 3918 }
3923 3919
3924 /// <summary> 3920 /// <summary>
3925 /// Tell neighboring regions about this agent
3926 /// When the regions respond with a true value,
3927 /// tell the agents about the region.
3928 ///
3929 /// We have to tell the regions about the agents first otherwise it'll deny them access
3930 ///
3931 /// </summary>
3932 /// <param name="presence"></param>
3933 public void InformClientOfNeighbours(ScenePresence presence)
3934 {
3935 m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
3936 }
3937
3938 /// <summary>
3939 /// Tell a neighboring region about this agent
3940 /// </summary>
3941 /// <param name="presence"></param>
3942 /// <param name="region"></param>
3943 public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
3944 {
3945 m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
3946 }
3947
3948 /// <summary>
3949 /// Tries to teleport agent to other region. 3921 /// Tries to teleport agent to other region.
3950 /// </summary> 3922 /// </summary>
3951 /// <param name="remoteClient"></param> 3923 /// <param name="remoteClient"></param>
@@ -3978,9 +3950,7 @@ namespace OpenSim.Region.Framework.Scenes
3978 public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position, 3950 public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
3979 Vector3 lookAt, uint teleportFlags) 3951 Vector3 lookAt, uint teleportFlags)
3980 { 3952 {
3981 ScenePresence sp; 3953 ScenePresence sp = GetScenePresence(remoteClient.AgentId);
3982 m_sceneGraph.TryGetAvatar(remoteClient.AgentId, out sp);
3983
3984 if (sp != null) 3954 if (sp != null)
3985 { 3955 {
3986 uint regionX = m_regInfo.RegionLocX; 3956 uint regionX = m_regInfo.RegionLocX;
@@ -4020,16 +3990,12 @@ namespace OpenSim.Region.Framework.Scenes
4020 } 3990 }
4021 3991
4022 if (m_teleportModule != null) 3992 if (m_teleportModule != null)
4023 { 3993 m_teleportModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
4024 m_teleportModule.RequestTeleportToLocation(sp, regionHandle,
4025 position, lookAt, teleportFlags);
4026 }
4027 else 3994 else
4028 { 3995 {
4029 m_sceneGridService.RequestTeleportToLocation(sp, regionHandle, 3996 m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
4030 position, lookAt, teleportFlags); 3997 sp.ControllingClient.SendTeleportFailed("Unable to perform teleports on this simulator.");
4031 } 3998 }
4032
4033 } 3999 }
4034 } 4000 }
4035 4001
@@ -4055,7 +4021,12 @@ namespace OpenSim.Region.Framework.Scenes
4055 4021
4056 public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying) 4022 public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
4057 { 4023 {
4058 m_sceneGridService.CrossAgentToNewRegion(this, agent, isFlying); 4024 if (m_teleportModule != null)
4025 m_teleportModule.Cross(agent, isFlying);
4026 else
4027 {
4028 m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
4029 }
4059 } 4030 }
4060 4031
4061 public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence) 4032 public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
@@ -4081,35 +4052,6 @@ namespace OpenSim.Region.Framework.Scenes
4081 objectCapacity = objects; 4052 objectCapacity = objects;
4082 } 4053 }
4083 4054
4084 public List<FriendListItem> GetFriendList(string id)
4085 {
4086 UUID avatarID;
4087 if (!UUID.TryParse(id, out avatarID))
4088 return new List<FriendListItem>();
4089
4090 return CommsManager.GetUserFriendList(avatarID);
4091 }
4092
4093 public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
4094 {
4095 return CommsManager.GetFriendRegionInfos(uuids);
4096 }
4097
4098 public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
4099 {
4100 m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
4101 }
4102
4103 public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
4104 {
4105 m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
4106 }
4107
4108 public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
4109 {
4110 m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
4111 }
4112
4113 #endregion 4055 #endregion
4114 4056
4115 public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set) 4057 public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
@@ -4187,17 +4129,17 @@ namespace OpenSim.Region.Framework.Scenes
4187 m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname", 4129 m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
4188 "Agent ID", "Session ID", "Circuit", "IP", "World"); 4130 "Agent ID", "Session ID", "Circuit", "IP", "World");
4189 4131
4190 foreach (ScenePresence scenePresence in GetAvatars()) 4132 ForEachScenePresence(delegate(ScenePresence sp)
4191 { 4133 {
4192 m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}", 4134 m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
4193 scenePresence.Firstname, 4135 sp.Firstname,
4194 scenePresence.Lastname, 4136 sp.Lastname,
4195 scenePresence.UUID, 4137 sp.UUID,
4196 scenePresence.ControllingClient.AgentId, 4138 sp.ControllingClient.AgentId,
4197 "Unknown", 4139 "Unknown",
4198 "Unknown", 4140 "Unknown",
4199 RegionInfo.RegionName); 4141 RegionInfo.RegionName);
4200 } 4142 });
4201 4143
4202 break; 4144 break;
4203 } 4145 }
@@ -4363,56 +4305,45 @@ namespace OpenSim.Region.Framework.Scenes
4363 m_sceneGraph.RemovePhysicalPrim(num); 4305 m_sceneGraph.RemovePhysicalPrim(num);
4364 } 4306 }
4365 4307
4366 //The idea is to have a group of method that return a list of avatars meeting some requirement 4308 public int GetRootAgentCount()
4367 // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
4368
4369 /// <summary>
4370 /// Return a list of all avatars in this region.
4371 /// This list is a new object, so it can be iterated over without locking.
4372 /// </summary>
4373 /// <returns></returns>
4374 public List<ScenePresence> GetAvatars()
4375 { 4309 {
4376 return m_sceneGraph.GetAvatars(); 4310 return m_sceneGraph.GetRootAgentCount();
4377 } 4311 }
4378 4312
4379 /// <summary> 4313 public int GetChildAgentCount()
4380 /// Cheaply return the number of avatars in a region (without fetching a list object)
4381 /// </summary>
4382 public int GetRootAgentCount()
4383 { 4314 {
4384 return m_sceneGraph.GetRootAgentCount(); 4315 return m_sceneGraph.GetChildAgentCount();
4385 } 4316 }
4386 4317
4387 /// <summary> 4318 /// <summary>
4388 /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents. 4319 /// Request a scene presence by UUID. Fast, indexed lookup.
4389 /// This list is a new object, so it can be iterated over without locking.
4390 /// </summary> 4320 /// </summary>
4391 /// <returns></returns> 4321 /// <param name="agentID"></param>
4392 public ScenePresence[] GetScenePresences() 4322 /// <returns>null if the presence was not found</returns>
4323 public ScenePresence GetScenePresence(UUID agentID)
4393 { 4324 {
4394 return m_sceneGraph.GetScenePresences(); 4325 return m_sceneGraph.GetScenePresence(agentID);
4395 } 4326 }
4396 4327
4397 /// <summary> 4328 /// <summary>
4398 /// Request a filtered list of ScenePresences in this region. 4329 /// Request the scene presence by name.
4399 /// This list is a new object, so it can be iterated over without locking.
4400 /// </summary> 4330 /// </summary>
4401 /// <param name="filter"></param> 4331 /// <param name="firstName"></param>
4402 /// <returns></returns> 4332 /// <param name="lastName"></param>
4403 public List<ScenePresence> GetScenePresences(FilterAvatarList filter) 4333 /// <returns>null if the presence was not found</returns>
4334 public ScenePresence GetScenePresence(string firstName, string lastName)
4404 { 4335 {
4405 return m_sceneGraph.GetScenePresences(filter); 4336 return m_sceneGraph.GetScenePresence(firstName, lastName);
4406 } 4337 }
4407 4338
4408 /// <summary> 4339 /// <summary>
4409 /// Request a scene presence by UUID 4340 /// Request the scene presence by localID.
4410 /// </summary> 4341 /// </summary>
4411 /// <param name="avatarID"></param> 4342 /// <param name="localID"></param>
4412 /// <returns></returns> 4343 /// <returns>null if the presence was not found</returns>
4413 public ScenePresence GetScenePresence(UUID avatarID) 4344 public ScenePresence GetScenePresence(uint localID)
4414 { 4345 {
4415 return m_sceneGraph.GetScenePresence(avatarID); 4346 return m_sceneGraph.GetScenePresence(localID);
4416 } 4347 }
4417 4348
4418 public override bool PresenceChildStatus(UUID avatarID) 4349 public override bool PresenceChildStatus(UUID avatarID)
@@ -4430,25 +4361,14 @@ namespace OpenSim.Region.Framework.Scenes
4430 } 4361 }
4431 4362
4432 /// <summary> 4363 /// <summary>
4433 /// 4364 /// Performs action on all scene presences.
4434 /// </summary> 4365 /// </summary>
4435 /// <param name="action"></param> 4366 /// <param name="action"></param>
4436 public void ForEachScenePresence(Action<ScenePresence> action) 4367 public void ForEachScenePresence(Action<ScenePresence> action)
4437 { 4368 {
4438 // We don't want to try to send messages if there are no avatars.
4439 if (m_sceneGraph != null) 4369 if (m_sceneGraph != null)
4440 { 4370 {
4441 try 4371 m_sceneGraph.ForEachScenePresence(action);
4442 {
4443 ScenePresence[] presences = GetScenePresences();
4444 for (int i = 0; i < presences.Length; i++)
4445 action(presences[i]);
4446 }
4447 catch (Exception e)
4448 {
4449 m_log.Info("[BUG] in " + RegionInfo.RegionName + ": " + e.ToString());
4450 m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
4451 }
4452 } 4372 }
4453 } 4373 }
4454 4374
@@ -4512,9 +4432,9 @@ namespace OpenSim.Region.Framework.Scenes
4512 return m_sceneGraph.GetGroupByPrim(localID); 4432 return m_sceneGraph.GetGroupByPrim(localID);
4513 } 4433 }
4514 4434
4515 public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar) 4435 public override bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
4516 { 4436 {
4517 return m_sceneGraph.TryGetAvatar(avatarId, out avatar); 4437 return m_sceneGraph.TryGetScenePresence(avatarId, out avatar);
4518 } 4438 }
4519 4439
4520 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 4440 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
@@ -4524,20 +4444,7 @@ namespace OpenSim.Region.Framework.Scenes
4524 4444
4525 public void ForEachClient(Action<IClientAPI> action) 4445 public void ForEachClient(Action<IClientAPI> action)
4526 { 4446 {
4527 ForEachClient(action, m_useAsyncWhenPossible);
4528 }
4529
4530 public void ForEachClient(Action<IClientAPI> action, bool doAsynchronous)
4531 {
4532 // FIXME: Asynchronous iteration is disabled until we have a threading model that
4533 // can support calling this function from an async packet handler without
4534 // potentially deadlocking
4535 m_clientManager.ForEachSync(action); 4447 m_clientManager.ForEachSync(action);
4536
4537 //if (doAsynchronous)
4538 // m_clientManager.ForEach(action);
4539 //else
4540 // m_clientManager.ForEachSync(action);
4541 } 4448 }
4542 4449
4543 public bool TryGetClient(UUID avatarID, out IClientAPI client) 4450 public bool TryGetClient(UUID avatarID, out IClientAPI client)
@@ -4664,6 +4571,7 @@ namespace OpenSim.Region.Framework.Scenes
4664 foreach (SceneObjectPart child in partList) 4571 foreach (SceneObjectPart child in partList)
4665 { 4572 {
4666 child.Inventory.ChangeInventoryOwner(remoteClient.AgentId); 4573 child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
4574 child.TriggerScriptChangedEvent(Changed.OWNER);
4667 child.ApplyNextOwnerPermissions(); 4575 child.ApplyNextOwnerPermissions();
4668 } 4576 }
4669 } 4577 }
@@ -4673,6 +4581,8 @@ namespace OpenSim.Region.Framework.Scenes
4673 4581
4674 group.HasGroupChanged = true; 4582 group.HasGroupChanged = true;
4675 part.GetProperties(remoteClient); 4583 part.GetProperties(remoteClient);
4584 part.TriggerScriptChangedEvent(Changed.OWNER);
4585 group.ResumeScripts();
4676 part.ScheduleFullUpdate(); 4586 part.ScheduleFullUpdate();
4677 4587
4678 break; 4588 break;
@@ -4709,7 +4619,8 @@ namespace OpenSim.Region.Framework.Scenes
4709 group.GetPartName(localID), 4619 group.GetPartName(localID),
4710 group.GetPartDescription(localID), 4620 group.GetPartDescription(localID),
4711 (sbyte)AssetType.Object, 4621 (sbyte)AssetType.Object,
4712 Utils.StringToBytes(sceneObjectXml)); 4622 Utils.StringToBytes(sceneObjectXml),
4623 group.OwnerID);
4713 AssetService.Store(asset); 4624 AssetService.Store(asset);
4714 4625
4715 InventoryItemBase item = new InventoryItemBase(); 4626 InventoryItemBase item = new InventoryItemBase();
@@ -5033,5 +4944,241 @@ namespace OpenSim.Region.Framework.Scenes
5033 if (Util.EnvironmentTickCountSubtract(m_lastUpdate) > 2000) 4944 if (Util.EnvironmentTickCountSubtract(m_lastUpdate) > 2000)
5034 StartTimer(); 4945 StartTimer();
5035 } 4946 }
4947
4948 public override ISceneObject DeserializeObject(string representation)
4949 {
4950 return SceneObjectSerializer.FromXml2Format(representation);
4951 }
4952
4953 public override bool AllowScriptCrossings
4954 {
4955 get { return m_allowScriptCrossings; }
4956 }
4957
4958 public Vector3? GetNearestAllowedPosition(ScenePresence avatar)
4959 {
4960 //simulate to make sure we have pretty up to date positions
4961 PhysicsScene.Simulate(0);
4962
4963 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
4964
4965 if (nearestParcel != null)
4966 {
4967 Vector3 dir = Vector3.Normalize(Vector3.Multiply(avatar.Velocity, -1));
4968 //Try to get a location that feels like where they came from
4969 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4970 if (nearestPoint != null)
4971 {
4972 Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
4973 return nearestPoint.Value;
4974 }
4975
4976 //Sometimes velocity might be zero (local teleport), so try finding point along path from avatar to center of nearest parcel
4977 Vector3 directionToParcelCenter = Vector3.Subtract(GetParcelCenterAtGround(nearestParcel), avatar.AbsolutePosition);
4978 dir = Vector3.Normalize(directionToParcelCenter);
4979 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4980 if (nearestPoint != null)
4981 {
4982 Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
4983 return nearestPoint.Value;
4984 }
4985
4986 //Ultimate backup if we have no idea where they are
4987 Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
4988 return avatar.lastKnownAllowedPosition;
4989
4990 }
4991
4992 //Go to the edge, this happens in teleporting to a region with no available parcels
4993 Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
4994 //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
4995 return nearestRegionEdgePoint;
4996 return null;
4997 }
4998
4999 private Vector3 GetParcelCenterAtGround(ILandObject parcel)
5000 {
5001 Vector2 center = GetParcelCenter(parcel);
5002 return GetPositionAtGround(center.X, center.Y);
5003 }
5004
5005 private Vector3? GetNearestPointInParcelAlongDirectionFromPoint(Vector3 pos, Vector3 direction, ILandObject parcel)
5006 {
5007 Vector3 unitDirection = Vector3.Normalize(direction);
5008 //Making distance to search go through some sane limit of distance
5009 for (float distance = 0; distance < Constants.RegionSize * 2; distance += .5f)
5010 {
5011 Vector3 testPos = Vector3.Add(pos, Vector3.Multiply(unitDirection, distance));
5012 if (parcel.ContainsPoint((int)testPos.X, (int)testPos.Y))
5013 {
5014 return testPos;
5015 }
5016 }
5017 return null;
5018 }
5019
5020 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
5021 {
5022 List<ILandObject> all = AllParcels();
5023 float minParcelDistance = float.MaxValue;
5024 ILandObject nearestParcel = null;
5025
5026 foreach (var parcel in all)
5027 {
5028 if (!parcel.IsEitherBannedOrRestricted(avatarId))
5029 {
5030 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
5031 if (parcelDistance < minParcelDistance)
5032 {
5033 minParcelDistance = parcelDistance;
5034 nearestParcel = parcel;
5035 }
5036 }
5037 }
5038
5039 return nearestParcel;
5040 }
5041
5042 private List<ILandObject> AllParcels()
5043 {
5044 return LandChannel.AllParcels();
5045 }
5046
5047 private float GetParcelDistancefromPoint(ILandObject parcel, float x, float y)
5048 {
5049 return Vector2.Distance(new Vector2(x, y), GetParcelCenter(parcel));
5050 }
5051
5052 //calculate the average center point of a parcel
5053 private Vector2 GetParcelCenter(ILandObject parcel)
5054 {
5055 int count = 0;
5056 int avgx = 0;
5057 int avgy = 0;
5058 for (int x = 0; x < Constants.RegionSize; x++)
5059 {
5060 for (int y = 0; y < Constants.RegionSize; y++)
5061 {
5062 //Just keep a running average as we check if all the points are inside or not
5063 if (parcel.ContainsPoint(x, y))
5064 {
5065 if (count == 0)
5066 {
5067 avgx = x;
5068 avgy = y;
5069 }
5070 else
5071 {
5072 avgx = (avgx * count + x) / (count + 1);
5073 avgy = (avgy * count + y) / (count + 1);
5074 }
5075 count += 1;
5076 }
5077 }
5078 }
5079 return new Vector2(avgx, avgy);
5080 }
5081
5082 private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
5083 {
5084 float xdistance = avatar.AbsolutePosition.X < Constants.RegionSize / 2 ? avatar.AbsolutePosition.X : Constants.RegionSize - avatar.AbsolutePosition.X;
5085 float ydistance = avatar.AbsolutePosition.Y < Constants.RegionSize / 2 ? avatar.AbsolutePosition.Y : Constants.RegionSize - avatar.AbsolutePosition.Y;
5086
5087 //find out what vertical edge to go to
5088 if (xdistance < ydistance)
5089 {
5090 if (avatar.AbsolutePosition.X < Constants.RegionSize / 2)
5091 {
5092 return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.0f, avatar.AbsolutePosition.Y);
5093 }
5094 else
5095 {
5096 return GetPositionAtAvatarHeightOrGroundHeight(avatar, Constants.RegionSize, avatar.AbsolutePosition.Y);
5097 }
5098 }
5099 //find out what horizontal edge to go to
5100 else
5101 {
5102 if (avatar.AbsolutePosition.Y < Constants.RegionSize / 2)
5103 {
5104 return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, 0.0f);
5105 }
5106 else
5107 {
5108 return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, Constants.RegionSize);
5109 }
5110 }
5111 }
5112
5113 private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
5114 {
5115 Vector3 ground = GetPositionAtGround(x, y);
5116 if (avatar.AbsolutePosition.Z > ground.Z)
5117 {
5118 ground.Z = avatar.AbsolutePosition.Z;
5119 }
5120 return ground;
5121 }
5122
5123 private Vector3 GetPositionAtGround(float x, float y)
5124 {
5125 return new Vector3(x, y, GetGroundHeight(x, y));
5126 }
5127
5128 public List<UUID> GetEstateRegions(int estateID)
5129 {
5130 if (m_storageManager.EstateDataStore == null)
5131 return new List<UUID>();
5132
5133 return m_storageManager.EstateDataStore.GetRegions(estateID);
5134 }
5135
5136 public void ReloadEstateData()
5137 {
5138 m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false);
5139
5140 TriggerEstateSunUpdate();
5141 }
5142
5143 public void TriggerEstateSunUpdate()
5144 {
5145 float sun;
5146 if (RegionInfo.RegionSettings.UseEstateSun)
5147 {
5148 sun = (float)RegionInfo.EstateSettings.SunPosition;
5149 if (RegionInfo.EstateSettings.UseGlobalTime)
5150 {
5151 sun = EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f;
5152 }
5153
5154 //
5155 EventManager.TriggerEstateToolsSunUpdate(
5156 RegionInfo.RegionHandle,
5157 RegionInfo.EstateSettings.FixedSun,
5158 RegionInfo.RegionSettings.UseEstateSun,
5159 sun);
5160 }
5161 else
5162 {
5163 // Use the Sun Position from the Region Settings
5164 sun = (float)RegionInfo.RegionSettings.SunPosition - 6.0f;
5165
5166 EventManager.TriggerEstateToolsSunUpdate(
5167 RegionInfo.RegionHandle,
5168 RegionInfo.RegionSettings.FixedSun,
5169 RegionInfo.RegionSettings.UseEstateSun,
5170 sun);
5171 }
5172 }
5173
5174 private void HandleReloadEstate(string module, string[] cmd)
5175 {
5176 if (MainConsole.Instance.ConsoleScene == null ||
5177 (MainConsole.Instance.ConsoleScene is Scene &&
5178 (Scene)MainConsole.Instance.ConsoleScene == this))
5179 {
5180 ReloadEstateData();
5181 }
5182 }
5036 } 5183 }
5037} 5184}
diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs
index 5e798c0..3218dad 100644
--- a/OpenSim/Region/Framework/Scenes/SceneBase.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs
@@ -34,7 +34,7 @@ using log4net;
34using Nini.Config; 34using Nini.Config;
35using OpenSim.Framework; 35using OpenSim.Framework;
36using OpenSim.Framework.Console; 36using OpenSim.Framework.Console;
37using OpenSim.Framework.Communications.Cache; 37
38using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
39using GridRegion = OpenSim.Services.Interfaces.GridRegion; 39using GridRegion = OpenSim.Services.Interfaces.GridRegion;
40 40
@@ -190,6 +190,21 @@ namespace OpenSim.Region.Framework.Scenes
190 /// <param name="agentID"></param> 190 /// <param name="agentID"></param>
191 public abstract void RemoveClient(UUID agentID); 191 public abstract void RemoveClient(UUID agentID);
192 192
193 public bool TryGetScenePresence(UUID agentID, out object scenePresence)
194 {
195 scenePresence = null;
196 ScenePresence sp = null;
197 if (TryGetScenePresence(agentID, out sp))
198 {
199 scenePresence = sp;
200 return true;
201 }
202
203 return false;
204 }
205
206 public abstract bool TryGetScenePresence(UUID agentID, out ScenePresence scenePresence);
207
193 #endregion 208 #endregion
194 209
195 /// <summary> 210 /// <summary>
@@ -510,5 +525,16 @@ namespace OpenSim.Region.Framework.Scenes
510 525
511 MainConsole.Instance.Commands.AddCommand(modulename, shared, command, shorthelp, longhelp, callback); 526 MainConsole.Instance.Commands.AddCommand(modulename, shared, command, shorthelp, longhelp, callback);
512 } 527 }
528
529 public virtual ISceneObject DeserializeObject(string representation)
530 {
531 return null;
532 }
533
534 public virtual bool AllowScriptCrossings
535 {
536 get { return false; }
537 }
538
513 } 539 }
514} 540}
diff --git a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
index 04626d3..9d0e6f4 100644
--- a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
@@ -36,7 +36,6 @@ using log4net;
36using OpenSim.Framework; 36using OpenSim.Framework;
37using OpenSim.Framework.Client; 37using OpenSim.Framework.Client;
38using OpenSim.Framework.Communications; 38using OpenSim.Framework.Communications;
39using OpenSim.Framework.Communications.Cache;
40using OpenSim.Framework.Capabilities; 39using OpenSim.Framework.Capabilities;
41using OpenSim.Region.Framework.Interfaces; 40using OpenSim.Region.Framework.Interfaces;
42using OpenSim.Services.Interfaces; 41using OpenSim.Services.Interfaces;
@@ -56,8 +55,6 @@ namespace OpenSim.Region.Framework.Scenes
56 { 55 {
57 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 56 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
58 57
59 protected CommunicationsManager m_commsProvider;
60 protected IInterregionCommsOut m_interregionCommsOut;
61 protected RegionInfo m_regionInfo; 58 protected RegionInfo m_regionInfo;
62 protected Scene m_scene; 59 protected Scene m_scene;
63 60
@@ -106,29 +103,26 @@ namespace OpenSim.Region.Framework.Scenes
106 /// </summary> 103 /// </summary>
107 public event GetLandData OnGetLandData; 104 public event GetLandData OnGetLandData;
108 105
109 private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion; 106// private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
110 private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser; 107// private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser;
111 private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection; 108// private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
112 private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion; 109// private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
113 //private RegionUp handlerRegionUp = null; // OnRegionUp; 110 //private RegionUp handlerRegionUp = null; // OnRegionUp;
114 private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate; 111// private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
115 //private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar; 112 //private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar;
116 private LogOffUser handlerLogOffUser = null; 113// private LogOffUser handlerLogOffUser = null;
117 private GetLandData handlerGetLandData = null; // OnGetLandData 114// private GetLandData handlerGetLandData = null; // OnGetLandData
118 115
119 public KiPrimitiveDelegate KiPrimitive; 116 public KiPrimitiveDelegate KiPrimitive;
120 117
121 public SceneCommunicationService(CommunicationsManager commsMan) 118 public SceneCommunicationService()
122 { 119 {
123 m_commsProvider = commsMan;
124 m_agentsInTransit = new List<UUID>();
125 } 120 }
126 121
127 public void SetScene(Scene s) 122 public void SetScene(Scene s)
128 { 123 {
129 m_scene = s; 124 m_scene = s;
130 m_regionInfo = s.RegionInfo; 125 m_regionInfo = s.RegionInfo;
131 m_interregionCommsOut = m_scene.RequestModuleInterface<IInterregionCommsOut>();
132 } 126 }
133 127
134 /// <summary> 128 /// <summary>
@@ -148,377 +142,6 @@ namespace OpenSim.Region.Framework.Scenes
148 { 142 {
149 } 143 }
150 144
151 #region CommsManager Event handlers
152
153 /// <summary>
154 /// A New User will arrive shortly, Informs the scene that there's a new user on the way
155 /// </summary>
156 /// <param name="agent">Data we need to ensure that the agent can connect</param>
157 ///
158 protected void NewUserConnection(AgentCircuitData agent)
159 {
160 handlerExpectUser = OnExpectUser;
161 if (handlerExpectUser != null)
162 {
163 //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname);
164 handlerExpectUser(agent);
165 }
166 }
167
168 /// <summary>
169 /// The Grid has requested us to log-off the user
170 /// </summary>
171 /// <param name="AgentID">Unique ID of agent to log-off</param>
172 /// <param name="RegionSecret">The secret string that the region establishes with the grid when registering</param>
173 /// <param name="message">The message to send to the user that tells them why they were logged off</param>
174 protected void GridLogOffUser(UUID AgentID, UUID RegionSecret, string message)
175 {
176 handlerLogOffUser = OnLogOffUser;
177 if (handlerLogOffUser != null)
178 {
179 handlerLogOffUser(AgentID, RegionSecret, message);
180 }
181 }
182
183 /// <summary>
184 /// Inform the scene that we've got an update about a child agent that we have
185 /// </summary>
186 /// <param name="cAgentData"></param>
187 /// <returns></returns>
188 protected bool ChildAgentUpdate(ChildAgentDataUpdate cAgentData)
189 {
190 handlerChildAgentUpdate = OnChildAgentUpdate;
191 if (handlerChildAgentUpdate != null)
192 handlerChildAgentUpdate(cAgentData);
193
194 return true;
195 }
196
197
198 protected void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
199 {
200 handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
201 if (handlerAvatarCrossingIntoRegion != null)
202 {
203 handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
204 }
205 }
206
207 protected void PrimCrossing(UUID primID, Vector3 position, bool isPhysical)
208 {
209 handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
210 if (handlerPrimCrossingIntoRegion != null)
211 {
212 handlerPrimCrossingIntoRegion(primID, position, isPhysical);
213 }
214 }
215
216 protected bool CloseConnection(UUID agentID)
217 {
218 m_log.Debug("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID);
219
220 handlerCloseAgentConnection = OnCloseAgentConnection;
221 if (handlerCloseAgentConnection != null)
222 {
223 return handlerCloseAgentConnection(agentID);
224 }
225
226 return false;
227 }
228
229 protected LandData FetchLandData(uint x, uint y)
230 {
231 handlerGetLandData = OnGetLandData;
232 if (handlerGetLandData != null)
233 {
234 return handlerGetLandData(x, y);
235 }
236 return null;
237 }
238
239 #endregion
240
241 #region Inform Client of Neighbours
242
243 private delegate void InformClientOfNeighbourDelegate(
244 ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
245
246 private void InformClientOfNeighbourCompleted(IAsyncResult iar)
247 {
248 InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState;
249 icon.EndInvoke(iar);
250 }
251
252 /// <summary>
253 /// Async component for informing client of which neighbours exist
254 /// </summary>
255 /// <remarks>
256 /// This needs to run asynchronously, as a network timeout may block the thread for a long while
257 /// </remarks>
258 /// <param name="remoteClient"></param>
259 /// <param name="a"></param>
260 /// <param name="regionHandle"></param>
261 /// <param name="endPoint"></param>
262 private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, GridRegion reg,
263 IPEndPoint endPoint, bool newAgent)
264 {
265 // Let's wait just a little to give time to originating regions to catch up with closing child agents
266 // after a cross here
267 Thread.Sleep(500);
268
269 uint x, y;
270 Utils.LongToUInts(reg.RegionHandle, out x, out y);
271 x = x / Constants.RegionSize;
272 y = y / Constants.RegionSize;
273 m_log.Info("[INTERGRID]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
274
275 string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
276 + "/CAPS/" + a.CapsPath + "0000/";
277
278 string reason = String.Empty;
279
280
281 bool regionAccepted = m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, 0, out reason);
282
283 if (regionAccepted && newAgent)
284 {
285 IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
286 if (eq != null)
287 {
288 #region IP Translation for NAT
289 IClientIPEndpoint ipepClient;
290 if (avatar.ClientView.TryGet(out ipepClient))
291 {
292 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
293 }
294 #endregion
295
296 eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
297 eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
298 m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1} in region {2}",
299 capsPath, avatar.UUID, avatar.Scene.RegionInfo.RegionName);
300 }
301 else
302 {
303 avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
304 // TODO: make Event Queue disablable!
305 }
306
307 m_log.Info("[INTERGRID]: Completed inform client about neighbour " + endPoint.ToString());
308
309 }
310
311 }
312
313 public List<GridRegion> RequestNeighbours(Scene pScene, uint pRegionLocX, uint pRegionLocY)
314 {
315 Border[] northBorders = pScene.NorthBorders.ToArray();
316 Border[] southBorders = pScene.SouthBorders.ToArray();
317 Border[] eastBorders = pScene.EastBorders.ToArray();
318 Border[] westBorders = pScene.WestBorders.ToArray();
319
320 // Legacy one region. Provided for simplicity while testing the all inclusive method in the else statement.
321 if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1)
322 {
323 return m_scene.GridService.GetNeighbours(m_regionInfo.ScopeID, m_regionInfo.RegionID);
324 }
325 else
326 {
327 Vector2 extent = Vector2.Zero;
328 for (int i = 0; i < eastBorders.Length; i++)
329 {
330 extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
331 }
332 for (int i = 0; i < northBorders.Length; i++)
333 {
334 extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
335 }
336
337 // Loss of fraction on purpose
338 extent.X = ((int)extent.X / (int)Constants.RegionSize) + 1;
339 extent.Y = ((int)extent.Y / (int)Constants.RegionSize) + 1;
340
341 int startX = (int)(pRegionLocX - 1) * (int)Constants.RegionSize;
342 int startY = (int)(pRegionLocY - 1) * (int)Constants.RegionSize;
343
344 int endX = ((int)pRegionLocX + (int)extent.X) * (int)Constants.RegionSize;
345 int endY = ((int)pRegionLocY + (int)extent.Y) * (int)Constants.RegionSize;
346
347 List<GridRegion> neighbours = m_scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
348 neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
349
350 return neighbours;
351 }
352 }
353
354 /// <summary>
355 /// This informs all neighboring regions about agent "avatar".
356 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
357 /// </summary>
358 public void EnableNeighbourChildAgents(ScenePresence avatar, List<RegionInfo> lstneighbours)
359 {
360 List<GridRegion> neighbours = new List<GridRegion>();
361
362 if (m_regionInfo != null)
363 {
364 neighbours = RequestNeighbours(avatar.Scene,m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
365 }
366 else
367 {
368 m_log.Debug("[ENABLENEIGHBOURCHILDAGENTS]: m_regionInfo was null in EnableNeighbourChildAgents, is this a NPC?");
369 }
370
371 /// We need to find the difference between the new regions where there are no child agents
372 /// and the regions where there are already child agents. We only send notification to the former.
373 List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
374 neighbourHandles.Add(avatar.Scene.RegionInfo.RegionHandle); // add this region too
375 List<ulong> previousRegionNeighbourHandles ;
376
377 if (avatar.Scene.CapsModule != null)
378 {
379 previousRegionNeighbourHandles =
380 new List<ulong>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID).Keys);
381 }
382 else
383 {
384 previousRegionNeighbourHandles = new List<ulong>();
385 }
386
387 List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
388 List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
389
390 //Dump("Current Neighbors", neighbourHandles);
391 //Dump("Previous Neighbours", previousRegionNeighbourHandles);
392 //Dump("New Neighbours", newRegions);
393 //Dump("Old Neighbours", oldRegions);
394
395 /// Update the scene presence's known regions here on this region
396 avatar.DropOldNeighbours(oldRegions);
397
398 /// Collect as many seeds as possible
399 Dictionary<ulong, string> seeds;
400 if (avatar.Scene.CapsModule != null)
401 seeds
402 = new Dictionary<ulong, string>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID));
403 else
404 seeds = new Dictionary<ulong, string>();
405
406 //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
407 if (!seeds.ContainsKey(avatar.Scene.RegionInfo.RegionHandle))
408 seeds.Add(avatar.Scene.RegionInfo.RegionHandle, avatar.ControllingClient.RequestClientInfo().CapsPath);
409
410 /// Create the necessary child agents
411 List<AgentCircuitData> cagents = new List<AgentCircuitData>();
412 foreach (GridRegion neighbour in neighbours)
413 {
414 if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
415 {
416
417 AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
418 agent.BaseFolder = UUID.Zero;
419 agent.InventoryFolder = UUID.Zero;
420 agent.startpos = new Vector3(128, 128, 70);
421 agent.child = true;
422
423 if (newRegions.Contains(neighbour.RegionHandle))
424 {
425 agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
426 avatar.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
427 seeds.Add(neighbour.RegionHandle, agent.CapsPath);
428 }
429 else
430 agent.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, neighbour.RegionHandle);
431
432 cagents.Add(agent);
433 }
434 }
435
436 /// Update all child agent with everyone's seeds
437 foreach (AgentCircuitData a in cagents)
438 {
439 a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
440 }
441
442 if (avatar.Scene.CapsModule != null)
443 {
444 // These two are the same thing!
445 avatar.Scene.CapsModule.SetChildrenSeed(avatar.UUID, seeds);
446 }
447 avatar.KnownRegions = seeds;
448 //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
449 //avatar.DumpKnownRegions();
450
451 bool newAgent = false;
452 int count = 0;
453 foreach (GridRegion neighbour in neighbours)
454 {
455 // Don't do it if there's already an agent in that region
456 if (newRegions.Contains(neighbour.RegionHandle))
457 newAgent = true;
458 else
459 newAgent = false;
460
461 if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
462 {
463 InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
464 try
465 {
466 d.BeginInvoke(avatar, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
467 InformClientOfNeighbourCompleted,
468 d);
469 }
470
471 catch (ArgumentOutOfRangeException)
472 {
473 m_log.ErrorFormat(
474 "[REGIONINFO]: Neighbour Regions response included the current region in the neighbor list. The following region will not display to the client: {0} for region {1} ({2}, {3}).",
475 neighbour.ExternalHostName,
476 neighbour.RegionHandle,
477 neighbour.RegionLocX,
478 neighbour.RegionLocY);
479 }
480 catch (Exception e)
481 {
482 m_log.ErrorFormat(
483 "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
484 neighbour.ExternalHostName,
485 neighbour.RegionHandle,
486 neighbour.RegionLocX,
487 neighbour.RegionLocY,
488 e);
489
490 // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
491 // since I don't know what will happen if we just let the client continue
492
493 // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
494 // throw e;
495
496 }
497 }
498 count++;
499 }
500 }
501
502 /// <summary>
503 /// This informs a single neighboring region about agent "avatar".
504 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
505 /// </summary>
506 public void InformNeighborChildAgent(ScenePresence avatar, GridRegion region)
507 {
508 AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
509 agent.BaseFolder = UUID.Zero;
510 agent.InventoryFolder = UUID.Zero;
511 agent.startpos = new Vector3(128, 128, 70);
512 agent.child = true;
513
514 InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
515 d.BeginInvoke(avatar, agent, region, region.ExternalEndPoint, true,
516 InformClientOfNeighbourCompleted,
517 d);
518 }
519
520 #endregion
521
522 public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle); 145 public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle);
523 146
524 private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar) 147 private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
@@ -550,7 +173,7 @@ namespace OpenSim.Region.Framework.Scenes
550 } 173 }
551 else 174 else
552 { 175 {
553 m_log.WarnFormat("[INTERGRID]: Failed to inform neighbour {0}-{1} that I'm here.", x / Constants.RegionSize, y / Constants.RegionSize); 176 m_log.InfoFormat("[INTERGRID]: Failed to inform neighbour {0}-{1} that I'm here.", x / Constants.RegionSize, y / Constants.RegionSize);
554 } 177 }
555 } 178 }
556 179
@@ -592,7 +215,10 @@ namespace OpenSim.Region.Framework.Scenes
592 try 215 try
593 { 216 {
594 //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData); 217 //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
595 m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData); 218 uint x = 0, y = 0;
219 Utils.LongToUInts(regionHandle, out x, out y);
220 GridRegion destination = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
221 m_scene.SimulationService.UpdateAgent(destination, cAgentData);
596 } 222 }
597 catch 223 catch
598 { 224 {
@@ -652,7 +278,10 @@ namespace OpenSim.Region.Framework.Scenes
652 // let's do our best, but there's not much we can do if the neighbour doesn't accept. 278 // let's do our best, but there's not much we can do if the neighbour doesn't accept.
653 279
654 //m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID); 280 //m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
655 m_interregionCommsOut.SendCloseAgent(regionHandle, agentID); 281 uint x = 0, y = 0;
282 Utils.LongToUInts(regionHandle, out x, out y);
283 GridRegion destination = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
284 m_scene.SimulationService.CloseAgent(destination, agentID);
656 } 285 }
657 286
658 private void SendCloseChildAgentCompleted(IAsyncResult iar) 287 private void SendCloseChildAgentCompleted(IAsyncResult iar)
@@ -672,848 +301,10 @@ namespace OpenSim.Region.Framework.Scenes
672 } 301 }
673 } 302 }
674 303
675
676 /// <summary>
677 /// Try to teleport an agent to a new region.
678 /// </summary>
679 /// <param name="remoteClient"></param>
680 /// <param name="RegionHandle"></param>
681 /// <param name="position"></param>
682 /// <param name="lookAt"></param>
683 /// <param name="flags"></param>
684 public virtual void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
685 Vector3 lookAt, uint teleportFlags)
686 {
687 if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
688 return;
689
690 bool destRegionUp = true;
691
692 IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
693
694 // Reset animations; the viewer does that in teleports.
695 avatar.Animator.ResetAnimations();
696
697 if (regionHandle == m_regionInfo.RegionHandle)
698 {
699 m_log.DebugFormat(
700 "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation {0} within {1}",
701 position, m_regionInfo.RegionName);
702
703 // Teleport within the same region
704 if (IsOutsideRegion(avatar.Scene, position) || position.Z < 0)
705 {
706 Vector3 emergencyPos = new Vector3(128, 128, 128);
707
708 m_log.WarnFormat(
709 "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
710 position, avatar.Name, avatar.UUID, emergencyPos);
711 position = emergencyPos;
712 }
713
714 Vector3 currentPos = avatar.AbsolutePosition;
715 ILandObject srcLand = m_scene.LandChannel.GetLandObject(currentPos.X, currentPos.Y);
716 ILandObject destLand = m_scene.LandChannel.GetLandObject(position.X, position.Y);
717 if (srcLand != null && destLand != null && (teleportFlags & (uint)TeleportFlags.ViaLure) == 0 && (teleportFlags & (uint)TeleportFlags.ViaGodlikeLure) == 0)
718 {
719 if (srcLand.LandData.LocalID == destLand.LandData.LocalID)
720 {
721 //TPing within the same parcel. If the landing point is restricted, block the TP.
722 //Don't restrict gods, estate managers, or land owners to the TP point. This behaviour mimics agni.
723 if (destLand.LandData.LandingType == (byte)1 && destLand.LandData.UserLocation != Vector3.Zero && avatar.GodLevel < 200 && !m_scene.RegionInfo.EstateSettings.IsEstateManager(avatar.UUID) && destLand.LandData.OwnerID != avatar.UUID)
724 {
725 //Disabling this behaviour for now pending review. ~CasperW
726
727 //avatar.ControllingClient.SendAgentAlertMessage("Can't TP to the destination; landing point set.", false);
728 //position = currentPos;
729 }
730 }
731 else
732 {
733 //Tping to a different parcel. Respect the landing point on the destination parcel.
734 if (destLand.LandData.LandingType == (byte)1 && destLand.LandData.UserLocation != Vector3.Zero && avatar.GodLevel < 200 && !m_scene.RegionInfo.EstateSettings.IsEstateManager(avatar.UUID) && destLand.LandData.OwnerID != avatar.UUID)
735 {
736 position = destLand.LandData.UserLocation;
737 }
738 }
739 }
740
741 // TODO: Get proper AVG Height
742 float localAVHeight = 1.56f;
743 float posZLimit = 22;
744
745 // TODO: Check other Scene HeightField
746 if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <=(int)Constants.RegionSize)
747 {
748 posZLimit = (float) avatar.Scene.Heightmap[(int) position.X, (int) position.Y];
749 }
750
751 float newPosZ = posZLimit + localAVHeight;
752 if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
753 {
754 position.Z = newPosZ;
755 }
756
757 // Only send this if the event queue is null
758 if (eq == null)
759 avatar.ControllingClient.SendTeleportLocationStart();
760
761 avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
762 avatar.Teleport(position);
763 }
764 else
765 {
766 uint x = 0, y = 0;
767 Utils.LongToUInts(regionHandle, out x, out y);
768 GridRegion reg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
769
770 if (reg != null)
771 {
772 m_log.DebugFormat(
773 "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation to {0} in {1}",
774 position, reg.RegionName);
775
776 if (eq == null)
777 avatar.ControllingClient.SendTeleportLocationStart();
778
779 // Let's do DNS resolution only once in this process, please!
780 // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
781 // it's actually doing a lot of work.
782 IPEndPoint endPoint = reg.ExternalEndPoint;
783 if (endPoint.Address == null)
784 {
785 // Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
786 destRegionUp = false;
787 }
788
789 if (destRegionUp)
790 {
791 uint newRegionX = (uint)(reg.RegionHandle >> 40);
792 uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
793 uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
794 uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
795
796 // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
797 // both regions
798 if (avatar.ParentID != (uint)0)
799 avatar.StandUp();
800
801 if (!avatar.ValidateAttachments())
802 {
803 avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
804 return;
805 }
806
807 // the avatar.Close below will clear the child region list. We need this below for (possibly)
808 // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
809 //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
810 // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
811 // failure at this point (unlike a border crossing failure). So perhaps this can never fail
812 // once we reach here...
813 //avatar.Scene.RemoveCapsHandler(avatar.UUID);
814
815 string capsPath = String.Empty;
816 AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
817 agentCircuit.BaseFolder = UUID.Zero;
818 agentCircuit.InventoryFolder = UUID.Zero;
819 agentCircuit.startpos = position;
820 agentCircuit.child = true;
821
822 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
823 {
824 // brand new agent, let's create a new caps seed
825 agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
826 }
827
828 string reason = String.Empty;
829
830 // Let's create an agent there if one doesn't exist yet.
831 //if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
832 if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, teleportFlags, out reason))
833 {
834 avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
835 reason));
836 return;
837 }
838
839 // OK, it got this agent. Let's close some child agents
840 avatar.CloseChildAgents(newRegionX, newRegionY);
841
842 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
843 {
844 #region IP Translation for NAT
845 IClientIPEndpoint ipepClient;
846 if (avatar.ClientView.TryGet(out ipepClient))
847 {
848 capsPath
849 = "http://"
850 + NetworkUtil.GetHostFor(ipepClient.EndPoint, reg.ExternalHostName)
851 + ":"
852 + reg.HttpPort
853 + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
854 }
855 else
856 {
857 capsPath
858 = "http://"
859 + reg.ExternalHostName
860 + ":"
861 + reg.HttpPort
862 + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
863 }
864 #endregion
865
866 if (eq != null)
867 {
868 #region IP Translation for NAT
869 // Uses ipepClient above
870 if (avatar.ClientView.TryGet(out ipepClient))
871 {
872 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
873 }
874 #endregion
875
876 eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
877
878 // ES makes the client send a UseCircuitCode message to the destination,
879 // which triggers a bunch of things there.
880 // So let's wait
881 Thread.Sleep(2000);
882
883 eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
884 }
885 else
886 {
887 avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
888 }
889 }
890 else
891 {
892 agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
893 capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
894 + "/CAPS/" + agentCircuit.CapsPath + "0000/";
895 }
896
897 // Expect avatar crossing is a heavy-duty function at the destination.
898 // That is where MakeRoot is called, which fetches appearance and inventory.
899 // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
900 //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
901 // position, false);
902
903 //{
904 // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
905 // // We should close that agent we just created over at destination...
906 // List<ulong> lst = new List<ulong>();
907 // lst.Add(reg.RegionHandle);
908 // SendCloseChildAgentAsync(avatar.UUID, lst);
909 // return;
910 //}
911
912 SetInTransit(avatar.UUID);
913 // Let's send a full update of the agent. This is a synchronous call.
914 AgentData agent = new AgentData();
915 avatar.CopyTo(agent);
916 agent.Position = position;
917 agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
918 "/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
919
920 m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
921
922 m_log.DebugFormat(
923 "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID);
924
925
926 if (eq != null)
927 {
928 eq.TeleportFinishEvent(reg.RegionHandle, 13, endPoint,
929 0, teleportFlags, capsPath, avatar.UUID);
930 }
931 else
932 {
933 avatar.ControllingClient.SendRegionTeleport(reg.RegionHandle, 13, endPoint, 4,
934 teleportFlags, capsPath);
935 }
936
937 // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
938 // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
939 // that the client contacted the destination before we send the attachments and close things here.
940 if (!WaitForCallback(avatar.UUID))
941 {
942 // Client never contacted destination. Let's restore everything back
943 avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
944
945 ResetFromTransit(avatar.UUID);
946
947 // Yikes! We should just have a ref to scene here.
948 avatar.Scene.InformClientOfNeighbours(avatar);
949
950 // Finally, kill the agent we just created at the destination.
951 m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
952
953 return;
954 }
955
956 // Can't go back from here
957 if (KiPrimitive != null)
958 {
959 KiPrimitive(avatar.LocalId);
960 }
961
962 avatar.MakeChildAgent();
963
964 // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
965 avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
966
967 // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
968
969 if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
970 {
971 Thread.Sleep(5000);
972 avatar.Close();
973 CloseConnection(avatar.UUID);
974 }
975 else
976 // now we have a child agent in this region.
977 avatar.Reset();
978
979
980 // if (teleport success) // seems to be always success here
981 // the user may change their profile information in other region,
982 // so the userinfo in UserProfileCache is not reliable any more, delete it
983 if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
984 {
985 m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
986 m_log.DebugFormat(
987 "[SCENE COMMUNICATION SERVICE]: User {0} is going to another region, profile cache removed",
988 avatar.UUID);
989 }
990 }
991 else
992 {
993 avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
994 }
995 }
996 else
997 {
998 // TP to a place that doesn't exist (anymore)
999 // Inform the viewer about that
1000 avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
1001
1002 // and set the map-tile to '(Offline)'
1003 uint regX, regY;
1004 Utils.LongToUInts(regionHandle, out regX, out regY);
1005
1006 MapBlockData block = new MapBlockData();
1007 block.X = (ushort)(regX / Constants.RegionSize);
1008 block.Y = (ushort)(regY / Constants.RegionSize);
1009 block.Access = 254; // == not there
1010
1011 List<MapBlockData> blocks = new List<MapBlockData>();
1012 blocks.Add(block);
1013 avatar.ControllingClient.SendMapBlock(blocks, 0);
1014 }
1015 }
1016 }
1017
1018 protected bool IsOutsideRegion(Scene s, Vector3 pos)
1019 {
1020
1021 if (s.TestBorderCross(pos,Cardinals.N))
1022 return true;
1023 if (s.TestBorderCross(pos, Cardinals.S))
1024 return true;
1025 if (s.TestBorderCross(pos, Cardinals.E))
1026 return true;
1027 if (s.TestBorderCross(pos, Cardinals.W))
1028 return true;
1029
1030 return false;
1031 }
1032
1033 public bool WaitForCallback(UUID id)
1034 {
1035 int count = 400;
1036 while (m_agentsInTransit.Contains(id) && count-- > 0)
1037 {
1038 //m_log.Debug(" >>> Waiting... " + count);
1039 Thread.Sleep(100);
1040 }
1041
1042 if (count > 0)
1043 return true;
1044 else
1045 return false;
1046 }
1047
1048 public bool ReleaseAgent(UUID id)
1049 {
1050 //m_log.Debug(" >>> ReleaseAgent called <<< ");
1051 return ResetFromTransit(id);
1052 }
1053
1054 public void SetInTransit(UUID id)
1055 {
1056 lock (m_agentsInTransit)
1057 {
1058 if (!m_agentsInTransit.Contains(id))
1059 m_agentsInTransit.Add(id);
1060 }
1061 }
1062
1063 protected bool ResetFromTransit(UUID id)
1064 {
1065 lock (m_agentsInTransit)
1066 {
1067 if (m_agentsInTransit.Contains(id))
1068 {
1069 m_agentsInTransit.Remove(id);
1070 return true;
1071 }
1072 }
1073 return false;
1074 }
1075
1076 private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
1077 {
1078 List<ulong> handles = new List<ulong>();
1079 foreach (GridRegion reg in neighbours)
1080 {
1081 handles.Add(reg.RegionHandle);
1082 }
1083 return handles;
1084 }
1085
1086 private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1087 {
1088 return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
1089 }
1090
1091// private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1092// {
1093// return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
1094// }
1095
1096 private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
1097 {
1098 return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
1099 }
1100
1101 public void CrossAgentToNewRegion(Scene scene, ScenePresence agent, bool isFlying)
1102 {
1103 Vector3 pos = agent.AbsolutePosition;
1104 Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
1105 uint neighbourx = m_regionInfo.RegionLocX;
1106 uint neighboury = m_regionInfo.RegionLocY;
1107 const float boundaryDistance = 1.7f;
1108 Vector3 northCross = new Vector3(0,boundaryDistance, 0);
1109 Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
1110 Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
1111 Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
1112
1113 // distance to edge that will trigger crossing
1114
1115
1116 // distance into new region to place avatar
1117 const float enterDistance = 0.5f;
1118
1119 if (scene.TestBorderCross(pos + westCross, Cardinals.W))
1120 {
1121 if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1122 {
1123 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1124 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1125 }
1126 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1127 {
1128 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1129 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
1130 {
1131 neighboury--;
1132 newpos.Y = Constants.RegionSize - enterDistance;
1133 }
1134 else
1135 {
1136 neighboury = b.TriggerRegionY;
1137 neighbourx = b.TriggerRegionX;
1138
1139 Vector3 newposition = pos;
1140 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1141 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1142 agent.ControllingClient.SendAgentAlertMessage(
1143 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1144 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1145 return;
1146 }
1147 }
1148
1149 Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
1150 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
1151 {
1152 neighbourx--;
1153 newpos.X = Constants.RegionSize - enterDistance;
1154 }
1155 else
1156 {
1157 neighboury = ba.TriggerRegionY;
1158 neighbourx = ba.TriggerRegionX;
1159
1160
1161 Vector3 newposition = pos;
1162 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1163 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1164 agent.ControllingClient.SendAgentAlertMessage(
1165 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1166 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1167
1168
1169 return;
1170 }
1171
1172 }
1173 else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
1174 {
1175 Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
1176 neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1177 newpos.X = enterDistance;
1178
1179 if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1180 {
1181 Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1182 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
1183 {
1184 neighboury--;
1185 newpos.Y = Constants.RegionSize - enterDistance;
1186 }
1187 else
1188 {
1189 neighboury = ba.TriggerRegionY;
1190 neighbourx = ba.TriggerRegionX;
1191 Vector3 newposition = pos;
1192 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1193 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1194 agent.ControllingClient.SendAgentAlertMessage(
1195 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1196 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1197 return;
1198 }
1199 }
1200 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1201 {
1202 Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1203 neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
1204 newpos.Y = enterDistance;
1205 }
1206
1207
1208 }
1209 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1210 {
1211 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1212 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
1213 {
1214 neighboury--;
1215 newpos.Y = Constants.RegionSize - enterDistance;
1216 }
1217 else
1218 {
1219 neighboury = b.TriggerRegionY;
1220 neighbourx = b.TriggerRegionX;
1221 Vector3 newposition = pos;
1222 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1223 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1224 agent.ControllingClient.SendAgentAlertMessage(
1225 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1226 InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1227 return;
1228 }
1229 }
1230 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1231 {
1232
1233 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1234 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1235 newpos.Y = enterDistance;
1236 }
1237
1238 /*
1239
1240 if (pos.X < boundaryDistance) //West
1241 {
1242 neighbourx--;
1243 newpos.X = Constants.RegionSize - enterDistance;
1244 }
1245 else if (pos.X > Constants.RegionSize - boundaryDistance) // East
1246 {
1247 neighbourx++;
1248 newpos.X = enterDistance;
1249 }
1250
1251 if (pos.Y < boundaryDistance) // South
1252 {
1253 neighboury--;
1254 newpos.Y = Constants.RegionSize - enterDistance;
1255 }
1256 else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
1257 {
1258 neighboury++;
1259 newpos.Y = enterDistance;
1260 }
1261 */
1262
1263 CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
1264 d.BeginInvoke(agent, newpos, neighbourx, neighboury, isFlying, CrossAgentToNewRegionCompleted, d);
1265 }
1266
1267 public delegate void InformClientToInitateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
1268 Vector3 position,
1269 Scene initiatingScene);
1270
1271 public void InformClientToInitateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
1272 Scene initiatingScene)
1273 {
1274
1275 // This assumes that we know what our neighbors are.
1276
1277 InformClientToInitateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
1278 d.BeginInvoke(agent,regionX,regionY,position,initiatingScene,
1279 InformClientToInitiateTeleportToLocationCompleted,
1280 d);
1281 }
1282
1283 public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
1284 Scene initiatingScene)
1285 {
1286 Thread.Sleep(10000);
1287 IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
1288 if (im != null)
1289 {
1290 UUID gotoLocation = Util.BuildFakeParcelID(
1291 Util.UIntsToLong(
1292 (regionX *
1293 (uint)Constants.RegionSize),
1294 (regionY *
1295 (uint)Constants.RegionSize)),
1296 (uint)(int)position.X,
1297 (uint)(int)position.Y,
1298 (uint)(int)position.Z);
1299 GridInstantMessage m = new GridInstantMessage(initiatingScene, UUID.Zero,
1300 "Region", agent.UUID,
1301 (byte)InstantMessageDialog.GodLikeRequestTeleport, false,
1302 "", gotoLocation, false, new Vector3(127, 0, 0),
1303 new Byte[0]);
1304 im.SendInstantMessage(m, delegate(bool success)
1305 {
1306 m_log.DebugFormat("[CLIENT]: Client Initiating Teleport sending IM success = {0}", success);
1307 });
1308
1309 }
1310 }
1311
1312 private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
1313 {
1314 InformClientToInitateTeleportToLocationDelegate icon =
1315 (InformClientToInitateTeleportToLocationDelegate) iar.AsyncState;
1316 icon.EndInvoke(iar);
1317 }
1318
1319 public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying);
1320
1321 /// <summary>
1322 /// This Closes child agents on neighboring regions
1323 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
1324 /// </summary>
1325 protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying)
1326 {
1327 m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} to {2}-{3}", agent.Firstname, agent.Lastname, neighbourx, neighboury);
1328
1329 ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
1330
1331 int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
1332 GridRegion neighbourRegion = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
1333
1334 if (neighbourRegion != null && agent.ValidateAttachments())
1335 {
1336 pos = pos + (agent.Velocity);
1337
1338 //CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
1339 //if (userInfo != null)
1340 //{
1341 // userInfo.DropInventory();
1342 //}
1343 //else
1344 //{
1345 // m_log.WarnFormat("[SCENE COMM]: No cached user info found for {0} {1} on leaving region {2}",
1346 // agent.Name, agent.UUID, agent.Scene.RegionInfo.RegionName);
1347 //}
1348
1349 //bool crossingSuccessful =
1350 // CrossToNeighbouringRegion(neighbourHandle, agent.ControllingClient.AgentId, pos,
1351 //isFlying);
1352
1353 SetInTransit(agent.UUID);
1354 AgentData cAgent = new AgentData();
1355 agent.CopyTo(cAgent);
1356 cAgent.Position = pos;
1357 if (isFlying)
1358 cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
1359 cAgent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
1360 "/agent/" + agent.UUID.ToString() + "/" + agent.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
1361
1362 m_interregionCommsOut.SendChildAgentUpdate(neighbourHandle, cAgent);
1363
1364 // Next, let's close the child agent connections that are too far away.
1365 agent.CloseChildAgents(neighbourx, neighboury);
1366
1367 //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
1368 agent.ControllingClient.RequestClientInfo();
1369
1370 //m_log.Debug("BEFORE CROSS");
1371 //Scene.DumpChildrenSeeds(UUID);
1372 //DumpKnownRegions();
1373 string agentcaps;
1374 if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
1375 {
1376 m_log.ErrorFormat("[SCENE COMM]: No CAPS information for region handle {0}, exiting CrossToNewRegion.",
1377 neighbourRegion.RegionHandle);
1378 return agent;
1379 }
1380 // TODO Should construct this behind a method
1381 string capsPath =
1382 "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort
1383 + "/CAPS/" + agentcaps /*circuitdata.CapsPath*/ + "0000/";
1384
1385 m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
1386
1387 IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
1388 if (eq != null)
1389 {
1390 eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
1391 capsPath, agent.UUID, agent.ControllingClient.SessionId);
1392 }
1393 else
1394 {
1395 agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
1396 capsPath);
1397 }
1398
1399 if (!WaitForCallback(agent.UUID))
1400 {
1401 ResetFromTransit(agent.UUID);
1402
1403 // Yikes! We should just have a ref to scene here.
1404 agent.Scene.InformClientOfNeighbours(agent);
1405
1406 return agent;
1407 }
1408
1409 agent.MakeChildAgent();
1410 // now we have a child agent in this region. Request all interesting data about other (root) agents
1411 agent.SendInitialFullUpdateToAllClients();
1412
1413 agent.CrossAttachmentsIntoNewRegion(neighbourHandle, true);
1414
1415 // m_scene.SendKillObject(m_localId);
1416
1417 agent.Scene.NotifyMyCoarseLocationChange();
1418 // the user may change their profile information in other region,
1419 // so the userinfo in UserProfileCache is not reliable any more, delete it
1420 if (agent.Scene.NeedSceneCacheClear(agent.UUID))
1421 {
1422 agent.Scene.CommsManager.UserProfileCacheService.RemoveUser(agent.UUID);
1423 m_log.DebugFormat(
1424 "[SCENE COMM]: User {0} is going to another region, profile cache removed", agent.UUID);
1425 }
1426 }
1427
1428 //m_log.Debug("AFTER CROSS");
1429 //Scene.DumpChildrenSeeds(UUID);
1430 //DumpKnownRegions();
1431 return agent;
1432 }
1433
1434 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
1435 {
1436 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
1437 ScenePresence agent = icon.EndInvoke(iar);
1438
1439 // If the cross was successful, this agent is a child agent
1440 if (agent.IsChildAgent)
1441 {
1442 agent.Reset();
1443 }
1444 else // Not successful
1445 {
1446 //CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
1447 //if (userInfo != null)
1448 //{
1449 // userInfo.FetchInventory();
1450 //}
1451 agent.RestoreInCurrentScene();
1452 }
1453 // In any case
1454 agent.NotInTransit();
1455
1456 //m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
1457 }
1458
1459
1460 public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
1461 {
1462 m_commsProvider.LogOffUser(userid, regionid, regionhandle, position, lookat);
1463 }
1464
1465 // deprecated as of 2008-08-27
1466 public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
1467 {
1468 m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
1469 }
1470
1471 public void ClearUserAgent(UUID avatarID)
1472 {
1473 m_commsProvider.UserService.ClearUserAgent(avatarID);
1474 }
1475
1476 public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
1477 {
1478 m_commsProvider.AddNewUserFriend(friendlistowner, friend, perms);
1479 }
1480
1481 public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
1482 {
1483 m_commsProvider.UpdateUserFriendPerms(friendlistowner, friend, perms);
1484 }
1485
1486 public void RemoveUserFriend(UUID friendlistowner, UUID friend)
1487 {
1488 m_commsProvider.RemoveUserFriend(friendlistowner, friend);
1489 }
1490
1491 public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
1492 {
1493 return m_commsProvider.GetUserFriendList(friendlistowner);
1494 }
1495
1496 public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
1497 {
1498 return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query);
1499 }
1500
1501 public List<GridRegion> RequestNamedRegions(string name, int maxNumber) 304 public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
1502 { 305 {
1503 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber); 306 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
1504 } 307 }
1505 308
1506 //private void Dump(string msg, List<ulong> handles)
1507 //{
1508 // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
1509 // foreach (ulong handle in handles)
1510 // {
1511 // uint x, y;
1512 // Utils.LongToUInts(handle, out x, out y);
1513 // x = x / Constants.RegionSize;
1514 // y = y / Constants.RegionSize;
1515 // m_log.InfoFormat("({0}, {1})", x, y);
1516 // }
1517 //}
1518 } 309 }
1519} 310}
diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
index 090f379..f43de20 100644
--- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
@@ -35,6 +35,7 @@ using log4net;
35using OpenSim.Framework; 35using OpenSim.Framework;
36using OpenSim.Region.Framework.Scenes.Types; 36using OpenSim.Region.Framework.Scenes.Types;
37using OpenSim.Region.Physics.Manager; 37using OpenSim.Region.Physics.Manager;
38using OpenSim.Region.Framework.Interfaces;
38 39
39namespace OpenSim.Region.Framework.Scenes 40namespace OpenSim.Region.Framework.Scenes
40{ 41{
@@ -164,9 +165,10 @@ namespace OpenSim.Region.Framework.Scenes
164 165
165 protected internal void UpdatePresences() 166 protected internal void UpdatePresences()
166 { 167 {
167 ScenePresence[] updateScenePresences = GetScenePresences(); 168 ForEachScenePresence(delegate(ScenePresence presence)
168 for (int i = 0; i < updateScenePresences.Length; i++) 169 {
169 updateScenePresences[i].Update(); 170 presence.Update();
171 });
170 } 172 }
171 173
172 protected internal float UpdatePhysics(double elapsed) 174 protected internal float UpdatePhysics(double elapsed)
@@ -195,9 +197,10 @@ namespace OpenSim.Region.Framework.Scenes
195 197
196 protected internal void UpdateScenePresenceMovement() 198 protected internal void UpdateScenePresenceMovement()
197 { 199 {
198 ScenePresence[] moveEntities = GetScenePresences(); 200 ForEachScenePresence(delegate(ScenePresence presence)
199 for (int i = 0; i < moveEntities.Length; i++) 201 {
200 moveEntities[i].UpdateMovement(); 202 presence.UpdateMovement();
203 });
201 } 204 }
202 205
203 #endregion 206 #endregion
@@ -464,9 +467,7 @@ namespace OpenSim.Region.Framework.Scenes
464 { 467 {
465 SceneObjectGroup group = GetGroupByPrim(objectLocalID); 468 SceneObjectGroup group = GetGroupByPrim(objectLocalID);
466 if (group != null) 469 if (group != null)
467 { 470 m_parentScene.AttachmentsModule.DetachSingleAttachmentToGround(group.UUID, remoteClient);
468 m_parentScene.DetachSingleAttachmentToGround(group.UUID, remoteClient);
469 }
470 } 471 }
471 472
472 protected internal void DetachObject(uint objectLocalID, IClientAPI remoteClient) 473 protected internal void DetachObject(uint objectLocalID, IClientAPI remoteClient)
@@ -475,7 +476,7 @@ namespace OpenSim.Region.Framework.Scenes
475 if (group != null) 476 if (group != null)
476 { 477 {
477 //group.DetachToGround(); 478 //group.DetachToGround();
478 m_parentScene.DetachSingleAttachmentToInv(group.GetFromItemID(), remoteClient); 479 m_parentScene.AttachmentsModule.ShowDetachInUserInventory(group.GetFromItemID(), remoteClient);
479 } 480 }
480 } 481 }
481 482
@@ -509,212 +510,6 @@ namespace OpenSim.Region.Framework.Scenes
509 } 510 }
510 } 511 }
511 512
512 /// <summary>
513 /// Event Handling routine for Attach Object
514 /// </summary>
515 /// <param name="remoteClient"></param>
516 /// <param name="objectLocalID"></param>
517 /// <param name="AttachmentPt"></param>
518 /// <param name="rot"></param>
519 protected internal void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent)
520 {
521 // If we can't take it, we can't attach it!
522 SceneObjectPart part = m_parentScene.GetSceneObjectPart(objectLocalID);
523 if (part == null)
524 return;
525
526 if (!m_parentScene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
527 return;
528
529 // Calls attach with a Zero position
530 if (AttachObject(remoteClient, objectLocalID, AttachmentPt, rot, Vector3.Zero, false))
531 {
532 m_parentScene.SendAttachEvent(objectLocalID, part.ParentGroup.GetFromItemID(), remoteClient.AgentId);
533
534 // Save avatar attachment information
535 ScenePresence presence;
536 if (m_parentScene.AvatarFactory != null && m_parentScene.TryGetAvatar(remoteClient.AgentId, out presence))
537 {
538 m_log.Info(
539 "[SCENE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
540 + ", AttachmentPoint: " + AttachmentPt);
541
542 m_parentScene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
543 }
544 }
545 }
546
547 /// <summary>
548 /// Rez an attachment
549 /// </summary>
550 /// <param name="remoteClient"></param>
551 /// <param name="itemID"></param>
552 /// <param name="AttachmentPt"></param>
553 /// <returns>The scene object that was attached. Null if the scene object could not be found</returns>
554 public SceneObjectGroup RezSingleAttachment(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
555 {
556 SceneObjectGroup objatt = m_parentScene.RezObject(remoteClient,
557 itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
558 false, false, remoteClient.AgentId, true);
559
560// m_log.DebugFormat(
561// "[SCENE GRAPH]: Retrieved single object {0} for attachment to {1} on point {2}",
562// objatt.Name, remoteClient.Name, AttachmentPt);
563
564 if (objatt != null)
565 {
566 bool tainted = false;
567 if (AttachmentPt != 0 && AttachmentPt != objatt.GetAttachmentPoint())
568 tainted = true;
569
570 AttachObject(remoteClient, objatt.LocalId, AttachmentPt, Quaternion.Identity, objatt.AbsolutePosition, false);
571 //objatt.ScheduleGroupForFullUpdate();
572
573 if (tainted)
574 objatt.HasGroupChanged = true;
575
576 // Fire after attach, so we don't get messy perms dialogs
577 // 3 == AttachedRez
578 objatt.CreateScriptInstances(0, true, m_parentScene.DefaultScriptEngine, 3);
579
580 // Do this last so that event listeners have access to all the effects of the attachment
581 m_parentScene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, remoteClient.AgentId);
582 }
583 else
584 {
585 m_log.WarnFormat(
586 "[SCENE GRAPH]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
587 itemID, remoteClient.Name, AttachmentPt);
588 }
589
590 return objatt;
591 }
592
593 // What makes this method odd and unique is it tries to detach using an UUID.... Yay for standards.
594 // To LocalId or UUID, *THAT* is the question. How now Brown UUID??
595 public void DetachSingleAttachmentToInv(UUID itemID, IClientAPI remoteClient)
596 {
597 if (itemID == UUID.Zero) // If this happened, someone made a mistake....
598 return;
599
600 // We can NOT use the dictionries here, as we are looking
601 // for an entity by the fromAssetID, which is NOT the prim UUID
602 //
603 List<EntityBase> detachEntities = GetEntities();
604 SceneObjectGroup group;
605
606 foreach (EntityBase entity in detachEntities)
607 {
608 if (entity is SceneObjectGroup)
609 {
610 group = (SceneObjectGroup)entity;
611 if (group.GetFromItemID() == itemID)
612 {
613 m_parentScene.SendAttachEvent(group.LocalId, itemID, UUID.Zero);
614 bool hasScripts = false;
615 foreach (SceneObjectPart part in group.Children.Values)
616 {
617 if (part.Inventory.ContainsScripts())
618 {
619 hasScripts = true;
620 break;
621 }
622 }
623
624 if (hasScripts) // Allow the object to execute the attach(NULL_KEY) event
625 System.Threading.Thread.Sleep(100);
626 group.DetachToInventoryPrep();
627 m_log.Debug("[DETACH]: Saving attachpoint: " +
628 ((uint)group.GetAttachmentPoint()).ToString());
629 m_parentScene.UpdateKnownItem(remoteClient, group,
630 group.GetFromItemID(), group.OwnerID);
631 m_parentScene.DeleteSceneObject(group, false);
632 return;
633 }
634 }
635 }
636 }
637
638 /// <summary>
639 /// Attach a scene object to an avatar.
640 /// </summary>
641 /// <param name="remoteClient"></param>
642 /// <param name="objectLocalID"></param>
643 /// <param name="AttachmentPt"></param>
644 /// <param name="rot"></param>
645 /// <param name="attachPos"></param>
646 /// <param name="silent"></param>
647 /// <returns>true if the attachment was successful, false otherwise</returns>
648 protected internal bool AttachObject(
649 IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent)
650 {
651 SceneObjectGroup group = GetGroupByPrim(objectLocalID);
652 if (group != null)
653 {
654 if (m_parentScene.Permissions.CanTakeObject(group.UUID, remoteClient.AgentId))
655 {
656 // If the attachment point isn't the same as the one previously used
657 // set it's offset position = 0 so that it appears on the attachment point
658 // and not in a weird location somewhere unknown.
659 if (AttachmentPt != 0 && AttachmentPt != (uint)group.GetAttachmentPoint())
660 {
661 attachPos = Vector3.Zero;
662 }
663
664 // AttachmentPt 0 means the client chose to 'wear' the attachment.
665 if (AttachmentPt == 0)
666 {
667 // Check object for stored attachment point
668 AttachmentPt = (uint)group.GetAttachmentPoint();
669 }
670
671 // if we still didn't find a suitable attachment point.......
672 if (AttachmentPt == 0)
673 {
674 // Stick it on left hand with Zero Offset from the attachment point.
675 AttachmentPt = (uint)AttachmentPoint.LeftHand;
676 attachPos = Vector3.Zero;
677 }
678
679 group.SetAttachmentPoint((byte)AttachmentPt);
680 group.AbsolutePosition = attachPos;
681
682 // Saves and gets itemID
683 UUID itemId;
684
685 if (group.GetFromItemID() == UUID.Zero)
686 {
687 m_parentScene.attachObjectAssetStore(remoteClient, group, remoteClient.AgentId, out itemId);
688 }
689 else
690 {
691 itemId = group.GetFromItemID();
692 }
693
694 m_parentScene.AttachObject(remoteClient, AttachmentPt, itemId, group);
695
696 group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos, silent);
697 // In case it is later dropped again, don't let
698 // it get cleaned up
699 //
700 group.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
701 group.HasGroupChanged = false;
702 }
703 else
704 {
705 remoteClient.SendAgentAlertMessage("You don't have sufficient permissions to attach this object", false);
706 return false;
707 }
708 }
709 else
710 {
711 m_log.DebugFormat("[SCENE GRAPH]: AttachObject found no such scene object {0}", objectLocalID);
712 return false;
713 }
714
715 return true;
716 }
717
718 protected internal ScenePresence CreateAndAddChildScenePresence(IClientAPI client, AvatarAppearance appearance) 513 protected internal ScenePresence CreateAndAddChildScenePresence(IClientAPI client, AvatarAppearance appearance)
719 { 514 {
720 ScenePresence newAvatar = null; 515 ScenePresence newAvatar = null;
@@ -845,18 +640,16 @@ namespace OpenSim.Region.Framework.Scenes
845 640
846 public void RecalculateStats() 641 public void RecalculateStats()
847 { 642 {
848 ScenePresence[] presences = GetScenePresences();
849 int rootcount = 0; 643 int rootcount = 0;
850 int childcount = 0; 644 int childcount = 0;
851 645
852 for (int i = 0; i < presences.Length; i++) 646 ForEachScenePresence(delegate(ScenePresence presence)
853 { 647 {
854 ScenePresence user = presences[i]; 648 if (presence.IsChildAgent)
855 if (user.IsChildAgent)
856 ++childcount; 649 ++childcount;
857 else 650 else
858 ++rootcount; 651 ++rootcount;
859 } 652 });
860 653
861 m_numRootAgents = rootcount; 654 m_numRootAgents = rootcount;
862 m_numChildAgents = childcount; 655 m_numChildAgents = childcount;
@@ -903,25 +696,6 @@ namespace OpenSim.Region.Framework.Scenes
903 #endregion 696 #endregion
904 697
905 #region Get Methods 698 #region Get Methods
906
907 /// <summary>
908 /// Request a List of all scene presences in this scene. This is a new list, so no
909 /// locking is required to iterate over it.
910 /// </summary>
911 /// <returns></returns>
912 protected internal ScenePresence[] GetScenePresences()
913 {
914 return m_scenePresenceArray;
915 }
916
917 protected internal List<ScenePresence> GetAvatars()
918 {
919 List<ScenePresence> result =
920 GetScenePresences(delegate(ScenePresence scenePresence) { return !scenePresence.IsChildAgent; });
921
922 return result;
923 }
924
925 /// <summary> 699 /// <summary>
926 /// Get the controlling client for the given avatar, if there is one. 700 /// Get the controlling client for the given avatar, if there is one.
927 /// 701 ///
@@ -948,41 +722,83 @@ namespace OpenSim.Region.Framework.Scenes
948 } 722 }
949 723
950 /// <summary> 724 /// <summary>
951 /// Request a filtered list of m_scenePresences in this World 725 /// Request a copy of m_scenePresences in this World
726 /// There is no guarantee that presences will remain in the scene after the list is returned.
727 /// This list should remain private to SceneGraph. Callers wishing to iterate should instead
728 /// pass a delegate to ForEachScenePresence.
952 /// </summary> 729 /// </summary>
953 /// <returns></returns> 730 /// <returns></returns>
954 protected internal List<ScenePresence> GetScenePresences(FilterAvatarList filter) 731 private List<ScenePresence> GetScenePresences()
955 { 732 {
956 // No locking of scene presences here since we're passing back a list... 733 lock (m_scenePresences)
957 734 return new List<ScenePresence>(m_scenePresenceArray);
958 List<ScenePresence> result = new List<ScenePresence>(); 735 }
959 ScenePresence[] scenePresences = GetScenePresences();
960 736
961 for (int i = 0; i < scenePresences.Length; i++) 737 /// <summary>
738 /// Request a scene presence by UUID. Fast, indexed lookup.
739 /// </summary>
740 /// <param name="agentID"></param>
741 /// <returns>null if the presence was not found</returns>
742 protected internal ScenePresence GetScenePresence(UUID agentID)
743 {
744 ScenePresence sp;
745 lock (m_scenePresences)
962 { 746 {
963 ScenePresence avatar = scenePresences[i]; 747 m_scenePresences.TryGetValue(agentID, out sp);
964 if (filter(avatar))
965 result.Add(avatar);
966 } 748 }
749 return sp;
750 }
967 751
968 return result; 752 /// <summary>
753 /// Request the scene presence by name.
754 /// </summary>
755 /// <param name="firstName"></param>
756 /// <param name="lastName"></param>
757 /// <returns>null if the presence was not found</returns>
758 protected internal ScenePresence GetScenePresence(string firstName, string lastName)
759 {
760 foreach (ScenePresence presence in GetScenePresences())
761 {
762 if (presence.Firstname == firstName && presence.Lastname == lastName)
763 return presence;
764 }
765 return null;
969 } 766 }
970 767
971 /// <summary> 768 /// <summary>
972 /// Request a scene presence by UUID 769 /// Request the scene presence by localID.
973 /// </summary> 770 /// </summary>
974 /// <param name="avatarID"></param> 771 /// <param name="localID"></param>
975 /// <returns>null if the agent was not found</returns> 772 /// <returns>null if the presence was not found</returns>
976 protected internal ScenePresence GetScenePresence(UUID agentID) 773 protected internal ScenePresence GetScenePresence(uint localID)
774 {
775 foreach (ScenePresence presence in GetScenePresences())
776 if (presence.LocalId == localID)
777 return presence;
778 return null;
779 }
780
781 protected internal bool TryGetScenePresence(UUID agentID, out ScenePresence avatar)
977 { 782 {
978 ScenePresence sp;
979
980 lock (m_scenePresences) 783 lock (m_scenePresences)
981 { 784 {
982 m_scenePresences.TryGetValue(agentID, out sp); 785 m_scenePresences.TryGetValue(agentID, out avatar);
983 } 786 }
787 return (avatar != null);
788 }
984 789
985 return sp; 790 protected internal bool TryGetAvatarByName(string name, out ScenePresence avatar)
791 {
792 avatar = null;
793 foreach (ScenePresence presence in GetScenePresences())
794 {
795 if (String.Compare(name, presence.ControllingClient.Name, true) == 0)
796 {
797 avatar = presence;
798 break;
799 }
800 }
801 return (avatar != null);
986 } 802 }
987 803
988 /// <summary> 804 /// <summary>
@@ -1136,34 +952,6 @@ namespace OpenSim.Region.Framework.Scenes
1136 return group.GetChildPart(fullID); 952 return group.GetChildPart(fullID);
1137 } 953 }
1138 954
1139 protected internal bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
1140 {
1141 lock (m_scenePresences)
1142 return m_scenePresences.TryGetValue(avatarId, out avatar);
1143 }
1144
1145 protected internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
1146 {
1147 ScenePresence[] presences = GetScenePresences();
1148
1149 for (int i = 0; i < presences.Length; i++)
1150 {
1151 ScenePresence presence = presences[i];
1152
1153 if (!presence.IsChildAgent)
1154 {
1155 if (String.Compare(avatarName, presence.ControllingClient.Name, true) == 0)
1156 {
1157 avatar = presence;
1158 return true;
1159 }
1160 }
1161 }
1162
1163 avatar = null;
1164 return false;
1165 }
1166
1167 /// <summary> 955 /// <summary>
1168 /// Returns a list of the entities in the scene. This is a new list so no locking is required to iterate over 956 /// Returns a list of the entities in the scene. This is a new list so no locking is required to iterate over
1169 /// it 957 /// it
@@ -1226,6 +1014,10 @@ namespace OpenSim.Region.Framework.Scenes
1226 return UUID.Zero; 1014 return UUID.Zero;
1227 } 1015 }
1228 1016
1017 /// <summary>
1018 /// Performs action on all scene object groups.
1019 /// </summary>
1020 /// <param name="action"></param>
1229 protected internal void ForEachSOG(Action<SceneObjectGroup> action) 1021 protected internal void ForEachSOG(Action<SceneObjectGroup> action)
1230 { 1022 {
1231 List<SceneObjectGroup> objlist = new List<SceneObjectGroup>(SceneObjectGroupsByFullID.Values); 1023 List<SceneObjectGroup> objlist = new List<SceneObjectGroup>(SceneObjectGroupsByFullID.Values);
@@ -1242,6 +1034,46 @@ namespace OpenSim.Region.Framework.Scenes
1242 } 1034 }
1243 } 1035 }
1244 } 1036 }
1037
1038
1039 /// <summary>
1040 /// Performs action on all scene presences. This can ultimately run the actions in parallel but
1041 /// any delegates passed in will need to implement their own locking on data they reference and
1042 /// modify outside of the scope of the delegate.
1043 /// </summary>
1044 /// <param name="action"></param>
1045 public void ForEachScenePresence(Action<ScenePresence> action)
1046 {
1047 // Once all callers have their delegates configured for parallelism, we can unleash this
1048 /*
1049 Action<ScenePresence> protectedAction = new Action<ScenePresence>(delegate(ScenePresence sp)
1050 {
1051 try
1052 {
1053 action(sp);
1054 }
1055 catch (Exception e)
1056 {
1057 m_log.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
1058 m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
1059 }
1060 });
1061 Parallel.ForEach<ScenePresence>(GetScenePresences(), protectedAction);
1062 */
1063 // For now, perform actiona serially
1064 foreach (ScenePresence sp in GetScenePresences())
1065 {
1066 try
1067 {
1068 action(sp);
1069 }
1070 catch (Exception e)
1071 {
1072 m_log.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
1073 m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
1074 }
1075 }
1076 }
1245 1077
1246 #endregion 1078 #endregion
1247 1079
@@ -1924,6 +1756,7 @@ namespace OpenSim.Region.Framework.Scenes
1924 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 0); 1756 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 0);
1925 copy.HasGroupChanged = true; 1757 copy.HasGroupChanged = true;
1926 copy.ScheduleGroupForFullUpdate(); 1758 copy.ScheduleGroupForFullUpdate();
1759 copy.ResumeScripts();
1927 1760
1928 // required for physics to update it's position 1761 // required for physics to update it's position
1929 copy.AbsolutePosition = copy.AbsolutePosition; 1762 copy.AbsolutePosition = copy.AbsolutePosition;
diff --git a/OpenSim/Region/Framework/Scenes/SceneManager.cs b/OpenSim/Region/Framework/Scenes/SceneManager.cs
index c2e3370..3b84734 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -414,22 +414,18 @@ namespace OpenSim.Region.Framework.Scenes
414 ForEachCurrentScene( 414 ForEachCurrentScene(
415 delegate(Scene scene) 415 delegate(Scene scene)
416 { 416 {
417 ScenePresence[] scenePresences = scene.GetScenePresences(); 417 scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
418
419 for (int i = 0; i < scenePresences.Length; i++)
420 { 418 {
421 ScenePresence scenePresence = scenePresences[i];
422
423 if (!scenePresence.IsChildAgent) 419 if (!scenePresence.IsChildAgent)
424 { 420 {
425 m_log.ErrorFormat("Packet debug for {0} {1} set to {2}", 421 m_log.DebugFormat("Packet debug for {0} {1} set to {2}",
426 scenePresence.Firstname, 422 scenePresence.Firstname,
427 scenePresence.Lastname, 423 scenePresence.Lastname,
428 newDebug); 424 newDebug);
429 425
430 scenePresence.ControllingClient.SetDebugPacketLevel(newDebug); 426 scenePresence.ControllingClient.SetDebugPacketLevel(newDebug);
431 } 427 }
432 } 428 });
433 } 429 }
434 ); 430 );
435 } 431 }
@@ -441,14 +437,11 @@ namespace OpenSim.Region.Framework.Scenes
441 ForEachCurrentScene( 437 ForEachCurrentScene(
442 delegate(Scene scene) 438 delegate(Scene scene)
443 { 439 {
444 ScenePresence[] scenePresences = scene.GetScenePresences(); 440 scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
445
446 for (int i = 0; i < scenePresences.Length; i++)
447 { 441 {
448 ScenePresence scenePresence = scenePresences[i];
449 if (!scenePresence.IsChildAgent) 442 if (!scenePresence.IsChildAgent)
450 avatars.Add(scenePresence); 443 avatars.Add(scenePresence);
451 } 444 });
452 } 445 }
453 ); 446 );
454 447
@@ -461,18 +454,20 @@ namespace OpenSim.Region.Framework.Scenes
461 454
462 ForEachCurrentScene(delegate(Scene scene) 455 ForEachCurrentScene(delegate(Scene scene)
463 { 456 {
464 ScenePresence[] scenePresences = scene.GetScenePresences(); 457 scene.ForEachScenePresence(delegate(ScenePresence sp)
465 presences.AddRange(scenePresences); 458 {
459 presences.Add(sp);
460 });
466 }); 461 });
467 462
468 return presences; 463 return presences;
469 } 464 }
470 465
471 public RegionInfo GetRegionInfo(ulong regionHandle) 466 public RegionInfo GetRegionInfo(UUID regionID)
472 { 467 {
473 foreach (Scene scene in m_localScenes) 468 foreach (Scene scene in m_localScenes)
474 { 469 {
475 if (scene.RegionInfo.RegionHandle == regionHandle) 470 if (scene.RegionInfo.RegionID == regionID)
476 { 471 {
477 return scene.RegionInfo; 472 return scene.RegionInfo;
478 } 473 }
@@ -491,11 +486,11 @@ namespace OpenSim.Region.Framework.Scenes
491 ForEachCurrentScene(delegate(Scene scene) { scene.HandleEditCommand(cmdparams); }); 486 ForEachCurrentScene(delegate(Scene scene) { scene.HandleEditCommand(cmdparams); });
492 } 487 }
493 488
494 public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar) 489 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
495 { 490 {
496 foreach (Scene scene in m_localScenes) 491 foreach (Scene scene in m_localScenes)
497 { 492 {
498 if (scene.TryGetAvatar(avatarId, out avatar)) 493 if (scene.TryGetScenePresence(avatarId, out avatar))
499 { 494 {
500 return true; 495 return true;
501 } 496 }
@@ -510,7 +505,7 @@ namespace OpenSim.Region.Framework.Scenes
510 ScenePresence avatar = null; 505 ScenePresence avatar = null;
511 foreach (Scene mScene in m_localScenes) 506 foreach (Scene mScene in m_localScenes)
512 { 507 {
513 if (mScene.TryGetAvatar(avatarId, out avatar)) 508 if (mScene.TryGetScenePresence(avatarId, out avatar))
514 { 509 {
515 scene = mScene; 510 scene = mScene;
516 return true; 511 return true;
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
index 8b58b3e..1149a20 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
@@ -171,7 +171,9 @@ namespace OpenSim.Region.Framework.Scenes
171 item.NextPermissions; 171 item.NextPermissions;
172 taskItem.NextPermissions = item.NextPermissions; 172 taskItem.NextPermissions = item.NextPermissions;
173 taskItem.CurrentPermissions |= 8; 173 taskItem.CurrentPermissions |= 8;
174 } else { 174 }
175 else
176 {
175 taskItem.BasePermissions = item.BasePermissions; 177 taskItem.BasePermissions = item.BasePermissions;
176 taskItem.CurrentPermissions = item.CurrentPermissions; 178 taskItem.CurrentPermissions = item.CurrentPermissions;
177 taskItem.CurrentPermissions |= 8; 179 taskItem.CurrentPermissions |= 8;
@@ -412,5 +414,13 @@ namespace OpenSim.Region.Framework.Scenes
412 scriptModule.SetXMLState(itemID, n.OuterXml); 414 scriptModule.SetXMLState(itemID, n.OuterXml);
413 } 415 }
414 } 416 }
417
418 public void ResumeScripts()
419 {
420 foreach (SceneObjectPart part in m_parts.Values)
421 {
422 part.Inventory.ResumeScripts();
423 }
424 }
415 } 425 }
416} 426}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
index 13d1d4e..ff471e0 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -418,6 +418,7 @@ namespace OpenSim.Region.Framework.Scenes
418 RootPart.ScriptSetPhysicsStatus(false); 418 RootPart.ScriptSetPhysicsStatus(false);
419 Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"), 419 Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
420 ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false); 420 ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false);
421 lockPartsForRead(false);
421 return; 422 return;
422 } 423 }
423 } 424 }
@@ -530,8 +531,8 @@ namespace OpenSim.Region.Framework.Scenes
530 private List<SceneObjectPart> m_PlaySoundSlavePrims = new List<SceneObjectPart>(); 531 private List<SceneObjectPart> m_PlaySoundSlavePrims = new List<SceneObjectPart>();
531 public List<SceneObjectPart> PlaySoundSlavePrims 532 public List<SceneObjectPart> PlaySoundSlavePrims
532 { 533 {
533 get { return m_LoopSoundSlavePrims; } 534 get { return m_PlaySoundSlavePrims; }
534 set { m_LoopSoundSlavePrims = value; } 535 set { m_PlaySoundSlavePrims = value; }
535 } 536 }
536 537
537 private SceneObjectPart m_LoopSoundMasterPrim = null; 538 private SceneObjectPart m_LoopSoundMasterPrim = null;
@@ -686,7 +687,7 @@ namespace OpenSim.Region.Framework.Scenes
686 ApplyPhysics(m_scene.m_physicalPrim); 687 ApplyPhysics(m_scene.m_physicalPrim);
687 688
688 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 689 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
689 // for the same object with very different properties. The caller must schedule the update. 690 // for the same object with very different properties. The caller must schedule the update.
690 //ScheduleGroupForFullUpdate(); 691 //ScheduleGroupForFullUpdate();
691 } 692 }
692 693
@@ -1040,6 +1041,11 @@ namespace OpenSim.Region.Framework.Scenes
1040 1041
1041 public void SaveScriptedState(XmlTextWriter writer) 1042 public void SaveScriptedState(XmlTextWriter writer)
1042 { 1043 {
1044 SaveScriptedState(writer, false);
1045 }
1046
1047 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1048 {
1043 XmlDocument doc = new XmlDocument(); 1049 XmlDocument doc = new XmlDocument();
1044 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1050 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1045 1051
@@ -1049,7 +1055,7 @@ namespace OpenSim.Region.Framework.Scenes
1049 foreach (SceneObjectPart part in m_parts.Values) 1055 foreach (SceneObjectPart part in m_parts.Values)
1050 { 1056 {
1051 1057
1052 Dictionary<UUID,string> pstates = part.Inventory.GetScriptStates(); 1058 Dictionary<UUID,string> pstates = part.Inventory.GetScriptStates(oldIDs);
1053 foreach (UUID itemid in pstates.Keys) 1059 foreach (UUID itemid in pstates.Keys)
1054 { 1060 {
1055 states.Add(itemid, pstates[itemid]); 1061 states.Add(itemid, pstates[itemid]);
@@ -1411,21 +1417,20 @@ namespace OpenSim.Region.Framework.Scenes
1411 { 1417 {
1412// part.Inventory.RemoveScriptInstances(); 1418// part.Inventory.RemoveScriptInstances();
1413 1419
1414 ScenePresence[] avatars = Scene.GetScenePresences(); 1420 Scene.ForEachScenePresence(delegate (ScenePresence sp)
1415 for (int i = 0; i < avatars.Length; i++)
1416 { 1421 {
1417 if (avatars[i].ParentID == LocalId) 1422 if (sp.ParentID == LocalId)
1418 { 1423 {
1419 avatars[i].StandUp(); 1424 sp.StandUp();
1420 } 1425 }
1421 1426
1422 if (!silent) 1427 if (!silent)
1423 { 1428 {
1424 part.UpdateFlag = 0; 1429 part.UpdateFlag = 0;
1425 if (part == m_rootPart) 1430 if (part == m_rootPart)
1426 avatars[i].ControllingClient.SendKillObject(m_regionHandle, part.LocalId); 1431 sp.ControllingClient.SendKillObject(m_regionHandle, part.LocalId);
1427 } 1432 }
1428 } 1433 });
1429 1434
1430 } 1435 }
1431 1436
@@ -1647,11 +1652,10 @@ namespace OpenSim.Region.Framework.Scenes
1647 1652
1648 #endregion 1653 #endregion
1649 1654
1650 #region Client Updating
1651
1652 public void SendFullUpdateToClient(IClientAPI remoteClient) 1655 public void SendFullUpdateToClient(IClientAPI remoteClient)
1653 { 1656 {
1654 SendPartFullUpdate(remoteClient, RootPart, m_scene.Permissions.GenerateClientFlags(remoteClient.AgentId, RootPart.UUID)); 1657 RootPart.SendFullUpdate(
1658 remoteClient, m_scene.Permissions.GenerateClientFlags(remoteClient.AgentId, RootPart.UUID));
1655 1659
1656 lockPartsForRead(true); 1660 lockPartsForRead(true);
1657 { 1661 {
@@ -1659,42 +1663,12 @@ namespace OpenSim.Region.Framework.Scenes
1659 { 1663 {
1660 1664
1661 if (part != RootPart) 1665 if (part != RootPart)
1662 SendPartFullUpdate(remoteClient, part, m_scene.Permissions.GenerateClientFlags(remoteClient.AgentId, part.UUID)); 1666 part.SendFullUpdate(
1663 1667 remoteClient, m_scene.Permissions.GenerateClientFlags(remoteClient.AgentId, part.UUID));
1664 } 1668 }
1665 } 1669 }
1666 lockPartsForRead(false);
1667 } 1670 }
1668 1671
1669 /// <summary>
1670 /// Send a full update to the client for the given part
1671 /// </summary>
1672 /// <param name="remoteClient"></param>
1673 /// <param name="part"></param>
1674 internal void SendPartFullUpdate(IClientAPI remoteClient, SceneObjectPart part, uint clientFlags)
1675 {
1676// m_log.DebugFormat(
1677// "[SOG]: Sendinging part full update to {0} for {1} {2}", remoteClient.Name, part.Name, part.LocalId);
1678
1679 if (m_rootPart.UUID == part.UUID)
1680 {
1681 if (IsAttachment)
1682 {
1683 part.SendFullUpdateToClient(remoteClient, m_rootPart.AttachedPos, clientFlags);
1684 }
1685 else
1686 {
1687 part.SendFullUpdateToClient(remoteClient, AbsolutePosition, clientFlags);
1688 }
1689 }
1690 else
1691 {
1692 part.SendFullUpdateToClient(remoteClient, clientFlags);
1693 }
1694 }
1695
1696 #endregion
1697
1698 #region Copying 1672 #region Copying
1699 1673
1700 /// <summary> 1674 /// <summary>
@@ -2206,14 +2180,12 @@ namespace OpenSim.Region.Framework.Scenes
2206 public void ScheduleTerseUpdateToAvatar(ScenePresence presence) 2180 public void ScheduleTerseUpdateToAvatar(ScenePresence presence)
2207 { 2181 {
2208 lockPartsForRead(true); 2182 lockPartsForRead(true);
2183
2184 foreach (SceneObjectPart part in m_parts.Values)
2209 { 2185 {
2210 foreach (SceneObjectPart part in m_parts.Values) 2186 part.AddTerseUpdateToAvatar(presence);
2211 {
2212
2213 part.AddTerseUpdateToAvatar(presence);
2214
2215 }
2216 } 2187 }
2188
2217 lockPartsForRead(false); 2189 lockPartsForRead(false);
2218 } 2190 }
2219 2191
@@ -2246,14 +2218,11 @@ namespace OpenSim.Region.Framework.Scenes
2246 public void ScheduleGroupForTerseUpdate() 2218 public void ScheduleGroupForTerseUpdate()
2247 { 2219 {
2248 lockPartsForRead(true); 2220 lockPartsForRead(true);
2221 foreach (SceneObjectPart part in m_parts.Values)
2249 { 2222 {
2250 foreach (SceneObjectPart part in m_parts.Values) 2223 part.ScheduleTerseUpdate();
2251 {
2252
2253 part.ScheduleTerseUpdate();
2254
2255 }
2256 } 2224 }
2225
2257 lockPartsForRead(false); 2226 lockPartsForRead(false);
2258 } 2227 }
2259 2228
@@ -3107,8 +3076,8 @@ namespace OpenSim.Region.Framework.Scenes
3107 { 3076 {
3108 if (obPart.UUID != m_rootPart.UUID) 3077 if (obPart.UUID != m_rootPart.UUID)
3109 { 3078 {
3110 obPart.IgnoreUndoUpdate = true;
3111 Vector3 oldSize = new Vector3(obPart.Scale); 3079 Vector3 oldSize = new Vector3(obPart.Scale);
3080 obPart.IgnoreUndoUpdate = true;
3112 3081
3113 float f = 1.0f; 3082 float f = 1.0f;
3114 float a = 1.0f; 3083 float a = 1.0f;
@@ -3962,5 +3931,13 @@ namespace OpenSim.Region.Framework.Scenes
3962 3931
3963 return priority; 3932 return priority;
3964 } 3933 }
3934
3935 public void ResetOwnerChangeFlag()
3936 {
3937 ForEachPart(delegate(SceneObjectPart part)
3938 {
3939 part.ResetOwnerChangeFlag();
3940 });
3941 }
3965 } 3942 }
3966} 3943}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index 548a64f..48e65a5 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
@@ -573,8 +573,8 @@ namespace OpenSim.Region.Framework.Scenes
573 private List<SceneObjectPart> m_PlaySoundSlavePrims = new List<SceneObjectPart>(); 573 private List<SceneObjectPart> m_PlaySoundSlavePrims = new List<SceneObjectPart>();
574 public List<SceneObjectPart> PlaySoundSlavePrims 574 public List<SceneObjectPart> PlaySoundSlavePrims
575 { 575 {
576 get { return m_LoopSoundSlavePrims; } 576 get { return m_PlaySoundSlavePrims; }
577 set { m_LoopSoundSlavePrims = value; } 577 set { m_PlaySoundSlavePrims = value; }
578 } 578 }
579 579
580 private SceneObjectPart m_LoopSoundMasterPrim = null; 580 private SceneObjectPart m_LoopSoundMasterPrim = null;
@@ -682,7 +682,7 @@ namespace OpenSim.Region.Framework.Scenes
682 if (m_parentGroup != null) // TODO can there be a SOP without a SOG? 682 if (m_parentGroup != null) // TODO can there be a SOP without a SOG?
683 { 683 {
684 ScenePresence avatar; 684 ScenePresence avatar;
685 if (m_parentGroup.Scene.TryGetAvatar(m_sitTargetAvatar, out avatar)) 685 if (m_parentGroup.Scene.TryGetScenePresence(m_sitTargetAvatar, out avatar))
686 { 686 {
687 avatar.ParentPosition = GetWorldPosition(); 687 avatar.ParentPosition = GetWorldPosition();
688 } 688 }
@@ -1208,15 +1208,14 @@ namespace OpenSim.Region.Framework.Scenes
1208 1208
1209 private void SendObjectPropertiesToClient(UUID AgentID) 1209 private void SendObjectPropertiesToClient(UUID AgentID)
1210 { 1210 {
1211 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 1211 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
1212 for (int i = 0; i < avatars.Length; i++)
1213 { 1212 {
1214 // Ugly reference :( 1213 // Ugly reference :(
1215 if (avatars[i].UUID == AgentID) 1214 if (avatar.UUID == AgentID)
1216 { 1215 {
1217 m_parentGroup.GetProperties(avatars[i].ControllingClient); 1216 m_parentGroup.GetProperties(avatar.ControllingClient);
1218 } 1217 }
1219 } 1218 });
1220 } 1219 }
1221 1220
1222 // TODO: unused: 1221 // TODO: unused:
@@ -1271,11 +1270,10 @@ namespace OpenSim.Region.Framework.Scenes
1271 /// </summary> 1270 /// </summary>
1272 public void AddFullUpdateToAllAvatars() 1271 public void AddFullUpdateToAllAvatars()
1273 { 1272 {
1274 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 1273 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
1275 for (int i = 0; i < avatars.Length; i++)
1276 { 1274 {
1277 avatars[i].SceneViewer.QueuePartForUpdate(this); 1275 avatar.SceneViewer.QueuePartForUpdate(this);
1278 } 1276 });
1279 } 1277 }
1280 1278
1281 public void AddFullUpdateToAvatar(ScenePresence presence) 1279 public void AddFullUpdateToAvatar(ScenePresence presence)
@@ -1296,11 +1294,10 @@ namespace OpenSim.Region.Framework.Scenes
1296 /// Terse updates 1294 /// Terse updates
1297 public void AddTerseUpdateToAllAvatars() 1295 public void AddTerseUpdateToAllAvatars()
1298 { 1296 {
1299 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 1297 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
1300 for (int i = 0; i < avatars.Length; i++)
1301 { 1298 {
1302 avatars[i].SceneViewer.QueuePartForUpdate(this); 1299 avatar.SceneViewer.QueuePartForUpdate(this);
1303 } 1300 });
1304 } 1301 }
1305 1302
1306 public void AddTerseUpdateToAvatar(ScenePresence presence) 1303 public void AddTerseUpdateToAvatar(ScenePresence presence)
@@ -1335,11 +1332,11 @@ namespace OpenSim.Region.Framework.Scenes
1335 if (volume < 0) 1332 if (volume < 0)
1336 volume = 0; 1333 volume = 0;
1337 1334
1338 List<ScenePresence> avatarts = m_parentGroup.Scene.GetAvatars(); 1335 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence sp)
1339 foreach (ScenePresence p in avatarts)
1340 { 1336 {
1341 p.ControllingClient.SendAttachedSoundGainChange(UUID, (float)volume); 1337 if(!sp.IsChildAgent)
1342 } 1338 sp.ControllingClient.SendAttachedSoundGainChange(UUID, (float)volume);
1339 });
1343 } 1340 }
1344 1341
1345 /// <summary> 1342 /// <summary>
@@ -2060,6 +2057,7 @@ namespace OpenSim.Region.Framework.Scenes
2060 { 2057 {
2061 m_lastColliders.Remove(localID); 2058 m_lastColliders.Remove(localID);
2062 } 2059 }
2060
2063 if (m_parentGroup == null) 2061 if (m_parentGroup == null)
2064 return; 2062 return;
2065 if (m_parentGroup.IsDeleted) 2063 if (m_parentGroup.IsDeleted)
@@ -2136,17 +2134,13 @@ namespace OpenSim.Region.Framework.Scenes
2136 } 2134 }
2137 else 2135 else
2138 { 2136 {
2139 ScenePresence[] avlist = m_parentGroup.Scene.GetScenePresences(); 2137 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence av)
2140
2141 for (int i = 0; i < avlist.Length; i++)
2142 { 2138 {
2143 ScenePresence av = avlist[i];
2144
2145 if (av.LocalId == localId) 2139 if (av.LocalId == localId)
2146 { 2140 {
2147 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name)) 2141 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name))
2148 { 2142 {
2149 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2143 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2150 //If it is 1, it is to accept ONLY collisions from this avatar 2144 //If it is 1, it is to accept ONLY collisions from this avatar
2151 if (found) 2145 if (found)
2152 { 2146 {
@@ -2168,7 +2162,7 @@ namespace OpenSim.Region.Framework.Scenes
2168 } 2162 }
2169 else 2163 else
2170 { 2164 {
2171 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2165 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2172 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work 2166 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work
2173 if (!found) 2167 if (!found)
2174 { 2168 {
@@ -2186,7 +2180,7 @@ namespace OpenSim.Region.Framework.Scenes
2186 } 2180 }
2187 2181
2188 } 2182 }
2189 } 2183 });
2190 } 2184 }
2191 } 2185 }
2192 if (colliding.Count > 0) 2186 if (colliding.Count > 0)
@@ -2272,17 +2266,13 @@ namespace OpenSim.Region.Framework.Scenes
2272 } 2266 }
2273 else 2267 else
2274 { 2268 {
2275 ScenePresence[] avlist = m_parentGroup.Scene.GetScenePresences(); 2269 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence av)
2276
2277 for (int i = 0; i < avlist.Length; i++)
2278 { 2270 {
2279 ScenePresence av = avlist[i];
2280
2281 if (av.LocalId == localId) 2271 if (av.LocalId == localId)
2282 { 2272 {
2283 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name)) 2273 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name))
2284 { 2274 {
2285 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2275 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2286 //If it is 1, it is to accept ONLY collisions from this avatar 2276 //If it is 1, it is to accept ONLY collisions from this avatar
2287 if (found) 2277 if (found)
2288 { 2278 {
@@ -2304,7 +2294,7 @@ namespace OpenSim.Region.Framework.Scenes
2304 } 2294 }
2305 else 2295 else
2306 { 2296 {
2307 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2297 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2308 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work 2298 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work
2309 if (!found) 2299 if (!found)
2310 { 2300 {
@@ -2322,7 +2312,7 @@ namespace OpenSim.Region.Framework.Scenes
2322 } 2312 }
2323 2313
2324 } 2314 }
2325 } 2315 });
2326 } 2316 }
2327 } 2317 }
2328 if (colliding.Count > 0) 2318 if (colliding.Count > 0)
@@ -2403,17 +2393,13 @@ namespace OpenSim.Region.Framework.Scenes
2403 } 2393 }
2404 else 2394 else
2405 { 2395 {
2406 ScenePresence[] avlist = m_parentGroup.Scene.GetScenePresences(); 2396 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence av)
2407
2408 for (int i = 0; i < avlist.Length; i++)
2409 { 2397 {
2410 ScenePresence av = avlist[i];
2411
2412 if (av.LocalId == localId) 2398 if (av.LocalId == localId)
2413 { 2399 {
2414 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name)) 2400 if (m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.UUID.ToString()) || m_parentGroup.RootPart.CollisionFilter.ContainsValue(av.Name))
2415 { 2401 {
2416 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2402 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2417 //If it is 1, it is to accept ONLY collisions from this avatar 2403 //If it is 1, it is to accept ONLY collisions from this avatar
2418 if (found) 2404 if (found)
2419 { 2405 {
@@ -2435,7 +2421,7 @@ namespace OpenSim.Region.Framework.Scenes
2435 } 2421 }
2436 else 2422 else
2437 { 2423 {
2438 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1,out data); 2424 bool found = m_parentGroup.RootPart.CollisionFilter.TryGetValue(1, out data);
2439 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work 2425 //If it is 1, it is to accept ONLY collisions from this avatar, so this other avatar will not work
2440 if (!found) 2426 if (!found)
2441 { 2427 {
@@ -2453,7 +2439,7 @@ namespace OpenSim.Region.Framework.Scenes
2453 } 2439 }
2454 2440
2455 } 2441 }
2456 } 2442 });
2457 } 2443 }
2458 } 2444 }
2459 2445
@@ -2640,12 +2626,13 @@ namespace OpenSim.Region.Framework.Scenes
2640 TaskInventory.LockItemsForRead(false); 2626 TaskInventory.LockItemsForRead(false);
2641 } 2627 }
2642 2628
2643 List<ScenePresence> avatarts = m_parentGroup.Scene.GetAvatars(); 2629 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence sp)
2644 foreach (ScenePresence p in avatarts)
2645 { 2630 {
2646 if (!(Util.GetDistanceTo(p.AbsolutePosition, AbsolutePosition) >= 100)) 2631 if (sp.IsChildAgent)
2647 p.ControllingClient.SendPreLoadSound(objectID, objectID, soundID); 2632 return;
2648 } 2633 if (!(Util.GetDistanceTo(sp.AbsolutePosition, AbsolutePosition) >= 100))
2634 sp.ControllingClient.SendPreLoadSound(objectID, objectID, soundID);
2635 });
2649 } 2636 }
2650 2637
2651 public void RemFlag(PrimFlags flag) 2638 public void RemFlag(PrimFlags flag)
@@ -2820,41 +2807,66 @@ namespace OpenSim.Region.Framework.Scenes
2820 } 2807 }
2821 } 2808 }
2822 2809
2810// /// <summary>
2811// ///
2812// /// </summary>
2813// /// <param name="remoteClient"></param>
2814// public void SendFullUpdate(IClientAPI remoteClient, uint clientFlags)
2815// {
2816// m_parentGroup.SendPartFullUpdate(remoteClient, this, clientFlags);
2817// }
2818
2819
2823 /// <summary> 2820 /// <summary>
2824 /// 2821 /// Send a full update to the client for the given part
2825 /// </summary> 2822 /// </summary>
2826 /// <param name="remoteClient"></param> 2823 /// <param name="remoteClient"></param>
2827 public void SendFullUpdate(IClientAPI remoteClient, uint clientFlags) 2824 /// <param name="clientFlags"></param>
2825 protected internal void SendFullUpdate(IClientAPI remoteClient, uint clientFlags)
2828 { 2826 {
2829 m_parentGroup.SendPartFullUpdate(remoteClient, this, clientFlags); 2827// m_log.DebugFormat(
2828// "[SOG]: Sendinging part full update to {0} for {1} {2}", remoteClient.Name, part.Name, part.LocalId);
2829
2830 if (IsRoot)
2831 {
2832 if (IsAttachment)
2833 {
2834 SendFullUpdateToClient(remoteClient, AttachedPos, clientFlags);
2835 }
2836 else
2837 {
2838 SendFullUpdateToClient(remoteClient, AbsolutePosition, clientFlags);
2839 }
2840 }
2841 else
2842 {
2843 SendFullUpdateToClient(remoteClient, clientFlags);
2844 }
2830 } 2845 }
2831 2846
2832 /// <summary> 2847 /// <summary>
2833 /// 2848 /// Send a full update for this part to all clients.
2834 /// </summary> 2849 /// </summary>
2835 public void SendFullUpdateToAllClients() 2850 public void SendFullUpdateToAllClients()
2836 { 2851 {
2837 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 2852 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
2838 for (int i = 0; i < avatars.Length; i++)
2839 { 2853 {
2840 // Ugly reference :( 2854 SendFullUpdate(avatar.ControllingClient, avatar.GenerateClientFlags(UUID));
2841 m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, 2855 });
2842 avatars[i].GenerateClientFlags(UUID));
2843 }
2844 } 2856 }
2845 2857
2858 /// <summary>
2859 /// Send a full update to all clients except the one nominated.
2860 /// </summary>
2861 /// <param name="agentID"></param>
2846 public void SendFullUpdateToAllClientsExcept(UUID agentID) 2862 public void SendFullUpdateToAllClientsExcept(UUID agentID)
2847 { 2863 {
2848 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 2864 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
2849 for (int i = 0; i < avatars.Length; i++)
2850 { 2865 {
2851 // Ugly reference :( 2866 // Ugly reference :(
2852 if (avatars[i].UUID != agentID) 2867 if (avatar.UUID != agentID)
2853 { 2868 SendFullUpdate(avatar.ControllingClient, avatar.GenerateClientFlags(UUID));
2854 m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, 2869 });
2855 avatars[i].GenerateClientFlags(UUID));
2856 }
2857 }
2858 } 2870 }
2859 2871
2860 /// <summary> 2872 /// <summary>
@@ -3055,11 +3067,10 @@ namespace OpenSim.Region.Framework.Scenes
3055 /// </summary> 3067 /// </summary>
3056 public void SendTerseUpdateToAllClients() 3068 public void SendTerseUpdateToAllClients()
3057 { 3069 {
3058 ScenePresence[] avatars = m_parentGroup.Scene.GetScenePresences(); 3070 m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
3059 for (int i = 0; i < avatars.Length; i++)
3060 { 3071 {
3061 SendTerseUpdateToClient(avatars[i].ControllingClient); 3072 SendTerseUpdateToClient(avatar.ControllingClient);
3062 } 3073 });
3063 } 3074 }
3064 3075
3065 public void SetAttachmentPoint(uint AttachmentPoint) 3076 public void SetAttachmentPoint(uint AttachmentPoint)
@@ -4672,5 +4683,17 @@ namespace OpenSim.Region.Framework.Scenes
4672 { 4683 {
4673 return new Color4((byte)Color.R, (byte)Color.G, (byte)Color.B, (byte)(0xFF - Color.A)); 4684 return new Color4((byte)Color.R, (byte)Color.G, (byte)Color.B, (byte)(0xFF - Color.A));
4674 } 4685 }
4686
4687 public void ResetOwnerChangeFlag()
4688 {
4689 List<UUID> inv = Inventory.GetInventoryList();
4690
4691 foreach (UUID itemID in inv)
4692 {
4693 TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
4694 item.OwnerChanged = false;
4695 Inventory.UpdateInventoryItem(item);
4696 }
4697 }
4675 } 4698 }
4676} 4699}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
index a2fceb7..62b44bd 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
@@ -34,7 +34,6 @@ using System.Reflection;
34using OpenMetaverse; 34using OpenMetaverse;
35using log4net; 35using log4net;
36using OpenSim.Framework; 36using OpenSim.Framework;
37using OpenSim.Framework.Communications.Cache;
38using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Region.Framework.Scenes.Scripting; 38using OpenSim.Region.Framework.Scenes.Scripting;
40 39
@@ -213,7 +212,7 @@ namespace OpenSim.Region.Framework.Scenes
213 } 212 }
214 } 213 }
215 214
216 private ArrayList GetScriptErrors(UUID itemID) 215 public ArrayList GetScriptErrors(UUID itemID)
217 { 216 {
218 ArrayList ret = new ArrayList(); 217 ArrayList ret = new ArrayList();
219 218
@@ -296,38 +295,36 @@ namespace OpenSim.Region.Framework.Scenes
296 return; 295 return;
297 } 296 }
298 297
299 m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString(), this, delegate(string id, object sender, AssetBase asset) 298 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
300 { 299 if (null == asset)
301 if (null == asset) 300 {
302 { 301 string msg = String.Format("asset ID {0} could not be found", item.AssetID);
303 string msg = String.Format("asset ID {0} could not be found", item.AssetID); 302 StoreScriptError(item.ItemID, msg);
304 StoreScriptError(item.ItemID, msg); 303 m_log.ErrorFormat(
305 m_log.ErrorFormat( 304 "[PRIM INVENTORY]: " +
306 "[PRIM INVENTORY]: " + 305 "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
307 "Couldn't start script {0}, {1} at {2} in {3} since {4}", 306 item.Name, item.ItemID, m_part.AbsolutePosition,
308 item.Name, item.ItemID, m_part.AbsolutePosition, 307 m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
309 m_part.ParentGroup.Scene.RegionInfo.RegionName, msg); 308 }
310 } 309 else
311 else 310 {
312 { 311 if (m_part.ParentGroup.m_savedScriptState != null)
313 if (m_part.ParentGroup.m_savedScriptState != null) 312 RestoreSavedScriptState(item.OldItemID, item.ItemID);
314 RestoreSavedScriptState(item.OldItemID, item.ItemID); 313
315 m_items.LockItemsForWrite(true); 314 m_items.LockItemsForWrite(true);
316 m_items[item.ItemID].PermsMask = 0; 315
317 m_items[item.ItemID].PermsGranter = UUID.Zero; 316 m_items[item.ItemID].PermsMask = 0;
318 m_items.LockItemsForWrite(false); 317 m_items[item.ItemID].PermsGranter = UUID.Zero;
319 string script = Utils.BytesToString(asset.Data); 318
320 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 319 m_items.LockItemsForWrite(false);
321 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); 320
322 StoreScriptErrors(item.ItemID, null); 321 string script = Utils.BytesToString(asset.Data);
323 m_part.ParentGroup.AddActiveScriptCount(1); 322 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
324 m_part.ScheduleFullUpdate(); 323 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
325 } 324 StoreScriptErrors(item.ItemID, null);
326 }); 325 m_part.ParentGroup.AddActiveScriptCount(1);
327 } 326 m_part.ScheduleFullUpdate();
328 else 327 }
329 {
330 StoreScriptError(item.ItemID, "scripts disabled");
331 } 328 }
332 } 329 }
333 330
@@ -654,6 +651,7 @@ namespace OpenSim.Region.Framework.Scenes
654 item.ParentID = m_part.UUID; 651 item.ParentID = m_part.UUID;
655 item.ParentPartID = m_part.UUID; 652 item.ParentPartID = m_part.UUID;
656 item.Name = name; 653 item.Name = name;
654 item.GroupID = m_part.GroupID;
657 655
658 m_items.LockItemsForWrite(true); 656 m_items.LockItemsForWrite(true);
659 m_items.Add(item.ItemID, item); 657 m_items.Add(item.ItemID, item);
@@ -716,15 +714,16 @@ namespace OpenSim.Region.Framework.Scenes
716 { 714 {
717 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(); 715 IList<TaskInventoryItem> items = new List<TaskInventoryItem>();
718 716
719 lock (m_items) 717 m_items.LockItemsForRead(true);
718
719 foreach (TaskInventoryItem item in m_items.Values)
720 { 720 {
721 foreach (TaskInventoryItem item in m_items.Values) 721 if (item.Name == name)
722 { 722 items.Add(item);
723 if (item.Name == name)
724 items.Add(item);
725 }
726 } 723 }
727 724
725 m_items.LockItemsForRead(false);
726
728 return items; 727 return items;
729 } 728 }
730 729
@@ -736,6 +735,11 @@ namespace OpenSim.Region.Framework.Scenes
736 /// <returns>false if the item did not exist, true if the update occurred successfully</returns> 735 /// <returns>false if the item did not exist, true if the update occurred successfully</returns>
737 public bool UpdateInventoryItem(TaskInventoryItem item) 736 public bool UpdateInventoryItem(TaskInventoryItem item)
738 { 737 {
738 return UpdateInventoryItem(item, true);
739 }
740
741 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents)
742 {
739 m_items.LockItemsForWrite(true); 743 m_items.LockItemsForWrite(true);
740 744
741 if (m_items.ContainsKey(item.ItemID)) 745 if (m_items.ContainsKey(item.ItemID))
@@ -743,6 +747,12 @@ namespace OpenSim.Region.Framework.Scenes
743 item.ParentID = m_part.UUID; 747 item.ParentID = m_part.UUID;
744 item.ParentPartID = m_part.UUID; 748 item.ParentPartID = m_part.UUID;
745 item.Flags = m_items[item.ItemID].Flags; 749 item.Flags = m_items[item.ItemID].Flags;
750
751 // If group permissions have been set on, check that the groupID is up to date in case it has
752 // changed since permissions were last set.
753 if (item.GroupPermissions != (uint)PermissionMask.None)
754 item.GroupID = m_part.GroupID;
755
746 if (item.AssetID == UUID.Zero) 756 if (item.AssetID == UUID.Zero)
747 { 757 {
748 item.AssetID = m_items[item.ItemID].AssetID; 758 item.AssetID = m_items[item.ItemID].AssetID;
@@ -760,8 +770,8 @@ namespace OpenSim.Region.Framework.Scenes
760 770
761 m_items[item.ItemID] = item; 771 m_items[item.ItemID] = item;
762 m_inventorySerial++; 772 m_inventorySerial++;
763 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 773 if (fireScriptEvents)
764 774 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
765 HasInventoryChanged = true; 775 HasInventoryChanged = true;
766 m_part.ParentGroup.HasGroupChanged = true; 776 m_part.ParentGroup.HasGroupChanged = true;
767 m_items.LockItemsForWrite(false); 777 m_items.LockItemsForWrite(false);
@@ -896,6 +906,7 @@ namespace OpenSim.Region.Framework.Scenes
896 uint everyoneMask = 0; 906 uint everyoneMask = 0;
897 uint baseMask = item.BasePermissions; 907 uint baseMask = item.BasePermissions;
898 uint ownerMask = item.CurrentPermissions; 908 uint ownerMask = item.CurrentPermissions;
909 uint groupMask = item.GroupPermissions;
899 910
900 invString.AddItemStart(); 911 invString.AddItemStart();
901 invString.AddNameValueLine("item_id", item.ItemID.ToString()); 912 invString.AddNameValueLine("item_id", item.ItemID.ToString());
@@ -905,7 +916,7 @@ namespace OpenSim.Region.Framework.Scenes
905 916
906 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask)); 917 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
907 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask)); 918 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
908 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(0)); 919 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
909 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask)); 920 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
910 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions)); 921 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
911 922
@@ -1071,12 +1082,11 @@ namespace OpenSim.Region.Framework.Scenes
1071 item.CurrentPermissions &= ~(uint)PermissionMask.Modify; 1082 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1072 item.CurrentPermissions |= 8; 1083 item.CurrentPermissions |= 8;
1073 } 1084 }
1085 item.OwnerChanged = true;
1074 item.CurrentPermissions &= item.NextPermissions; 1086 item.CurrentPermissions &= item.NextPermissions;
1075 item.BasePermissions &= item.NextPermissions; 1087 item.BasePermissions &= item.NextPermissions;
1076 item.EveryonePermissions &= item.NextPermissions; 1088 item.EveryonePermissions &= item.NextPermissions;
1077 } 1089 }
1078
1079 m_part.TriggerScriptChangedEvent(Changed.OWNER);
1080 } 1090 }
1081 1091
1082 public void ApplyGodPermissions(uint perms) 1092 public void ApplyGodPermissions(uint perms)
@@ -1112,6 +1122,11 @@ namespace OpenSim.Region.Framework.Scenes
1112 1122
1113 public Dictionary<UUID, string> GetScriptStates() 1123 public Dictionary<UUID, string> GetScriptStates()
1114 { 1124 {
1125 return GetScriptStates(false);
1126 }
1127
1128 public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
1129 {
1115 IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); 1130 IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
1116 1131
1117 Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); 1132 Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
@@ -1129,8 +1144,16 @@ namespace OpenSim.Region.Framework.Scenes
1129 string n = e.GetXMLState(item.ItemID); 1144 string n = e.GetXMLState(item.ItemID);
1130 if (n != String.Empty) 1145 if (n != String.Empty)
1131 { 1146 {
1132 if (!ret.ContainsKey(item.ItemID)) 1147 if (oldIDs)
1133 ret[item.ItemID] = n; 1148 {
1149 if (!ret.ContainsKey(item.OldItemID))
1150 ret[item.OldItemID] = n;
1151 }
1152 else
1153 {
1154 if (!ret.ContainsKey(item.ItemID))
1155 ret[item.ItemID] = n;
1156 }
1134 break; 1157 break;
1135 } 1158 }
1136 } 1159 }
@@ -1139,5 +1162,34 @@ namespace OpenSim.Region.Framework.Scenes
1139 } 1162 }
1140 return ret; 1163 return ret;
1141 } 1164 }
1165
1166 public void ResumeScripts()
1167 {
1168 IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
1169 if (engines == null)
1170 return;
1171
1172
1173 Items.LockItemsForRead(true);
1174
1175 foreach (TaskInventoryItem item in m_items.Values)
1176 {
1177 if (item.InvType == (int)InventoryType.LSL)
1178 {
1179 foreach (IScriptModule engine in engines)
1180 {
1181 if (engine != null)
1182 {
1183 if (item.OwnerChanged)
1184 engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER });
1185 item.OwnerChanged = false;
1186 engine.ResumeScript(item.ItemID);
1187 }
1188 }
1189 }
1190 }
1191
1192 Items.LockItemsForRead(false);
1193 }
1142 } 1194 }
1143} 1195}
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index 565438d..d76f029 100644
--- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs
+++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
@@ -26,6 +26,7 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Xml;
29using System.Collections.Generic; 30using System.Collections.Generic;
30using System.Reflection; 31using System.Reflection;
31using System.Timers; 32using System.Timers;
@@ -33,12 +34,12 @@ using OpenMetaverse;
33using log4net; 34using log4net;
34using OpenSim.Framework; 35using OpenSim.Framework;
35using OpenSim.Framework.Client; 36using OpenSim.Framework.Client;
36using OpenSim.Framework.Communications.Cache;
37using OpenSim.Region.Framework.Interfaces; 37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes.Animation; 38using OpenSim.Region.Framework.Scenes.Animation;
39using OpenSim.Region.Framework.Scenes.Types; 39using OpenSim.Region.Framework.Scenes.Types;
40using OpenSim.Region.Physics.Manager; 40using OpenSim.Region.Physics.Manager;
41using GridRegion = OpenSim.Services.Interfaces.GridRegion; 41using GridRegion = OpenSim.Services.Interfaces.GridRegion;
42using OpenSim.Services.Interfaces;
42 43
43namespace OpenSim.Region.Framework.Scenes 44namespace OpenSim.Region.Framework.Scenes
44{ 45{
@@ -150,7 +151,8 @@ namespace OpenSim.Region.Framework.Scenes
150 151
151 private float m_sitAvatarHeight = 2.0f; 152 private float m_sitAvatarHeight = 2.0f;
152 153
153 private float m_godlevel; 154 private int m_godLevel;
155 private int m_userLevel;
154 156
155 private bool m_invulnerable = true; 157 private bool m_invulnerable = true;
156 158
@@ -225,7 +227,6 @@ namespace OpenSim.Region.Framework.Scenes
225 private int m_lastColCount = -1; //KF: Look for Collision chnages 227 private int m_lastColCount = -1; //KF: Look for Collision chnages
226 private int m_updateCount = 0; //KF: Update Anims for a while 228 private int m_updateCount = 0; //KF: Update Anims for a while
227 private static readonly int UPDATE_COUNT = 10; // how many frames to update for 229 private static readonly int UPDATE_COUNT = 10; // how many frames to update for
228
229 private const int NumMovementsBetweenRayCast = 5; 230 private const int NumMovementsBetweenRayCast = 5;
230 231
231 private bool CameraConstraintActive; 232 private bool CameraConstraintActive;
@@ -266,6 +267,8 @@ namespace OpenSim.Region.Framework.Scenes
266 267
267 // For teleports and crossings callbacks 268 // For teleports and crossings callbacks
268 string m_callbackURI; 269 string m_callbackURI;
270 UUID m_originRegionID;
271
269 ulong m_rootRegionHandle; 272 ulong m_rootRegionHandle;
270 273
271 /// <value> 274 /// <value>
@@ -302,9 +305,14 @@ namespace OpenSim.Region.Framework.Scenes
302 get { return m_invulnerable; } 305 get { return m_invulnerable; }
303 } 306 }
304 307
305 public float GodLevel 308 public int UserLevel
306 { 309 {
307 get { return m_godlevel; } 310 get { return m_userLevel; }
311 }
312
313 public int GodLevel
314 {
315 get { return m_godLevel; }
308 } 316 }
309 317
310 public ulong RegionHandle 318 public ulong RegionHandle
@@ -457,7 +465,7 @@ namespace OpenSim.Region.Framework.Scenes
457 PhysicsActor actor = m_physicsActor; 465 PhysicsActor actor = m_physicsActor;
458// if (actor != null) 466// if (actor != null)
459 if ((actor != null) && (m_parentID == 0)) // KF Do NOT update m_pos here if Av is sitting! 467 if ((actor != null) && (m_parentID == 0)) // KF Do NOT update m_pos here if Av is sitting!
460 m_pos = actor.Position; 468 m_pos = actor.Position;
461 469
462 return m_parentPosition + m_pos; 470 return m_parentPosition + m_pos;
463 } 471 }
@@ -655,6 +663,11 @@ namespace OpenSim.Region.Framework.Scenes
655 set { m_flyDisabled = value; } 663 set { m_flyDisabled = value; }
656 } 664 }
657 665
666 public string Viewer
667 {
668 get { return m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode).Viewer; }
669 }
670
658 #endregion 671 #endregion
659 672
660 #region Constructor(s) 673 #region Constructor(s)
@@ -678,6 +691,11 @@ namespace OpenSim.Region.Framework.Scenes
678 m_regionInfo = reginfo; 691 m_regionInfo = reginfo;
679 m_localId = m_scene.AllocateLocalId(); 692 m_localId = m_scene.AllocateLocalId();
680 693
694 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
695
696 if (account != null)
697 m_userLevel = account.UserLevel;
698
681 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>(); 699 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
682 if (gm != null) 700 if (gm != null)
683 m_grouptitle = gm.GetGroupTitle(m_uuid); 701 m_grouptitle = gm.GetGroupTitle(m_uuid);
@@ -868,47 +886,22 @@ namespace OpenSim.Region.Framework.Scenes
868 if (land != null) 886 if (land != null)
869 { 887 {
870 //Don't restrict gods, estate managers, or land owners to the TP point. This behaviour mimics agni. 888 //Don't restrict gods, estate managers, or land owners to the TP point. This behaviour mimics agni.
871 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero && m_godlevel < 200 && !m_scene.RegionInfo.EstateSettings.IsEstateManager(m_uuid) && land.LandData.OwnerID != m_uuid) 889 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero && m_userLevel < 200 && !m_scene.RegionInfo.EstateSettings.IsEstateManager(m_uuid) && land.LandData.OwnerID != m_uuid)
872 { 890 {
873 pos = land.LandData.UserLocation; 891 pos = land.LandData.UserLocation;
874 } 892 }
875 } 893 }
876 } 894 }
877 895
878 if (pos.X < 0 || pos.Y < 0 || pos.Z < 0) 896 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
879 { 897 {
880 Vector3 emergencyPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 128);
881
882 if (pos.X < 0)
883 {
884 emergencyPos.X = (int)Constants.RegionSize + pos.X;
885 if (!(pos.Y < 0))
886 emergencyPos.Y = pos.Y;
887 if (!(pos.Z < 0))
888 emergencyPos.X = pos.X;
889 }
890 if (pos.Y < 0)
891 {
892 emergencyPos.Y = (int)Constants.RegionSize + pos.Y;
893 if (!(pos.X < 0))
894 emergencyPos.X = pos.X;
895 if (!(pos.Z < 0))
896 emergencyPos.Z = pos.Z;
897 }
898 if (pos.Z < 0)
899 {
900 if (!(pos.X < 0))
901 emergencyPos.X = pos.X;
902 if (!(pos.Y < 0))
903 emergencyPos.Y = pos.Y;
904 //Leave as 128
905 }
906
907 m_log.WarnFormat( 898 m_log.WarnFormat(
908 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}", 899 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
909 pos, Name, UUID, emergencyPos); 900 pos, Name, UUID);
910 901
911 pos = emergencyPos; 902 if (pos.X < 0f) pos.X = 0f;
903 if (pos.Y < 0f) pos.Y = 0f;
904 if (pos.Z < 0f) pos.Z = 0f;
912 } 905 }
913 906
914 float localAVHeight = 1.56f; 907 float localAVHeight = 1.56f;
@@ -919,7 +912,7 @@ namespace OpenSim.Region.Framework.Scenes
919 912
920 float posZLimit = 0; 913 float posZLimit = 0;
921 914
922 if (pos.X <Constants.RegionSize && pos.Y < Constants.RegionSize) 915 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
923 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y]; 916 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
924 917
925 float newPosZ = posZLimit + localAVHeight / 2; 918 float newPosZ = posZLimit + localAVHeight / 2;
@@ -971,14 +964,12 @@ namespace OpenSim.Region.Framework.Scenes
971 964
972 m_isChildAgent = false; 965 m_isChildAgent = false;
973 966
974 ScenePresence[] animAgents = m_scene.GetScenePresences(); 967 // send the animations of the other presences to me
975 for (int i = 0; i < animAgents.Length; i++) 968 m_scene.ForEachScenePresence(delegate(ScenePresence presence)
976 { 969 {
977 ScenePresence presence = animAgents[i];
978
979 if (presence != this) 970 if (presence != this)
980 presence.Animator.SendAnimPackToClient(ControllingClient); 971 presence.Animator.SendAnimPackToClient(ControllingClient);
981 } 972 });
982 973
983 m_scene.EventManager.TriggerOnMakeRootAgent(this); 974 m_scene.EventManager.TriggerOnMakeRootAgent(this);
984 } 975 }
@@ -1162,8 +1153,10 @@ namespace OpenSim.Region.Framework.Scenes
1162 /// This is called upon a very important packet sent from the client, 1153 /// This is called upon a very important packet sent from the client,
1163 /// so it's client-controlled. Never call this method directly. 1154 /// so it's client-controlled. Never call this method directly.
1164 /// </summary> 1155 /// </summary>
1165 public void CompleteMovement() 1156 public void CompleteMovement(IClientAPI client)
1166 { 1157 {
1158 //m_log.Debug("[SCENE PRESENCE]: CompleteMovement");
1159
1167 Vector3 look = Velocity; 1160 Vector3 look = Velocity;
1168 if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) 1161 if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
1169 { 1162 {
@@ -1188,7 +1181,7 @@ namespace OpenSim.Region.Framework.Scenes
1188 if ((m_callbackURI != null) && !m_callbackURI.Equals("")) 1181 if ((m_callbackURI != null) && !m_callbackURI.Equals(""))
1189 { 1182 {
1190 m_log.DebugFormat("[SCENE PRESENCE]: Releasing agent in URI {0}", m_callbackURI); 1183 m_log.DebugFormat("[SCENE PRESENCE]: Releasing agent in URI {0}", m_callbackURI);
1191 Scene.SendReleaseAgent(m_rootRegionHandle, UUID, m_callbackURI); 1184 Scene.SimulationService.ReleaseAgent(m_originRegionID, UUID, m_callbackURI);
1192 m_callbackURI = null; 1185 m_callbackURI = null;
1193 } 1186 }
1194 1187
@@ -1196,6 +1189,21 @@ namespace OpenSim.Region.Framework.Scenes
1196 1189
1197 m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look); 1190 m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look);
1198 SendInitialData(); 1191 SendInitialData();
1192
1193 // Create child agents in neighbouring regions
1194 if (!m_isChildAgent)
1195 {
1196 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
1197 if (m_agentTransfer != null)
1198 m_agentTransfer.EnableChildAgents(this);
1199 else
1200 m_log.DebugFormat("[SCENE PRESENCE]: Unable to create child agents in neighbours, because AgentTransferModule is not active");
1201
1202 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
1203 if (friendsModule != null)
1204 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
1205 }
1206
1199 } 1207 }
1200 1208
1201 /// <summary> 1209 /// <summary>
@@ -1264,6 +1272,7 @@ namespace OpenSim.Region.Framework.Scenes
1264 m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902"); 1272 m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
1265 1273
1266 m_pos = m_LastFinitePos; 1274 m_pos = m_LastFinitePos;
1275
1267 if (!m_pos.IsFinite()) 1276 if (!m_pos.IsFinite())
1268 { 1277 {
1269 m_pos.X = 127f; 1278 m_pos.X = 127f;
@@ -1900,6 +1909,7 @@ namespace OpenSim.Region.Framework.Scenes
1900 { 1909 {
1901 m_avUnscriptedSitPos = Vector3.Zero; // Zero = Sit on prim center 1910 m_avUnscriptedSitPos = Vector3.Zero; // Zero = Sit on prim center
1902 autopilotTarget = part.AbsolutePosition; 1911 autopilotTarget = part.AbsolutePosition;
1912//Console.WriteLine("UsSmall autopilotTarget={0}", autopilotTarget);
1903 } 1913 }
1904 else return; // occupied small 1914 else return; // occupied small
1905 } // end large/small 1915 } // end large/small
@@ -2276,7 +2286,8 @@ namespace OpenSim.Region.Framework.Scenes
2276 m_pos += SIT_TARGET_ADJUSTMENT; 2286 m_pos += SIT_TARGET_ADJUSTMENT;
2277 m_bodyRot = sitTargetOrient; 2287 m_bodyRot = sitTargetOrient;
2278 m_parentPosition = part.AbsolutePosition; 2288 m_parentPosition = part.AbsolutePosition;
2279 part.IsOccupied = true; 2289 part.IsOccupied = true;
2290Console.WriteLine("Scripted Sit ofset {0}", m_pos);
2280 } 2291 }
2281 else 2292 else
2282 { 2293 {
@@ -2398,6 +2409,7 @@ namespace OpenSim.Region.Framework.Scenes
2398 { 2409 {
2399 if (m_isChildAgent) 2410 if (m_isChildAgent)
2400 { 2411 {
2412 // WHAT???
2401 m_log.Debug("[SCENEPRESENCE]: AddNewMovement() called on child agent, making root agent!"); 2413 m_log.Debug("[SCENEPRESENCE]: AddNewMovement() called on child agent, making root agent!");
2402 2414
2403 // we have to reset the user's child agent connections. 2415 // we have to reset the user's child agent connections.
@@ -2421,7 +2433,9 @@ namespace OpenSim.Region.Framework.Scenes
2421 2433
2422 if (m_scene.SceneGridService != null) 2434 if (m_scene.SceneGridService != null)
2423 { 2435 {
2424 m_scene.SceneGridService.EnableNeighbourChildAgents(this, new List<RegionInfo>()); 2436 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
2437 if (m_agentTransfer != null)
2438 m_agentTransfer.EnableChildAgents(this);
2425 } 2439 }
2426 2440
2427 return; 2441 return;
@@ -2597,35 +2611,33 @@ namespace OpenSim.Region.Framework.Scenes
2597 2611
2598 List<Vector3> CoarseLocations = new List<Vector3>(); 2612 List<Vector3> CoarseLocations = new List<Vector3>();
2599 List<UUID> AvatarUUIDs = new List<UUID>(); 2613 List<UUID> AvatarUUIDs = new List<UUID>();
2600 List<ScenePresence> avatars = m_scene.GetAvatars(); 2614 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
2601 for (int i = 0; i < avatars.Count; i++)
2602 { 2615 {
2603 // Requested by LibOMV. Send Course Location on self. 2616 if (sp.IsChildAgent)
2604 //if (avatars[i] != this) 2617 return;
2605 //{ 2618
2606 if (avatars[i].ParentID != 0) 2619 if (sp.ParentID != 0)
2620 {
2621 // sitting avatar
2622 SceneObjectPart sop = m_scene.GetSceneObjectPart(sp.ParentID);
2623 if (sop != null)
2607 { 2624 {
2608 // sitting avatar 2625 CoarseLocations.Add(sop.AbsolutePosition + sp.m_pos);
2609 SceneObjectPart sop = m_scene.GetSceneObjectPart(avatars[i].ParentID); 2626 AvatarUUIDs.Add(sp.UUID);
2610 if (sop != null)
2611 {
2612 CoarseLocations.Add(sop.AbsolutePosition + avatars[i].m_pos);
2613 AvatarUUIDs.Add(avatars[i].UUID);
2614 }
2615 else
2616 {
2617 // we can't find the parent.. ! arg!
2618 CoarseLocations.Add(avatars[i].m_pos);
2619 AvatarUUIDs.Add(avatars[i].UUID);
2620 }
2621 } 2627 }
2622 else 2628 else
2623 { 2629 {
2624 CoarseLocations.Add(avatars[i].m_pos); 2630 // we can't find the parent.. ! arg!
2625 AvatarUUIDs.Add(avatars[i].UUID); 2631 CoarseLocations.Add(sp.m_pos);
2632 AvatarUUIDs.Add(sp.UUID);
2626 } 2633 }
2627 //} 2634 }
2628 } 2635 else
2636 {
2637 CoarseLocations.Add(sp.m_pos);
2638 AvatarUUIDs.Add(sp.UUID);
2639 }
2640 });
2629 2641
2630 m_controllingClient.SendCoarseLocationUpdate(AvatarUUIDs, CoarseLocations); 2642 m_controllingClient.SendCoarseLocationUpdate(AvatarUUIDs, CoarseLocations);
2631 2643
@@ -2667,13 +2679,10 @@ namespace OpenSim.Region.Framework.Scenes
2667 public void SendInitialFullUpdateToAllClients() 2679 public void SendInitialFullUpdateToAllClients()
2668 { 2680 {
2669 m_perfMonMS = Util.EnvironmentTickCount(); 2681 m_perfMonMS = Util.EnvironmentTickCount();
2670 2682 int avUpdates = 0;
2671 ScenePresence[] avatars = m_scene.GetScenePresences(); 2683 m_scene.ForEachScenePresence(delegate(ScenePresence avatar)
2672
2673 for (int i = 0; i < avatars.Length; i++)
2674 { 2684 {
2675 ScenePresence avatar = avatars[i]; 2685 ++avUpdates;
2676
2677 // only send if this is the root (children are only "listening posts" in a foreign region) 2686 // only send if this is the root (children are only "listening posts" in a foreign region)
2678 if (!IsChildAgent) 2687 if (!IsChildAgent)
2679 { 2688 {
@@ -2689,9 +2698,9 @@ namespace OpenSim.Region.Framework.Scenes
2689 avatar.Animator.SendAnimPackToClient(ControllingClient); 2698 avatar.Animator.SendAnimPackToClient(ControllingClient);
2690 } 2699 }
2691 } 2700 }
2692 } 2701 });
2693 2702
2694 m_scene.StatsReporter.AddAgentUpdates(avatars.Length); 2703 m_scene.StatsReporter.AddAgentUpdates(avUpdates);
2695 m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS)); 2704 m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
2696 2705
2697 //Animator.SendAnimPack(); 2706 //Animator.SendAnimPack();
@@ -2702,13 +2711,15 @@ namespace OpenSim.Region.Framework.Scenes
2702 m_perfMonMS = Util.EnvironmentTickCount(); 2711 m_perfMonMS = Util.EnvironmentTickCount();
2703 2712
2704 // only send update from root agents to other clients; children are only "listening posts" 2713 // only send update from root agents to other clients; children are only "listening posts"
2705 List<ScenePresence> avatars = m_scene.GetAvatars(); 2714 int count = 0;
2706 foreach (ScenePresence avatar in avatars) 2715 m_scene.ForEachScenePresence(delegate(ScenePresence sp)
2707 { 2716 {
2708 SendFullUpdateToOtherClient(avatar); 2717 if (sp.IsChildAgent)
2709 2718 return;
2710 } 2719 SendFullUpdateToOtherClient(sp);
2711 m_scene.StatsReporter.AddAgentUpdates(avatars.Count); 2720 ++count;
2721 });
2722 m_scene.StatsReporter.AddAgentUpdates(count);
2712 m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS)); 2723 m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
2713 2724
2714 Animator.SendAnimPack(); 2725 Animator.SendAnimPack();
@@ -2729,14 +2740,9 @@ namespace OpenSim.Region.Framework.Scenes
2729 m_controllingClient.SendAvatarData(new SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId, 2740 m_controllingClient.SendAvatarData(new SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId,
2730 pos, m_appearance.Texture.GetBytes(), m_parentID, m_bodyRot)); 2741 pos, m_appearance.Texture.GetBytes(), m_parentID, m_bodyRot));
2731 2742
2732 if (!m_isChildAgent)
2733 {
2734 m_scene.InformClientOfNeighbours(this);
2735 }
2736
2737 SendInitialFullUpdateToAllClients(); 2743 SendInitialFullUpdateToAllClients();
2738 SendAppearanceToAllOtherAgents(); 2744 SendAppearanceToAllOtherAgents();
2739 } 2745 }
2740 2746
2741 /// <summary> 2747 /// <summary>
2742 /// Tell the client for this scene presence what items it should be wearing now 2748 /// Tell the client for this scene presence what items it should be wearing now
@@ -2818,14 +2824,19 @@ namespace OpenSim.Region.Framework.Scenes
2818 } 2824 }
2819 } 2825 }
2820 } 2826 }
2827
2821 } 2828 }
2822 2829
2830
2823 #endregion Bake Cache Check 2831 #endregion Bake Cache Check
2824 2832
2825 m_appearance.SetAppearance(textureEntry, visualParams); 2833 m_appearance.SetAppearance(textureEntry, visualParams);
2826 if (m_appearance.AvatarHeight > 0) 2834 if (m_appearance.AvatarHeight > 0)
2827 SetHeight(m_appearance.AvatarHeight); 2835 SetHeight(m_appearance.AvatarHeight);
2828 m_scene.CommsManager.AvatarService.UpdateUserAppearance(m_controllingClient.AgentId, m_appearance); 2836
2837 // This is not needed, because only the transient data changed
2838 //AvatarData adata = new AvatarData(m_appearance);
2839 //m_scene.AvatarService.SetAvatar(m_controllingClient.AgentId, adata);
2829 2840
2830 SendAppearanceToAllOtherAgents(); 2841 SendAppearanceToAllOtherAgents();
2831 if (!m_startAnimationSet) 2842 if (!m_startAnimationSet)
@@ -2845,7 +2856,8 @@ namespace OpenSim.Region.Framework.Scenes
2845 public void SetWearable(int wearableId, AvatarWearable wearable) 2856 public void SetWearable(int wearableId, AvatarWearable wearable)
2846 { 2857 {
2847 m_appearance.SetWearable(wearableId, wearable); 2858 m_appearance.SetWearable(wearableId, wearable);
2848 m_scene.CommsManager.AvatarService.UpdateUserAppearance(m_controllingClient.AgentId, m_appearance); 2859 AvatarData adata = new AvatarData(m_appearance);
2860 m_scene.AvatarService.SetAvatar(m_controllingClient.AgentId, adata);
2849 m_controllingClient.SendWearables(m_appearance.Wearables, m_appearance.Serial++); 2861 m_controllingClient.SendWearables(m_appearance.Wearables, m_appearance.Serial++);
2850 } 2862 }
2851 2863
@@ -2867,7 +2879,12 @@ namespace OpenSim.Region.Framework.Scenes
2867 /// </summary> 2879 /// </summary>
2868 protected void CheckForSignificantMovement() 2880 protected void CheckForSignificantMovement()
2869 { 2881 {
2870 if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > 0.5) 2882 // Movement updates for agents in neighboring regions are sent directly to clients.
2883 // This value only affects how often agent positions are sent to neighbor regions
2884 // for things such as distance-based update prioritization
2885 const float SIGNIFICANT_MOVEMENT = 2.0f;
2886
2887 if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > SIGNIFICANT_MOVEMENT)
2871 { 2888 {
2872 posLastSignificantMove = AbsolutePosition; 2889 posLastSignificantMove = AbsolutePosition;
2873 m_scene.EventManager.TriggerSignificantClientMovement(m_controllingClient); 2890 m_scene.EventManager.TriggerSignificantClientMovement(m_controllingClient);
@@ -2878,18 +2895,19 @@ namespace OpenSim.Region.Framework.Scenes
2878 if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance || 2895 if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance ||
2879 Util.GetDistanceTo(CameraPosition, m_lastChildAgentUpdateCamPosition) >= Scene.ChildReprioritizationDistance) 2896 Util.GetDistanceTo(CameraPosition, m_lastChildAgentUpdateCamPosition) >= Scene.ChildReprioritizationDistance)
2880 { 2897 {
2898 m_lastChildAgentUpdatePosition = AbsolutePosition;
2899 m_lastChildAgentUpdateCamPosition = CameraPosition;
2900
2881 ChildAgentDataUpdate cadu = new ChildAgentDataUpdate(); 2901 ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
2882 cadu.ActiveGroupID = UUID.Zero.Guid; 2902 cadu.ActiveGroupID = UUID.Zero.Guid;
2883 cadu.AgentID = UUID.Guid; 2903 cadu.AgentID = UUID.Guid;
2884 cadu.alwaysrun = m_setAlwaysRun; 2904 cadu.alwaysrun = m_setAlwaysRun;
2885 cadu.AVHeight = m_avHeight; 2905 cadu.AVHeight = m_avHeight;
2886 sLLVector3 tempCameraCenter = new sLLVector3(new Vector3(m_CameraCenter.X, m_CameraCenter.Y, m_CameraCenter.Z)); 2906 Vector3 tempCameraCenter = m_CameraCenter;
2887 cadu.cameraPosition = tempCameraCenter; 2907 cadu.cameraPosition = tempCameraCenter;
2888 cadu.drawdistance = m_DrawDistance; 2908 cadu.drawdistance = m_DrawDistance;
2889 if (m_scene.Permissions.IsGod(new UUID(cadu.AgentID)))
2890 cadu.godlevel = m_godlevel;
2891 cadu.GroupAccess = 0; 2909 cadu.GroupAccess = 0;
2892 cadu.Position = new sLLVector3(AbsolutePosition); 2910 cadu.Position = AbsolutePosition;
2893 cadu.regionHandle = m_rootRegionHandle; 2911 cadu.regionHandle = m_rootRegionHandle;
2894 float multiplier = 1; 2912 float multiplier = 1;
2895 int innacurateNeighbors = m_scene.GetInaccurateNeighborCount(); 2913 int innacurateNeighbors = m_scene.GetInaccurateNeighborCount();
@@ -2904,15 +2922,12 @@ namespace OpenSim.Region.Framework.Scenes
2904 2922
2905 //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString()); 2923 //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString());
2906 cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier); 2924 cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
2907 cadu.Velocity = new sLLVector3(Velocity); 2925 cadu.Velocity = Velocity;
2908 2926
2909 AgentPosition agentpos = new AgentPosition(); 2927 AgentPosition agentpos = new AgentPosition();
2910 agentpos.CopyFrom(cadu); 2928 agentpos.CopyFrom(cadu);
2911 2929
2912 m_scene.SendOutChildAgentUpdates(agentpos, this); 2930 m_scene.SendOutChildAgentUpdates(agentpos, this);
2913
2914 m_lastChildAgentUpdatePosition = AbsolutePosition;
2915 m_lastChildAgentUpdateCamPosition = CameraPosition;
2916 } 2931 }
2917 } 2932 }
2918 2933
@@ -3168,18 +3183,21 @@ namespace OpenSim.Region.Framework.Scenes
3168 // For now, assign god level 200 to anyone 3183 // For now, assign god level 200 to anyone
3169 // who is granted god powers, but has no god level set. 3184 // who is granted god powers, but has no god level set.
3170 // 3185 //
3171 CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); 3186 UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, agentID);
3172 if (profile.UserProfile.GodLevel > 0) 3187 if (account != null)
3173 m_godlevel = profile.UserProfile.GodLevel; 3188 {
3174 else 3189 if (account.UserLevel > 0)
3175 m_godlevel = 200; 3190 m_godLevel = account.UserLevel;
3191 else
3192 m_godLevel = 200;
3193 }
3176 } 3194 }
3177 else 3195 else
3178 { 3196 {
3179 m_godlevel = 0; 3197 m_godLevel = 0;
3180 } 3198 }
3181 3199
3182 ControllingClient.SendAdminResponse(token, (uint)m_godlevel); 3200 ControllingClient.SendAdminResponse(token, (uint)m_godLevel);
3183 } 3201 }
3184 3202
3185 #region Child Agent Updates 3203 #region Child Agent Updates
@@ -3238,7 +3256,7 @@ namespace OpenSim.Region.Framework.Scenes
3238 public void CopyTo(AgentData cAgent) 3256 public void CopyTo(AgentData cAgent)
3239 { 3257 {
3240 cAgent.AgentID = UUID; 3258 cAgent.AgentID = UUID;
3241 cAgent.RegionHandle = m_rootRegionHandle; 3259 cAgent.RegionID = Scene.RegionInfo.RegionID;
3242 3260
3243 cAgent.Position = AbsolutePosition; 3261 cAgent.Position = AbsolutePosition;
3244 cAgent.Velocity = m_velocity; 3262 cAgent.Velocity = m_velocity;
@@ -3270,7 +3288,7 @@ namespace OpenSim.Region.Framework.Scenes
3270 cAgent.ControlFlags = (uint)m_AgentControlFlags; 3288 cAgent.ControlFlags = (uint)m_AgentControlFlags;
3271 3289
3272 if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID))) 3290 if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
3273 cAgent.GodLevel = (byte)m_godlevel; 3291 cAgent.GodLevel = (byte)m_godLevel;
3274 else 3292 else
3275 cAgent.GodLevel = (byte) 0; 3293 cAgent.GodLevel = (byte) 0;
3276 3294
@@ -3337,11 +3355,12 @@ namespace OpenSim.Region.Framework.Scenes
3337 3355
3338 public void CopyFrom(AgentData cAgent) 3356 public void CopyFrom(AgentData cAgent)
3339 { 3357 {
3340 m_rootRegionHandle = cAgent.RegionHandle; 3358 m_originRegionID = cAgent.RegionID;
3341 3359
3342 m_callbackURI = cAgent.CallbackURI; 3360 m_callbackURI = cAgent.CallbackURI;
3343 3361
3344 m_pos = cAgent.Position; 3362 m_pos = cAgent.Position;
3363
3345 m_velocity = cAgent.Velocity; 3364 m_velocity = cAgent.Velocity;
3346 m_CameraCenter = cAgent.Center; 3365 m_CameraCenter = cAgent.Center;
3347 //m_avHeight = cAgent.Size.Z; 3366 //m_avHeight = cAgent.Size.Z;
@@ -3359,7 +3378,7 @@ namespace OpenSim.Region.Framework.Scenes
3359 m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags; 3378 m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
3360 3379
3361 if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID))) 3380 if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
3362 m_godlevel = cAgent.GodLevel; 3381 m_godLevel = cAgent.GodLevel;
3363 m_setAlwaysRun = cAgent.AlwaysRun; 3382 m_setAlwaysRun = cAgent.AlwaysRun;
3364 3383
3365 uint i = 0; 3384 uint i = 0;
@@ -3717,36 +3736,6 @@ namespace OpenSim.Region.Framework.Scenes
3717 } 3736 }
3718 } 3737 }
3719 3738
3720 public bool CrossAttachmentsIntoNewRegion(ulong regionHandle, bool silent)
3721 {
3722 lock (m_attachments)
3723 {
3724 // Validate
3725 foreach (SceneObjectGroup gobj in m_attachments)
3726 {
3727 if (gobj == null || gobj.IsDeleted)
3728 return false;
3729 }
3730
3731 foreach (SceneObjectGroup gobj in m_attachments)
3732 {
3733 // If the prim group is null then something must have happened to it!
3734 if (gobj != null && gobj.RootPart != null)
3735 {
3736 // Set the parent localID to 0 so it transfers over properly.
3737 gobj.RootPart.SetParentLocalId(0);
3738 gobj.AbsolutePosition = gobj.RootPart.AttachedPos;
3739 gobj.RootPart.IsAttachment = false;
3740 //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
3741 m_log.DebugFormat("[ATTACHMENT]: Sending attachment {0} to region {1}", gobj.UUID, regionHandle);
3742 m_scene.CrossPrimGroupIntoNewRegion(regionHandle, gobj, silent);
3743 }
3744 }
3745 m_attachments.Clear();
3746
3747 return true;
3748 }
3749 }
3750 3739
3751 public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene) 3740 public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene)
3752 { 3741 {
@@ -3982,10 +3971,36 @@ namespace OpenSim.Region.Framework.Scenes
3982 { 3971 {
3983 if (null == m_appearance) 3972 if (null == m_appearance)
3984 { 3973 {
3985 m_log.WarnFormat("[ATTACHMENT] Appearance has not been initialized for agent {0}", UUID); 3974 m_log.WarnFormat("[ATTACHMENT]: Appearance has not been initialized for agent {0}", UUID);
3986 return; 3975 return;
3987 } 3976 }
3988 3977
3978 XmlDocument doc = new XmlDocument();
3979 string stateData = String.Empty;
3980
3981 IAttachmentsService attServ = m_scene.RequestModuleInterface<IAttachmentsService>();
3982 if (attServ != null)
3983 {
3984 m_log.DebugFormat("[ATTACHMENT]: Loading attachment data from attachment service");
3985 stateData = attServ.Get(ControllingClient.AgentId.ToString());
3986 doc.LoadXml(stateData);
3987 }
3988
3989 Dictionary<UUID, string> itemData = new Dictionary<UUID, string>();
3990
3991 XmlNodeList nodes = doc.GetElementsByTagName("Attachment");
3992 if (nodes.Count > 0)
3993 {
3994 foreach (XmlNode n in nodes)
3995 {
3996 XmlElement elem = (XmlElement)n;
3997 string itemID = elem.GetAttribute("ItemID");
3998 string xml = elem.InnerXml;
3999
4000 itemData[new UUID(itemID)] = xml;
4001 }
4002 }
4003
3989 List<int> attPoints = m_appearance.GetAttachedPoints(); 4004 List<int> attPoints = m_appearance.GetAttachedPoints();
3990 foreach (int p in attPoints) 4005 foreach (int p in attPoints)
3991 { 4006 {
@@ -4005,13 +4020,30 @@ namespace OpenSim.Region.Framework.Scenes
4005 4020
4006 try 4021 try
4007 { 4022 {
4008 // Rez from inventory 4023 string xmlData;
4009 UUID asset = m_scene.RezSingleAttachment(ControllingClient, 4024 XmlDocument d = new XmlDocument();
4010 itemID, (uint)p); 4025 UUID asset;
4026 if (itemData.TryGetValue(itemID, out xmlData))
4027 {
4028 d.LoadXml(xmlData);
4029 m_log.InfoFormat("[ATTACHMENT]: Found saved state for item {0}, loading it", itemID);
4030
4031 // Rez from inventory
4032 asset
4033 = m_scene.AttachmentsModule.RezSingleAttachmentFromInventory(ControllingClient, itemID, (uint)p, true, d);
4011 4034
4012 m_log.InfoFormat("[ATTACHMENT]: Rezzed attachment in point {0} from item {1} and asset {2} ({3})", 4035 }
4013 p, itemID, assetID, asset); 4036 else
4037 {
4038 // Rez from inventory (with a null doc to let
4039 // CHANGED_OWNER happen)
4040 asset
4041 = m_scene.AttachmentsModule.RezSingleAttachmentFromInventory(ControllingClient, itemID, (uint)p, true, null);
4042 }
4014 4043
4044 m_log.InfoFormat(
4045 "[ATTACHMENT]: Rezzed attachment in point {0} from item {1} and asset {2} ({3})",
4046 p, itemID, assetID, asset);
4015 } 4047 }
4016 catch (Exception e) 4048 catch (Exception e)
4017 { 4049 {
diff --git a/OpenSim/Region/Framework/Scenes/SceneViewer.cs b/OpenSim/Region/Framework/Scenes/SceneViewer.cs
index 1cff0eb..4ba4fab 100644
--- a/OpenSim/Region/Framework/Scenes/SceneViewer.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneViewer.cs
@@ -31,7 +31,6 @@ using OpenMetaverse;
31using log4net; 31using log4net;
32using OpenSim.Framework; 32using OpenSim.Framework;
33using OpenSim.Framework.Client; 33using OpenSim.Framework.Client;
34using OpenSim.Framework.Communications.Cache;
35using OpenSim.Region.Framework.Interfaces; 34using OpenSim.Region.Framework.Interfaces;
36using OpenSim.Region.Framework.Scenes.Types; 35using OpenSim.Region.Framework.Scenes.Types;
37 36
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
index cf0f345..b6677f0 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
@@ -182,6 +182,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
182 foreach (SceneObjectGroup sceneObject in sceneObjects) 182 foreach (SceneObjectGroup sceneObject in sceneObjects)
183 { 183 {
184 sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0); 184 sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
185 sceneObject.ResumeScripts();
185 } 186 }
186 } 187 }
187 188
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs
index 8230f32..dd9f8f6 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs
@@ -65,6 +65,11 @@ namespace OpenSim.Region.Framework.Scenes.Tests
65 { 65 {
66 throw new NotImplementedException(); 66 throw new NotImplementedException();
67 } 67 }
68
69 public override bool TryGetScenePresence(UUID agentID, out ScenePresence scenePresence)
70 {
71 throw new NotImplementedException();
72 }
68 } 73 }
69 74
70 [Test] 75 [Test]
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs
index 0ed00de..78f2ae3 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs
@@ -32,8 +32,7 @@ using NUnit.Framework.SyntaxHelpers;
32using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications; 34using OpenSim.Framework.Communications;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Region.Communications.Local;
37using OpenSim.Region.Framework.Scenes; 36using OpenSim.Region.Framework.Scenes;
38using OpenSim.Tests.Common; 37using OpenSim.Tests.Common;
39using OpenSim.Tests.Common.Mock; 38using OpenSim.Tests.Common.Mock;
@@ -87,6 +86,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
87 public void TestDeleteSceneObjectAsync() 86 public void TestDeleteSceneObjectAsync()
88 { 87 {
89 TestHelper.InMethod(); 88 TestHelper.InMethod();
89 //log4net.Config.XmlConfigurator.Configure();
90 90
91 UUID agentId = UUID.Parse("00000000-0000-0000-0000-000000000001"); 91 UUID agentId = UUID.Parse("00000000-0000-0000-0000-000000000001");
92 92
@@ -95,16 +95,18 @@ namespace OpenSim.Region.Framework.Scenes.Tests
95 // Turn off the timer on the async sog deleter - we'll crank it by hand for this test. 95 // Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
96 AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter; 96 AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;
97 sogd.Enabled = false; 97 sogd.Enabled = false;
98 98
99 SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene); 99 SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene);
100 100
101 IClientAPI client = SceneSetupHelpers.AddRootAgent(scene, agentId); 101 IClientAPI client = SceneSetupHelpers.AddRootAgent(scene, agentId);
102 scene.DeRezObject(client, part.LocalId, UUID.Zero, DeRezAction.Delete, UUID.Zero); 102 scene.DeRezObject(client, part.LocalId, UUID.Zero, DeRezAction.Delete, UUID.Zero);
103 103
104 SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId); 104 SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId);
105
105 Assert.That(retrievedPart, Is.Not.Null); 106 Assert.That(retrievedPart, Is.Not.Null);
106 107
107 sogd.InventoryDeQueueAndDelete(); 108 sogd.InventoryDeQueueAndDelete();
109
108 SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(part.LocalId); 110 SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(part.LocalId);
109 Assert.That(retrievedPart2, Is.Null); 111 Assert.That(retrievedPart2, Is.Null);
110 } 112 }
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs
index 709cca2..0b7608d 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs
@@ -32,8 +32,7 @@ using NUnit.Framework.SyntaxHelpers;
32using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework; 33using OpenSim.Framework;
34using OpenSim.Framework.Communications; 34using OpenSim.Framework.Communications;
35using OpenSim.Framework.Communications.Cache; 35
36using OpenSim.Region.Communications.Local;
37using OpenSim.Region.Framework.Scenes; 36using OpenSim.Region.Framework.Scenes;
38using OpenSim.Tests.Common; 37using OpenSim.Tests.Common;
39using OpenSim.Tests.Common.Mock; 38using OpenSim.Tests.Common.Mock;
diff --git a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs
index f00dd66..501207e 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs
@@ -40,8 +40,8 @@ using OpenSim.Framework;
40using OpenSim.Framework.Communications; 40using OpenSim.Framework.Communications;
41using OpenSim.Region.Framework.Scenes; 41using OpenSim.Region.Framework.Scenes;
42using OpenSim.Region.Framework.Interfaces; 42using OpenSim.Region.Framework.Interfaces;
43using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion;
44using OpenSim.Region.CoreModules.World.Serialiser; 43using OpenSim.Region.CoreModules.World.Serialiser;
44using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
45using OpenSim.Tests.Common; 45using OpenSim.Tests.Common;
46using OpenSim.Tests.Common.Mock; 46using OpenSim.Tests.Common.Mock;
47using OpenSim.Tests.Common.Setup; 47using OpenSim.Tests.Common.Setup;
@@ -58,7 +58,6 @@ namespace OpenSim.Region.Framework.Scenes.Tests
58 public UUID agent1, agent2, agent3; 58 public UUID agent1, agent2, agent3;
59 public static Random random; 59 public static Random random;
60 public ulong region1,region2,region3; 60 public ulong region1,region2,region3;
61 public TestCommunicationsManager cm;
62 public AgentCircuitData acd1; 61 public AgentCircuitData acd1;
63 public SceneObjectGroup sog1, sog2, sog3; 62 public SceneObjectGroup sog1, sog2, sog3;
64 public TestClient testclient; 63 public TestClient testclient;
@@ -66,12 +65,11 @@ namespace OpenSim.Region.Framework.Scenes.Tests
66 [TestFixtureSetUp] 65 [TestFixtureSetUp]
67 public void Init() 66 public void Init()
68 { 67 {
69 cm = new TestCommunicationsManager(); 68 scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000);
70 scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000, cm); 69 scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000);
71 scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000, cm); 70 scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000);
72 scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000, cm);
73 71
74 ISharedRegionModule interregionComms = new RESTInterregionComms(); 72 ISharedRegionModule interregionComms = new LocalSimulationConnectorModule();
75 interregionComms.Initialise(new IniConfigSource()); 73 interregionComms.Initialise(new IniConfigSource());
76 interregionComms.PostInitialise(); 74 interregionComms.PostInitialise();
77 SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); 75 SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms);
@@ -373,7 +371,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
373 371
374 Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross"); 372 Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross");
375 373
376 Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful"); 374 //Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful");
377 Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted"); 375 Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted");
378 Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects"); 376 Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects");
379 } 377 }
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs
index 5abbb82..8b2d387 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs
@@ -101,13 +101,13 @@ namespace OpenSim.Region.Framework.Scenes.Tests
101 { 101 {
102 throw new NotImplementedException(); 102 throw new NotImplementedException();
103 } 103 }
104 public RegionMeta7WindlightData LoadRegionWindlightSettings(UUID regionUUID) 104 public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
105 { 105 {
106 //This connector doesn't support the windlight module yet 106 //This connector doesn't support the windlight module yet
107 //Return default LL windlight settings 107 //Return default LL windlight settings
108 return new RegionMeta7WindlightData(); 108 return new RegionLightShareData();
109 } 109 }
110 public void StoreRegionWindlightSettings(RegionMeta7WindlightData wl) 110 public void StoreRegionWindlightSettings(RegionLightShareData wl)
111 { 111 {
112 //This connector doesn't support the windlight module yet 112 //This connector doesn't support the windlight module yet
113 } 113 }
@@ -141,7 +141,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
141 RegionInfo regionInfo = new RegionInfo(0,0,null,null); 141 RegionInfo regionInfo = new RegionInfo(0,0,null,null);
142 FakeStorageManager storageManager = new FakeStorageManager(); 142 FakeStorageManager storageManager = new FakeStorageManager();
143 143
144 new Scene(regionInfo, null, null, null, storageManager, null, false, false, false, null, null); 144 new Scene(regionInfo, null, null, storageManager, null, false, false, false, null, null);
145 } 145 }
146 } 146 }
147} 147}
diff --git a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs
index b46eb8e..cafe48a 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs
@@ -34,7 +34,7 @@ using OpenMetaverse;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Communications; 35using OpenSim.Framework.Communications;
36using OpenSim.Region.Framework.Interfaces; 36using OpenSim.Region.Framework.Interfaces;
37using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion; 37using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
38using OpenSim.Tests.Common; 38using OpenSim.Tests.Common;
39using OpenSim.Tests.Common.Mock; 39using OpenSim.Tests.Common.Mock;
40using OpenSim.Tests.Common.Setup; 40using OpenSim.Tests.Common.Setup;
@@ -113,17 +113,16 @@ namespace OpenSim.Region.Framework.Scenes.Tests
113 113
114 UUID sceneAId = UUID.Parse("00000000-0000-0000-0000-000000000100"); 114 UUID sceneAId = UUID.Parse("00000000-0000-0000-0000-000000000100");
115 UUID sceneBId = UUID.Parse("00000000-0000-0000-0000-000000000200"); 115 UUID sceneBId = UUID.Parse("00000000-0000-0000-0000-000000000200");
116 TestCommunicationsManager cm = new TestCommunicationsManager();
117 116
118 // shared module 117 // shared module
119 ISharedRegionModule interregionComms = new RESTInterregionComms(); 118 ISharedRegionModule interregionComms = new LocalSimulationConnectorModule();
120 119
121 120
122 Scene sceneB = SceneSetupHelpers.SetupScene("sceneB", sceneBId, 1010, 1010, cm, "grid"); 121 Scene sceneB = SceneSetupHelpers.SetupScene("sceneB", sceneBId, 1010, 1010, "grid");
123 SceneSetupHelpers.SetupSceneModules(sceneB, new IniConfigSource(), interregionComms); 122 SceneSetupHelpers.SetupSceneModules(sceneB, new IniConfigSource(), interregionComms);
124 sceneB.RegisterRegionWithGrid(); 123 sceneB.RegisterRegionWithGrid();
125 124
126 Scene sceneA = SceneSetupHelpers.SetupScene("sceneA", sceneAId, 1000, 1000, cm, "grid"); 125 Scene sceneA = SceneSetupHelpers.SetupScene("sceneA", sceneAId, 1000, 1000, "grid");
127 SceneSetupHelpers.SetupSceneModules(sceneA, new IniConfigSource(), interregionComms); 126 SceneSetupHelpers.SetupSceneModules(sceneA, new IniConfigSource(), interregionComms);
128 sceneA.RegisterRegionWithGrid(); 127 sceneA.RegisterRegionWithGrid();
129 128
diff --git a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs
index a36c4db..8b80ebe 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs
@@ -58,10 +58,10 @@ namespace OpenSim.Region.Framework.Scenes.Tests
58 TestHelper.InMethod(); 58 TestHelper.InMethod();
59 59
60 UUID corruptAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); 60 UUID corruptAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
61 AssetBase corruptAsset = AssetHelpers.CreateAsset(corruptAssetUuid, "CORRUPT ASSET"); 61 AssetBase corruptAsset = AssetHelpers.CreateAsset(corruptAssetUuid, "CORRUPT ASSET", UUID.Zero);
62 m_assetService.Store(corruptAsset); 62 m_assetService.Store(corruptAsset);
63 63
64 IDictionary<UUID, int> foundAssetUuids = new Dictionary<UUID, int>(); 64 IDictionary<UUID, AssetType> foundAssetUuids = new Dictionary<UUID, AssetType>();
65 m_uuidGatherer.GatherAssetUuids(corruptAssetUuid, AssetType.Object, foundAssetUuids); 65 m_uuidGatherer.GatherAssetUuids(corruptAssetUuid, AssetType.Object, foundAssetUuids);
66 66
67 // We count the uuid as gathered even if the asset itself is corrupt. 67 // We count the uuid as gathered even if the asset itself is corrupt.
@@ -77,7 +77,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
77 TestHelper.InMethod(); 77 TestHelper.InMethod();
78 78
79 UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); 79 UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
80 IDictionary<UUID, int> foundAssetUuids = new Dictionary<UUID, int>(); 80 IDictionary<UUID, AssetType> foundAssetUuids = new Dictionary<UUID, AssetType>();
81 81
82 m_uuidGatherer.GatherAssetUuids(missingAssetUuid, AssetType.Object, foundAssetUuids); 82 m_uuidGatherer.GatherAssetUuids(missingAssetUuid, AssetType.Object, foundAssetUuids);
83 83
diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
index 3edb677..0ec3cc3 100644
--- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
+++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
@@ -84,9 +84,9 @@ namespace OpenSim.Region.Framework.Scenes
84 /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> 84 /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
85 /// <param name="assetType">The type of the asset for the uuid given</param> 85 /// <param name="assetType">The type of the asset for the uuid given</param>
86 /// <param name="assetUuids">The assets gathered</param> 86 /// <param name="assetUuids">The assets gathered</param>
87 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, int> assetUuids) 87 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
88 { 88 {
89 assetUuids[assetUuid] = 1; 89 assetUuids[assetUuid] = assetType;
90 90
91 if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType) 91 if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType)
92 { 92 {
@@ -116,7 +116,7 @@ namespace OpenSim.Region.Framework.Scenes
116 /// 116 ///
117 /// <param name="sceneObject">The scene object for which to gather assets</param> 117 /// <param name="sceneObject">The scene object for which to gather assets</param>
118 /// <param name="assetUuids">The assets gathered</param> 118 /// <param name="assetUuids">The assets gathered</param>
119 public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, int> assetUuids) 119 public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, AssetType> assetUuids)
120 { 120 {
121// m_log.DebugFormat( 121// m_log.DebugFormat(
122// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); 122// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
@@ -129,25 +129,26 @@ namespace OpenSim.Region.Framework.Scenes
129 try 129 try
130 { 130 {
131 Primitive.TextureEntry textureEntry = part.Shape.Textures; 131 Primitive.TextureEntry textureEntry = part.Shape.Textures;
132 132 if (textureEntry != null)
133 // Get the prim's default texture. This will be used for faces which don't have their own texture
134 assetUuids[textureEntry.DefaultTexture.TextureID] = 1;
135
136 // XXX: Not a great way to iterate through face textures, but there's no
137 // other method available to tell how many faces there actually are
138 //int i = 0;
139 foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
140 { 133 {
141 if (texture != null) 134 // Get the prim's default texture. This will be used for faces which don't have their own texture
135 if (textureEntry.DefaultTexture != null)
136 assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture;
137
138 if (textureEntry.FaceTextures != null)
142 { 139 {
143 //m_log.DebugFormat("[ARCHIVER]: Got face {0}", i++); 140 // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
144 assetUuids[texture.TextureID] = 1; 141 foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
142 {
143 if (texture != null)
144 assetUuids[texture.TextureID] = AssetType.Texture;
145 }
145 } 146 }
146 } 147 }
147 148
148 // If the prim is a sculpt then preserve this information too 149 // If the prim is a sculpt then preserve this information too
149 if (part.Shape.SculptTexture != UUID.Zero) 150 if (part.Shape.SculptTexture != UUID.Zero)
150 assetUuids[part.Shape.SculptTexture] = 1; 151 assetUuids[part.Shape.SculptTexture] = AssetType.Texture;
151 152
152 TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone(); 153 TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
153 154
@@ -217,7 +218,7 @@ namespace OpenSim.Region.Framework.Scenes
217 /// </summary> 218 /// </summary>
218 /// <param name="scriptUuid"></param> 219 /// <param name="scriptUuid"></param>
219 /// <param name="assetUuids">Dictionary in which to record the references</param> 220 /// <param name="assetUuids">Dictionary in which to record the references</param>
220 protected void GetScriptAssetUuids(UUID scriptUuid, IDictionary<UUID, int> assetUuids) 221 protected void GetScriptAssetUuids(UUID scriptUuid, IDictionary<UUID, AssetType> assetUuids)
221 { 222 {
222 AssetBase scriptAsset = GetAsset(scriptUuid); 223 AssetBase scriptAsset = GetAsset(scriptUuid);
223 224
@@ -232,7 +233,9 @@ namespace OpenSim.Region.Framework.Scenes
232 { 233 {
233 UUID uuid = new UUID(uuidMatch.Value); 234 UUID uuid = new UUID(uuidMatch.Value);
234 //m_log.DebugFormat("[ARCHIVER]: Recording {0} in script", uuid); 235 //m_log.DebugFormat("[ARCHIVER]: Recording {0} in script", uuid);
235 assetUuids[uuid] = 1; 236
237 // Assume AssetIDs embedded in scripts are textures
238 assetUuids[uuid] = AssetType.Texture;
236 } 239 }
237 } 240 }
238 } 241 }
@@ -242,7 +245,7 @@ namespace OpenSim.Region.Framework.Scenes
242 /// </summary> 245 /// </summary>
243 /// <param name="wearableAssetUuid"></param> 246 /// <param name="wearableAssetUuid"></param>
244 /// <param name="assetUuids">Dictionary in which to record the references</param> 247 /// <param name="assetUuids">Dictionary in which to record the references</param>
245 protected void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, int> assetUuids) 248 protected void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids)
246 { 249 {
247 AssetBase assetBase = GetAsset(wearableAssetUuid); 250 AssetBase assetBase = GetAsset(wearableAssetUuid);
248 251
@@ -257,8 +260,7 @@ namespace OpenSim.Region.Framework.Scenes
257 260
258 foreach (UUID uuid in wearableAsset.Textures.Values) 261 foreach (UUID uuid in wearableAsset.Textures.Values)
259 { 262 {
260 //m_log.DebugFormat("[ARCHIVER]: Got bodypart uuid {0}", uuid); 263 assetUuids[uuid] = AssetType.Texture;
261 assetUuids[uuid] = 1;
262 } 264 }
263 } 265 }
264 } 266 }
@@ -270,7 +272,7 @@ namespace OpenSim.Region.Framework.Scenes
270 /// </summary> 272 /// </summary>
271 /// <param name="sceneObject"></param> 273 /// <param name="sceneObject"></param>
272 /// <param name="assetUuids"></param> 274 /// <param name="assetUuids"></param>
273 protected void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, int> assetUuids) 275 protected void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids)
274 { 276 {
275 AssetBase objectAsset = GetAsset(sceneObjectUuid); 277 AssetBase objectAsset = GetAsset(sceneObjectUuid);
276 278
@@ -284,7 +286,7 @@ namespace OpenSim.Region.Framework.Scenes
284 } 286 }
285 } 287 }
286 288
287 protected void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, int> assetUuids) 289 protected void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids)
288 { 290 {
289 AssetBase assetBase = GetAsset(gestureUuid); 291 AssetBase assetBase = GetAsset(gestureUuid);
290 292
@@ -316,7 +318,7 @@ namespace OpenSim.Region.Framework.Scenes
316 // If it can be parsed as a UUID, it is an asset ID 318 // If it can be parsed as a UUID, it is an asset ID
317 UUID uuid; 319 UUID uuid;
318 if (UUID.TryParse(id, out uuid)) 320 if (UUID.TryParse(id, out uuid))
319 assetUuids[uuid] = 1; 321 assetUuids[uuid] = AssetType.Animation;
320 } 322 }
321 } 323 }
322 } 324 }
diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
index 85e3fb3..69e78b3 100644
--- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
+++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
@@ -627,6 +627,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
627 set { if (!value) Disconnect("IsActive Disconnected?"); } 627 set { if (!value) Disconnect("IsActive Disconnected?"); }
628 } 628 }
629 629
630 public bool IsLoggingOut
631 {
632 get { return false; }
633 set { }
634 }
635
630 public bool SendLogoutPacketWhenClosing 636 public bool SendLogoutPacketWhenClosing
631 { 637 {
632 set { } 638 set { }
@@ -673,7 +679,8 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
673 public event DeRezObject OnDeRezObject; 679 public event DeRezObject OnDeRezObject;
674 public event Action<IClientAPI> OnRegionHandShakeReply; 680 public event Action<IClientAPI> OnRegionHandShakeReply;
675 public event GenericCall2 OnRequestWearables; 681 public event GenericCall2 OnRequestWearables;
676 public event GenericCall2 OnCompleteMovementToRegion; 682 public event GenericCall1 OnCompleteMovementToRegion;
683 public event UpdateAgent OnPreAgentUpdate;
677 public event UpdateAgent OnAgentUpdate; 684 public event UpdateAgent OnAgentUpdate;
678 public event AgentRequestSit OnAgentRequestSit; 685 public event AgentRequestSit OnAgentRequestSit;
679 public event AgentSit OnAgentSit; 686 public event AgentSit OnAgentSit;
@@ -717,6 +724,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
717 public event Action<UUID> OnRemoveAvatar; 724 public event Action<UUID> OnRemoveAvatar;
718 public event ObjectPermissions OnObjectPermissions; 725 public event ObjectPermissions OnObjectPermissions;
719 public event CreateNewInventoryItem OnCreateNewInventoryItem; 726 public event CreateNewInventoryItem OnCreateNewInventoryItem;
727 public event LinkInventoryItem OnLinkInventoryItem;
720 public event CreateInventoryFolder OnCreateNewInventoryFolder; 728 public event CreateInventoryFolder OnCreateNewInventoryFolder;
721 public event UpdateInventoryFolder OnUpdateInventoryFolder; 729 public event UpdateInventoryFolder OnUpdateInventoryFolder;
722 public event MoveInventoryFolder OnMoveInventoryFolder; 730 public event MoveInventoryFolder OnMoveInventoryFolder;
@@ -907,7 +915,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
907 915
908 if (OnCompleteMovementToRegion != null) 916 if (OnCompleteMovementToRegion != null)
909 { 917 {
910 OnCompleteMovementToRegion(); 918 OnCompleteMovementToRegion(this);
911 } 919 }
912 } 920 }
913 921
@@ -1669,5 +1677,13 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
1669 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) 1677 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
1670 { 1678 {
1671 } 1679 }
1680
1681 public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
1682 {
1683 }
1684
1685 public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
1686 {
1687 }
1672 } 1688 }
1673} 1689}
diff --git a/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs b/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs
index b3fa07f..66265d8 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs
@@ -483,12 +483,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat
483 case "%host" : 483 case "%host" :
484 result = result.Replace(vvar, rs.Host); 484 result = result.Replace(vvar, rs.Host);
485 break; 485 break;
486 case "%master1" :
487 result = result.Replace(vvar, rs.MA1);
488 break;
489 case "%master2" :
490 result = result.Replace(vvar, rs.MA2);
491 break;
492 case "%locx" : 486 case "%locx" :
493 result = result.Replace(vvar, rs.LocX); 487 result = result.Replace(vvar, rs.LocX);
494 break; 488 break;
diff --git a/OpenSim/Region/OptionalModules/Avatar/Chat/IRCBridgeModule.cs b/OpenSim/Region/OptionalModules/Avatar/Chat/IRCBridgeModule.cs
index e664b44..d49a489 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Chat/IRCBridgeModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Chat/IRCBridgeModule.cs
@@ -109,7 +109,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat
109 } 109 }
110 else 110 else
111 { 111 {
112 m_log.WarnFormat("[IRC-Bridge] Not enabled. Connect for region {0} ignored", scene.RegionInfo.RegionName); 112 //m_log.DebugFormat("[IRC-Bridge] Not enabled. Connect for region {0} ignored", scene.RegionInfo.RegionName);
113 } 113 }
114 } 114 }
115 115
diff --git a/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs b/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs
index 773507c..53b103e 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs
@@ -57,8 +57,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat
57 internal string Host = String.Empty; 57 internal string Host = String.Empty;
58 internal string LocX = String.Empty; 58 internal string LocX = String.Empty;
59 internal string LocY = String.Empty; 59 internal string LocY = String.Empty;
60 internal string MA1 = String.Empty;
61 internal string MA2 = String.Empty;
62 internal string IDK = String.Empty; 60 internal string IDK = String.Empty;
63 61
64 // System values - used only be the IRC classes themselves 62 // System values - used only be the IRC classes themselves
@@ -85,8 +83,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat
85 Host = scene.RegionInfo.ExternalHostName; 83 Host = scene.RegionInfo.ExternalHostName;
86 LocX = Convert.ToString(scene.RegionInfo.RegionLocX); 84 LocX = Convert.ToString(scene.RegionInfo.RegionLocX);
87 LocY = Convert.ToString(scene.RegionInfo.RegionLocY); 85 LocY = Convert.ToString(scene.RegionInfo.RegionLocY);
88 MA1 = scene.RegionInfo.MasterAvatarFirstName;
89 MA2 = scene.RegionInfo.MasterAvatarLastName;
90 IDK = Convert.ToString(_idk_++); 86 IDK = Convert.ToString(_idk_++);
91 87
92 // OpenChannel conditionally establishes a connection to the 88 // OpenChannel conditionally establishes a connection to the
diff --git a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
index c864993..2fcc477 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
@@ -318,9 +318,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
318 { 318 {
319 Scene scene = client.Scene as Scene; 319 Scene scene = client.Scene as Scene;
320 m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName); 320 m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName);
321 List<ScenePresence> avs = scene.GetAvatars(); 321 AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
322 AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, avs.Count)); 322 UpdateBroker(scene);
323 UpdateBroker(scene, avs);
324 } 323 }
325 } 324 }
326 325
@@ -331,11 +330,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
331 { 330 {
332 Scene scene = agent.Scene; 331 Scene scene = agent.Scene;
333 m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); 332 m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName);
334 List<ScenePresence> avs = scene.GetAvatars();
335 WelcomeAvatar(agent, scene); 333 WelcomeAvatar(agent, scene);
336 AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, 334 AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name,
337 scene.RegionInfo.RegionName, avs.Count)); 335 scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
338 UpdateBroker(scene, avs); 336 UpdateBroker(scene);
339 } 337 }
340 } 338 }
341 339
@@ -346,10 +344,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
346 { 344 {
347 Scene scene = agent.Scene; 345 Scene scene = agent.Scene;
348 m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); 346 m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName);
349 List<ScenePresence> avs = scene.GetAvatars();
350 AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, 347 AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name,
351 scene.RegionInfo.RegionName, avs.Count)); 348 scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
352 UpdateBroker(scene, avs); 349 UpdateBroker(scene);
353 } 350 }
354 } 351 }
355 352
@@ -368,7 +365,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
368 } 365 }
369 } 366 }
370 367
371 protected void UpdateBroker(IScene scene, List<ScenePresence> avatars) 368 protected void UpdateBroker(Scene scene)
372 { 369 {
373 if (String.IsNullOrEmpty(m_brokerURI)) 370 if (String.IsNullOrEmpty(m_brokerURI))
374 return; 371 return;
@@ -377,24 +374,18 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
377 374
378 // create XML sniplet 375 // create XML sniplet
379 StringBuilder list = new StringBuilder(); 376 StringBuilder list = new StringBuilder();
380 if (0 == avatars.Count) 377 list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n",
381 { 378 scene.GetRootAgentCount(), scene.RegionInfo.RegionName,
382 list.Append(String.Format("<avatars count=\"0\" region_name=\"{0}\" region_uuid=\"{1}\" timestamp=\"{2}\" />", 379 scene.RegionInfo.RegionID,
383 scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
384 DateTime.UtcNow.ToString("s"))); 380 DateTime.UtcNow.ToString("s")));
385 } 381 scene.ForEachScenePresence(delegate(ScenePresence sp)
386 else
387 { 382 {
388 list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n", 383 if (!sp.IsChildAgent)
389 avatars.Count, scene.RegionInfo.RegionName,
390 scene.RegionInfo.RegionID,
391 DateTime.UtcNow.ToString("s")));
392 foreach (ScenePresence av in avatars)
393 { 384 {
394 list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", av.Name, av.UUID)); 385 list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID));
386 list.Append("</avatars>");
395 } 387 }
396 list.Append("</avatars>"); 388 });
397 }
398 string payload = list.ToString(); 389 string payload = list.ToString();
399 390
400 // post via REST to broker 391 // post via REST to broker
@@ -529,7 +520,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
529 // protected void AnnounceToAgentsRegion(Scene scene, string msg) 520 // protected void AnnounceToAgentsRegion(Scene scene, string msg)
530 // { 521 // {
531 // ScenePresence agent = null; 522 // ScenePresence agent = null;
532 // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetAvatar(client.AgentId, out agent)) 523 // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent))
533 // AnnounceToAgentsRegion(agent, msg); 524 // AnnounceToAgentsRegion(agent, msg);
534 // else 525 // else
535 // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); 526 // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name);
diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
index 35819a6..242bc3f 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
@@ -41,7 +41,7 @@ using log4net;
41using Nini.Config; 41using Nini.Config;
42using Nwc.XmlRpc; 42using Nwc.XmlRpc;
43using OpenSim.Framework; 43using OpenSim.Framework;
44using OpenSim.Framework.Communications.Cache; 44
45using OpenSim.Framework.Capabilities; 45using OpenSim.Framework.Capabilities;
46using OpenSim.Framework.Servers; 46using OpenSim.Framework.Servers;
47using OpenSim.Framework.Servers.HttpServer; 47using OpenSim.Framework.Servers.HttpServer;
diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs
index cb76200..34d0e24 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs
@@ -39,7 +39,7 @@ using log4net;
39using Nini.Config; 39using Nini.Config;
40using Nwc.XmlRpc; 40using Nwc.XmlRpc;
41using OpenSim.Framework; 41using OpenSim.Framework;
42using OpenSim.Framework.Communications.Cache; 42
43using OpenSim.Framework.Capabilities; 43using OpenSim.Framework.Capabilities;
44using OpenSim.Framework.Servers; 44using OpenSim.Framework.Servers;
45using OpenSim.Framework.Servers.HttpServer; 45using OpenSim.Framework.Servers.HttpServer;
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs
index 00fe5df..185d44d 100644
--- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs
@@ -28,41 +28,30 @@
28using System; 28using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30using System.Reflection; 30using System.Reflection;
31
32
33using log4net; 31using log4net;
34using Mono.Addins; 32using Mono.Addins;
35using Nini.Config; 33using Nini.Config;
36
37using OpenMetaverse; 34using OpenMetaverse;
38using OpenMetaverse.StructuredData; 35using OpenMetaverse.StructuredData;
39
40using OpenSim.Framework; 36using OpenSim.Framework;
41using OpenSim.Region.CoreModules.Framework.EventQueue; 37using OpenSim.Region.CoreModules.Framework.EventQueue;
42using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
43using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
44 40
45
46using Caps = OpenSim.Framework.Capabilities.Caps; 41using Caps = OpenSim.Framework.Capabilities.Caps;
47 42
48namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups 43namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
49{ 44{
50 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] 45 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
51 public class GroupsMessagingModule : ISharedRegionModule 46 public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule
52 { 47 {
53
54 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
55 49
56 private List<Scene> m_sceneList = new List<Scene>(); 50 private List<Scene> m_sceneList = new List<Scene>();
57 51
58 private IMessageTransferModule m_msgTransferModule = null; 52 private IMessageTransferModule m_msgTransferModule = null;
59 53
60 private IGroupsModule m_groupsModule = null; 54 private IGroupsServicesConnector m_groupData = null;
61
62 // TODO: Move this off to the Groups Server
63 public Dictionary<Guid, List<Guid>> m_agentsInGroupSession = new Dictionary<Guid, List<Guid>>();
64 public Dictionary<Guid, List<Guid>> m_agentsDroppedSession = new Dictionary<Guid, List<Guid>>();
65
66 55
67 // Config Options 56 // Config Options
68 private bool m_groupMessagingEnabled = false; 57 private bool m_groupMessagingEnabled = false;
@@ -108,8 +97,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
108 97
109 public void AddRegion(Scene scene) 98 public void AddRegion(Scene scene)
110 { 99 {
111 // NoOp 100 if (!m_groupMessagingEnabled)
101 return;
102
103 scene.RegisterModuleInterface<IGroupsMessagingModule>(this);
112 } 104 }
105
113 public void RegionLoaded(Scene scene) 106 public void RegionLoaded(Scene scene)
114 { 107 {
115 if (!m_groupMessagingEnabled) 108 if (!m_groupMessagingEnabled)
@@ -117,12 +110,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
117 110
118 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 111 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
119 112
120 m_groupsModule = scene.RequestModuleInterface<IGroupsModule>(); 113 m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
121 114
122 // No groups module, no groups messaging 115 // No groups module, no groups messaging
123 if (m_groupsModule == null) 116 if (m_groupData == null)
124 { 117 {
125 m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsModule, GroupsMessagingModule is now disabled."); 118 m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled.");
126 Close(); 119 Close();
127 m_groupMessagingEnabled = false; 120 m_groupMessagingEnabled = false;
128 return; 121 return;
@@ -144,7 +137,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
144 137
145 scene.EventManager.OnNewClient += OnNewClient; 138 scene.EventManager.OnNewClient += OnNewClient;
146 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; 139 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
147 140 scene.EventManager.OnClientLogin += OnClientLogin;
148 } 141 }
149 142
150 public void RemoveRegion(Scene scene) 143 public void RemoveRegion(Scene scene)
@@ -172,7 +165,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
172 165
173 m_sceneList.Clear(); 166 m_sceneList.Clear();
174 167
175 m_groupsModule = null; 168 m_groupData = null;
176 m_msgTransferModule = null; 169 m_msgTransferModule = null;
177 } 170 }
178 171
@@ -197,8 +190,84 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
197 190
198 #endregion 191 #endregion
199 192
193 /// <summary>
194 /// Not really needed, but does confirm that the group exists.
195 /// </summary>
196 public bool StartGroupChatSession(UUID agentID, UUID groupID)
197 {
198 if (m_debugEnabled)
199 m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
200
201 GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null);
202
203 if (groupInfo != null)
204 {
205 return true;
206 }
207 else
208 {
209 return false;
210 }
211 }
212
213 public void SendMessageToGroup(GridInstantMessage im, UUID groupID)
214 {
215 if (m_debugEnabled)
216 m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
217
218
219 foreach (GroupMembersData member in m_groupData.GetGroupMembers(UUID.Zero, groupID))
220 {
221 if (m_groupData.hasAgentDroppedGroupChatSession(member.AgentID, groupID))
222 {
223 // Don't deliver messages to people who have dropped this session
224 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID);
225 continue;
226 }
227
228 // Copy Message
229 GridInstantMessage msg = new GridInstantMessage();
230 msg.imSessionID = groupID.Guid;
231 msg.fromAgentName = im.fromAgentName;
232 msg.message = im.message;
233 msg.dialog = im.dialog;
234 msg.offline = im.offline;
235 msg.ParentEstateID = im.ParentEstateID;
236 msg.Position = im.Position;
237 msg.RegionID = im.RegionID;
238 msg.binaryBucket = im.binaryBucket;
239 msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
240
241 msg.fromAgentID = im.fromAgentID;
242 msg.fromGroup = true;
243
244 msg.toAgentID = member.AgentID.Guid;
245
246 IClientAPI client = GetActiveClient(member.AgentID);
247 if (client == null)
248 {
249 // If they're not local, forward across the grid
250 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID);
251 m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
252 }
253 else
254 {
255 // Deliver locally, directly
256 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
257 ProcessMessageFromGroupSession(msg);
258 }
259 }
260 }
261
200 #region SimGridEventHandlers 262 #region SimGridEventHandlers
201 263
264 void OnClientLogin(IClientAPI client)
265 {
266 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name);
267
268
269 }
270
202 private void OnNewClient(IClientAPI client) 271 private void OnNewClient(IClientAPI client)
203 { 272 {
204 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name); 273 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name);
@@ -236,42 +305,46 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
236 { 305 {
237 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID); 306 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
238 307
308 UUID AgentID = new UUID(msg.fromAgentID);
309 UUID GroupID = new UUID(msg.imSessionID);
310
239 switch (msg.dialog) 311 switch (msg.dialog)
240 { 312 {
241 case (byte)InstantMessageDialog.SessionAdd: 313 case (byte)InstantMessageDialog.SessionAdd:
242 AddAgentToGroupSession(msg.fromAgentID, msg.imSessionID); 314 m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
243 break; 315 break;
244 316
245 case (byte)InstantMessageDialog.SessionDrop: 317 case (byte)InstantMessageDialog.SessionDrop:
246 RemoveAgentFromGroupSession(msg.fromAgentID, msg.imSessionID); 318 m_groupData.AgentDroppedFromGroupChatSession(AgentID, GroupID);
247 break; 319 break;
248 320
249 case (byte)InstantMessageDialog.SessionSend: 321 case (byte)InstantMessageDialog.SessionSend:
250 if (!m_agentsInGroupSession.ContainsKey(msg.toAgentID) 322 if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID)
251 && !m_agentsDroppedSession.ContainsKey(msg.toAgentID)) 323 && !m_groupData.hasAgentBeenInvitedToGroupChatSession(AgentID, GroupID)
324 )
252 { 325 {
253 // Agent not in session and hasn't dropped from session 326 // Agent not in session and hasn't dropped from session
254 // Add them to the session for now, and Invite them 327 // Add them to the session for now, and Invite them
255 AddAgentToGroupSession(msg.toAgentID, msg.imSessionID); 328 m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
256 329
257 UUID toAgentID = new UUID(msg.toAgentID); 330 UUID toAgentID = new UUID(msg.toAgentID);
258 IClientAPI activeClient = GetActiveClient(toAgentID); 331 IClientAPI activeClient = GetActiveClient(toAgentID);
259 if (activeClient != null) 332 if (activeClient != null)
260 { 333 {
261 UUID groupID = new UUID(msg.fromAgentID); 334 GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
262
263 GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
264 if (groupInfo != null) 335 if (groupInfo != null)
265 { 336 {
266 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message"); 337 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message");
267 338
268 // Force? open the group session dialog??? 339 // Force? open the group session dialog???
340 // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
269 IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>(); 341 IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
270 eq.ChatterboxInvitation( 342 eq.ChatterboxInvitation(
271 groupID 343 GroupID
272 , groupInfo.GroupName 344 , groupInfo.GroupName
273 , new UUID(msg.fromAgentID) 345 , new UUID(msg.fromAgentID)
274 , msg.message, new UUID(msg.toAgentID) 346 , msg.message
347 , new UUID(msg.toAgentID)
275 , msg.fromAgentName 348 , msg.fromAgentName
276 , msg.dialog 349 , msg.dialog
277 , msg.timestamp 350 , msg.timestamp
@@ -285,7 +358,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
285 ); 358 );
286 359
287 eq.ChatterBoxSessionAgentListUpdates( 360 eq.ChatterBoxSessionAgentListUpdates(
288 new UUID(groupID) 361 new UUID(GroupID)
289 , new UUID(msg.fromAgentID) 362 , new UUID(msg.fromAgentID)
290 , new UUID(msg.toAgentID) 363 , new UUID(msg.toAgentID)
291 , false //canVoiceChat 364 , false //canVoiceChat
@@ -295,7 +368,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
295 } 368 }
296 } 369 }
297 } 370 }
298 else if (!m_agentsDroppedSession.ContainsKey(msg.toAgentID)) 371 else if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID))
299 { 372 {
300 // User hasn't dropped, so they're in the session, 373 // User hasn't dropped, so they're in the session,
301 // maybe we should deliver it. 374 // maybe we should deliver it.
@@ -321,56 +394,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
321 394
322 #endregion 395 #endregion
323 396
324 #region ClientEvents
325
326 private void RemoveAgentFromGroupSession(Guid agentID, Guid sessionID)
327 {
328 if (m_agentsInGroupSession.ContainsKey(sessionID))
329 {
330 // If in session remove
331 if (m_agentsInGroupSession[sessionID].Contains(agentID))
332 {
333 m_agentsInGroupSession[sessionID].Remove(agentID);
334 }
335
336 // If not in dropped list, add
337 if (!m_agentsDroppedSession[sessionID].Contains(agentID))
338 {
339 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Dropped {1} from session {0}", sessionID, agentID);
340 m_agentsDroppedSession[sessionID].Add(agentID);
341 }
342 }
343 }
344
345 private void AddAgentToGroupSession(Guid agentID, Guid sessionID)
346 {
347 // Add Session Status if it doesn't exist for this session
348 CreateGroupSessionTracking(sessionID);
349
350 // If nessesary, remove from dropped list
351 if (m_agentsDroppedSession[sessionID].Contains(agentID))
352 {
353 m_agentsDroppedSession[sessionID].Remove(agentID);
354 }
355
356 // If nessesary, add to in session list
357 if (!m_agentsInGroupSession[sessionID].Contains(agentID))
358 {
359 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Added {1} to session {0}", sessionID, agentID);
360 m_agentsInGroupSession[sessionID].Add(agentID);
361 }
362 }
363
364 private void CreateGroupSessionTracking(Guid sessionID)
365 {
366 if (!m_agentsInGroupSession.ContainsKey(sessionID))
367 {
368 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Creating session tracking for : {0}", sessionID);
369 m_agentsInGroupSession.Add(sessionID, new List<Guid>());
370 m_agentsDroppedSession.Add(sessionID, new List<Guid>());
371 }
372 }
373 397
398 #region ClientEvents
374 private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) 399 private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
375 { 400 {
376 if (m_debugEnabled) 401 if (m_debugEnabled)
@@ -383,21 +408,23 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
383 // Start group IM session 408 // Start group IM session
384 if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart)) 409 if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
385 { 410 {
386 UUID groupID = new UUID(im.toAgentID); 411 if (m_debugEnabled) m_log.InfoFormat("[GROUPS-MESSAGING]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID);
387 412
388 GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID); 413 UUID GroupID = new UUID(im.imSessionID);
414 UUID AgentID = new UUID(im.fromAgentID);
415
416 GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
417
389 if (groupInfo != null) 418 if (groupInfo != null)
390 { 419 {
391 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Start Group Session for {0}", groupInfo.GroupName); 420 m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
392
393 AddAgentToGroupSession(im.fromAgentID, im.imSessionID);
394 421
395 ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, groupID); 422 ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
396 423
397 IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); 424 IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
398 queue.ChatterBoxSessionAgentListUpdates( 425 queue.ChatterBoxSessionAgentListUpdates(
399 new UUID(groupID) 426 GroupID
400 , new UUID(im.fromAgentID) 427 , AgentID
401 , new UUID(im.toAgentID) 428 , new UUID(im.toAgentID)
402 , false //canVoiceChat 429 , false //canVoiceChat
403 , false //isModerator 430 , false //isModerator
@@ -409,64 +436,21 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
409 // Send a message from locally connected client to a group 436 // Send a message from locally connected client to a group
410 if ((im.dialog == (byte)InstantMessageDialog.SessionSend)) 437 if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
411 { 438 {
412 UUID groupID = new UUID(im.toAgentID); 439 UUID GroupID = new UUID(im.imSessionID);
440 UUID AgentID = new UUID(im.fromAgentID);
441
442 if (m_debugEnabled)
443 m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString());
413 444
414 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", groupID, im.imSessionID.ToString()); 445 //If this agent is sending a message, then they want to be in the session
446 m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
415 447
416 SendMessageToGroup(im, groupID); 448 SendMessageToGroup(im, GroupID);
417 } 449 }
418 } 450 }
419 451
420 #endregion 452 #endregion
421 453
422 private void SendMessageToGroup(GridInstantMessage im, UUID groupID)
423 {
424 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
425
426 foreach (GroupMembersData member in m_groupsModule.GroupMembersRequest(null, groupID))
427 {
428 if (!m_agentsDroppedSession.ContainsKey(im.imSessionID) || m_agentsDroppedSession[im.imSessionID].Contains(member.AgentID.Guid))
429 {
430 // Don't deliver messages to people who have dropped this session
431 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID);
432 continue;
433 }
434
435 // Copy Message
436 GridInstantMessage msg = new GridInstantMessage();
437 msg.imSessionID = im.imSessionID;
438 msg.fromAgentName = im.fromAgentName;
439 msg.message = im.message;
440 msg.dialog = im.dialog;
441 msg.offline = im.offline;
442 msg.ParentEstateID = im.ParentEstateID;
443 msg.Position = im.Position;
444 msg.RegionID = im.RegionID;
445 msg.binaryBucket = im.binaryBucket;
446 msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
447
448 // Updat Pertinate fields to make it a "group message"
449 msg.fromAgentID = groupID.Guid;
450 msg.fromGroup = true;
451
452 msg.toAgentID = member.AgentID.Guid;
453
454 IClientAPI client = GetActiveClient(member.AgentID);
455 if (client == null)
456 {
457 // If they're not local, forward across the grid
458 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID);
459 m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
460 }
461 else
462 {
463 // Deliver locally, directly
464 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
465 ProcessMessageFromGroupSession(msg);
466 }
467 }
468 }
469
470 void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID) 454 void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
471 { 455 {
472 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 456 if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@@ -518,6 +502,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
518 /// </summary> 502 /// </summary>
519 private IClientAPI GetActiveClient(UUID agentID) 503 private IClientAPI GetActiveClient(UUID agentID)
520 { 504 {
505 if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Looking for local client {0}", agentID);
506
521 IClientAPI child = null; 507 IClientAPI child = null;
522 508
523 // Try root avatar first 509 // Try root avatar first
@@ -529,16 +515,26 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
529 ScenePresence user = (ScenePresence)scene.Entities[agentID]; 515 ScenePresence user = (ScenePresence)scene.Entities[agentID];
530 if (!user.IsChildAgent) 516 if (!user.IsChildAgent)
531 { 517 {
518 if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Found root agent for client : {0}", user.ControllingClient.Name);
532 return user.ControllingClient; 519 return user.ControllingClient;
533 } 520 }
534 else 521 else
535 { 522 {
523 if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Found child agent for client : {0}", user.ControllingClient.Name);
536 child = user.ControllingClient; 524 child = user.ControllingClient;
537 } 525 }
538 } 526 }
539 } 527 }
540 528
541 // If we didn't find a root, then just return whichever child we found, or null if none 529 // If we didn't find a root, then just return whichever child we found, or null if none
530 if (child == null)
531 {
532 if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Could not find local client for agent : {0}", agentID);
533 }
534 else
535 {
536 if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Returning child agent for client : {0}", child.Name);
537 }
542 return child; 538 return child;
543 } 539 }
544 540
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
index 8d32e66..56c0d98 100644
--- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
@@ -43,6 +43,8 @@ using OpenSim.Region.CoreModules.Framework.EventQueue;
43using OpenSim.Region.Framework.Interfaces; 43using OpenSim.Region.Framework.Interfaces;
44using OpenSim.Region.Framework.Scenes; 44using OpenSim.Region.Framework.Scenes;
45 45
46using OpenSim.Services.Interfaces;
47
46using Caps = OpenSim.Framework.Capabilities.Caps; 48using Caps = OpenSim.Framework.Capabilities.Caps;
47using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; 49using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
48 50
@@ -87,16 +89,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
87 89
88 private IGroupsServicesConnector m_groupData = null; 90 private IGroupsServicesConnector m_groupData = null;
89 91
90 class GroupRequestIDInfo
91 {
92 public GroupRequestID RequestID = new GroupRequestID();
93 public DateTime LastUsedTMStamp = DateTime.MinValue;
94 }
95 private Dictionary<UUID, GroupRequestIDInfo> m_clientRequestIDInfo = new Dictionary<UUID, GroupRequestIDInfo>();
96 private const int m_clientRequestIDFlushTimeOut = 300000; // Every 5 minutes
97 private Timer m_clientRequestIDFlushTimer;
98
99
100 // Configuration settings 92 // Configuration settings
101 private bool m_groupsEnabled = false; 93 private bool m_groupsEnabled = false;
102 private bool m_groupNoticesEnabled = true; 94 private bool m_groupNoticesEnabled = true;
@@ -133,30 +125,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
133 m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); 125 m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true);
134 m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); 126 m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
135 127
136 m_clientRequestIDFlushTimer = new Timer();
137 m_clientRequestIDFlushTimer.Interval = m_clientRequestIDFlushTimeOut;
138 m_clientRequestIDFlushTimer.Elapsed += FlushClientRequestIDInfoCache;
139 m_clientRequestIDFlushTimer.AutoReset = true;
140 m_clientRequestIDFlushTimer.Start();
141 }
142 }
143
144 void FlushClientRequestIDInfoCache(object sender, ElapsedEventArgs e)
145 {
146 lock (m_clientRequestIDInfo)
147 {
148 TimeSpan cacheTimeout = new TimeSpan(0,0, m_clientRequestIDFlushTimeOut / 1000);
149 UUID[] CurrentKeys = new UUID[m_clientRequestIDInfo.Count];
150 foreach (UUID key in CurrentKeys)
151 {
152 if (m_clientRequestIDInfo.ContainsKey(key))
153 {
154 if (DateTime.Now - m_clientRequestIDInfo[key].LastUsedTMStamp > cacheTimeout)
155 {
156 m_clientRequestIDInfo.Remove(key);
157 }
158 }
159 }
160 } 128 }
161 } 129 }
162 130
@@ -208,7 +176,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
208 176
209 scene.EventManager.OnNewClient += OnNewClient; 177 scene.EventManager.OnNewClient += OnNewClient;
210 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; 178 scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
211
212 // The InstantMessageModule itself doesn't do this, 179 // The InstantMessageModule itself doesn't do this,
213 // so lets see if things explode if we don't do it 180 // so lets see if things explode if we don't do it
214 // scene.EventManager.OnClientClosed += OnClientClosed; 181 // scene.EventManager.OnClientClosed += OnClientClosed;
@@ -234,8 +201,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
234 return; 201 return;
235 202
236 if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); 203 if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module.");
237
238 m_clientRequestIDFlushTimer.Stop();
239 } 204 }
240 205
241 public Type ReplaceableInterface 206 public Type ReplaceableInterface
@@ -272,14 +237,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
272 // Used for Notices and Group Invites/Accept/Reject 237 // Used for Notices and Group Invites/Accept/Reject
273 client.OnInstantMessage += OnInstantMessage; 238 client.OnInstantMessage += OnInstantMessage;
274 239
275 lock (m_clientRequestIDInfo) 240 // Send client thier groups information.
276 {
277 if (m_clientRequestIDInfo.ContainsKey(client.AgentId))
278 {
279 // flush any old RequestID information
280 m_clientRequestIDInfo.Remove(client.AgentId);
281 }
282 }
283 SendAgentGroupDataUpdate(client, client.AgentId); 241 SendAgentGroupDataUpdate(client, client.AgentId);
284 } 242 }
285 243
@@ -287,7 +245,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
287 { 245 {
288 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 246 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
289 247
290 //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetClientGroupRequestID(remoteClient), avatarID).ToArray(); 248 //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray();
291 GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); 249 GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
292 remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); 250 remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
293 } 251 }
@@ -326,15 +284,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
326 } 284 }
327 */ 285 */
328 286
329
330 void OnDirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) 287 void OnDirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart)
331 { 288 {
332 if (((DirFindFlags)queryFlags & DirFindFlags.Groups) == DirFindFlags.Groups) 289 if (((DirFindFlags)queryFlags & DirFindFlags.Groups) == DirFindFlags.Groups)
333 { 290 {
334 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called with queryText({1}) queryFlags({2}) queryStart({3})", System.Reflection.MethodBase.GetCurrentMethod().Name, queryText, (DirFindFlags)queryFlags, queryStart); 291 if (m_debugEnabled)
292 m_log.DebugFormat(
293 "[GROUPS]: {0} called with queryText({1}) queryFlags({2}) queryStart({3})",
294 System.Reflection.MethodBase.GetCurrentMethod().Name, queryText, (DirFindFlags)queryFlags, queryStart);
335 295
336 // TODO: This currently ignores pretty much all the query flags including Mature and sort order 296 // TODO: This currently ignores pretty much all the query flags including Mature and sort order
337 remoteClient.SendDirGroupsReply(queryID, m_groupData.FindGroups(GetClientGroupRequestID(remoteClient), queryText).ToArray()); 297 remoteClient.SendDirGroupsReply(queryID, m_groupData.FindGroups(GetRequestingAgentID(remoteClient), queryText).ToArray());
338 } 298 }
339 299
340 } 300 }
@@ -348,7 +308,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
348 string activeGroupName = string.Empty; 308 string activeGroupName = string.Empty;
349 ulong activeGroupPowers = (ulong)GroupPowers.None; 309 ulong activeGroupPowers = (ulong)GroupPowers.None;
350 310
351 GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetClientGroupRequestID(remoteClient), dataForAgentID); 311 GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient), dataForAgentID);
352 if (membership != null) 312 if (membership != null)
353 { 313 {
354 activeGroupID = membership.GroupID; 314 activeGroupID = membership.GroupID;
@@ -361,13 +321,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
361 SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); 321 SendScenePresenceUpdate(dataForAgentID, activeGroupTitle);
362 } 322 }
363 323
364 private void HandleUUIDGroupNameRequest(UUID GroupID,IClientAPI remoteClient) 324 private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient)
365 { 325 {
366 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 326 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
367 327
368 string GroupName; 328 string GroupName;
369 329
370 GroupRecord group = m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), GroupID, null); 330 GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null);
371 if (group != null) 331 if (group != null)
372 { 332 {
373 GroupName = group.GroupName; 333 GroupName = group.GroupName;
@@ -388,7 +348,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
388 if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) 348 if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
389 { 349 {
390 UUID inviteID = new UUID(im.imSessionID); 350 UUID inviteID = new UUID(im.imSessionID);
391 GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); 351 GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
392 352
393 if (inviteInfo == null) 353 if (inviteInfo == null)
394 { 354 {
@@ -407,7 +367,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
407 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice."); 367 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice.");
408 368
409 // and the sessionid is the role 369 // and the sessionid is the role
410 m_groupData.AddAgentToGroup(GetClientGroupRequestID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID); 370 m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID);
411 371
412 GridInstantMessage msg = new GridInstantMessage(); 372 GridInstantMessage msg = new GridInstantMessage();
413 msg.imSessionID = UUID.Zero.Guid; 373 msg.imSessionID = UUID.Zero.Guid;
@@ -431,14 +391,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
431 // TODO: If the inviter is still online, they need an agent dataupdate 391 // TODO: If the inviter is still online, they need an agent dataupdate
432 // and maybe group membership updates for the invitee 392 // and maybe group membership updates for the invitee
433 393
434 m_groupData.RemoveAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); 394 m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
435 } 395 }
436 396
437 // Reject 397 // Reject
438 if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) 398 if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
439 { 399 {
440 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice."); 400 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice.");
441 m_groupData.RemoveAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); 401 m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
442 } 402 }
443 } 403 }
444 } 404 }
@@ -452,7 +412,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
452 } 412 }
453 413
454 UUID GroupID = new UUID(im.toAgentID); 414 UUID GroupID = new UUID(im.toAgentID);
455 if (m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), GroupID, null) != null) 415 if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null)
456 { 416 {
457 UUID NoticeID = UUID.Random(); 417 UUID NoticeID = UUID.Random();
458 string Subject = im.message.Substring(0, im.message.IndexOf('|')); 418 string Subject = im.message.Substring(0, im.message.IndexOf('|'));
@@ -496,21 +456,21 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
496 } 456 }
497 457
498 458
499 m_groupData.AddGroupNotice(GetClientGroupRequestID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket); 459 m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket);
500 if (OnNewGroupNotice != null) 460 if (OnNewGroupNotice != null)
501 { 461 {
502 OnNewGroupNotice(GroupID, NoticeID); 462 OnNewGroupNotice(GroupID, NoticeID);
503 } 463 }
504 464
505 // Send notice out to everyone that wants notices 465 // Send notice out to everyone that wants notices
506 foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetClientGroupRequestID(remoteClient), GroupID)) 466 foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID))
507 { 467 {
508 if (m_debugEnabled) 468 if (m_debugEnabled)
509 { 469 {
510 UserProfileData targetUserProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(member.AgentID); 470 UserAccount targetUser = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, member.AgentID);
511 if (targetUserProfile != null) 471 if (targetUser != null)
512 { 472 {
513 m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUserProfile.Name, member.AcceptNotices); 473 m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices);
514 } 474 }
515 else 475 else
516 { 476 {
@@ -549,7 +509,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
549 IClientAPI ejectee = GetActiveClient(ejecteeID); 509 IClientAPI ejectee = GetActiveClient(ejecteeID);
550 if (ejectee != null) 510 if (ejectee != null)
551 { 511 {
552 UUID groupID = new UUID(im.fromAgentID); 512 UUID groupID = new UUID(im.imSessionID);
553 ejectee.SendAgentDropGroup(groupID); 513 ejectee.SendAgentDropGroup(groupID);
554 } 514 }
555 } 515 }
@@ -588,20 +548,25 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
588 548
589 public GroupRecord GetGroupRecord(UUID GroupID) 549 public GroupRecord GetGroupRecord(UUID GroupID)
590 { 550 {
591 return m_groupData.GetGroupRecord(null, GroupID, null); 551 return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
592 } 552 }
593 553
554 public GroupRecord GetGroupRecord(string name)
555 {
556 return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name);
557 }
558
594 public void ActivateGroup(IClientAPI remoteClient, UUID groupID) 559 public void ActivateGroup(IClientAPI remoteClient, UUID groupID)
595 { 560 {
596 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 561 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
597 562
598 m_groupData.SetAgentActiveGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID); 563 m_groupData.SetAgentActiveGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
599 564
600 // Changing active group changes title, active powers, all kinds of things 565 // Changing active group changes title, active powers, all kinds of things
601 // anyone who is in any region that can see this client, should probably be 566 // anyone who is in any region that can see this client, should probably be
602 // updated with new group info. At a minimum, they should get ScenePresence 567 // updated with new group info. At a minimum, they should get ScenePresence
603 // updated with new title. 568 // updated with new title.
604 UpdateAllClientsWithGroupInfo(remoteClient.AgentId); 569 UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient));
605 } 570 }
606 571
607 /// <summary> 572 /// <summary>
@@ -611,10 +576,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
611 { 576 {
612 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 577 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
613 578
614 GroupRequestID grID = GetClientGroupRequestID(remoteClient);
615 579
616 List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(grID, remoteClient.AgentId, groupID); 580 List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
617 GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(grID, remoteClient.AgentId, groupID); 581 GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
618 582
619 List<GroupTitlesData> titles = new List<GroupTitlesData>(); 583 List<GroupTitlesData> titles = new List<GroupTitlesData>();
620 foreach (GroupRolesData role in agentRoles) 584 foreach (GroupRolesData role in agentRoles)
@@ -636,8 +600,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
636 public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) 600 public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID)
637 { 601 {
638 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 602 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
603 List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID);
639 604
640 List<GroupMembersData> data = m_groupData.GetGroupMembers(GetClientGroupRequestID(remoteClient), groupID); 605 if (m_debugEnabled)
606 {
607 foreach (GroupMembersData member in data)
608 {
609 m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner);
610 }
611 }
641 612
642 return data; 613 return data;
643 614
@@ -647,21 +618,25 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
647 { 618 {
648 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 619 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
649 620
650 List<GroupRolesData> data = m_groupData.GetGroupRoles(GetClientGroupRequestID(remoteClient), groupID); 621 List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID);
651 622
652 return data; 623 return data;
653
654 } 624 }
655 625
656 public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) 626 public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID)
657 { 627 {
658 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 628 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
659 629
660 List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetClientGroupRequestID(remoteClient), groupID); 630 List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID);
661 631
632 if (m_debugEnabled)
633 {
634 foreach (GroupRoleMembersData member in data)
635 {
636 m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID);
637 }
638 }
662 return data; 639 return data;
663
664
665 } 640 }
666 641
667 public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) 642 public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID)
@@ -670,17 +645,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
670 645
671 GroupProfileData profile = new GroupProfileData(); 646 GroupProfileData profile = new GroupProfileData();
672 647
673 GroupRequestID grID = GetClientGroupRequestID(remoteClient);
674 648
675 GroupRecord groupInfo = m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), groupID, null); 649 GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
676 if (groupInfo != null) 650 if (groupInfo != null)
677 { 651 {
678 profile.AllowPublish = groupInfo.AllowPublish; 652 profile.AllowPublish = groupInfo.AllowPublish;
679 profile.Charter = groupInfo.Charter; 653 profile.Charter = groupInfo.Charter;
680 profile.FounderID = groupInfo.FounderID; 654 profile.FounderID = groupInfo.FounderID;
681 profile.GroupID = groupID; 655 profile.GroupID = groupID;
682 profile.GroupMembershipCount = m_groupData.GetGroupMembers(grID, groupID).Count; 656 profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count;
683 profile.GroupRolesCount = m_groupData.GetGroupRoles(grID, groupID).Count; 657 profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count;
684 profile.InsigniaID = groupInfo.GroupPicture; 658 profile.InsigniaID = groupInfo.GroupPicture;
685 profile.MaturePublish = groupInfo.MaturePublish; 659 profile.MaturePublish = groupInfo.MaturePublish;
686 profile.MembershipFee = groupInfo.MembershipFee; 660 profile.MembershipFee = groupInfo.MembershipFee;
@@ -691,7 +665,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
691 profile.ShowInList = groupInfo.ShowInList; 665 profile.ShowInList = groupInfo.ShowInList;
692 } 666 }
693 667
694 GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(grID, remoteClient.AgentId, groupID); 668 GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
695 if (memberInfo != null) 669 if (memberInfo != null)
696 { 670 {
697 profile.MemberTitle = memberInfo.GroupTitle; 671 profile.MemberTitle = memberInfo.GroupTitle;
@@ -705,46 +679,46 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
705 { 679 {
706 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 680 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
707 681
708 return m_groupData.GetAgentGroupMemberships(null, agentID).ToArray(); 682 return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray();
709 } 683 }
710 684
711 public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) 685 public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID)
712 { 686 {
713 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 687 if (m_debugEnabled)
688 m_log.DebugFormat(
689 "[GROUPS]: {0} called with groupID={1}, agentID={2}",
690 System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID);
714 691
715 return m_groupData.GetAgentGroupMembership(null, agentID, groupID); 692 return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID);
716 } 693 }
717 694
718 public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) 695 public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
719 { 696 {
720 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 697 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
721 698
722 // TODO: Security Check? 699 // Note: Permissions checking for modification rights is handled by the Groups Server/Service
723 700 m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish);
724 m_groupData.UpdateGroup(GetClientGroupRequestID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish);
725 } 701 }
726 702
727 public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) 703 public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile)
728 { 704 {
729 // TODO: Security Check? 705 // Note: Permissions checking for modification rights is handled by the Groups Server/Service
730 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 706 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
731 707
732 m_groupData.SetAgentGroupInfo(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, acceptNotices, listInProfile); 708 m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile);
733 } 709 }
734 710
735 public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) 711 public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
736 { 712 {
737 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 713 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
738 714
739 GroupRequestID grID = GetClientGroupRequestID(remoteClient); 715 if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name) != null)
740
741 if (m_groupData.GetGroupRecord(grID, UUID.Zero, name) != null)
742 { 716 {
743 remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); 717 remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists.");
744 return UUID.Zero; 718 return UUID.Zero;
745 } 719 }
746 // is there is a money module present ? 720 // is there is a money module present ?
747 IMoneyModule money=remoteClient.Scene.RequestModuleInterface<IMoneyModule>(); 721 IMoneyModule money = remoteClient.Scene.RequestModuleInterface<IMoneyModule>();
748 if (money != null) 722 if (money != null)
749 { 723 {
750 // do the transaction, that is if the agent has got sufficient funds 724 // do the transaction, that is if the agent has got sufficient funds
@@ -752,14 +726,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
752 remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got issuficient funds to create a group."); 726 remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got issuficient funds to create a group.");
753 return UUID.Zero; 727 return UUID.Zero;
754 } 728 }
755 money.ApplyGroupCreationCharge(remoteClient.AgentId); 729 money.ApplyGroupCreationCharge(GetRequestingAgentID(remoteClient));
756 } 730 }
757 UUID groupID = m_groupData.CreateGroup(grID, name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, remoteClient.AgentId); 731 UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient));
758 732
759 remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); 733 remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly");
760 734
761 // Update the founder with new group information. 735 // Update the founder with new group information.
762 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 736 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
763 737
764 return groupID; 738 return groupID;
765 } 739 }
@@ -770,7 +744,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
770 744
771 // ToDo: check if agent is a member of group and is allowed to see notices? 745 // ToDo: check if agent is a member of group and is allowed to see notices?
772 746
773 return m_groupData.GetGroupNotices(GetClientGroupRequestID(remoteClient), groupID).ToArray(); 747 return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray();
774 } 748 }
775 749
776 /// <summary> 750 /// <summary>
@@ -780,7 +754,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
780 { 754 {
781 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 755 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
782 756
783 GroupMembershipData membership = m_groupData.GetAgentActiveMembership(null, avatarID); 757 GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID);
784 if (membership != null) 758 if (membership != null)
785 { 759 {
786 return membership.GroupTitle; 760 return membership.GroupTitle;
@@ -795,13 +769,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
795 { 769 {
796 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 770 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
797 771
798 m_groupData.SetAgentActiveGroupRole(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, titleRoleID); 772 m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID);
799 773
800 // TODO: Not sure what all is needed here, but if the active group role change is for the group 774 // TODO: Not sure what all is needed here, but if the active group role change is for the group
801 // the client currently has set active, then we need to do a scene presence update too 775 // the client currently has set active, then we need to do a scene presence update too
802 // if (m_groupData.GetAgentActiveMembership(remoteClient.AgentId).GroupID == GroupID) 776 // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID)
803 777
804 UpdateAllClientsWithGroupInfo(remoteClient.AgentId); 778 UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient));
805 } 779 }
806 780
807 781
@@ -811,16 +785,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
811 785
812 // Security Checks are handled in the Groups Service. 786 // Security Checks are handled in the Groups Service.
813 787
814 GroupRequestID grID = GetClientGroupRequestID(remoteClient);
815
816 switch ((OpenMetaverse.GroupRoleUpdate)updateType) 788 switch ((OpenMetaverse.GroupRoleUpdate)updateType)
817 { 789 {
818 case OpenMetaverse.GroupRoleUpdate.Create: 790 case OpenMetaverse.GroupRoleUpdate.Create:
819 m_groupData.AddGroupRole(grID, groupID, UUID.Random(), name, description, title, powers); 791 m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers);
820 break; 792 break;
821 793
822 case OpenMetaverse.GroupRoleUpdate.Delete: 794 case OpenMetaverse.GroupRoleUpdate.Delete:
823 m_groupData.RemoveGroupRole(grID, groupID, roleID); 795 m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID);
824 break; 796 break;
825 797
826 case OpenMetaverse.GroupRoleUpdate.UpdateAll: 798 case OpenMetaverse.GroupRoleUpdate.UpdateAll:
@@ -831,7 +803,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
831 GroupPowers gp = (GroupPowers)powers; 803 GroupPowers gp = (GroupPowers)powers;
832 m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); 804 m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString());
833 } 805 }
834 m_groupData.UpdateGroupRole(grID, groupID, roleID, name, description, title, powers); 806 m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers);
835 break; 807 break;
836 808
837 case OpenMetaverse.GroupRoleUpdate.NoUpdate: 809 case OpenMetaverse.GroupRoleUpdate.NoUpdate:
@@ -842,7 +814,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
842 } 814 }
843 815
844 // TODO: This update really should send out updates for everyone in the role that just got changed. 816 // TODO: This update really should send out updates for everyone in the role that just got changed.
845 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 817 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
846 } 818 }
847 819
848 public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) 820 public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes)
@@ -850,18 +822,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
850 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 822 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
851 // Todo: Security check 823 // Todo: Security check
852 824
853 GroupRequestID grID = GetClientGroupRequestID(remoteClient);
854
855 switch (changes) 825 switch (changes)
856 { 826 {
857 case 0: 827 case 0:
858 // Add 828 // Add
859 m_groupData.AddAgentToGroupRole(grID, memberID, groupID, roleID); 829 m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
860 830
861 break; 831 break;
862 case 1: 832 case 1:
863 // Remove 833 // Remove
864 m_groupData.RemoveAgentFromGroupRole(grID, memberID, groupID, roleID); 834 m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
865 835
866 break; 836 break;
867 default: 837 default:
@@ -870,25 +840,23 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
870 } 840 }
871 841
872 // TODO: This update really should send out updates for everyone in the role that just got changed. 842 // TODO: This update really should send out updates for everyone in the role that just got changed.
873 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 843 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
874 } 844 }
875 845
876 public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) 846 public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID)
877 { 847 {
878 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 848 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
879 849
880 GroupRequestID grID = GetClientGroupRequestID(remoteClient); 850 GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID);
881
882 GroupNoticeInfo data = m_groupData.GetGroupNotice(grID, groupNoticeID);
883 851
884 if (data != null) 852 if (data != null)
885 { 853 {
886 GroupRecord groupInfo = m_groupData.GetGroupRecord(grID, data.GroupID, null); 854 GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), data.GroupID, null);
887 855
888 GridInstantMessage msg = new GridInstantMessage(); 856 GridInstantMessage msg = new GridInstantMessage();
889 msg.imSessionID = UUID.Zero.Guid; 857 msg.imSessionID = UUID.Zero.Guid;
890 msg.fromAgentID = data.GroupID.Guid; 858 msg.fromAgentID = data.GroupID.Guid;
891 msg.toAgentID = remoteClient.AgentId.Guid; 859 msg.toAgentID = GetRequestingAgentID(remoteClient).Guid;
892 msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); 860 msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
893 msg.fromAgentName = "Group Notice : " + groupInfo == null ? "Unknown" : groupInfo.GroupName; 861 msg.fromAgentName = "Group Notice : " + groupInfo == null ? "Unknown" : groupInfo.GroupName;
894 msg.message = data.noticeData.Subject + "|" + data.Message; 862 msg.message = data.noticeData.Subject + "|" + data.Message;
@@ -900,7 +868,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
900 msg.RegionID = UUID.Zero.Guid; 868 msg.RegionID = UUID.Zero.Guid;
901 msg.binaryBucket = data.BinaryBucket; 869 msg.binaryBucket = data.BinaryBucket;
902 870
903 OutgoingInstantMessage(msg, remoteClient.AgentId); 871 OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
904 } 872 }
905 873
906 } 874 }
@@ -920,7 +888,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
920 msg.Position = Vector3.Zero; 888 msg.Position = Vector3.Zero;
921 msg.RegionID = UUID.Zero.Guid; 889 msg.RegionID = UUID.Zero.Guid;
922 890
923 GroupNoticeInfo info = m_groupData.GetGroupNotice(null, groupNoticeID); 891 GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID);
924 if (info != null) 892 if (info != null)
925 { 893 {
926 msg.fromAgentID = info.GroupID.Guid; 894 msg.fromAgentID = info.GroupID.Guid;
@@ -947,7 +915,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
947 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 915 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
948 916
949 // Send agent information about his groups 917 // Send agent information about his groups
950 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 918 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
951 } 919 }
952 920
953 public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) 921 public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID)
@@ -955,19 +923,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
955 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 923 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
956 924
957 // Should check to see if OpenEnrollment, or if there's an outstanding invitation 925 // Should check to see if OpenEnrollment, or if there's an outstanding invitation
958 m_groupData.AddAgentToGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, UUID.Zero); 926 m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero);
959 927
960 remoteClient.SendJoinGroupReply(groupID, true); 928 remoteClient.SendJoinGroupReply(groupID, true);
961 929
962 // Should this send updates to everyone in the group? 930 // Should this send updates to everyone in the group?
963 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 931 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
964 } 932 }
965 933
966 public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) 934 public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID)
967 { 935 {
968 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 936 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
969 937
970 m_groupData.RemoveAgentFromGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID); 938 m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
971 939
972 remoteClient.SendLeaveGroupReply(groupID, true); 940 remoteClient.SendLeaveGroupReply(groupID, true);
973 941
@@ -975,34 +943,32 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
975 943
976 // SL sends out notifcations to the group messaging session that the person has left 944 // SL sends out notifcations to the group messaging session that the person has left
977 // Should this also update everyone who is in the group? 945 // Should this also update everyone who is in the group?
978 SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); 946 SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
979 } 947 }
980 948
981 public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) 949 public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID)
982 { 950 {
983 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 951 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
984 952
985 GroupRequestID grID = GetClientGroupRequestID(remoteClient);
986 953
987 // Todo: Security check? 954 // Todo: Security check?
988 m_groupData.RemoveAgentFromGroup(grID, ejecteeID, groupID); 955 m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), ejecteeID, groupID);
989 956
990 remoteClient.SendEjectGroupMemberReply(remoteClient.AgentId, groupID, true); 957 remoteClient.SendEjectGroupMemberReply(GetRequestingAgentID(remoteClient), groupID, true);
991 958
992 GroupRecord groupInfo = m_groupData.GetGroupRecord(grID, groupID, null); 959 GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
993 UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(ejecteeID);
994 960
995 if ((groupInfo == null) || (userProfile == null)) 961 UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, ejecteeID);
962 if ((groupInfo == null) || (account == null))
996 { 963 {
997 return; 964 return;
998 } 965 }
999
1000 966
1001 // Send Message to Ejectee 967 // Send Message to Ejectee
1002 GridInstantMessage msg = new GridInstantMessage(); 968 GridInstantMessage msg = new GridInstantMessage();
1003 969
1004 msg.imSessionID = UUID.Zero.Guid; 970 msg.imSessionID = UUID.Zero.Guid;
1005 msg.fromAgentID = remoteClient.AgentId.Guid; 971 msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
1006 // msg.fromAgentID = info.GroupID; 972 // msg.fromAgentID = info.GroupID;
1007 msg.toAgentID = ejecteeID.Guid; 973 msg.toAgentID = ejecteeID.Guid;
1008 //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); 974 //msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
@@ -1028,13 +994,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1028 994
1029 msg = new GridInstantMessage(); 995 msg = new GridInstantMessage();
1030 msg.imSessionID = UUID.Zero.Guid; 996 msg.imSessionID = UUID.Zero.Guid;
1031 msg.fromAgentID = remoteClient.AgentId.Guid; 997 msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
1032 msg.toAgentID = remoteClient.AgentId.Guid; 998 msg.toAgentID = GetRequestingAgentID(remoteClient).Guid;
1033 msg.timestamp = 0; 999 msg.timestamp = 0;
1034 msg.fromAgentName = remoteClient.Name; 1000 msg.fromAgentName = remoteClient.Name;
1035 if (userProfile != null) 1001 if (account != null)
1036 { 1002 {
1037 msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, userProfile.Name); 1003 msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, account.FirstName + " " + account.LastName);
1038 } 1004 }
1039 else 1005 else
1040 { 1006 {
@@ -1047,7 +1013,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1047 msg.Position = Vector3.Zero; 1013 msg.Position = Vector3.Zero;
1048 msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid; 1014 msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid;
1049 msg.binaryBucket = new byte[0]; 1015 msg.binaryBucket = new byte[0];
1050 OutgoingInstantMessage(msg, remoteClient.AgentId); 1016 OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
1051 1017
1052 1018
1053 // SL sends out messages to everyone in the group 1019 // SL sends out messages to everyone in the group
@@ -1061,13 +1027,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1061 1027
1062 // Todo: Security check, probably also want to send some kind of notification 1028 // Todo: Security check, probably also want to send some kind of notification
1063 UUID InviteID = UUID.Random(); 1029 UUID InviteID = UUID.Random();
1064 GroupRequestID grid = GetClientGroupRequestID(remoteClient);
1065 1030
1066 m_groupData.AddAgentToGroupInvite(grid, InviteID, groupID, roleID, invitedAgentID); 1031 m_groupData.AddAgentToGroupInvite(GetRequestingAgentID(remoteClient), InviteID, groupID, roleID, invitedAgentID);
1067 1032
1068 // Check to see if the invite went through, if it did not then it's possible 1033 // Check to see if the invite went through, if it did not then it's possible
1069 // the remoteClient did not validate or did not have permission to invite. 1034 // the remoteClient did not validate or did not have permission to invite.
1070 GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(grid, InviteID); 1035 GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), InviteID);
1071 1036
1072 if (inviteInfo != null) 1037 if (inviteInfo != null)
1073 { 1038 {
@@ -1079,7 +1044,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1079 1044
1080 msg.imSessionID = inviteUUID; 1045 msg.imSessionID = inviteUUID;
1081 1046
1082 // msg.fromAgentID = remoteClient.AgentId.Guid; 1047 // msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
1083 msg.fromAgentID = groupID.Guid; 1048 msg.fromAgentID = groupID.Guid;
1084 msg.toAgentID = invitedAgentID.Guid; 1049 msg.toAgentID = invitedAgentID.Guid;
1085 //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); 1050 //msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
@@ -1132,57 +1097,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1132 return child; 1097 return child;
1133 } 1098 }
1134 1099
1135 private GroupRequestID GetClientGroupRequestID(IClientAPI client)
1136 {
1137 if (client == null)
1138 {
1139 return new GroupRequestID();
1140 }
1141
1142 lock (m_clientRequestIDInfo)
1143 {
1144 if (!m_clientRequestIDInfo.ContainsKey(client.AgentId))
1145 {
1146 GroupRequestIDInfo info = new GroupRequestIDInfo();
1147 info.RequestID.AgentID = client.AgentId;
1148 info.RequestID.SessionID = client.SessionId;
1149
1150 UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(client.AgentId);
1151 if (userProfile == null)
1152 {
1153 // This should be impossible. If I've been passed a reference to a client
1154 // that client should be registered with the UserService. So something
1155 // is horribly wrong somewhere.
1156
1157 m_log.WarnFormat("[GROUPS]: Could not find a user profile for {0} / {1}", client.Name, client.AgentId);
1158
1159 // Default to local user service and hope for the best?
1160 info.RequestID.UserServiceURL = m_sceneList[0].CommsManager.NetworkServersInfo.UserURL;
1161
1162 }
1163 else if (userProfile is ForeignUserProfileData)
1164 {
1165 // They aren't from around here
1166 ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
1167 info.RequestID.UserServiceURL = fupd.UserServerURI;
1168 }
1169 else
1170 {
1171 // They're a local user, use this:
1172 info.RequestID.UserServiceURL = m_sceneList[0].CommsManager.NetworkServersInfo.UserURL;
1173 }
1174
1175 m_clientRequestIDInfo.Add(client.AgentId, info);
1176 }
1177
1178 m_clientRequestIDInfo[client.AgentId].LastUsedTMStamp = DateTime.Now;
1179
1180 return m_clientRequestIDInfo[client.AgentId].RequestID;
1181 }
1182// Unreachable code!
1183// return new GroupRequestID();
1184 }
1185
1186 /// <summary> 1100 /// <summary>
1187 /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. 1101 /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'.
1188 /// </summary> 1102 /// </summary>
@@ -1201,7 +1115,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1201 1115
1202 foreach (GroupMembershipData membership in data) 1116 foreach (GroupMembershipData membership in data)
1203 { 1117 {
1204 if (remoteClient.AgentId != dataForAgentID) 1118 if (GetRequestingAgentID(remoteClient) != dataForAgentID)
1205 { 1119 {
1206 if (!membership.ListInProfile) 1120 if (!membership.ListInProfile)
1207 { 1121 {
@@ -1231,11 +1145,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1231 llDataStruct.Add("GroupData", GroupData); 1145 llDataStruct.Add("GroupData", GroupData);
1232 llDataStruct.Add("NewGroupData", NewGroupData); 1146 llDataStruct.Add("NewGroupData", NewGroupData);
1233 1147
1148 if (m_debugEnabled)
1149 {
1150 m_log.InfoFormat("[GROUPS]: {0}", OSDParser.SerializeJsonString(llDataStruct));
1151 }
1152
1234 IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); 1153 IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
1235 1154
1236 if (queue != null) 1155 if (queue != null)
1237 { 1156 {
1238 queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), remoteClient.AgentId); 1157 queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient));
1239 } 1158 }
1240 1159
1241 } 1160 }
@@ -1308,7 +1227,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1308 /// <returns></returns> 1227 /// <returns></returns>
1309 private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) 1228 private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID)
1310 { 1229 {
1311 List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(GetClientGroupRequestID(requestingClient), dataForAgentID); 1230 List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID);
1312 GroupMembershipData[] membershipArray; 1231 GroupMembershipData[] membershipArray;
1313 1232
1314 if (requestingClient.AgentId != dataForAgentID) 1233 if (requestingClient.AgentId != dataForAgentID)
@@ -1330,7 +1249,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1330 m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); 1249 m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId);
1331 foreach (GroupMembershipData membership in membershipArray) 1250 foreach (GroupMembershipData membership in membershipArray)
1332 { 1251 {
1333 m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2}", dataForAgentID, membership.GroupName, membership.GroupTitle); 1252 m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers);
1334 } 1253 }
1335 } 1254 }
1336 1255
@@ -1342,12 +1261,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1342 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); 1261 if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
1343 1262
1344 // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff 1263 // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
1345 UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(dataForAgentID); 1264 UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, dataForAgentID);
1346 string firstname, lastname; 1265 string firstname, lastname;
1347 if (userProfile != null) 1266 if (account != null)
1348 { 1267 {
1349 firstname = userProfile.FirstName; 1268 firstname = account.FirstName;
1350 lastname = userProfile.SurName; 1269 lastname = account.LastName;
1351 } 1270 }
1352 else 1271 else
1353 { 1272 {
@@ -1389,6 +1308,23 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
1389 } 1308 }
1390 1309
1391 #endregion 1310 #endregion
1311
1312 private UUID GetRequestingAgentID(IClientAPI client)
1313 {
1314 UUID requestingAgentID = UUID.Zero;
1315 if (client != null)
1316 {
1317 requestingAgentID = client.AgentId;
1318 }
1319 return requestingAgentID;
1320 }
1392 } 1321 }
1393 1322
1323 public class GroupNoticeInfo
1324 {
1325 public GroupNoticeData noticeData = new GroupNoticeData();
1326 public UUID GroupID = UUID.Zero;
1327 public string Message = string.Empty;
1328 public byte[] BinaryBucket = new byte[0];
1329 }
1394} 1330}
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs
index 9e0fa2d..a046e09 100644
--- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs
@@ -36,42 +36,47 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
36{ 36{
37 interface IGroupsServicesConnector 37 interface IGroupsServicesConnector
38 { 38 {
39 UUID CreateGroup(GroupRequestID requestID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID); 39 UUID CreateGroup(UUID RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID);
40 void UpdateGroup(GroupRequestID requestID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish); 40 void UpdateGroup(UUID RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish);
41 GroupRecord GetGroupRecord(GroupRequestID requestID, UUID GroupID, string GroupName); 41 GroupRecord GetGroupRecord(UUID RequestingAgentID, UUID GroupID, string GroupName);
42 List<DirGroupsReplyData> FindGroups(GroupRequestID requestID, string search); 42 List<DirGroupsReplyData> FindGroups(UUID RequestingAgentID, string search);
43 List<GroupMembersData> GetGroupMembers(GroupRequestID requestID, UUID GroupID); 43 List<GroupMembersData> GetGroupMembers(UUID RequestingAgentID, UUID GroupID);
44 44
45 void AddGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers); 45 void AddGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers);
46 void UpdateGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers); 46 void UpdateGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers);
47 void RemoveGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID); 47 void RemoveGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID);
48 List<GroupRolesData> GetGroupRoles(GroupRequestID requestID, UUID GroupID); 48 List<GroupRolesData> GetGroupRoles(UUID RequestingAgentID, UUID GroupID);
49 List<GroupRoleMembersData> GetGroupRoleMembers(GroupRequestID requestID, UUID GroupID); 49 List<GroupRoleMembersData> GetGroupRoleMembers(UUID RequestingAgentID, UUID GroupID);
50 50
51 void AddAgentToGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID); 51 void AddAgentToGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
52 void RemoveAgentFromGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID); 52 void RemoveAgentFromGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
53 53
54 void AddAgentToGroupInvite(GroupRequestID requestID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID); 54 void AddAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID);
55 GroupInviteInfo GetAgentToGroupInvite(GroupRequestID requestID, UUID inviteID); 55 GroupInviteInfo GetAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID);
56 void RemoveAgentToGroupInvite(GroupRequestID requestID, UUID inviteID); 56 void RemoveAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID);
57 57
58 void AddAgentToGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
59 void RemoveAgentFromGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
60 List<GroupRolesData> GetAgentGroupRoles(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
58 61
59 void AddAgentToGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID); 62 void SetAgentActiveGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
60 void RemoveAgentFromGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID); 63 GroupMembershipData GetAgentActiveMembership(UUID RequestingAgentID, UUID AgentID);
61 List<GroupRolesData> GetAgentGroupRoles(GroupRequestID requestID, UUID AgentID, UUID GroupID);
62 64
63 void SetAgentActiveGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID); 65 void SetAgentActiveGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
64 GroupMembershipData GetAgentActiveMembership(GroupRequestID requestID, UUID AgentID); 66 void SetAgentGroupInfo(UUID RequestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile);
65 67
66 void SetAgentActiveGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID); 68 GroupMembershipData GetAgentGroupMembership(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
67 void SetAgentGroupInfo(GroupRequestID requestID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile); 69 List<GroupMembershipData> GetAgentGroupMemberships(UUID RequestingAgentID, UUID AgentID);
68 70
69 GroupMembershipData GetAgentGroupMembership(GroupRequestID requestID, UUID AgentID, UUID GroupID); 71 void AddGroupNotice(UUID RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket);
70 List<GroupMembershipData> GetAgentGroupMemberships(GroupRequestID requestID, UUID AgentID); 72 GroupNoticeInfo GetGroupNotice(UUID RequestingAgentID, UUID noticeID);
73 List<GroupNoticeData> GetGroupNotices(UUID RequestingAgentID, UUID GroupID);
71 74
72 void AddGroupNotice(GroupRequestID requestID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket); 75 void ResetAgentGroupChatSessions(UUID agentID);
73 GroupNoticeInfo GetGroupNotice(GroupRequestID requestID, UUID noticeID); 76 bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID);
74 List<GroupNoticeData> GetGroupNotices(GroupRequestID requestID, UUID GroupID); 77 bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID);
78 void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID);
79 void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID);
75 } 80 }
76 81
77 public class GroupInviteInfo 82 public class GroupInviteInfo
@@ -81,11 +86,4 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
81 public UUID AgentID = UUID.Zero; 86 public UUID AgentID = UUID.Zero;
82 public UUID InviteID = UUID.Zero; 87 public UUID InviteID = UUID.Zero;
83 } 88 }
84
85 public class GroupRequestID
86 {
87 public UUID AgentID = UUID.Zero;
88 public string UserServiceURL = string.Empty;
89 public UUID SessionID = UUID.Zero;
90 }
91} 89}
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs
new file mode 100644
index 0000000..9363205
--- /dev/null
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs
@@ -0,0 +1,1390 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Collections.Specialized;
32using System.Reflection;
33
34using Nwc.XmlRpc;
35
36using log4net;
37using Mono.Addins;
38using Nini.Config;
39
40using OpenMetaverse;
41using OpenMetaverse.StructuredData;
42
43using OpenSim.Framework;
44using OpenSim.Framework.Communications;
45using OpenSim.Region.Framework.Interfaces;
46using OpenSim.Services.Interfaces;
47
48/***************************************************************************
49 * Simian Data Map
50 * ===============
51 *
52 * OwnerID -> Type -> Key
53 * -----------------------
54 *
55 * UserID -> Group -> ActiveGroup
56 * + GroupID
57 *
58 * UserID -> GroupSessionDropped -> GroupID
59 * UserID -> GroupSessionInvited -> GroupID
60 *
61 * UserID -> GroupMember -> GroupID
62 * + SelectedRoleID [UUID]
63 * + AcceptNotices [bool]
64 * + ListInProfile [bool]
65 * + Contribution [int]
66 *
67 * UserID -> GroupRole[GroupID] -> RoleID
68 *
69 *
70 * GroupID -> Group -> GroupName
71 * + Charter
72 * + ShowInList
73 * + InsigniaID
74 * + MembershipFee
75 * + OpenEnrollment
76 * + AllowPublish
77 * + MaturePublish
78 * + FounderID
79 * + EveryonePowers
80 * + OwnerRoleID
81 * + OwnersPowers
82 *
83 * GroupID -> GroupRole -> RoleID
84 * + Name
85 * + Description
86 * + Title
87 * + Powers
88 *
89 * GroupID -> GroupMemberInvite -> InviteID
90 * + AgentID
91 * + RoleID
92 *
93 * GroupID -> GroupNotice -> NoticeID
94 * + TimeStamp [uint]
95 * + FromName [string]
96 * + Subject [string]
97 * + Message [string]
98 * + BinaryBucket [byte[]]
99 *
100 * */
101
102namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
103{
104 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
105 public class SimianGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
106 {
107 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
108
109 public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome |
110 GroupPowers.Accountable |
111 GroupPowers.JoinChat |
112 GroupPowers.AllowVoiceChat |
113 GroupPowers.ReceiveNotices |
114 GroupPowers.StartProposal |
115 GroupPowers.VoteOnProposal;
116
117 // Would this be cleaner as (GroupPowers)ulong.MaxValue;
118 public const GroupPowers m_DefaultOwnerPowers = GroupPowers.Accountable
119 | GroupPowers.AllowEditLand
120 | GroupPowers.AllowFly
121 | GroupPowers.AllowLandmark
122 | GroupPowers.AllowRez
123 | GroupPowers.AllowSetHome
124 | GroupPowers.AllowVoiceChat
125 | GroupPowers.AssignMember
126 | GroupPowers.AssignMemberLimited
127 | GroupPowers.ChangeActions
128 | GroupPowers.ChangeIdentity
129 | GroupPowers.ChangeMedia
130 | GroupPowers.ChangeOptions
131 | GroupPowers.CreateRole
132 | GroupPowers.DeedObject
133 | GroupPowers.DeleteRole
134 | GroupPowers.Eject
135 | GroupPowers.FindPlaces
136 | GroupPowers.Invite
137 | GroupPowers.JoinChat
138 | GroupPowers.LandChangeIdentity
139 | GroupPowers.LandDeed
140 | GroupPowers.LandDivideJoin
141 | GroupPowers.LandEdit
142 | GroupPowers.LandEjectAndFreeze
143 | GroupPowers.LandGardening
144 | GroupPowers.LandManageAllowed
145 | GroupPowers.LandManageBanned
146 | GroupPowers.LandManagePasses
147 | GroupPowers.LandOptions
148 | GroupPowers.LandRelease
149 | GroupPowers.LandSetSale
150 | GroupPowers.ModerateChat
151 | GroupPowers.ObjectManipulate
152 | GroupPowers.ObjectSetForSale
153 | GroupPowers.ReceiveNotices
154 | GroupPowers.RemoveMember
155 | GroupPowers.ReturnGroupOwned
156 | GroupPowers.ReturnGroupSet
157 | GroupPowers.ReturnNonGroup
158 | GroupPowers.RoleProperties
159 | GroupPowers.SendNotices
160 | GroupPowers.SetLandingPoint
161 | GroupPowers.StartProposal
162 | GroupPowers.VoteOnProposal;
163
164 private bool m_connectorEnabled = false;
165
166 private string m_groupsServerURI = string.Empty;
167
168 private bool m_debugEnabled = false;
169
170 private ExpiringCache<string, OSDMap> m_memoryCache;
171 private int m_cacheTimeout = 30;
172
173 // private IUserAccountService m_accountService = null;
174
175
176 #region IRegionModuleBase Members
177
178 public string Name
179 {
180 get { return "SimianGroupsServicesConnector"; }
181 }
182
183 // this module is not intended to be replaced, but there should only be 1 of them.
184 public Type ReplaceableInterface
185 {
186 get { return null; }
187 }
188
189 public void Initialise(IConfigSource config)
190 {
191 IConfig groupsConfig = config.Configs["Groups"];
192
193 if (groupsConfig == null)
194 {
195 // Do not run this module by default.
196 return;
197 }
198 else
199 {
200 // if groups aren't enabled, we're not needed.
201 // if we're not specified as the connector to use, then we're not wanted
202 if ((groupsConfig.GetBoolean("Enabled", false) == false)
203 || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name))
204 {
205 m_connectorEnabled = false;
206 return;
207 }
208
209 m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
210
211 m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
212 if ((m_groupsServerURI == null) ||
213 (m_groupsServerURI == string.Empty))
214 {
215 m_log.ErrorFormat("Please specify a valid Simian Server for GroupsServerURI in OpenSim.ini, [Groups]");
216 m_connectorEnabled = false;
217 return;
218 }
219
220
221 m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
222 if (m_cacheTimeout == 0)
223 {
224 m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Disabled.");
225 }
226 else
227 {
228 m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Timeout set to {0}.", m_cacheTimeout);
229 }
230
231
232
233 m_memoryCache = new ExpiringCache<string,OSDMap>();
234
235
236 // If we got all the config options we need, lets start'er'up
237 m_connectorEnabled = true;
238
239 m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
240
241 }
242 }
243
244 public void Close()
245 {
246 m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Closing {0}", this.Name);
247 }
248
249 public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
250 {
251 if (m_connectorEnabled)
252 {
253 scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
254 }
255 }
256
257 public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
258 {
259 if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
260 {
261 scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
262 }
263 }
264
265 public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
266 {
267 // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
268 // scene.EventManager.OnNewClient += OnNewClient;
269 }
270
271 #endregion
272
273 #region ISharedRegionModule Members
274
275 public void PostInitialise()
276 {
277 // NoOp
278 }
279
280 #endregion
281
282
283
284
285 #region IGroupsServicesConnector Members
286
287 /// <summary>
288 /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
289 /// </summary>
290 public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
291 int membershipFee, bool openEnrollment, bool allowPublish,
292 bool maturePublish, UUID founderID)
293 {
294 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
295
296 UUID GroupID = UUID.Random();
297 UUID OwnerRoleID = UUID.Random();
298
299 OSDMap GroupInfoMap = new OSDMap();
300 GroupInfoMap["Charter"] = OSD.FromString(charter);
301 GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
302 GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
303 GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
304 GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
305 GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
306 GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
307 GroupInfoMap["FounderID"] = OSD.FromUUID(founderID);
308 GroupInfoMap["EveryonePowers"] = OSD.FromULong((ulong)m_DefaultEveryonePowers);
309 GroupInfoMap["OwnerRoleID"] = OSD.FromUUID(OwnerRoleID);
310 GroupInfoMap["OwnersPowers"] = OSD.FromULong((ulong)m_DefaultOwnerPowers);
311
312 if(SimianAddGeneric(GroupID, "Group", name, GroupInfoMap))
313 {
314 AddGroupRole(requestingAgentID, GroupID, UUID.Zero, "Everyone", "Members of " + name, "Member of " + name, (ulong)m_DefaultEveryonePowers);
315 AddGroupRole(requestingAgentID, GroupID, OwnerRoleID, "Owners", "Owners of " + name, "Owner of " + name, (ulong)m_DefaultOwnerPowers);
316
317 AddAgentToGroup(requestingAgentID, requestingAgentID, GroupID, OwnerRoleID);
318
319 return GroupID;
320 }
321 else
322 {
323 return UUID.Zero;
324 }
325 }
326
327
328 public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
329 UUID insigniaID, int membershipFee, bool openEnrollment,
330 bool allowPublish, bool maturePublish)
331 {
332 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
333 // TODO: Check to make sure requestingAgentID has permission to update group
334
335 string GroupName;
336 OSDMap GroupInfoMap;
337 if( SimianGetFirstGenericEntry(groupID, "GroupInfo", out GroupName, out GroupInfoMap) )
338 {
339 GroupInfoMap["Charter"] = OSD.FromString(charter);
340 GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
341 GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
342 GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
343 GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
344 GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
345 GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
346
347 SimianAddGeneric(groupID, "Group", GroupName, GroupInfoMap);
348 }
349
350 }
351
352
353 public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
354 string title, ulong powers)
355 {
356 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
357
358 OSDMap GroupRoleInfo = new OSDMap();
359 GroupRoleInfo["Name"] = OSD.FromString(name);
360 GroupRoleInfo["Description"] = OSD.FromString(description);
361 GroupRoleInfo["Title"] = OSD.FromString(title);
362 GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
363
364 // TODO: Add security, make sure that requestingAgentID has permision to add roles
365 SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
366 }
367
368 public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
369 {
370 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
371
372 // TODO: Add security
373
374 // Can't delete the Everyone Role
375 if (roleID != UUID.Zero)
376 {
377 // Remove all GroupRole Members from Role
378 Dictionary<UUID, OSDMap> GroupRoleMembers;
379 string GroupRoleMemberType = "GroupRole" + groupID.ToString();
380 if (SimianGetGenericEntries(GroupRoleMemberType, roleID.ToString(), out GroupRoleMembers))
381 {
382 foreach(UUID UserID in GroupRoleMembers.Keys)
383 {
384 EnsureRoleNotSelectedByMember(groupID, roleID, UserID);
385
386 SimianRemoveGenericEntry(UserID, GroupRoleMemberType, roleID.ToString());
387 }
388 }
389
390 // Remove role
391 SimianRemoveGenericEntry(groupID, "GroupRole", roleID.ToString());
392 }
393 }
394
395
396 public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
397 string title, ulong powers)
398 {
399 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
400
401 // TODO: Security, check that requestingAgentID is allowed to update group roles
402
403 OSDMap GroupRoleInfo;
404 if (SimianGetGenericEntry(groupID, "GroupRole", roleID.ToString(), out GroupRoleInfo))
405 {
406 if (name != null)
407 {
408 GroupRoleInfo["Name"] = OSD.FromString(name);
409 }
410 if (description != null)
411 {
412 GroupRoleInfo["Description"] = OSD.FromString(description);
413 }
414 if (title != null)
415 {
416 GroupRoleInfo["Title"] = OSD.FromString(title);
417 }
418 GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
419
420 }
421
422
423 SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
424 }
425
426 public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName)
427 {
428 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
429
430 OSDMap GroupInfoMap = null;
431 if (groupID != UUID.Zero)
432 {
433 if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out GroupInfoMap))
434 {
435 return null;
436 }
437 }
438 else if ((groupName != null) && (groupName != string.Empty))
439 {
440 if (!SimianGetFirstGenericEntry("Group", groupName, out groupID, out GroupInfoMap))
441 {
442 return null;
443 }
444 }
445
446 GroupRecord GroupInfo = new GroupRecord();
447
448 GroupInfo.GroupID = groupID;
449 GroupInfo.GroupName = groupName;
450 GroupInfo.Charter = GroupInfoMap["Charter"].AsString();
451 GroupInfo.ShowInList = GroupInfoMap["ShowInList"].AsBoolean();
452 GroupInfo.GroupPicture = GroupInfoMap["InsigniaID"].AsUUID();
453 GroupInfo.MembershipFee = GroupInfoMap["MembershipFee"].AsInteger();
454 GroupInfo.OpenEnrollment = GroupInfoMap["OpenEnrollment"].AsBoolean();
455 GroupInfo.AllowPublish = GroupInfoMap["AllowPublish"].AsBoolean();
456 GroupInfo.MaturePublish = GroupInfoMap["MaturePublish"].AsBoolean();
457 GroupInfo.FounderID = GroupInfoMap["FounderID"].AsUUID();
458 GroupInfo.OwnerRoleID = GroupInfoMap["OwnerRoleID"].AsUUID();
459
460 return GroupInfo;
461
462 }
463
464 public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID groupID, UUID memberID)
465 {
466 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
467
468 OSDMap groupProfile;
469 string groupName;
470 if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out groupProfile))
471 {
472 // GroupProfileData is not nullable
473 return new GroupProfileData();
474 }
475
476 GroupProfileData MemberGroupProfile = new GroupProfileData();
477 MemberGroupProfile.GroupID = groupID;
478 MemberGroupProfile.Name = groupName;
479
480 if (groupProfile["Charter"] != null)
481 {
482 MemberGroupProfile.Charter = groupProfile["Charter"].AsString();
483 }
484
485 MemberGroupProfile.ShowInList = groupProfile["ShowInList"].AsString() == "1";
486 MemberGroupProfile.InsigniaID = groupProfile["InsigniaID"].AsUUID();
487 MemberGroupProfile.MembershipFee = groupProfile["MembershipFee"].AsInteger();
488 MemberGroupProfile.OpenEnrollment = groupProfile["OpenEnrollment"].AsBoolean();
489 MemberGroupProfile.AllowPublish = groupProfile["AllowPublish"].AsBoolean();
490 MemberGroupProfile.MaturePublish = groupProfile["MaturePublish"].AsBoolean();
491 MemberGroupProfile.FounderID = groupProfile["FounderID"].AsUUID();;
492 MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID();
493
494 Dictionary<UUID, OSDMap> Members;
495 if (SimianGetGenericEntries("GroupMember",groupID.ToString(), out Members))
496 {
497 MemberGroupProfile.GroupMembershipCount = Members.Count;
498 }
499
500 Dictionary<string, OSDMap> Roles;
501 if (SimianGetGenericEntries(groupID, "GroupRole", out Roles))
502 {
503 MemberGroupProfile.GroupRolesCount = Roles.Count;
504 }
505
506 // TODO: Get Group Money balance from somewhere
507 // group.Money = 0;
508
509 GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, memberID, groupID);
510
511 MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
512 MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
513
514 return MemberGroupProfile;
515 }
516
517 public void SetAgentActiveGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
518 {
519 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
520
521 OSDMap ActiveGroup = new OSDMap();
522 ActiveGroup.Add("GroupID", OSD.FromUUID(groupID));
523 SimianAddGeneric(agentID, "Group", "ActiveGroup", ActiveGroup);
524 }
525
526 public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
527 {
528 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
529
530 OSDMap GroupMemberInfo;
531 if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
532 {
533 GroupMemberInfo = new OSDMap();
534 }
535
536 GroupMemberInfo["SelectedRoleID"] = OSD.FromUUID(roleID);
537 SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
538 }
539
540 public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile)
541 {
542 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
543
544 OSDMap GroupMemberInfo;
545 if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
546 {
547 GroupMemberInfo = new OSDMap();
548 }
549
550 GroupMemberInfo["AcceptNotices"] = OSD.FromBoolean(acceptNotices);
551 GroupMemberInfo["ListInProfile"] = OSD.FromBoolean(listInProfile);
552 GroupMemberInfo["Contribution"] = OSD.FromInteger(0);
553 GroupMemberInfo["SelectedRole"] = OSD.FromUUID(UUID.Zero);
554 SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
555 }
556
557 public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
558 {
559 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
560
561 OSDMap Invite = new OSDMap();
562 Invite["AgentID"] = OSD.FromUUID(agentID);
563 Invite["RoleID"] = OSD.FromUUID(roleID);
564
565 SimianAddGeneric(groupID, "GroupMemberInvite", inviteID.ToString(), Invite);
566 }
567
568 public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
569 {
570 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
571
572 OSDMap GroupMemberInvite;
573 UUID GroupID;
574 if (!SimianGetFirstGenericEntry("GroupMemberInvite", inviteID.ToString(), out GroupID, out GroupMemberInvite))
575 {
576 return null;
577 }
578
579 GroupInviteInfo inviteInfo = new GroupInviteInfo();
580 inviteInfo.InviteID = inviteID;
581 inviteInfo.GroupID = GroupID;
582 inviteInfo.AgentID = GroupMemberInvite["AgentID"].AsUUID();
583 inviteInfo.RoleID = GroupMemberInvite["RoleID"].AsUUID();
584
585 return inviteInfo;
586 }
587
588 public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
589 {
590 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
591
592 GroupInviteInfo invite = GetAgentToGroupInvite(requestingAgentID, inviteID);
593 SimianRemoveGenericEntry(invite.GroupID, "GroupMemberInvite", inviteID.ToString());
594 }
595
596 public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
597 {
598 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
599
600 // Setup Agent/Group information
601 SetAgentGroupInfo(requestingAgentID, AgentID, GroupID, true, true);
602
603 // Add agent to Everyone Group
604 AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, UUID.Zero);
605
606 // Add agent to Specified Role
607 AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
608
609 // Set selected role in this group to specified role
610 SetAgentActiveGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
611 }
612
613 public void RemoveAgentFromGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
614 {
615 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
616
617 // If current active group is the group the agent is being removed from, change their group to UUID.Zero
618 GroupMembershipData memberActiveMembership = GetAgentActiveMembership(requestingAgentID, agentID);
619 if (memberActiveMembership.GroupID == groupID)
620 {
621 SetAgentActiveGroup(agentID, agentID, UUID.Zero);
622 }
623
624 // Remove Group Member information for this group
625 SimianRemoveGenericEntry(agentID, "GroupMember", groupID.ToString());
626
627 // By using a Simian Generics Type consisting of a prefix and a groupID,
628 // combined with RoleID as key allows us to get a list of roles a particular member
629 // of a group is assigned to.
630 string GroupRoleMemberType = "GroupRole" + groupID.ToString();
631
632 // Take Agent out of all other group roles
633 Dictionary<string, OSDMap> GroupRoles;
634 if (SimianGetGenericEntries(agentID, GroupRoleMemberType, out GroupRoles))
635 {
636 foreach (string roleID in GroupRoles.Keys)
637 {
638 SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID);
639 }
640 }
641 }
642
643 public void AddAgentToGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
644 {
645 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
646
647 SimianAddGeneric(agentID, "GroupRole" + groupID.ToString(), roleID.ToString(), new OSDMap());
648 }
649
650 public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
651 {
652 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
653
654 // Cannot remove members from the Everyone Role
655 if (roleID != UUID.Zero)
656 {
657 EnsureRoleNotSelectedByMember(groupID, roleID, agentID);
658
659 string GroupRoleMemberType = "GroupRole" + groupID.ToString();
660 SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID.ToString());
661 }
662 }
663
664 public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
665 {
666 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
667
668 List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
669
670 NameValueCollection requestArgs = new NameValueCollection
671 {
672 { "RequestMethod", "GetGenerics" },
673 { "Type", "Group" },
674 { "Key", search },
675 { "Fuzzy", "1" }
676 };
677
678
679 OSDMap response = CachedPostRequest(requestArgs);
680 if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
681 {
682 OSDArray entryArray = (OSDArray)response["Entries"];
683 foreach (OSDMap entryMap in entryArray)
684 {
685 DirGroupsReplyData data = new DirGroupsReplyData();
686 data.groupID = entryMap["OwnerID"].AsUUID();
687 data.groupName = entryMap["Key"].AsString();
688
689 // TODO: is there a better way to do this?
690 Dictionary<UUID, OSDMap> Members;
691 if (SimianGetGenericEntries("GroupMember", data.groupID.ToString(), out Members))
692 {
693 data.members = Members.Count;
694 }
695 else
696 {
697 data.members = 0;
698 }
699
700 // TODO: sort results?
701 // data.searchOrder = order;
702
703 findings.Add(data);
704 }
705 }
706
707
708 return findings;
709 }
710
711 public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID agentID, UUID groupID)
712 {
713 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
714
715 GroupMembershipData data = new GroupMembershipData();
716
717 ///////////////////////////////
718 // Agent Specific Information:
719 //
720 OSDMap UserActiveGroup;
721 if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
722 {
723 data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID);
724 }
725
726 OSDMap UserGroupMemberInfo;
727 if( SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out UserGroupMemberInfo) )
728 {
729 data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean();
730 data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger();
731 data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean();
732 data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID();
733
734 ///////////////////////////////
735 // Role Specific Information:
736 //
737
738 OSDMap GroupRoleInfo;
739 if( SimianGetGenericEntry(groupID, "GroupRole", data.ActiveRole.ToString(), out GroupRoleInfo) )
740 {
741 data.GroupTitle = GroupRoleInfo["Title"].AsString();
742 data.GroupPowers = GroupRoleInfo["Powers"].AsULong();
743 }
744 }
745
746 ///////////////////////////////
747 // Group Specific Information:
748 //
749 OSDMap GroupInfo;
750 string GroupName;
751 if( SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo) )
752 {
753 data.GroupID = groupID;
754 data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean();
755 data.Charter = GroupInfo["Charter"].AsString();
756 data.FounderID = GroupInfo["FounderID"].AsUUID();
757 data.GroupName = GroupName;
758 data.GroupPicture = GroupInfo["InsigniaID"].AsUUID();
759 data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean();
760 data.MembershipFee = GroupInfo["MembershipFee"].AsInteger();
761 data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean();
762 data.ShowInList = GroupInfo["ShowInList"].AsBoolean();
763 }
764
765 return data;
766 }
767
768 public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID agentID)
769 {
770 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
771
772 UUID GroupID = UUID.Zero;
773 OSDMap UserActiveGroup;
774 if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
775 {
776 GroupID = UserActiveGroup["GroupID"].AsUUID();
777 }
778
779 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Active GroupID : {0}", GroupID.ToString());
780 return GetAgentGroupMembership(requestingAgentID, agentID, GroupID);
781 }
782
783 public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID agentID)
784 {
785 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
786
787 List<GroupMembershipData> memberships = new List<GroupMembershipData>();
788
789 Dictionary<string,OSDMap> GroupMemberShips;
790 if (SimianGetGenericEntries(agentID, "GroupMember", out GroupMemberShips))
791 {
792 foreach (string key in GroupMemberShips.Keys)
793 {
794 memberships.Add(GetAgentGroupMembership(requestingAgentID, agentID, UUID.Parse(key)));
795 }
796 }
797
798 return memberships;
799 }
800
801 public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID agentID, UUID groupID)
802 {
803 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
804
805 List<GroupRolesData> Roles = new List<GroupRolesData>();
806
807 Dictionary<string, OSDMap> GroupRoles;
808 if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
809 {
810 Dictionary<string, OSDMap> MemberRoles;
811 if (SimianGetGenericEntries(agentID, "GroupRole" + groupID.ToString(), out MemberRoles))
812 {
813 foreach (KeyValuePair<string, OSDMap> kvp in MemberRoles)
814 {
815 GroupRolesData data = new GroupRolesData();
816 data.RoleID = UUID.Parse(kvp.Key);
817 data.Name = GroupRoles[kvp.Key]["Name"].AsString();
818 data.Description = GroupRoles[kvp.Key]["Description"].AsString();
819 data.Title = GroupRoles[kvp.Key]["Title"].AsString();
820 data.Powers = GroupRoles[kvp.Key]["Powers"].AsULong();
821
822 Roles.Add(data);
823 }
824 }
825 }
826 return Roles;
827 }
828
829 public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID groupID)
830 {
831 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
832
833 List<GroupRolesData> Roles = new List<GroupRolesData>();
834
835 Dictionary<string, OSDMap> GroupRoles;
836 if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
837 {
838 foreach (KeyValuePair<string, OSDMap> role in GroupRoles)
839 {
840 GroupRolesData data = new GroupRolesData();
841
842 data.RoleID = UUID.Parse(role.Key);
843
844 data.Name = role.Value["Name"].AsString();
845 data.Description = role.Value["Description"].AsString();
846 data.Title = role.Value["Title"].AsString();
847 data.Powers = role.Value["Powers"].AsULong();
848
849 Dictionary<UUID, OSDMap> GroupRoleMembers;
850 if (SimianGetGenericEntries("GroupRole" + groupID.ToString(), role.Key, out GroupRoleMembers))
851 {
852 data.Members = GroupRoleMembers.Count;
853 }
854 else
855 {
856 data.Members = 0;
857 }
858
859 Roles.Add(data);
860 }
861 }
862
863 return Roles;
864
865 }
866
867
868
869 public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
870 {
871 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
872
873 List<GroupMembersData> members = new List<GroupMembersData>();
874
875 OSDMap GroupInfo;
876 string GroupName;
877 UUID GroupOwnerRoleID = UUID.Zero;
878 if (!SimianGetFirstGenericEntry(GroupID, "Group", out GroupName, out GroupInfo))
879 {
880 return members;
881 }
882 GroupOwnerRoleID = GroupInfo["OwnerRoleID"].AsUUID();
883
884 // Locally cache group roles, since we'll be needing this data for each member
885 Dictionary<string,OSDMap> GroupRoles;
886 SimianGetGenericEntries(GroupID, "GroupRole", out GroupRoles);
887
888 // Locally cache list of group owners
889 Dictionary<UUID, OSDMap> GroupOwners;
890 SimianGetGenericEntries("GroupRole" + GroupID.ToString(), GroupOwnerRoleID.ToString(), out GroupOwners);
891
892
893 Dictionary<UUID, OSDMap> GroupMembers;
894 if (SimianGetGenericEntries("GroupMember", GroupID.ToString(), out GroupMembers))
895 {
896 foreach (KeyValuePair<UUID, OSDMap> member in GroupMembers)
897 {
898 GroupMembersData data = new GroupMembersData();
899
900 data.AgentID = member.Key;
901
902 UUID SelectedRoleID = member.Value["SelectedRoleID"].AsUUID();
903
904 data.AcceptNotices = member.Value["AcceptNotices"].AsBoolean();
905 data.ListInProfile = member.Value["ListInProfile"].AsBoolean();
906 data.Contribution = member.Value["Contribution"].AsInteger();
907
908 data.IsOwner = GroupOwners.ContainsKey(member.Key);
909
910 OSDMap GroupRoleInfo = GroupRoles[SelectedRoleID.ToString()];
911 data.Title = GroupRoleInfo["Title"].AsString();
912 data.AgentPowers = GroupRoleInfo["Powers"].AsULong();
913
914 members.Add(data);
915 }
916 }
917
918 return members;
919
920 }
921
922 public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID groupID)
923 {
924 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
925
926 List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
927
928 Dictionary<string, OSDMap> GroupRoles;
929 if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
930 {
931 foreach( KeyValuePair<string, OSDMap> Role in GroupRoles )
932 {
933 Dictionary<UUID, OSDMap> GroupRoleMembers;
934 if( SimianGetGenericEntries("GroupRole"+groupID.ToString(), Role.Key, out GroupRoleMembers) )
935 {
936 foreach( KeyValuePair<UUID, OSDMap> GroupRoleMember in GroupRoleMembers )
937 {
938 GroupRoleMembersData data = new GroupRoleMembersData();
939
940 data.MemberID = GroupRoleMember.Key;
941 data.RoleID = UUID.Parse(Role.Key);
942
943 members.Add(data);
944 }
945 }
946 }
947 }
948
949 return members;
950 }
951
952 public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
953 {
954 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
955
956 List<GroupNoticeData> values = new List<GroupNoticeData>();
957
958 Dictionary<string, OSDMap> Notices;
959 if (SimianGetGenericEntries(GroupID, "GroupNotice", out Notices))
960 {
961 foreach (KeyValuePair<string, OSDMap> Notice in Notices)
962 {
963 GroupNoticeData data = new GroupNoticeData();
964 data.NoticeID = UUID.Parse(Notice.Key);
965 data.Timestamp = Notice.Value["TimeStamp"].AsUInteger();
966 data.FromName = Notice.Value["FromName"].AsString();
967 data.Subject = Notice.Value["Subject"].AsString();
968 data.HasAttachment = Notice.Value["BinaryBucket"].AsBinary().Length > 0;
969
970 //TODO: Figure out how to get this
971 data.AssetType = 0;
972
973 values.Add(data);
974 }
975 }
976
977 return values;
978
979 }
980 public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
981 {
982 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
983
984 OSDMap GroupNotice;
985 UUID GroupID;
986 if (SimianGetFirstGenericEntry("GroupNotice", noticeID.ToString(), out GroupID, out GroupNotice))
987 {
988 GroupNoticeInfo data = new GroupNoticeInfo();
989 data.GroupID = GroupID;
990 data.Message = GroupNotice["Message"].AsString();
991 data.BinaryBucket = GroupNotice["BinaryBucket"].AsBinary();
992 data.noticeData.NoticeID = noticeID;
993 data.noticeData.Timestamp = GroupNotice["TimeStamp"].AsUInteger();
994 data.noticeData.FromName = GroupNotice["FromName"].AsString();
995 data.noticeData.Subject = GroupNotice["Subject"].AsString();
996 data.noticeData.HasAttachment = data.BinaryBucket.Length > 0;
997 data.noticeData.AssetType = 0;
998
999 if (data.Message == null)
1000 {
1001 data.Message = string.Empty;
1002 }
1003
1004 return data;
1005 }
1006 return null;
1007 }
1008 public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
1009 {
1010 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
1011
1012 OSDMap Notice = new OSDMap();
1013 Notice["TimeStamp"] = OSD.FromUInteger((uint)Util.UnixTimeSinceEpoch());
1014 Notice["FromName"] = OSD.FromString(fromName);
1015 Notice["Subject"] = OSD.FromString(subject);
1016 Notice["Message"] = OSD.FromString(message);
1017 Notice["BinaryBucket"] = OSD.FromBinary(binaryBucket);
1018
1019 SimianAddGeneric(groupID, "GroupNotice", noticeID.ToString(), Notice);
1020
1021 }
1022 #endregion
1023
1024 #region GroupSessionTracking
1025
1026 public void ResetAgentGroupChatSessions(UUID agentID)
1027 {
1028 Dictionary<string, OSDMap> agentSessions;
1029
1030 if (SimianGetGenericEntries(agentID, "GroupSessionDropped", out agentSessions))
1031 {
1032 foreach (string GroupID in agentSessions.Keys)
1033 {
1034 SimianRemoveGenericEntry(agentID, "GroupSessionDropped", GroupID);
1035 }
1036 }
1037
1038 if (SimianGetGenericEntries(agentID, "GroupSessionInvited", out agentSessions))
1039 {
1040 foreach (string GroupID in agentSessions.Keys)
1041 {
1042 SimianRemoveGenericEntry(agentID, "GroupSessionInvited", GroupID);
1043 }
1044 }
1045 }
1046
1047 public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
1048 {
1049 OSDMap session;
1050 return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
1051 }
1052
1053 public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
1054 {
1055 SimianAddGeneric(agentID, "GroupSessionDropped", groupID.ToString(), new OSDMap());
1056 }
1057
1058 public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
1059 {
1060 SimianAddGeneric(agentID, "GroupSessionInvited", groupID.ToString(), new OSDMap());
1061 }
1062
1063 public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
1064 {
1065 OSDMap session;
1066 return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
1067 }
1068
1069 #endregion
1070
1071 private void EnsureRoleNotSelectedByMember(UUID groupID, UUID roleID, UUID userID)
1072 {
1073 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
1074
1075 // If member's SelectedRole is roleID, change their selected role to Everyone
1076 // before removing them from the role
1077 OSDMap UserGroupInfo;
1078 if (SimianGetGenericEntry(userID, "GroupMember", groupID.ToString(), out UserGroupInfo))
1079 {
1080 if (UserGroupInfo["SelectedRoleID"].AsUUID() == roleID)
1081 {
1082 UserGroupInfo["SelectedRoleID"] = OSD.FromUUID(UUID.Zero);
1083 }
1084 SimianAddGeneric(userID, "GroupMember", groupID.ToString(), UserGroupInfo);
1085 }
1086 }
1087
1088
1089 #region Simian Util Methods
1090 private bool SimianAddGeneric(UUID ownerID, string type, string key, OSDMap map)
1091 {
1092 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
1093
1094 string value = OSDParser.SerializeJsonString(map);
1095
1096 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] value: {0}", value);
1097
1098 NameValueCollection RequestArgs = new NameValueCollection
1099 {
1100 { "RequestMethod", "AddGeneric" },
1101 { "OwnerID", ownerID.ToString() },
1102 { "Type", type },
1103 { "Key", key },
1104 { "Value", value}
1105 };
1106
1107
1108 OSDMap Response = CachedPostRequest(RequestArgs);
1109 if (Response["Success"].AsBoolean())
1110 {
1111 return true;
1112 }
1113 else
1114 {
1115 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, Response["Message"]);
1116 return false;
1117 }
1118 }
1119
1120 /// <summary>
1121 /// Returns the first of possibly many entries for Owner/Type pair
1122 /// </summary>
1123 private bool SimianGetFirstGenericEntry(UUID ownerID, string type, out string key, out OSDMap map)
1124 {
1125 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type);
1126
1127 NameValueCollection RequestArgs = new NameValueCollection
1128 {
1129 { "RequestMethod", "GetGenerics" },
1130 { "OwnerID", ownerID.ToString() },
1131 { "Type", type }
1132 };
1133
1134
1135 OSDMap Response = CachedPostRequest(RequestArgs);
1136 if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
1137 {
1138 OSDArray entryArray = (OSDArray)Response["Entries"];
1139 if (entryArray.Count >= 1)
1140 {
1141 OSDMap entryMap = entryArray[0] as OSDMap;
1142 key = entryMap["Key"].AsString();
1143 map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
1144
1145 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
1146
1147 return true;
1148 }
1149 else
1150 {
1151 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
1152 }
1153 }
1154 else
1155 {
1156 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
1157 }
1158 key = null;
1159 map = null;
1160 return false;
1161 }
1162 private bool SimianGetFirstGenericEntry(string type, string key, out UUID ownerID, out OSDMap map)
1163 {
1164 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
1165
1166
1167 NameValueCollection RequestArgs = new NameValueCollection
1168 {
1169 { "RequestMethod", "GetGenerics" },
1170 { "Type", type },
1171 { "Key", key}
1172 };
1173
1174
1175 OSDMap Response = CachedPostRequest(RequestArgs);
1176 if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
1177 {
1178 OSDArray entryArray = (OSDArray)Response["Entries"];
1179 if (entryArray.Count >= 1)
1180 {
1181 OSDMap entryMap = entryArray[0] as OSDMap;
1182 ownerID = entryMap["OwnerID"].AsUUID();
1183 map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
1184
1185 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
1186
1187 return true;
1188 }
1189 else
1190 {
1191 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
1192 }
1193 }
1194 else
1195 {
1196 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
1197 }
1198 ownerID = UUID.Zero;
1199 map = null;
1200 return false;
1201 }
1202
1203 private bool SimianGetGenericEntry(UUID ownerID, string type, string key, out OSDMap map)
1204 {
1205 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
1206
1207 NameValueCollection RequestArgs = new NameValueCollection
1208 {
1209 { "RequestMethod", "GetGenerics" },
1210 { "OwnerID", ownerID.ToString() },
1211 { "Type", type },
1212 { "Key", key}
1213 };
1214
1215
1216 OSDMap Response = CachedPostRequest(RequestArgs);
1217 if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
1218 {
1219 OSDArray entryArray = (OSDArray)Response["Entries"];
1220 if (entryArray.Count == 1)
1221 {
1222 OSDMap entryMap = entryArray[0] as OSDMap;
1223 key = entryMap["Key"].AsString();
1224 map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
1225
1226 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
1227
1228 return true;
1229 }
1230 else
1231 {
1232 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
1233 }
1234 }
1235 else
1236 {
1237 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
1238 }
1239 map = null;
1240 return false;
1241 }
1242
1243 private bool SimianGetGenericEntries(UUID ownerID, string type, out Dictionary<string, OSDMap> maps)
1244 {
1245 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name,ownerID, type);
1246
1247 NameValueCollection requestArgs = new NameValueCollection
1248 {
1249 { "RequestMethod", "GetGenerics" },
1250 { "OwnerID", ownerID.ToString() },
1251 { "Type", type }
1252 };
1253
1254
1255
1256 OSDMap response = CachedPostRequest(requestArgs);
1257 if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
1258 {
1259 maps = new Dictionary<string, OSDMap>();
1260
1261 OSDArray entryArray = (OSDArray)response["Entries"];
1262 foreach (OSDMap entryMap in entryArray)
1263 {
1264 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
1265 maps.Add(entryMap["Key"].AsString(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
1266 }
1267 if(maps.Count == 0)
1268 {
1269 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
1270 }
1271
1272 return true;
1273 }
1274 else
1275 {
1276 maps = null;
1277 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
1278 }
1279 return false;
1280 }
1281 private bool SimianGetGenericEntries(string type, string key, out Dictionary<UUID, OSDMap> maps)
1282 {
1283 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
1284
1285 NameValueCollection requestArgs = new NameValueCollection
1286 {
1287 { "RequestMethod", "GetGenerics" },
1288 { "Type", type },
1289 { "Key", key }
1290 };
1291
1292
1293
1294 OSDMap response = CachedPostRequest(requestArgs);
1295 if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
1296 {
1297 maps = new Dictionary<UUID, OSDMap>();
1298
1299 OSDArray entryArray = (OSDArray)response["Entries"];
1300 foreach (OSDMap entryMap in entryArray)
1301 {
1302 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
1303 maps.Add(entryMap["OwnerID"].AsUUID(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
1304 }
1305 if (maps.Count == 0)
1306 {
1307 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
1308 }
1309 return true;
1310 }
1311 else
1312 {
1313 maps = null;
1314 m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
1315 }
1316 return false;
1317 }
1318
1319 private bool SimianRemoveGenericEntry(UUID ownerID, string type, string key)
1320 {
1321 if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
1322
1323 NameValueCollection requestArgs = new NameValueCollection
1324 {
1325 { "RequestMethod", "RemoveGeneric" },
1326 { "OwnerID", ownerID.ToString() },
1327 { "Type", type },
1328 { "Key", key }
1329 };
1330
1331
1332 OSDMap response = CachedPostRequest(requestArgs);
1333 if (response["Success"].AsBoolean())
1334 {
1335 return true;
1336 }
1337 else
1338 {
1339 m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, response["Message"]);
1340 return false;
1341 }
1342 }
1343 #endregion
1344
1345 #region CheesyCache
1346 OSDMap CachedPostRequest(NameValueCollection requestArgs)
1347 {
1348 // Immediately forward the request if the cache is disabled.
1349 if (m_cacheTimeout == 0)
1350 {
1351 return WebUtil.PostToService(m_groupsServerURI, requestArgs);
1352 }
1353
1354 // Check if this is an update or a request
1355 if ( requestArgs["RequestMethod"] == "RemoveGeneric"
1356 || requestArgs["RequestMethod"] == "AddGeneric"
1357 )
1358
1359 {
1360 // Any and all updates cause the cache to clear
1361 m_memoryCache.Clear();
1362
1363 // Send update to server, return the response without caching it
1364 return WebUtil.PostToService(m_groupsServerURI, requestArgs);
1365
1366 }
1367
1368 // If we're not doing an update, we must be requesting data
1369
1370 // Create the cache key for the request and see if we have it cached
1371 string CacheKey = WebUtil.BuildQueryString(requestArgs);
1372 OSDMap response = null;
1373 if (!m_memoryCache.TryGetValue(CacheKey, out response))
1374 {
1375 // if it wasn't in the cache, pass the request to the Simian Grid Services
1376 response = WebUtil.PostToService(m_groupsServerURI, requestArgs);
1377
1378 // and cache the response
1379 m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout));
1380 }
1381
1382 // return cached response
1383 return response;
1384 }
1385 #endregion
1386
1387 }
1388
1389}
1390
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs
index 964d0bb..79b9a16 100644
--- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs
@@ -29,6 +29,7 @@ using System;
29using System.Collections; 29using System.Collections;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Reflection; 31using System.Reflection;
32using System.Text;
32 33
33using Nwc.XmlRpc; 34using Nwc.XmlRpc;
34 35
@@ -40,16 +41,16 @@ using OpenMetaverse;
40using OpenMetaverse.StructuredData; 41using OpenMetaverse.StructuredData;
41 42
42using OpenSim.Framework; 43using OpenSim.Framework;
44using OpenSim.Framework.Communications;
43using OpenSim.Region.Framework.Interfaces; 45using OpenSim.Region.Framework.Interfaces;
46using OpenSim.Services.Interfaces;
44 47
45namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups 48namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
46{ 49{
47 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] 50 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
48 public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector 51 public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
49 { 52 {
50 private static readonly ILog m_log = 53 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
52
53 54
54 public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | 55 public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome |
55 GroupPowers.Accountable | 56 GroupPowers.Accountable |
@@ -61,13 +62,25 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
61 62
62 private bool m_connectorEnabled = false; 63 private bool m_connectorEnabled = false;
63 64
64 private string m_serviceURL = string.Empty; 65 private string m_groupsServerURI = string.Empty;
65 66
66 private bool m_disableKeepAlive = false; 67 private bool m_disableKeepAlive = false;
67 68
68 private string m_groupReadKey = string.Empty; 69 private string m_groupReadKey = string.Empty;
69 private string m_groupWriteKey = string.Empty; 70 private string m_groupWriteKey = string.Empty;
70 71
72 private IUserAccountService m_accountService = null;
73
74 private ExpiringCache<string, XmlRpcResponse> m_memoryCache;
75 private int m_cacheTimeout = 30;
76
77 // Used to track which agents are have dropped from a group chat session
78 // Should be reset per agent, on logon
79 // TODO: move this to Flotsam XmlRpc Service
80 // SessionID, List<AgentID>
81 private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>();
82 private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>();
83
71 84
72 #region IRegionModuleBase Members 85 #region IRegionModuleBase Members
73 86
@@ -102,13 +115,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
102 return; 115 return;
103 } 116 }
104 117
105 m_log.InfoFormat("[GROUPS-CONNECTOR]: Initializing {0}", this.Name); 118 m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
106 119
107 m_serviceURL = groupsConfig.GetString("XmlRpcServiceURL", string.Empty); 120 m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
108 if ((m_serviceURL == null) || 121 if ((m_groupsServerURI == null) ||
109 (m_serviceURL == string.Empty)) 122 (m_groupsServerURI == string.Empty))
110 { 123 {
111 m_log.ErrorFormat("Please specify a valid URL for XmlRpcServiceURL in OpenSim.ini, [Groups]"); 124 m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]");
112 m_connectorEnabled = false; 125 m_connectorEnabled = false;
113 return; 126 return;
114 } 127 }
@@ -118,26 +131,49 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
118 m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); 131 m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty);
119 m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); 132 m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty);
120 133
134
135 m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
136 if (m_cacheTimeout == 0)
137 {
138 m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled.");
139 }
140 else
141 {
142 m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout);
143 }
144
121 // If we got all the config options we need, lets start'er'up 145 // If we got all the config options we need, lets start'er'up
146 m_memoryCache = new ExpiringCache<string, XmlRpcResponse>();
122 m_connectorEnabled = true; 147 m_connectorEnabled = true;
123 } 148 }
124 } 149 }
125 150
126 public void Close() 151 public void Close()
127 { 152 {
128 m_log.InfoFormat("[GROUPS-CONNECTOR]: Closing {0}", this.Name); 153 m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name);
129 } 154 }
130 155
131 public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) 156 public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
132 { 157 {
133 if (m_connectorEnabled) 158 if (m_connectorEnabled)
159 {
160
161 if (m_accountService == null)
162 {
163 m_accountService = scene.UserAccountService;
164 }
165
166
134 scene.RegisterModuleInterface<IGroupsServicesConnector>(this); 167 scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
168 }
135 } 169 }
136 170
137 public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene) 171 public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
138 { 172 {
139 if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) 173 if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
174 {
140 scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); 175 scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
176 }
141 } 177 }
142 178
143 public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene) 179 public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
@@ -157,14 +193,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
157 193
158 #endregion 194 #endregion
159 195
160
161
162 #region IGroupsServicesConnector Members 196 #region IGroupsServicesConnector Members
163 197
164 /// <summary> 198 /// <summary>
165 /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. 199 /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
166 /// </summary> 200 /// </summary>
167 public UUID CreateGroup(GroupRequestID requestID, string name, string charter, bool showInList, UUID insigniaID, 201 public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
168 int membershipFee, bool openEnrollment, bool allowPublish, 202 int membershipFee, bool openEnrollment, bool allowPublish,
169 bool maturePublish, UUID founderID) 203 bool maturePublish, UUID founderID)
170 { 204 {
@@ -236,7 +270,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
236 270
237 271
238 272
239 Hashtable respData = XmlRpcCall(requestID, "groups.createGroup", param); 273 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);
240 274
241 if (respData.Contains("error")) 275 if (respData.Contains("error"))
242 { 276 {
@@ -248,7 +282,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
248 return UUID.Parse((string)respData["GroupID"]); 282 return UUID.Parse((string)respData["GroupID"]);
249 } 283 }
250 284
251 public void UpdateGroup(GroupRequestID requestID, UUID groupID, string charter, bool showInList, 285 public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
252 UUID insigniaID, int membershipFee, bool openEnrollment, 286 UUID insigniaID, int membershipFee, bool openEnrollment,
253 bool allowPublish, bool maturePublish) 287 bool allowPublish, bool maturePublish)
254 { 288 {
@@ -262,10 +296,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
262 param["AllowPublish"] = allowPublish == true ? 1 : 0; 296 param["AllowPublish"] = allowPublish == true ? 1 : 0;
263 param["MaturePublish"] = maturePublish == true ? 1 : 0; 297 param["MaturePublish"] = maturePublish == true ? 1 : 0;
264 298
265 XmlRpcCall(requestID, "groups.updateGroup", param); 299 XmlRpcCall(requestingAgentID, "groups.updateGroup", param);
266 } 300 }
267 301
268 public void AddGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, 302 public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
269 string title, ulong powers) 303 string title, ulong powers)
270 { 304 {
271 Hashtable param = new Hashtable(); 305 Hashtable param = new Hashtable();
@@ -276,19 +310,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
276 param["Title"] = title; 310 param["Title"] = title;
277 param["Powers"] = powers.ToString(); 311 param["Powers"] = powers.ToString();
278 312
279 XmlRpcCall(requestID, "groups.addRoleToGroup", param); 313 XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param);
280 } 314 }
281 315
282 public void RemoveGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID) 316 public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
283 { 317 {
284 Hashtable param = new Hashtable(); 318 Hashtable param = new Hashtable();
285 param["GroupID"] = groupID.ToString(); 319 param["GroupID"] = groupID.ToString();
286 param["RoleID"] = roleID.ToString(); 320 param["RoleID"] = roleID.ToString();
287 321
288 XmlRpcCall(requestID, "groups.removeRoleFromGroup", param); 322 XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param);
289 } 323 }
290 324
291 public void UpdateGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, 325 public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
292 string title, ulong powers) 326 string title, ulong powers)
293 { 327 {
294 Hashtable param = new Hashtable(); 328 Hashtable param = new Hashtable();
@@ -308,10 +342,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
308 } 342 }
309 param["Powers"] = powers.ToString(); 343 param["Powers"] = powers.ToString();
310 344
311 XmlRpcCall(requestID, "groups.updateGroupRole", param); 345 XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param);
312 } 346 }
313 347
314 public GroupRecord GetGroupRecord(GroupRequestID requestID, UUID GroupID, string GroupName) 348 public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName)
315 { 349 {
316 Hashtable param = new Hashtable(); 350 Hashtable param = new Hashtable();
317 if (GroupID != UUID.Zero) 351 if (GroupID != UUID.Zero)
@@ -323,7 +357,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
323 param["Name"] = GroupName.ToString(); 357 param["Name"] = GroupName.ToString();
324 } 358 }
325 359
326 Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); 360 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
327 361
328 if (respData.Contains("error")) 362 if (respData.Contains("error"))
329 { 363 {
@@ -334,12 +368,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
334 368
335 } 369 }
336 370
337 public GroupProfileData GetMemberGroupProfile(GroupRequestID requestID, UUID GroupID, UUID AgentID) 371 public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
338 { 372 {
339 Hashtable param = new Hashtable(); 373 Hashtable param = new Hashtable();
340 param["GroupID"] = GroupID.ToString(); 374 param["GroupID"] = GroupID.ToString();
341 375
342 Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); 376 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
343 377
344 if (respData.Contains("error")) 378 if (respData.Contains("error"))
345 { 379 {
@@ -347,38 +381,35 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
347 return new GroupProfileData(); 381 return new GroupProfileData();
348 } 382 }
349 383
350 GroupMembershipData MemberInfo = GetAgentGroupMembership(requestID, AgentID, GroupID); 384 GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID);
351 GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); 385 GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData);
352 386
353 MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; 387 MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
354 MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; 388 MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
355 389
356 return MemberGroupProfile; 390 return MemberGroupProfile;
357
358 } 391 }
359 392
360 393 public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
361
362 public void SetAgentActiveGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID)
363 { 394 {
364 Hashtable param = new Hashtable(); 395 Hashtable param = new Hashtable();
365 param["AgentID"] = AgentID.ToString(); 396 param["AgentID"] = AgentID.ToString();
366 param["GroupID"] = GroupID.ToString(); 397 param["GroupID"] = GroupID.ToString();
367 398
368 XmlRpcCall(requestID, "groups.setAgentActiveGroup", param); 399 XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param);
369 } 400 }
370 401
371 public void SetAgentActiveGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) 402 public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
372 { 403 {
373 Hashtable param = new Hashtable(); 404 Hashtable param = new Hashtable();
374 param["AgentID"] = AgentID.ToString(); 405 param["AgentID"] = AgentID.ToString();
375 param["GroupID"] = GroupID.ToString(); 406 param["GroupID"] = GroupID.ToString();
376 param["SelectedRoleID"] = RoleID.ToString(); 407 param["SelectedRoleID"] = RoleID.ToString();
377 408
378 XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); 409 XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
379 } 410 }
380 411
381 public void SetAgentGroupInfo(GroupRequestID requestID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) 412 public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
382 { 413 {
383 Hashtable param = new Hashtable(); 414 Hashtable param = new Hashtable();
384 param["AgentID"] = AgentID.ToString(); 415 param["AgentID"] = AgentID.ToString();
@@ -386,11 +417,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
386 param["AcceptNotices"] = AcceptNotices ? "1" : "0"; 417 param["AcceptNotices"] = AcceptNotices ? "1" : "0";
387 param["ListInProfile"] = ListInProfile ? "1" : "0"; 418 param["ListInProfile"] = ListInProfile ? "1" : "0";
388 419
389 XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); 420 XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
390 421
391 } 422 }
392 423
393 public void AddAgentToGroupInvite(GroupRequestID requestID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) 424 public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
394 { 425 {
395 Hashtable param = new Hashtable(); 426 Hashtable param = new Hashtable();
396 param["InviteID"] = inviteID.ToString(); 427 param["InviteID"] = inviteID.ToString();
@@ -398,16 +429,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
398 param["RoleID"] = roleID.ToString(); 429 param["RoleID"] = roleID.ToString();
399 param["GroupID"] = groupID.ToString(); 430 param["GroupID"] = groupID.ToString();
400 431
401 XmlRpcCall(requestID, "groups.addAgentToGroupInvite", param); 432 XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param);
402 433
403 } 434 }
404 435
405 public GroupInviteInfo GetAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) 436 public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
406 { 437 {
407 Hashtable param = new Hashtable(); 438 Hashtable param = new Hashtable();
408 param["InviteID"] = inviteID.ToString(); 439 param["InviteID"] = inviteID.ToString();
409 440
410 Hashtable respData = XmlRpcCall(requestID, "groups.getAgentToGroupInvite", param); 441 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param);
411 442
412 if (respData.Contains("error")) 443 if (respData.Contains("error"))
413 { 444 {
@@ -423,60 +454,59 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
423 return inviteInfo; 454 return inviteInfo;
424 } 455 }
425 456
426 public void RemoveAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) 457 public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
427 { 458 {
428 Hashtable param = new Hashtable(); 459 Hashtable param = new Hashtable();
429 param["InviteID"] = inviteID.ToString(); 460 param["InviteID"] = inviteID.ToString();
430 461
431 XmlRpcCall(requestID, "groups.removeAgentToGroupInvite", param); 462 XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param);
432 } 463 }
433 464
434 public void AddAgentToGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) 465 public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
435 { 466 {
436 Hashtable param = new Hashtable(); 467 Hashtable param = new Hashtable();
437 param["AgentID"] = AgentID.ToString(); 468 param["AgentID"] = AgentID.ToString();
438 param["GroupID"] = GroupID.ToString(); 469 param["GroupID"] = GroupID.ToString();
439 param["RoleID"] = RoleID.ToString(); 470 param["RoleID"] = RoleID.ToString();
440 471
441 XmlRpcCall(requestID, "groups.addAgentToGroup", param); 472 XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param);
442 } 473 }
443 474
444 public void RemoveAgentFromGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID) 475 public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
445 { 476 {
446 Hashtable param = new Hashtable(); 477 Hashtable param = new Hashtable();
447 param["AgentID"] = AgentID.ToString(); 478 param["AgentID"] = AgentID.ToString();
448 param["GroupID"] = GroupID.ToString(); 479 param["GroupID"] = GroupID.ToString();
449 480
450 XmlRpcCall(requestID, "groups.removeAgentFromGroup", param); 481 XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param);
451 } 482 }
452 483
453 public void AddAgentToGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) 484 public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
454 { 485 {
455 Hashtable param = new Hashtable(); 486 Hashtable param = new Hashtable();
456 param["AgentID"] = AgentID.ToString(); 487 param["AgentID"] = AgentID.ToString();
457 param["GroupID"] = GroupID.ToString(); 488 param["GroupID"] = GroupID.ToString();
458 param["RoleID"] = RoleID.ToString(); 489 param["RoleID"] = RoleID.ToString();
459 490
460 XmlRpcCall(requestID, "groups.addAgentToGroupRole", param); 491 XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param);
461 } 492 }
462 493
463 public void RemoveAgentFromGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) 494 public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
464 { 495 {
465 Hashtable param = new Hashtable(); 496 Hashtable param = new Hashtable();
466 param["AgentID"] = AgentID.ToString(); 497 param["AgentID"] = AgentID.ToString();
467 param["GroupID"] = GroupID.ToString(); 498 param["GroupID"] = GroupID.ToString();
468 param["RoleID"] = RoleID.ToString(); 499 param["RoleID"] = RoleID.ToString();
469 500
470 XmlRpcCall(requestID, "groups.removeAgentFromGroupRole", param); 501 XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param);
471 } 502 }
472 503
473 504 public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
474 public List<DirGroupsReplyData> FindGroups(GroupRequestID requestID, string search)
475 { 505 {
476 Hashtable param = new Hashtable(); 506 Hashtable param = new Hashtable();
477 param["Search"] = search; 507 param["Search"] = search;
478 508
479 Hashtable respData = XmlRpcCall(requestID, "groups.findGroups", param); 509 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param);
480 510
481 List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); 511 List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
482 512
@@ -498,13 +528,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
498 return findings; 528 return findings;
499 } 529 }
500 530
501 public GroupMembershipData GetAgentGroupMembership(GroupRequestID requestID, UUID AgentID, UUID GroupID) 531 public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
502 { 532 {
503 Hashtable param = new Hashtable(); 533 Hashtable param = new Hashtable();
504 param["AgentID"] = AgentID.ToString(); 534 param["AgentID"] = AgentID.ToString();
505 param["GroupID"] = GroupID.ToString(); 535 param["GroupID"] = GroupID.ToString();
506 536
507 Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMembership", param); 537 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param);
508 538
509 if (respData.Contains("error")) 539 if (respData.Contains("error"))
510 { 540 {
@@ -516,12 +546,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
516 return data; 546 return data;
517 } 547 }
518 548
519 public GroupMembershipData GetAgentActiveMembership(GroupRequestID requestID, UUID AgentID) 549 public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
520 { 550 {
521 Hashtable param = new Hashtable(); 551 Hashtable param = new Hashtable();
522 param["AgentID"] = AgentID.ToString(); 552 param["AgentID"] = AgentID.ToString();
523 553
524 Hashtable respData = XmlRpcCall(requestID, "groups.getAgentActiveMembership", param); 554 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param);
525 555
526 if (respData.Contains("error")) 556 if (respData.Contains("error"))
527 { 557 {
@@ -531,13 +561,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
531 return HashTableToGroupMembershipData(respData); 561 return HashTableToGroupMembershipData(respData);
532 } 562 }
533 563
534 564 public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
535 public List<GroupMembershipData> GetAgentGroupMemberships(GroupRequestID requestID, UUID AgentID)
536 { 565 {
537 Hashtable param = new Hashtable(); 566 Hashtable param = new Hashtable();
538 param["AgentID"] = AgentID.ToString(); 567 param["AgentID"] = AgentID.ToString();
539 568
540 Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMemberships", param); 569 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param);
541 570
542 List<GroupMembershipData> memberships = new List<GroupMembershipData>(); 571 List<GroupMembershipData> memberships = new List<GroupMembershipData>();
543 572
@@ -552,13 +581,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
552 return memberships; 581 return memberships;
553 } 582 }
554 583
555 public List<GroupRolesData> GetAgentGroupRoles(GroupRequestID requestID, UUID AgentID, UUID GroupID) 584 public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
556 { 585 {
557 Hashtable param = new Hashtable(); 586 Hashtable param = new Hashtable();
558 param["AgentID"] = AgentID.ToString(); 587 param["AgentID"] = AgentID.ToString();
559 param["GroupID"] = GroupID.ToString(); 588 param["GroupID"] = GroupID.ToString();
560 589
561 Hashtable respData = XmlRpcCall(requestID, "groups.getAgentRoles", param); 590 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param);
562 591
563 List<GroupRolesData> Roles = new List<GroupRolesData>(); 592 List<GroupRolesData> Roles = new List<GroupRolesData>();
564 593
@@ -584,12 +613,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
584 613
585 } 614 }
586 615
587 public List<GroupRolesData> GetGroupRoles(GroupRequestID requestID, UUID GroupID) 616 public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
588 { 617 {
589 Hashtable param = new Hashtable(); 618 Hashtable param = new Hashtable();
590 param["GroupID"] = GroupID.ToString(); 619 param["GroupID"] = GroupID.ToString();
591 620
592 Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoles", param); 621 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param);
593 622
594 List<GroupRolesData> Roles = new List<GroupRolesData>(); 623 List<GroupRolesData> Roles = new List<GroupRolesData>();
595 624
@@ -617,12 +646,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
617 646
618 647
619 648
620 public List<GroupMembersData> GetGroupMembers(GroupRequestID requestID, UUID GroupID) 649 public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
621 { 650 {
622 Hashtable param = new Hashtable(); 651 Hashtable param = new Hashtable();
623 param["GroupID"] = GroupID.ToString(); 652 param["GroupID"] = GroupID.ToString();
624 653
625 Hashtable respData = XmlRpcCall(requestID, "groups.getGroupMembers", param); 654 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param);
626 655
627 List<GroupMembersData> members = new List<GroupMembersData>(); 656 List<GroupMembersData> members = new List<GroupMembersData>();
628 657
@@ -650,12 +679,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
650 679
651 } 680 }
652 681
653 public List<GroupRoleMembersData> GetGroupRoleMembers(GroupRequestID requestID, UUID GroupID) 682 public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
654 { 683 {
655 Hashtable param = new Hashtable(); 684 Hashtable param = new Hashtable();
656 param["GroupID"] = GroupID.ToString(); 685 param["GroupID"] = GroupID.ToString();
657 686
658 Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoleMembers", param); 687 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param);
659 688
660 List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); 689 List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
661 690
@@ -674,12 +703,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
674 return members; 703 return members;
675 } 704 }
676 705
677 public List<GroupNoticeData> GetGroupNotices(GroupRequestID requestID, UUID GroupID) 706 public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
678 { 707 {
679 Hashtable param = new Hashtable(); 708 Hashtable param = new Hashtable();
680 param["GroupID"] = GroupID.ToString(); 709 param["GroupID"] = GroupID.ToString();
681 710
682 Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotices", param); 711 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param);
683 712
684 List<GroupNoticeData> values = new List<GroupNoticeData>(); 713 List<GroupNoticeData> values = new List<GroupNoticeData>();
685 714
@@ -701,12 +730,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
701 return values; 730 return values;
702 731
703 } 732 }
704 public GroupNoticeInfo GetGroupNotice(GroupRequestID requestID, UUID noticeID) 733 public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
705 { 734 {
706 Hashtable param = new Hashtable(); 735 Hashtable param = new Hashtable();
707 param["NoticeID"] = noticeID.ToString(); 736 param["NoticeID"] = noticeID.ToString();
708 737
709 Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotice", param); 738 Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param);
710 739
711 740
712 if (respData.Contains("error")) 741 if (respData.Contains("error"))
@@ -732,7 +761,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
732 761
733 return data; 762 return data;
734 } 763 }
735 public void AddGroupNotice(GroupRequestID requestID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) 764 public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
736 { 765 {
737 string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, ""); 766 string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, "");
738 767
@@ -745,7 +774,70 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
745 param["BinaryBucket"] = binBucket; 774 param["BinaryBucket"] = binBucket;
746 param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); 775 param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
747 776
748 XmlRpcCall(requestID, "groups.addGroupNotice", param); 777 XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param);
778 }
779
780
781
782 #endregion
783
784 #region GroupSessionTracking
785
786 public void ResetAgentGroupChatSessions(UUID agentID)
787 {
788 foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values)
789 {
790 agentList.Remove(agentID);
791 }
792 }
793
794 public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
795 {
796 // If we're tracking this group, and we can find them in the tracking, then they've been invited
797 return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
798 && m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
799 }
800
801 public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
802 {
803 // If we're tracking drops for this group,
804 // and we find them, well... then they've dropped
805 return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
806 && m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
807 }
808
809 public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
810 {
811 if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
812 {
813 // If not in dropped list, add
814 if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
815 {
816 m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
817 }
818 }
819 }
820
821 public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
822 {
823 // Add Session Status if it doesn't exist for this session
824 CreateGroupChatSessionTracking(groupID);
825
826 // If nessesary, remove from dropped list
827 if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
828 {
829 m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
830 }
831 }
832
833 private void CreateGroupChatSessionTracking(UUID groupID)
834 {
835 if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
836 {
837 m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>());
838 m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>());
839 }
840
749 } 841 }
750 #endregion 842 #endregion
751 843
@@ -778,7 +870,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
778 870
779 private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) 871 private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile)
780 { 872 {
781
782 GroupRecord group = new GroupRecord(); 873 GroupRecord group = new GroupRecord();
783 group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); 874 group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
784 group.GroupName = groupProfile["Name"].ToString(); 875 group.GroupName = groupProfile["Name"].ToString();
@@ -797,6 +888,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
797 888
798 return group; 889 return group;
799 } 890 }
891
800 private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) 892 private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData)
801 { 893 {
802 GroupMembershipData data = new GroupMembershipData(); 894 GroupMembershipData data = new GroupMembershipData();
@@ -829,6 +921,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
829 data.MembershipFee = int.Parse((string)respData["MembershipFee"]); 921 data.MembershipFee = int.Parse((string)respData["MembershipFee"]);
830 data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1"); 922 data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1");
831 data.ShowInList = ((string)respData["ShowInList"] == "1"); 923 data.ShowInList = ((string)respData["ShowInList"] == "1");
924
832 return data; 925 return data;
833 } 926 }
834 927
@@ -837,53 +930,86 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
837 /// <summary> 930 /// <summary>
838 /// Encapsulate the XmlRpc call to standardize security and error handling. 931 /// Encapsulate the XmlRpc call to standardize security and error handling.
839 /// </summary> 932 /// </summary>
840 private Hashtable XmlRpcCall(GroupRequestID requestID, string function, Hashtable param) 933 private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param)
841 { 934 {
842 if (requestID == null) 935 XmlRpcResponse resp = null;
936 string CacheKey = null;
937
938 // Only bother with the cache if it isn't disabled.
939 if (m_cacheTimeout > 0)
843 { 940 {
844 requestID = new GroupRequestID(); 941 if (!function.StartsWith("groups.get"))
942 {
943 // Any and all updates cause the cache to clear
944 m_memoryCache.Clear();
945 }
946 else
947 {
948 StringBuilder sb = new StringBuilder(requestingAgentID + function);
949 foreach (object key in param.Keys)
950 {
951 if (param[key] != null)
952 {
953 sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString());
954 }
955 }
956
957 CacheKey = sb.ToString();
958 m_memoryCache.TryGetValue(CacheKey, out resp);
959 }
960
845 } 961 }
846 param.Add("RequestingAgentID", requestID.AgentID.ToString());
847 param.Add("RequestingAgentUserService", requestID.UserServiceURL);
848 param.Add("RequestingSessionID", requestID.SessionID.ToString());
849 962
963 if( resp == null )
964 {
965 string UserService;
966 UUID SessionID;
967 GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID);
968 param.Add("requestingAgentID", requestingAgentID.ToString());
969 param.Add("RequestingAgentUserService", UserService);
970 param.Add("RequestingSessionID", SessionID.ToString());
850 971
851 param.Add("ReadKey", m_groupReadKey);
852 param.Add("WriteKey", m_groupWriteKey);
853 972
973 param.Add("ReadKey", m_groupReadKey);
974 param.Add("WriteKey", m_groupWriteKey);
854 975
855 IList parameters = new ArrayList();
856 parameters.Add(param);
857 976
858 ConfigurableKeepAliveXmlRpcRequest req; 977 IList parameters = new ArrayList();
859 req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive); 978 parameters.Add(param);
860 979
861 XmlRpcResponse resp = null; 980 ConfigurableKeepAliveXmlRpcRequest req;
981 req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive);
862 982
863 try
864 {
865 resp = req.Send(m_serviceURL, 10000);
866 }
867 catch (Exception e)
868 {
869
870
871 m_log.ErrorFormat("[XMLRPCGROUPDATA]: An error has occured while attempting to access the XmlRpcGroups server method: {0}", function);
872 m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", e.ToString());
873 983
874 foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine },StringSplitOptions.None)) 984 try
875 { 985 {
876 m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", ResponseLine); 986 resp = req.Send(m_groupsServerURI, 10000);
877 } 987
988 if ((m_cacheTimeout > 0) && (CacheKey != null))
989 {
990 m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout));
991 }
878 992
879 foreach (string key in param.Keys) 993 }
994 catch (Exception e)
880 { 995 {
881 m_log.WarnFormat("[XMLRPCGROUPDATA]: {0} :: {1}", key, param[key].ToString()); 996 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method: {0}", function);
997 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", e.ToString());
998
999 foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
1000 {
1001 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine);
1002 }
1003
1004 foreach (string key in param.Keys)
1005 {
1006 m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString());
1007 }
1008
1009 Hashtable respData = new Hashtable();
1010 respData.Add("error", e.ToString());
1011 return respData;
882 } 1012 }
883
884 Hashtable respData = new Hashtable();
885 respData.Add("error", e.ToString());
886 return respData;
887 } 1013 }
888 1014
889 if (resp.Value is Hashtable) 1015 if (resp.Value is Hashtable)
@@ -897,21 +1023,21 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
897 return respData; 1023 return respData;
898 } 1024 }
899 1025
900 m_log.ErrorFormat("[XMLRPCGROUPDATA]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString()); 1026 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString());
901 1027
902 if (resp.Value is ArrayList) 1028 if (resp.Value is ArrayList)
903 { 1029 {
904 ArrayList al = (ArrayList)resp.Value; 1030 ArrayList al = (ArrayList)resp.Value;
905 m_log.ErrorFormat("[XMLRPCGROUPDATA]: Contains {0} elements", al.Count); 1031 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count);
906 1032
907 foreach (object o in al) 1033 foreach (object o in al)
908 { 1034 {
909 m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} :: {1}", o.GetType().ToString(), o.ToString()); 1035 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString());
910 } 1036 }
911 } 1037 }
912 else 1038 else
913 { 1039 {
914 m_log.ErrorFormat("[XMLRPCGROUPDATA]: Function returned: {0}", resp.Value.ToString()); 1040 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString());
915 } 1041 }
916 1042
917 Hashtable error = new Hashtable(); 1043 Hashtable error = new Hashtable();
@@ -921,30 +1047,64 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
921 1047
922 private void LogRespDataToConsoleError(Hashtable respData) 1048 private void LogRespDataToConsoleError(Hashtable respData)
923 { 1049 {
924 m_log.Error("[XMLRPCGROUPDATA]: Error:"); 1050 m_log.Error("[XMLRPC-GROUPS-CONNECTOR]: Error:");
925 1051
926 foreach (string key in respData.Keys) 1052 foreach (string key in respData.Keys)
927 { 1053 {
928 m_log.ErrorFormat("[XMLRPCGROUPDATA]: Key: {0}", key); 1054 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Key: {0}", key);
929 1055
930 string[] lines = respData[key].ToString().Split(new char[] { '\n' }); 1056 string[] lines = respData[key].ToString().Split(new char[] { '\n' });
931 foreach (string line in lines) 1057 foreach (string line in lines)
932 { 1058 {
933 m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0}", line); 1059 m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}", line);
934 } 1060 }
935 1061
936 } 1062 }
937 } 1063 }
938 1064
1065
1066 /// <summary>
1067 /// Group Request Tokens are an attempt to allow the groups service to authenticate
1068 /// requests.
1069 /// TODO: This broke after the big grid refactor, either find a better way, or discard this
1070 /// </summary>
1071 /// <param name="client"></param>
1072 /// <returns></returns>
1073 private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID)
1074 {
1075 UserServiceURL = "";
1076 SessionID = UUID.Zero;
939 1077
940 }
941 1078
942 public class GroupNoticeInfo 1079 // Need to rework this based on changes to User Services
943 { 1080 /*
944 public GroupNoticeData noticeData = new GroupNoticeData(); 1081 UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID);
945 public UUID GroupID = UUID.Zero; 1082 if (userAccount == null)
946 public string Message = string.Empty; 1083 {
947 public byte[] BinaryBucket = new byte[0]; 1084 // This should be impossible. If I've been passed a reference to a client
1085 // that client should be registered with the UserService. So something
1086 // is horribly wrong somewhere.
1087
1088 m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID);
1089
1090 }
1091 else if (userProfile is ForeignUserProfileData)
1092 {
1093 // They aren't from around here
1094 ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
1095 UserServiceURL = fupd.UserServerURI;
1096 SessionID = fupd.CurrentAgent.SessionID;
1097
1098 }
1099 else
1100 {
1101 // They're a local user, use this:
1102 UserServiceURL = m_commManager.NetworkServersInfo.UserURL;
1103 SessionID = userProfile.CurrentAgent.SessionID;
1104 }
1105 */
1106 }
1107
948 } 1108 }
949} 1109}
950 1110
diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Graphics.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Graphics.cs
index 8ea7ad3..a0dc38b 100644
--- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Graphics.cs
+++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Graphics.cs
@@ -49,7 +49,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
49 49
50 public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary) 50 public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary)
51 { 51 {
52 AssetBase asset = new AssetBase(UUID.Random(), "MRMDynamicImage", (sbyte)AssetType.Texture); 52 AssetBase asset = new AssetBase(UUID.Random(), "MRMDynamicImage", (sbyte)AssetType.Texture, m_scene.RegionInfo.RegionID.ToString());
53 asset.Data = OpenJPEG.EncodeFromImage(data, lossless); 53 asset.Data = OpenJPEG.EncodeFromImage(data, lossless);
54 asset.Description = "MRM Image"; 54 asset.Description = "MRM Image";
55 asset.Local = false; 55 asset.Local = false;
diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs
index 5fac189..16cd7e4 100644
--- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs
+++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs
@@ -39,6 +39,6 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
39 { 39 {
40 int Type { get; } 40 int Type { get; }
41 UUID AssetID { get; } 41 UUID AssetID { get; }
42 T RetreiveAsset<T>() where T : Asset, new(); 42 T RetrieveAsset<T>() where T : Asset, new();
43 } 43 }
44} 44}
diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs
index 5bf29d7..bf85cbc 100644
--- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs
+++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs
@@ -39,11 +39,11 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
39 public class InventoryItem : IInventoryItem 39 public class InventoryItem : IInventoryItem
40 { 40 {
41 TaskInventoryItem m_privateItem; 41 TaskInventoryItem m_privateItem;
42 Scene m_rootSceene; 42 Scene m_rootScene;
43 43
44 public InventoryItem(Scene rootScene, TaskInventoryItem internalItem) 44 public InventoryItem(Scene rootScene, TaskInventoryItem internalItem)
45 { 45 {
46 m_rootSceene = rootScene; 46 m_rootScene = rootScene;
47 m_privateItem = internalItem; 47 m_privateItem = internalItem;
48 } 48 }
49 49
@@ -82,9 +82,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
82 public UUID AssetID { get { return m_privateItem.AssetID; } } 82 public UUID AssetID { get { return m_privateItem.AssetID; } }
83 83
84 // This method exposes OpenSim/OpenMetaverse internals and needs to be replaced with a IAsset specific to MRM. 84 // This method exposes OpenSim/OpenMetaverse internals and needs to be replaced with a IAsset specific to MRM.
85 public T RetreiveAsset<T>() where T : OpenMetaverse.Assets.Asset, new() 85 public T RetrieveAsset<T>() where T : OpenMetaverse.Assets.Asset, new()
86 { 86 {
87 AssetBase a = m_rootSceene.AssetService.Get(AssetID.ToString()); 87 AssetBase a = m_rootScene.AssetService.Get(AssetID.ToString());
88 T result = new T(); 88 T result = new T();
89 89
90 if ((sbyte)result.AssetType != a.Type) 90 if ((sbyte)result.AssetType != a.Type)
diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs
index f2adcb7..2ddc31b 100644
--- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs
+++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs
@@ -212,8 +212,8 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
212 if (script.StartsWith("//MRM:C#")) 212 if (script.StartsWith("//MRM:C#"))
213 { 213 {
214 if (m_config.GetBoolean("OwnerOnly", true)) 214 if (m_config.GetBoolean("OwnerOnly", true))
215 if (m_scene.GetSceneObjectPart(localID).OwnerID != m_scene.RegionInfo.MasterAvatarAssignedUUID 215 if (m_scene.GetSceneObjectPart(localID).OwnerID != m_scene.RegionInfo.EstateSettings.EstateOwner
216 || m_scene.GetSceneObjectPart(localID).CreatorID != m_scene.RegionInfo.MasterAvatarAssignedUUID) 216 || m_scene.GetSceneObjectPart(localID).CreatorID != m_scene.RegionInfo.EstateSettings.EstateOwner)
217 return; 217 return;
218 218
219 script = ConvertMRMKeywords(script); 219 script = ConvertMRMKeywords(script);
@@ -280,7 +280,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
280 public void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host) 280 public void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host)
281 { 281 {
282 // UUID should be changed to object owner. 282 // UUID should be changed to object owner.
283 UUID owner = m_scene.RegionInfo.MasterAvatarAssignedUUID; 283 UUID owner = m_scene.RegionInfo.EstateSettings.EstateOwner;
284 SEUser securityUser = new SEUser(owner, "Name Unassigned"); 284 SEUser securityUser = new SEUser(owner, "Name Unassigned");
285 SecurityCredential creds = new SecurityCredential(securityUser, m_scene); 285 SecurityCredential creds = new SecurityCredential(securityUser, m_scene);
286 286
diff --git a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
index 3160cd3..b9a75cc 100644
--- a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
+++ b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
@@ -36,10 +36,11 @@ using Nwc.XmlRpc;
36using Mono.Addins; 36using Mono.Addins;
37using OpenMetaverse; 37using OpenMetaverse;
38using OpenSim.Framework; 38using OpenSim.Framework;
39using OpenSim.Framework.Communications.Cache; 39
40using OpenSim.Framework.Servers.HttpServer; 40using OpenSim.Framework.Servers.HttpServer;
41using OpenSim.Region.Framework.Interfaces; 41using OpenSim.Region.Framework.Interfaces;
42using OpenSim.Region.Framework.Scenes; 42using OpenSim.Region.Framework.Scenes;
43using OpenSim.Services.Interfaces;
43 44
44namespace OpenSim.Region.OptionalModules.World.MoneyModule 45namespace OpenSim.Region.OptionalModules.World.MoneyModule
45{ 46{
@@ -65,7 +66,6 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
65 // private UUID EconomyBaseAccount = UUID.Zero; 66 // private UUID EconomyBaseAccount = UUID.Zero;
66 67
67 private float EnergyEfficiency = 0f; 68 private float EnergyEfficiency = 0f;
68 private bool gridmode = false;
69 // private ObjectPaid handerOnObjectPaid; 69 // private ObjectPaid handerOnObjectPaid;
70 private bool m_enabled = true; 70 private bool m_enabled = true;
71 private bool m_sellEnabled = false; 71 private bool m_sellEnabled = false;
@@ -242,7 +242,6 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
242 { 242 {
243 if (config == "Startup" && startupConfig != null) 243 if (config == "Startup" && startupConfig != null)
244 { 244 {
245 gridmode = startupConfig.GetBoolean("gridmode", false);
246 m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule"); 245 m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule");
247 } 246 }
248 247
@@ -292,18 +291,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
292 291
293 private void GetClientFunds(IClientAPI client) 292 private void GetClientFunds(IClientAPI client)
294 { 293 {
295 // Here we check if we're in grid mode 294 CheckExistAndRefreshFunds(client.AgentId);
296 // I imagine that the 'check balance'
297 // function for the client should be here or shortly after
298
299 if (gridmode)
300 {
301 CheckExistAndRefreshFunds(client.AgentId);
302 }
303 else
304 {
305 CheckExistAndRefreshFunds(client.AgentId);
306 }
307 295
308 } 296 }
309 297
@@ -398,10 +386,10 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
398 { 386 {
399 // try avatar username surname 387 // try avatar username surname
400 Scene scene = GetRandomScene(); 388 Scene scene = GetRandomScene();
401 CachedUserInfo profile = scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); 389 UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agentID);
402 if (profile != null && profile.UserProfile != null) 390 if (account != null)
403 { 391 {
404 string avatarname = profile.UserProfile.FirstName + " " + profile.UserProfile.SurName; 392 string avatarname = account.FirstName + " " + account.LastName;
405 return avatarname; 393 return avatarname;
406 } 394 }
407 else 395 else
diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
index cf2076f..6360c99 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
@@ -189,7 +189,8 @@ namespace OpenSim.Region.OptionalModules.World.NPC
189 public event DeRezObject OnDeRezObject; 189 public event DeRezObject OnDeRezObject;
190 public event Action<IClientAPI> OnRegionHandShakeReply; 190 public event Action<IClientAPI> OnRegionHandShakeReply;
191 public event GenericCall2 OnRequestWearables; 191 public event GenericCall2 OnRequestWearables;
192 public event GenericCall2 OnCompleteMovementToRegion; 192 public event GenericCall1 OnCompleteMovementToRegion;
193 public event UpdateAgent OnPreAgentUpdate;
193 public event UpdateAgent OnAgentUpdate; 194 public event UpdateAgent OnAgentUpdate;
194 public event AgentRequestSit OnAgentRequestSit; 195 public event AgentRequestSit OnAgentRequestSit;
195 public event AgentSit OnAgentSit; 196 public event AgentSit OnAgentSit;
@@ -234,6 +235,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
234 public event Action<UUID> OnRemoveAvatar; 235 public event Action<UUID> OnRemoveAvatar;
235 236
236 public event CreateNewInventoryItem OnCreateNewInventoryItem; 237 public event CreateNewInventoryItem OnCreateNewInventoryItem;
238 public event LinkInventoryItem OnLinkInventoryItem;
237 public event CreateInventoryFolder OnCreateNewInventoryFolder; 239 public event CreateInventoryFolder OnCreateNewInventoryFolder;
238 public event UpdateInventoryFolder OnUpdateInventoryFolder; 240 public event UpdateInventoryFolder OnUpdateInventoryFolder;
239 public event MoveInventoryFolder OnMoveInventoryFolder; 241 public event MoveInventoryFolder OnMoveInventoryFolder;
@@ -457,6 +459,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
457 set { } 459 set { }
458 } 460 }
459 461
462 public bool IsLoggingOut
463 {
464 get { return false; }
465 set { }
466 }
460 public UUID ActiveGroupId 467 public UUID ActiveGroupId
461 { 468 {
462 get { return UUID.Zero; } 469 get { return UUID.Zero; }
@@ -739,7 +746,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
739 746
740 if (OnCompleteMovementToRegion != null) 747 if (OnCompleteMovementToRegion != null)
741 { 748 {
742 OnCompleteMovementToRegion(); 749 OnCompleteMovementToRegion(this);
743 } 750 }
744 } 751 }
745 public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) 752 public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
@@ -1150,5 +1157,13 @@ namespace OpenSim.Region.OptionalModules.World.NPC
1150 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) 1157 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
1151 { 1158 {
1152 } 1159 }
1160
1161 public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
1162 {
1163 }
1164
1165 public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
1166 {
1167 }
1153 } 1168 }
1154} 1169}
diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
index ac39a53..ab0be77 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
@@ -34,6 +34,7 @@ using OpenSim.Region.Framework.Scenes;
34using OpenSim.Region.CoreModules.Avatar.NPC; 34using OpenSim.Region.CoreModules.Avatar.NPC;
35using OpenSim.Framework; 35using OpenSim.Framework;
36using Timer=System.Timers.Timer; 36using Timer=System.Timers.Timer;
37using OpenSim.Services.Interfaces;
37 38
38namespace OpenSim.Region.OptionalModules.World.NPC 39namespace OpenSim.Region.OptionalModules.World.NPC
39{ 40{
@@ -63,11 +64,16 @@ namespace OpenSim.Region.OptionalModules.World.NPC
63 if (m_appearanceCache.ContainsKey(target)) 64 if (m_appearanceCache.ContainsKey(target))
64 return m_appearanceCache[target]; 65 return m_appearanceCache[target];
65 66
66 AvatarAppearance x = scene.CommsManager.AvatarService.GetUserAppearance(target); 67 AvatarData adata = scene.AvatarService.GetAvatar(target);
68 if (adata != null)
69 {
70 AvatarAppearance x = adata.ToAvatarAppearance(target);
67 71
68 m_appearanceCache.Add(target, x); 72 m_appearanceCache.Add(target, x);
69 73
70 return x; 74 return x;
75 }
76 return new AvatarAppearance();
71 } 77 }
72 78
73 public UUID CreateNPC(string firstname, string lastname,Vector3 position, Scene scene, UUID cloneAppearanceFrom) 79 public UUID CreateNPC(string firstname, string lastname,Vector3 position, Scene scene, UUID cloneAppearanceFrom)
@@ -104,7 +110,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
104 if (m_avatars.ContainsKey(agentID)) 110 if (m_avatars.ContainsKey(agentID))
105 { 111 {
106 ScenePresence sp; 112 ScenePresence sp;
107 scene.TryGetAvatar(agentID, out sp); 113 scene.TryGetScenePresence(agentID, out sp);
108 sp.DoAutoPilot(0, pos, m_avatars[agentID]); 114 sp.DoAutoPilot(0, pos, m_avatars[agentID]);
109 } 115 }
110 } 116 }
@@ -159,7 +165,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
159 p_scene.AddNewClient(npcAvatar); 165 p_scene.AddNewClient(npcAvatar);
160 166
161 ScenePresence sp; 167 ScenePresence sp;
162 if (p_scene.TryGetAvatar(npcAvatar.AgentId, out sp)) 168 if (p_scene.TryGetScenePresence(npcAvatar.AgentId, out sp))
163 { 169 {
164 AvatarAppearance x = GetAppearance(p_cloneAppearanceFrom, p_scene); 170 AvatarAppearance x = GetAppearance(p_cloneAppearanceFrom, p_scene);
165 171
diff --git a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
index c8e6e4b..3ed338b 100644
--- a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
+++ b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
@@ -306,8 +306,6 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
306 306
307 m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename); 307 m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
308 UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; 308 UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
309 if (uuid == UUID.Zero)
310 uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
311 309
312 foreach (Copse copse in m_copse) 310 foreach (Copse copse in m_copse)
313 { 311 {
@@ -760,8 +758,6 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
760 Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range) 758 Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
761 { 759 {
762 UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; 760 UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
763 if (uuid == UUID.Zero)
764 uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
765 761
766 CreateTree(uuid, copse, position); 762 CreateTree(uuid, copse, position);
767 } 763 }
diff --git a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETCharacter.cs b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETCharacter.cs
index 198962b..f13c323 100644
--- a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETCharacter.cs
+++ b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETCharacter.cs
@@ -108,12 +108,11 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
108 private bool[] m_colliderarr = new bool[11]; 108 private bool[] m_colliderarr = new bool[11];
109 private bool[] m_colliderGroundarr = new bool[11]; 109 private bool[] m_colliderGroundarr = new bool[11];
110 110
111
112
113 private BulletDotNETScene m_parent_scene; 111 private BulletDotNETScene m_parent_scene;
114 112
115 public int m_eventsubscription = 0; 113 public int m_eventsubscription = 0;
116 // private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate(); 114 private CollisionEventUpdate CollisionEventsThisFrame = null;
115 private int m_requestedUpdateFrequency = 0;
117 116
118 public BulletDotNETCharacter(string avName, BulletDotNETScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor) 117 public BulletDotNETCharacter(string avName, BulletDotNETScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
119 { 118 {
@@ -212,7 +211,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
212 m_mass = Mass; 211 m_mass = Mass;
213 212
214 Body = new btRigidBody(m_mass, m_bodyMotionState, Shell); 213 Body = new btRigidBody(m_mass, m_bodyMotionState, Shell);
215 Body.setUserPointer(new IntPtr((int)Body.Handle)); 214 // this is used for self identification. User localID instead of body handle
215 Body.setUserPointer(new IntPtr((int)m_localID));
216 216
217 if (ClosestCastResult != null) 217 if (ClosestCastResult != null)
218 ClosestCastResult.Dispose(); 218 ClosestCastResult.Dispose();
@@ -716,6 +716,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
716 public override void SubscribeEvents(int ms) 716 public override void SubscribeEvents(int ms)
717 { 717 {
718 m_eventsubscription = ms; 718 m_eventsubscription = ms;
719 m_requestedUpdateFrequency = ms;
719 m_parent_scene.addCollisionEventReporting(this); 720 m_parent_scene.addCollisionEventReporting(this);
720 } 721 }
721 722
@@ -723,6 +724,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
723 { 724 {
724 m_parent_scene.remCollisionEventReporting(this); 725 m_parent_scene.remCollisionEventReporting(this);
725 m_eventsubscription = 0; 726 m_eventsubscription = 0;
727 m_requestedUpdateFrequency = 0;
726 } 728 }
727 729
728 public override bool SubscribedEvents() 730 public override bool SubscribedEvents()
@@ -732,6 +734,29 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
732 return false; 734 return false;
733 } 735 }
734 736
737 public void AddCollision(uint collideWith, ContactPoint contact)
738 {
739 if (CollisionEventsThisFrame == null)
740 {
741 CollisionEventsThisFrame = new CollisionEventUpdate();
742 }
743 CollisionEventsThisFrame.addCollider(collideWith, contact);
744 }
745
746 public void SendCollisions()
747 {
748 if (m_eventsubscription >= m_requestedUpdateFrequency)
749 {
750 if (CollisionEventsThisFrame != null)
751 {
752 base.SendCollisionUpdate(CollisionEventsThisFrame);
753 }
754 CollisionEventsThisFrame = new CollisionEventUpdate();
755 m_eventsubscription = 0;
756 }
757 return;
758 }
759
735 internal void Dispose() 760 internal void Dispose()
736 { 761 {
737 if (Body.isInWorld()) 762 if (Body.isInWorld())
diff --git a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETPrim.cs b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETPrim.cs
index 920ed96..dc3229a 100644
--- a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETPrim.cs
+++ b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETPrim.cs
@@ -154,7 +154,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
154 private Vector3 _target_velocity; 154 private Vector3 _target_velocity;
155 155
156 public int m_eventsubscription; 156 public int m_eventsubscription;
157 // private CollisionEventUpdate CollisionEventsThisFrame = null; 157 private int m_requestedUpdateFrequency = 0;
158 private CollisionEventUpdate CollisionEventsThisFrame = null;
158 159
159 public volatile bool childPrim; 160 public volatile bool childPrim;
160 161
@@ -595,6 +596,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
595 public override void SubscribeEvents(int ms) 596 public override void SubscribeEvents(int ms)
596 { 597 {
597 m_eventsubscription = ms; 598 m_eventsubscription = ms;
599 m_requestedUpdateFrequency = ms;
598 _parent_scene.addCollisionEventReporting(this); 600 _parent_scene.addCollisionEventReporting(this);
599 } 601 }
600 602
@@ -602,6 +604,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
602 { 604 {
603 _parent_scene.remCollisionEventReporting(this); 605 _parent_scene.remCollisionEventReporting(this);
604 m_eventsubscription = 0; 606 m_eventsubscription = 0;
607 m_requestedUpdateFrequency = 0;
605 } 608 }
606 609
607 public override bool SubscribedEvents() 610 public override bool SubscribedEvents()
@@ -611,7 +614,28 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
611 614
612 #endregion 615 #endregion
613 616
617 public void AddCollision(uint collideWith, ContactPoint contact)
618 {
619 if (CollisionEventsThisFrame == null)
620 {
621 CollisionEventsThisFrame = new CollisionEventUpdate();
622 }
623 CollisionEventsThisFrame.addCollider(collideWith, contact);
624 }
614 625
626 public void SendCollisions()
627 {
628 if (m_eventsubscription >= m_requestedUpdateFrequency)
629 {
630 if (CollisionEventsThisFrame != null)
631 {
632 base.SendCollisionUpdate(CollisionEventsThisFrame);
633 }
634 CollisionEventsThisFrame = null;
635 // m_eventsubscription = 0;
636 }
637 return;
638 }
615 639
616 internal void Dispose() 640 internal void Dispose()
617 { 641 {
@@ -759,7 +783,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
759 { 783 {
760 if (m_taintadd) 784 if (m_taintadd)
761 { 785 {
762 m_log.Debug("[PHYSICS]: TaintAdd"); 786 // m_log.Debug("[PHYSICS]: TaintAdd");
763 changeadd(timestep); 787 changeadd(timestep);
764 } 788 }
765 789
@@ -771,7 +795,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
771 SetBody(Mass); 795 SetBody(Mass);
772 else 796 else
773 SetBody(0); 797 SetBody(0);
774 m_log.Debug("[PHYSICS]: GEOM_DOESNT_EXSIT"); 798 // m_log.Debug("[PHYSICS]: GEOM_DOESNT_EXSIT");
775 } 799 }
776 800
777 if (prim_geom.Handle == IntPtr.Zero) 801 if (prim_geom.Handle == IntPtr.Zero)
@@ -782,31 +806,31 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
782 SetBody(Mass); 806 SetBody(Mass);
783 else 807 else
784 SetBody(0); 808 SetBody(0);
785 m_log.Debug("[PHYSICS]: GEOM_DOESNT_EXSIT"); 809 // m_log.Debug("[PHYSICS]: GEOM_DOESNT_EXSIT");
786 810
787 } 811 }
788 812
789 if (!_position.ApproxEquals(m_taintposition, 0f)) 813 if (!_position.ApproxEquals(m_taintposition, 0f))
790 { 814 {
791 m_log.Debug("[PHYSICS]: TaintMove"); 815 // m_log.Debug("[PHYSICS]: TaintMove");
792 changemove(timestep); 816 changemove(timestep);
793 } 817 }
794 if (m_taintrot != _orientation) 818 if (m_taintrot != _orientation)
795 { 819 {
796 m_log.Debug("[PHYSICS]: TaintRotate"); 820 // m_log.Debug("[PHYSICS]: TaintRotate");
797 rotate(timestep); 821 rotate(timestep);
798 } // 822 } //
799 823
800 if (m_taintPhysics != m_isphysical && !(m_taintparent != _parent)) 824 if (m_taintPhysics != m_isphysical && !(m_taintparent != _parent))
801 { 825 {
802 m_log.Debug("[PHYSICS]: TaintPhysics"); 826 // m_log.Debug("[PHYSICS]: TaintPhysics");
803 changePhysicsStatus(timestep); 827 changePhysicsStatus(timestep);
804 } 828 }
805 // 829 //
806 830
807 if (!_size.ApproxEquals(m_taintsize, 0f)) 831 if (!_size.ApproxEquals(m_taintsize, 0f))
808 { 832 {
809 m_log.Debug("[PHYSICS]: TaintSize"); 833 // m_log.Debug("[PHYSICS]: TaintSize");
810 changesize(timestep); 834 changesize(timestep);
811 } 835 }
812 836
@@ -814,43 +838,43 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
814 838
815 if (m_taintshape) 839 if (m_taintshape)
816 { 840 {
817 m_log.Debug("[PHYSICS]: TaintShape"); 841 // m_log.Debug("[PHYSICS]: TaintShape");
818 changeshape(timestep); 842 changeshape(timestep);
819 } // 843 } //
820 844
821 if (m_taintforce) 845 if (m_taintforce)
822 { 846 {
823 m_log.Debug("[PHYSICS]: TaintForce"); 847 // m_log.Debug("[PHYSICS]: TaintForce");
824 changeAddForce(timestep); 848 changeAddForce(timestep);
825 } 849 }
826 if (m_taintaddangularforce) 850 if (m_taintaddangularforce)
827 { 851 {
828 m_log.Debug("[PHYSICS]: TaintAngularForce"); 852 // m_log.Debug("[PHYSICS]: TaintAngularForce");
829 changeAddAngularForce(timestep); 853 changeAddAngularForce(timestep);
830 } 854 }
831 if (!m_taintTorque.ApproxEquals(Vector3.Zero, 0.001f)) 855 if (!m_taintTorque.ApproxEquals(Vector3.Zero, 0.001f))
832 { 856 {
833 m_log.Debug("[PHYSICS]: TaintTorque"); 857 // m_log.Debug("[PHYSICS]: TaintTorque");
834 changeSetTorque(timestep); 858 changeSetTorque(timestep);
835 } 859 }
836 if (m_taintdisable) 860 if (m_taintdisable)
837 { 861 {
838 m_log.Debug("[PHYSICS]: TaintDisable"); 862 // m_log.Debug("[PHYSICS]: TaintDisable");
839 changedisable(timestep); 863 changedisable(timestep);
840 } 864 }
841 if (m_taintselected != m_isSelected) 865 if (m_taintselected != m_isSelected)
842 { 866 {
843 m_log.Debug("[PHYSICS]: TaintSelected"); 867 // m_log.Debug("[PHYSICS]: TaintSelected");
844 changeSelectedStatus(timestep); 868 changeSelectedStatus(timestep);
845 } 869 }
846 if (!m_taintVelocity.ApproxEquals(Vector3.Zero, 0.001f)) 870 if (!m_taintVelocity.ApproxEquals(Vector3.Zero, 0.001f))
847 { 871 {
848 m_log.Debug("[PHYSICS]: TaintVelocity"); 872 // m_log.Debug("[PHYSICS]: TaintVelocity");
849 changevelocity(timestep); 873 changevelocity(timestep);
850 } 874 }
851 if (m_taintparent != _parent) 875 if (m_taintparent != _parent)
852 { 876 {
853 m_log.Debug("[PHYSICS]: TaintLink"); 877 // m_log.Debug("[PHYSICS]: TaintLink");
854 changelink(timestep); 878 changelink(timestep);
855 } 879 }
856 if (m_taintCollidesWater != m_collidesWater) 880 if (m_taintCollidesWater != m_collidesWater)
@@ -859,7 +883,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
859 } 883 }
860 if (!m_angularlock.ApproxEquals(m_taintAngularLock, 0)) 884 if (!m_angularlock.ApproxEquals(m_taintAngularLock, 0))
861 { 885 {
862 m_log.Debug("[PHYSICS]: TaintAngularLock"); 886 // m_log.Debug("[PHYSICS]: TaintAngularLock");
863 changeAngularLock(timestep); 887 changeAngularLock(timestep);
864 } 888 }
865 if (m_taintremove) 889 if (m_taintremove)
@@ -917,7 +941,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
917 private void changemove(float timestep) 941 private void changemove(float timestep)
918 { 942 {
919 943
920 m_log.Debug("[PHYSICS]: _________ChangeMove"); 944 // m_log.Debug("[PHYSICS]: _________ChangeMove");
921 if (!m_isphysical) 945 if (!m_isphysical)
922 { 946 {
923 tempTransform2 = Body.getWorldTransform(); 947 tempTransform2 = Body.getWorldTransform();
@@ -977,7 +1001,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
977 1001
978 private void rotate(float timestep) 1002 private void rotate(float timestep)
979 { 1003 {
980 m_log.Debug("[PHYSICS]: _________ChangeRotate"); 1004 // m_log.Debug("[PHYSICS]: _________ChangeRotate");
981 tempTransform2 = Body.getWorldTransform(); 1005 tempTransform2 = Body.getWorldTransform();
982 tempOrientation2 = new btQuaternion(_orientation.X, _orientation.Y, _orientation.Z, _orientation.W); 1006 tempOrientation2 = new btQuaternion(_orientation.X, _orientation.Y, _orientation.Z, _orientation.W);
983 tempTransform2.setRotation(tempOrientation2); 1007 tempTransform2.setRotation(tempOrientation2);
@@ -1000,7 +1024,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1000 //Body = null; 1024 //Body = null;
1001 // TODO: dispose parts that make up body 1025 // TODO: dispose parts that make up body
1002 } 1026 }
1003 m_log.Debug("[PHYSICS]: _________ChangePhysics"); 1027 // m_log.Debug("[PHYSICS]: _________ChangePhysics");
1004 1028
1005 ProcessGeomCreation(); 1029 ProcessGeomCreation();
1006 1030
@@ -1092,7 +1116,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1092 // TODO: dispose parts that make up body 1116 // TODO: dispose parts that make up body
1093 } 1117 }
1094 1118
1095 m_log.Debug("[PHYSICS]: _________ChangeSize"); 1119 // m_log.Debug("[PHYSICS]: _________ChangeSize");
1096 SetCollisionShape(null); 1120 SetCollisionShape(null);
1097 // Construction of new prim 1121 // Construction of new prim
1098 ProcessGeomCreation(); 1122 ProcessGeomCreation();
@@ -1297,13 +1321,13 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1297 // TODO: throw new NotImplementedException(); 1321 // TODO: throw new NotImplementedException();
1298 if (m_taintselected) 1322 if (m_taintselected)
1299 { 1323 {
1300 Body.setCollisionFlags((int)ContactFlags.CF_NO_CONTACT_RESPONSE); 1324 // Body.setCollisionFlags((int)ContactFlags.CF_NO_CONTACT_RESPONSE);
1301 disableBodySoft(); 1325 disableBodySoft();
1302 1326
1303 } 1327 }
1304 else 1328 else
1305 { 1329 {
1306 Body.setCollisionFlags(0 | (int)ContactFlags.CF_CUSTOM_MATERIAL_CALLBACK); 1330 // Body.setCollisionFlags(0 | (int)ContactFlags.CF_CUSTOM_MATERIAL_CALLBACK);
1307 enableBodySoft(); 1331 enableBodySoft();
1308 } 1332 }
1309 m_isSelected = m_taintselected; 1333 m_isSelected = m_taintselected;
@@ -1605,6 +1629,11 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1605 enableBodySoft(); 1629 enableBodySoft();
1606 } 1630 }
1607 */ 1631 */
1632 if (!Body.isActive())
1633 {
1634 Body.clearForces();
1635 enableBodySoft();
1636 }
1608 // 35x10 = 350n times the mass per second applied maximum. 1637 // 35x10 = 350n times the mass per second applied maximum.
1609 1638
1610 float nmax = 35f * m_mass; 1639 float nmax = 35f * m_mass;
@@ -1632,6 +1661,12 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1632 Body.applyCentralImpulse(tempAddForce); 1661 Body.applyCentralImpulse(tempAddForce);
1633 } 1662 }
1634 } 1663 }
1664 else
1665 {
1666 // if no forces on the prim, make sure everything is zero
1667 Body.clearForces();
1668 enableBodySoft();
1669 }
1635 } 1670 }
1636 else 1671 else
1637 { 1672 {
@@ -1985,7 +2020,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
1985 2020
1986 public void CreateGeom(IntPtr m_targetSpace, IMesh p_mesh) 2021 public void CreateGeom(IntPtr m_targetSpace, IMesh p_mesh)
1987 { 2022 {
1988 m_log.Debug("[PHYSICS]: _________CreateGeom"); 2023 // m_log.Debug("[PHYSICS]: _________CreateGeom");
1989 if (p_mesh != null) 2024 if (p_mesh != null)
1990 { 2025 {
1991 //_mesh = _parent_scene.mesher.CreateMesh(m_primName, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical); 2026 //_mesh = _parent_scene.mesher.CreateMesh(m_primName, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical);
@@ -2042,7 +2077,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
2042 // TODO: Set Collision Body Mesh 2077 // TODO: Set Collision Body Mesh
2043 // This sleeper is there to moderate how long it takes between 2078 // This sleeper is there to moderate how long it takes between
2044 // setting up the mesh and pre-processing it when we get rapid fire mesh requests on a single object 2079 // setting up the mesh and pre-processing it when we get rapid fire mesh requests on a single object
2045 m_log.Debug("_________SetMesh"); 2080 // m_log.Debug("_________SetMesh");
2046 Thread.Sleep(10); 2081 Thread.Sleep(10);
2047 2082
2048 //Kill Body so that mesh can re-make the geom 2083 //Kill Body so that mesh can re-make the geom
@@ -2159,7 +2194,14 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
2159 2194
2160 // Body = new btRigidBody(mass, tempMotionState1, prim_geom); 2195 // Body = new btRigidBody(mass, tempMotionState1, prim_geom);
2161 //else 2196 //else
2162 Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1); 2197 // Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1);
2198 if (Body == null)
2199 {
2200 Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1);
2201 // add localID so we can later map bullet object back to OpenSim object
2202 Body.setUserPointer(new IntPtr((int)m_localID));
2203 }
2204
2163 2205
2164 if (prim_geom is btGImpactMeshShape) 2206 if (prim_geom is btGImpactMeshShape)
2165 { 2207 {
@@ -2250,7 +2292,13 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
2250 2292
2251 // Body = new btRigidBody(mass, tempMotionState1, prim_geom); 2293 // Body = new btRigidBody(mass, tempMotionState1, prim_geom);
2252 //else 2294 //else
2253 Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1); 2295 // Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1);
2296 if (Body == null)
2297 {
2298 Body = new btRigidBody(mass, tempMotionState1, prim_geom, tempInertia1);
2299 // each body has the localID stored into it so we can identify collision objects
2300 Body.setUserPointer(new IntPtr((int)m_localID));
2301 }
2254 2302
2255 if (prim_geom is btGImpactMeshShape) 2303 if (prim_geom is btGImpactMeshShape)
2256 { 2304 {
diff --git a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs
index 9e048ab..85e34c1 100644
--- a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs
+++ b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs
@@ -47,7 +47,9 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
47 // private string m_sceneIdentifier = string.Empty; 47 // private string m_sceneIdentifier = string.Empty;
48 48
49 private List<BulletDotNETCharacter> m_characters = new List<BulletDotNETCharacter>(); 49 private List<BulletDotNETCharacter> m_characters = new List<BulletDotNETCharacter>();
50 private Dictionary<uint, BulletDotNETCharacter> m_charactersLocalID = new Dictionary<uint, BulletDotNETCharacter>();
50 private List<BulletDotNETPrim> m_prims = new List<BulletDotNETPrim>(); 51 private List<BulletDotNETPrim> m_prims = new List<BulletDotNETPrim>();
52 private Dictionary<uint, BulletDotNETPrim> m_primsLocalID = new Dictionary<uint, BulletDotNETPrim>();
51 private List<BulletDotNETPrim> m_activePrims = new List<BulletDotNETPrim>(); 53 private List<BulletDotNETPrim> m_activePrims = new List<BulletDotNETPrim>();
52 private List<PhysicsActor> m_taintedActors = new List<PhysicsActor>(); 54 private List<PhysicsActor> m_taintedActors = new List<PhysicsActor>();
53 private btDiscreteDynamicsWorld m_world; 55 private btDiscreteDynamicsWorld m_world;
@@ -134,7 +136,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
134 m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); 136 m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
135 m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); 137 m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
136 m_world.setGravity(m_gravity); 138 m_world.setGravity(m_gravity);
137 //EnableCollisionInterface(); 139 EnableCollisionInterface();
138 140
139 141
140 } 142 }
@@ -145,7 +147,16 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
145 avCapRadius, avStandupTensor, avDensity, 147 avCapRadius, avStandupTensor, avDensity,
146 avHeightFudgeFactor, avMovementDivisorWalk, 148 avHeightFudgeFactor, avMovementDivisorWalk,
147 avMovementDivisorRun); 149 avMovementDivisorRun);
148 m_characters.Add(chr); 150 try
151 {
152 m_characters.Add(chr);
153 m_charactersLocalID.Add(chr.m_localID, chr);
154 }
155 catch
156 {
157 // noop if it's already there
158 m_log.Debug("[PHYSICS] BulletDotNet: adding duplicate avatar localID");
159 }
149 AddPhysicsActorTaint(chr); 160 AddPhysicsActorTaint(chr);
150 return chr; 161 return chr;
151 } 162 }
@@ -154,6 +165,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
154 { 165 {
155 BulletDotNETCharacter chr = (BulletDotNETCharacter) actor; 166 BulletDotNETCharacter chr = (BulletDotNETCharacter) actor;
156 167
168 m_charactersLocalID.Remove(chr.m_localID);
157 m_characters.Remove(chr); 169 m_characters.Remove(chr);
158 m_world.removeRigidBody(chr.Body); 170 m_world.removeRigidBody(chr.Body);
159 m_world.removeCollisionObject(chr.Body); 171 m_world.removeCollisionObject(chr.Body);
@@ -279,7 +291,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
279 prim.Move(timeStep); 291 prim.Move(timeStep);
280 } 292 }
281 } 293 }
282 float steps = m_world.stepSimulation(timeStep * 1000, 10, WorldTimeComp); 294 float steps = m_world.stepSimulation(timeStep, 10, WorldTimeComp);
283 295
284 foreach (BulletDotNETCharacter chr in m_characters) 296 foreach (BulletDotNETCharacter chr in m_characters)
285 { 297 {
@@ -296,20 +308,67 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
296 } 308 }
297 if (m_CollisionInterface != null) 309 if (m_CollisionInterface != null)
298 { 310 {
299 List<int> collisions = m_CollisionInterface.GetContactList(); 311 List<BulletDotNETPrim> primsWithCollisions = new List<BulletDotNETPrim>();
300 lock (collisions) 312 List<BulletDotNETCharacter> charactersWithCollisions = new List<BulletDotNETCharacter>();
313
314 // get the collisions that happened this tick
315 List<BulletDotNET.ContactAddedCallbackHandler.ContactInfo> collisions = m_CollisionInterface.GetContactList();
316 // passed back the localID of the prim so we can associate the prim
317 foreach (BulletDotNET.ContactAddedCallbackHandler.ContactInfo ci in collisions)
301 { 318 {
302 foreach (int pvalue in collisions) 319 // ContactPoint = { contactPoint, contactNormal, penetrationDepth }
303 { 320 ContactPoint contact = new ContactPoint(new Vector3(ci.pX, ci.pY, ci.pZ),
304 System.Console.Write(string.Format("{0} ", pvalue)); 321 new Vector3(ci.nX, ci.nY, ci.nZ), ci.depth);
305 } 322
323 ProcessContact(ci.contact, ci.contactWith, contact, ref primsWithCollisions, ref charactersWithCollisions);
324 ProcessContact(ci.contactWith, ci.contact, contact, ref primsWithCollisions, ref charactersWithCollisions);
325
306 } 326 }
307 m_CollisionInterface.Clear(); 327 m_CollisionInterface.Clear();
308 328 // for those prims and characters that had collisions cause collision events
329 foreach (BulletDotNETPrim bdnp in primsWithCollisions)
330 {
331 bdnp.SendCollisions();
332 }
333 foreach (BulletDotNETCharacter bdnc in charactersWithCollisions)
334 {
335 bdnc.SendCollisions();
336 }
309 } 337 }
310 return steps; 338 return steps;
311 } 339 }
312 340
341 private void ProcessContact(uint cont, uint contWith, ContactPoint contact,
342 ref List<BulletDotNETPrim> primsWithCollisions,
343 ref List<BulletDotNETCharacter> charactersWithCollisions)
344 {
345 BulletDotNETPrim bdnp;
346 // collisions with a normal prim?
347 if (m_primsLocalID.TryGetValue(cont, out bdnp))
348 {
349 // Added collision event to the prim. This creates a pile of events
350 // that will be sent to any subscribed listeners.
351 bdnp.AddCollision(contWith, contact);
352 if (!primsWithCollisions.Contains(bdnp))
353 {
354 primsWithCollisions.Add(bdnp);
355 }
356 }
357 else
358 {
359 BulletDotNETCharacter bdnc;
360 // if not a prim, maybe it's one of the characters
361 if (m_charactersLocalID.TryGetValue(cont, out bdnc))
362 {
363 bdnc.AddCollision(contWith, contact);
364 if (!charactersWithCollisions.Contains(bdnc))
365 {
366 charactersWithCollisions.Add(bdnc);
367 }
368 }
369 }
370 }
371
313 public override void GetResults() 372 public override void GetResults()
314 { 373 {
315 374
@@ -387,6 +446,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
387 m_terrainTransform = new btTransform(QuatIdentity, m_terrainPosition); 446 m_terrainTransform = new btTransform(QuatIdentity, m_terrainPosition);
388 m_terrainMotionState = new btDefaultMotionState(m_terrainTransform); 447 m_terrainMotionState = new btDefaultMotionState(m_terrainTransform);
389 TerrainBody = new btRigidBody(0, m_terrainMotionState, m_terrainShape); 448 TerrainBody = new btRigidBody(0, m_terrainMotionState, m_terrainShape);
449 TerrainBody.setUserPointer((IntPtr)0);
390 m_world.addRigidBody(TerrainBody); 450 m_world.addRigidBody(TerrainBody);
391 451
392 452
@@ -459,6 +519,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
459 { 519 {
460 lock (m_prims) 520 lock (m_prims)
461 { 521 {
522 m_primsLocalID.Clear();
462 foreach (BulletDotNETPrim prim in m_prims) 523 foreach (BulletDotNETPrim prim in m_prims)
463 { 524 {
464 if (prim.Body != null) 525 if (prim.Body != null)
@@ -513,6 +574,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
513 m_world.removeRigidBody(body); 574 m_world.removeRigidBody(body);
514 } 575 }
515 remActivePrim(prm); 576 remActivePrim(prm);
577 m_primsLocalID.Remove(prm.m_localID);
516 m_prims.Remove(prm); 578 m_prims.Remove(prm);
517 } 579 }
518 580
@@ -686,9 +748,18 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
686 { 748 {
687 if (!m_prims.Contains(pPrim)) 749 if (!m_prims.Contains(pPrim))
688 { 750 {
689 m_prims.Add(pPrim); 751 try
752 {
753 m_prims.Add(pPrim);
754 m_primsLocalID.Add(pPrim.m_localID, pPrim);
755 }
756 catch
757 {
758 // noop if it's already there
759 m_log.Debug("[PHYSICS] BulletDotNet: adding duplicate prim localID");
760 }
690 m_world.addRigidBody(pPrim.Body); 761 m_world.addRigidBody(pPrim.Body);
691 m_log.Debug("ADDED"); 762 // m_log.Debug("[PHYSICS] added prim to scene");
692 } 763 }
693 } 764 }
694 } 765 }
@@ -696,8 +767,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
696 { 767 {
697 if (m_CollisionInterface == null) 768 if (m_CollisionInterface == null)
698 { 769 {
699 m_CollisionInterface = new ContactAddedCallbackHandler(); 770 m_CollisionInterface = new ContactAddedCallbackHandler(m_world);
700 m_world.SetCollisionAddedCallback(m_CollisionInterface); 771 // m_world.SetCollisionAddedCallback(m_CollisionInterface);
701 } 772 }
702 } 773 }
703 774
diff --git a/OpenSim/Region/Physics/Meshing/PrimMesher.cs b/OpenSim/Region/Physics/Meshing/PrimMesher.cs
index 2a213c3..53022ad 100644
--- a/OpenSim/Region/Physics/Meshing/PrimMesher.cs
+++ b/OpenSim/Region/Physics/Meshing/PrimMesher.cs
@@ -257,7 +257,6 @@ namespace PrimMesher
257 public int uv2; 257 public int uv2;
258 public int uv3; 258 public int uv3;
259 259
260
261 public Face(int v1, int v2, int v3) 260 public Face(int v1, int v2, int v3)
262 { 261 {
263 primFace = 0; 262 primFace = 0;
@@ -630,6 +629,9 @@ namespace PrimMesher
630 internal int numOuterVerts = 0; 629 internal int numOuterVerts = 0;
631 internal int numHollowVerts = 0; 630 internal int numHollowVerts = 0;
632 631
632 internal int outerFaceNumber = -1;
633 internal int hollowFaceNumber = -1;
634
633 internal bool calcVertexNormals = false; 635 internal bool calcVertexNormals = false;
634 internal int bottomFaceNumber = 0; 636 internal int bottomFaceNumber = 0;
635 internal int numPrimFaces = 0; 637 internal int numPrimFaces = 0;
@@ -827,15 +829,16 @@ namespace PrimMesher
827 829
828 if (createFaces) 830 if (createFaces)
829 { 831 {
830 int numOuterVerts = this.coords.Count; 832 //int numOuterVerts = this.coords.Count;
831 int numHollowVerts = hollowCoords.Count; 833 //numOuterVerts = this.coords.Count;
832 int numTotalVerts = numOuterVerts + numHollowVerts; 834 //int numHollowVerts = hollowCoords.Count;
835 int numTotalVerts = this.numOuterVerts + this.numHollowVerts;
833 836
834 if (numOuterVerts == numHollowVerts) 837 if (this.numOuterVerts == this.numHollowVerts)
835 { 838 {
836 Face newFace = new Face(); 839 Face newFace = new Face();
837 840
838 for (int coordIndex = 0; coordIndex < numOuterVerts - 1; coordIndex++) 841 for (int coordIndex = 0; coordIndex < this.numOuterVerts - 1; coordIndex++)
839 { 842 {
840 newFace.v1 = coordIndex; 843 newFace.v1 = coordIndex;
841 newFace.v2 = coordIndex + 1; 844 newFace.v2 = coordIndex + 1;
@@ -850,12 +853,12 @@ namespace PrimMesher
850 } 853 }
851 else 854 else
852 { 855 {
853 if (numOuterVerts < numHollowVerts) 856 if (this.numOuterVerts < this.numHollowVerts)
854 { 857 {
855 Face newFace = new Face(); 858 Face newFace = new Face();
856 int j = 0; // j is the index for outer vertices 859 int j = 0; // j is the index for outer vertices
857 int maxJ = numOuterVerts - 1; 860 int maxJ = this.numOuterVerts - 1;
858 for (int i = 0; i < numHollowVerts; i++) // i is the index for inner vertices 861 for (int i = 0; i < this.numHollowVerts; i++) // i is the index for inner vertices
859 { 862 {
860 if (j < maxJ) 863 if (j < maxJ)
861 if (angles.angles[j + 1].angle - hollowAngles.angles[i].angle < hollowAngles.angles[i].angle - angles.angles[j].angle + 0.000001f) 864 if (angles.angles[j + 1].angle - hollowAngles.angles[i].angle < hollowAngles.angles[i].angle - angles.angles[j].angle + 0.000001f)
@@ -879,8 +882,8 @@ namespace PrimMesher
879 { 882 {
880 Face newFace = new Face(); 883 Face newFace = new Face();
881 int j = 0; // j is the index for inner vertices 884 int j = 0; // j is the index for inner vertices
882 int maxJ = numHollowVerts - 1; 885 int maxJ = this.numHollowVerts - 1;
883 for (int i = 0; i < numOuterVerts; i++) 886 for (int i = 0; i < this.numOuterVerts; i++)
884 { 887 {
885 if (j < maxJ) 888 if (j < maxJ)
886 if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f) 889 if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f)
@@ -935,10 +938,10 @@ namespace PrimMesher
935 938
936 if (calcVertexNormals && hasProfileCut) 939 if (calcVertexNormals && hasProfileCut)
937 { 940 {
941 int lastOuterVertIndex = this.numOuterVerts - 1;
942
938 if (hasHollow) 943 if (hasHollow)
939 { 944 {
940 int lastOuterVertIndex = this.numOuterVerts - 1;
941
942 this.cut1CoordIndices.Add(0); 945 this.cut1CoordIndices.Add(0);
943 this.cut1CoordIndices.Add(this.coords.Count - 1); 946 this.cut1CoordIndices.Add(this.coords.Count - 1);
944 947
@@ -954,6 +957,12 @@ namespace PrimMesher
954 957
955 else 958 else
956 { 959 {
960 this.cut1CoordIndices.Add(0);
961 this.cut1CoordIndices.Add(1);
962
963 this.cut2CoordIndices.Add(lastOuterVertIndex);
964 this.cut2CoordIndices.Add(0);
965
957 this.cutNormal1.X = this.vertexNormals[1].Y; 966 this.cutNormal1.X = this.vertexNormals[1].Y;
958 this.cutNormal1.Y = -this.vertexNormals[1].X; 967 this.cutNormal1.Y = -this.vertexNormals[1].X;
959 968
@@ -978,11 +987,14 @@ namespace PrimMesher
978 // I know it's ugly but so is the whole concept of prim face numbers 987 // I know it's ugly but so is the whole concept of prim face numbers
979 988
980 int faceNum = 1; // start with outer faces 989 int faceNum = 1; // start with outer faces
990 this.outerFaceNumber = faceNum;
991
981 int startVert = hasProfileCut && !hasHollow ? 1 : 0; 992 int startVert = hasProfileCut && !hasHollow ? 1 : 0;
982 if (startVert > 0) 993 if (startVert > 0)
983 this.faceNumbers.Add(-1); 994 this.faceNumbers.Add(-1);
984 for (int i = 0; i < numOuterVerts - 1; i++) 995 for (int i = 0; i < this.numOuterVerts - 1; i++)
985 this.faceNumbers.Add(sides < 5 ? faceNum++ : faceNum); 996 //this.faceNumbers.Add(sides < 5 ? faceNum++ : faceNum);
997 this.faceNumbers.Add(sides < 5 && i < sides ? faceNum++ : faceNum);
986 998
987 //if (!hasHollow && !hasProfileCut) 999 //if (!hasHollow && !hasProfileCut)
988 // this.bottomFaceNumber = faceNum++; 1000 // this.bottomFaceNumber = faceNum++;
@@ -992,12 +1004,15 @@ namespace PrimMesher
992 if (sides > 4 && (hasHollow || hasProfileCut)) 1004 if (sides > 4 && (hasHollow || hasProfileCut))
993 faceNum++; 1005 faceNum++;
994 1006
1007 if (sides < 5 && (hasHollow || hasProfileCut) && this.numOuterVerts < sides)
1008 faceNum++;
1009
995 if (hasHollow) 1010 if (hasHollow)
996 { 1011 {
997 for (int i = 0; i < numHollowVerts; i++) 1012 for (int i = 0; i < this.numHollowVerts; i++)
998 this.faceNumbers.Add(faceNum); 1013 this.faceNumbers.Add(faceNum);
999 1014
1000 faceNum++; 1015 this.hollowFaceNumber = faceNum++;
1001 } 1016 }
1002 //if (hasProfileCut || hasHollow) 1017 //if (hasProfileCut || hasHollow)
1003 // this.bottomFaceNumber = faceNum++; 1018 // this.bottomFaceNumber = faceNum++;
@@ -1005,11 +1020,11 @@ namespace PrimMesher
1005 1020
1006 if (hasHollow && hasProfileCut) 1021 if (hasHollow && hasProfileCut)
1007 this.faceNumbers.Add(faceNum++); 1022 this.faceNumbers.Add(faceNum++);
1023
1008 for (int i = 0; i < this.faceNumbers.Count; i++) 1024 for (int i = 0; i < this.faceNumbers.Count; i++)
1009 if (this.faceNumbers[i] == -1) 1025 if (this.faceNumbers[i] == -1)
1010 this.faceNumbers[i] = faceNum++; 1026 this.faceNumbers[i] = faceNum++;
1011 1027
1012
1013 this.numPrimFaces = faceNum; 1028 this.numPrimFaces = faceNum;
1014 } 1029 }
1015 1030
@@ -1019,7 +1034,7 @@ namespace PrimMesher
1019 { 1034 {
1020 this.faceUVs = new List<UVCoord>(); 1035 this.faceUVs = new List<UVCoord>();
1021 foreach (Coord c in this.coords) 1036 foreach (Coord c in this.coords)
1022 this.faceUVs.Add(new UVCoord(1.0f - (0.5f + c.X), 1.0f - (0.5f - c.Y))); 1037 this.faceUVs.Add(new UVCoord(0.5f + c.X, 0.5f - c.Y));
1023 } 1038 }
1024 1039
1025 internal Profile Copy() 1040 internal Profile Copy()
@@ -1348,7 +1363,6 @@ namespace PrimMesher
1348 float stepSize = twoPi / this.stepsPerRevolution; 1363 float stepSize = twoPi / this.stepsPerRevolution;
1349 1364
1350 int step = (int)(startAngle / stepSize); 1365 int step = (int)(startAngle / stepSize);
1351// int firstStep = step;
1352 float angle = startAngle; 1366 float angle = startAngle;
1353 1367
1354 bool done = false; 1368 bool done = false;
@@ -1455,11 +1469,15 @@ namespace PrimMesher
1455 public float revolutions = 1.0f; 1469 public float revolutions = 1.0f;
1456 public int stepsPerRevolution = 24; 1470 public int stepsPerRevolution = 24;
1457 1471
1472 private int profileOuterFaceNumber = -1;
1473 private int profileHollowFaceNumber = -1;
1474
1458 private bool hasProfileCut = false; 1475 private bool hasProfileCut = false;
1459 private bool hasHollow = false; 1476 private bool hasHollow = false;
1460 public bool calcVertexNormals = false; 1477 public bool calcVertexNormals = false;
1461 private bool normalsProcessed = false; 1478 private bool normalsProcessed = false;
1462 public bool viewerMode = false; 1479 public bool viewerMode = false;
1480 public bool sphereMode = false;
1463 1481
1464 public int numPrimFaces = 0; 1482 public int numPrimFaces = 0;
1465 1483
@@ -1491,10 +1509,35 @@ namespace PrimMesher
1491 s += "\nradius...............: " + this.radius.ToString(); 1509 s += "\nradius...............: " + this.radius.ToString();
1492 s += "\nrevolutions..........: " + this.revolutions.ToString(); 1510 s += "\nrevolutions..........: " + this.revolutions.ToString();
1493 s += "\nstepsPerRevolution...: " + this.stepsPerRevolution.ToString(); 1511 s += "\nstepsPerRevolution...: " + this.stepsPerRevolution.ToString();
1512 s += "\nsphereMode...........: " + this.sphereMode.ToString();
1513 s += "\nhasProfileCut........: " + this.hasProfileCut.ToString();
1514 s += "\nhasHollow............: " + this.hasHollow.ToString();
1515 s += "\nviewerMode...........: " + this.viewerMode.ToString();
1494 1516
1495 return s; 1517 return s;
1496 } 1518 }
1497 1519
1520 public int ProfileOuterFaceNumber
1521 {
1522 get { return profileOuterFaceNumber; }
1523 }
1524
1525 public int ProfileHollowFaceNumber
1526 {
1527 get { return profileHollowFaceNumber; }
1528 }
1529
1530 public bool HasProfileCut
1531 {
1532 get { return hasProfileCut; }
1533 }
1534
1535 public bool HasHollow
1536 {
1537 get { return hasHollow; }
1538 }
1539
1540
1498 /// <summary> 1541 /// <summary>
1499 /// Constructs a PrimMesh object and creates the profile for extrusion. 1542 /// Constructs a PrimMesh object and creates the profile for extrusion.
1500 /// </summary> 1543 /// </summary>
@@ -1531,8 +1574,12 @@ namespace PrimMesher
1531 if (hollow < 0.0f) 1574 if (hollow < 0.0f)
1532 this.hollow = 0.0f; 1575 this.hollow = 0.0f;
1533 1576
1534 this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f); 1577 //if (sphereMode)
1535 this.hasHollow = (this.hollow > 0.001f); 1578 // this.hasProfileCut = this.profileEnd - this.profileStart < 0.4999f;
1579 //else
1580 // //this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f);
1581 // this.hasProfileCut = this.profileEnd - this.profileStart < 0.9999f;
1582 //this.hasHollow = (this.hollow > 0.001f);
1536 } 1583 }
1537 1584
1538 /// <summary> 1585 /// <summary>
@@ -1540,6 +1587,8 @@ namespace PrimMesher
1540 /// </summary> 1587 /// </summary>
1541 public void Extrude(PathType pathType) 1588 public void Extrude(PathType pathType)
1542 { 1589 {
1590 bool needEndFaces = false;
1591
1543 this.coords = new List<Coord>(); 1592 this.coords = new List<Coord>();
1544 this.faces = new List<Face>(); 1593 this.faces = new List<Face>();
1545 1594
@@ -1565,6 +1614,12 @@ namespace PrimMesher
1565 steps = (int)(steps * 4.5 * length); 1614 steps = (int)(steps * 4.5 * length);
1566 } 1615 }
1567 1616
1617 if (sphereMode)
1618 this.hasProfileCut = this.profileEnd - this.profileStart < 0.4999f;
1619 else
1620 //this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f);
1621 this.hasProfileCut = this.profileEnd - this.profileStart < 0.9999f;
1622 this.hasHollow = (this.hollow > 0.001f);
1568 1623
1569 float twistBegin = this.twistBegin / 360.0f * twoPi; 1624 float twistBegin = this.twistBegin / 360.0f * twoPi;
1570 float twistEnd = this.twistEnd / 360.0f * twoPi; 1625 float twistEnd = this.twistEnd / 360.0f * twoPi;
@@ -1634,6 +1689,32 @@ namespace PrimMesher
1634 1689
1635 this.numPrimFaces = profile.numPrimFaces; 1690 this.numPrimFaces = profile.numPrimFaces;
1636 1691
1692 //profileOuterFaceNumber = profile.faceNumbers[0];
1693 //if (!needEndFaces)
1694 // profileOuterFaceNumber--;
1695 //profileOuterFaceNumber = needEndFaces ? 1 : 0;
1696
1697
1698 //if (hasHollow)
1699 //{
1700 // if (needEndFaces)
1701 // profileHollowFaceNumber = profile.faceNumbers[profile.numOuterVerts + 1];
1702 // else
1703 // profileHollowFaceNumber = profile.faceNumbers[profile.numOuterVerts] - 1;
1704 //}
1705
1706
1707 profileOuterFaceNumber = profile.outerFaceNumber;
1708 if (!needEndFaces)
1709 profileOuterFaceNumber--;
1710
1711 if (hasHollow)
1712 {
1713 profileHollowFaceNumber = profile.hollowFaceNumber;
1714 if (!needEndFaces)
1715 profileHollowFaceNumber--;
1716 }
1717
1637 int cut1Vert = -1; 1718 int cut1Vert = -1;
1638 int cut2Vert = -1; 1719 int cut2Vert = -1;
1639 if (hasProfileCut) 1720 if (hasProfileCut)
@@ -1673,7 +1754,7 @@ namespace PrimMesher
1673 1754
1674 path.Create(pathType, steps); 1755 path.Create(pathType, steps);
1675 1756
1676 bool needEndFaces = false; 1757
1677 if (pathType == PathType.Circular) 1758 if (pathType == PathType.Circular)
1678 { 1759 {
1679 needEndFaces = false; 1760 needEndFaces = false;
@@ -1738,7 +1819,6 @@ namespace PrimMesher
1738 // append this layer 1819 // append this layer
1739 1820
1740 int coordsLen = this.coords.Count; 1821 int coordsLen = this.coords.Count;
1741// int lastCoordsLen = coordsLen;
1742 newLayer.AddValue2FaceVertexIndices(coordsLen); 1822 newLayer.AddValue2FaceVertexIndices(coordsLen);
1743 1823
1744 this.coords.AddRange(newLayer.coords); 1824 this.coords.AddRange(newLayer.coords);
@@ -1762,7 +1842,7 @@ namespace PrimMesher
1762 int startVert = coordsLen + 1; 1842 int startVert = coordsLen + 1;
1763 int endVert = this.coords.Count; 1843 int endVert = this.coords.Count;
1764 1844
1765 if (sides < 5 || this.hasProfileCut || hollow > 0.0f) 1845 if (sides < 5 || this.hasProfileCut || this.hasHollow)
1766 startVert--; 1846 startVert--;
1767 1847
1768 for (int i = startVert; i < endVert; i++) 1848 for (int i = startVert; i < endVert; i++)
@@ -1814,11 +1894,13 @@ namespace PrimMesher
1814 u1 -= (int)u1; 1894 u1 -= (int)u1;
1815 if (u2 < 0.1f) 1895 if (u2 < 0.1f)
1816 u2 = 1.0f; 1896 u2 = 1.0f;
1897 //this.profileOuterFaceNumber = primFaceNum;
1817 } 1898 }
1818 else if (whichVert > profile.coords.Count - profile.numHollowVerts - 1) 1899 else if (whichVert > profile.coords.Count - profile.numHollowVerts - 1)
1819 { 1900 {
1820 u1 *= 2.0f; 1901 u1 *= 2.0f;
1821 u2 *= 2.0f; 1902 u2 *= 2.0f;
1903 //this.profileHollowFaceNumber = primFaceNum;
1822 } 1904 }
1823 } 1905 }
1824 1906
diff --git a/OpenSim/Region/Physics/Meshing/SculptMap.cs b/OpenSim/Region/Physics/Meshing/SculptMap.cs
new file mode 100644
index 0000000..d2d71de
--- /dev/null
+++ b/OpenSim/Region/Physics/Meshing/SculptMap.cs
@@ -0,0 +1,176 @@
1/*
2 * Copyright (c) Contributors
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28// to build without references to System.Drawing, comment this out
29#define SYSTEM_DRAWING
30
31using System;
32using System.Collections.Generic;
33using System.Text;
34
35#if SYSTEM_DRAWING
36using System.Drawing;
37using System.Drawing.Imaging;
38
39namespace PrimMesher
40{
41 public class SculptMap
42 {
43 public int width;
44 public int height;
45 public byte[] redBytes;
46 public byte[] greenBytes;
47 public byte[] blueBytes;
48
49 public SculptMap()
50 {
51 }
52
53 public SculptMap(Bitmap bm, int lod)
54 {
55 int bmW = bm.Width;
56 int bmH = bm.Height;
57
58 if (bmW == 0 || bmH == 0)
59 throw new Exception("SculptMap: bitmap has no data");
60
61 int numLodPixels = lod * 2 * lod * 2; // (32 * 2)^2 = 64^2 pixels for default sculpt map image
62
63 bool needsScaling = false;
64
65 width = bmW;
66 height = bmH;
67 while (width * height > numLodPixels)
68 {
69 width >>= 1;
70 height >>= 1;
71 needsScaling = true;
72 }
73
74
75
76 try
77 {
78 if (needsScaling)
79 bm = ScaleImage(bm, width, height,
80 System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor);
81 }
82
83 catch (Exception e)
84 {
85 throw new Exception("Exception in ScaleImage(): e: " + e.ToString());
86 }
87
88 if (width * height > lod * lod)
89 {
90 width >>= 1;
91 height >>= 1;
92 }
93
94 int numBytes = (width + 1) * (height + 1);
95 redBytes = new byte[numBytes];
96 greenBytes = new byte[numBytes];
97 blueBytes = new byte[numBytes];
98
99 int byteNdx = 0;
100
101 try
102 {
103 for (int y = 0; y <= height; y++)
104 {
105 for (int x = 0; x <= width; x++)
106 {
107 int bmY = y < height ? y * 2 : y * 2 - 1;
108 int bmX = x < width ? x * 2 : x * 2 - 1;
109 Color c = bm.GetPixel(bmX, bmY);
110
111 redBytes[byteNdx] = c.R;
112 greenBytes[byteNdx] = c.G;
113 blueBytes[byteNdx] = c.B;
114
115 ++byteNdx;
116 }
117 }
118 }
119 catch (Exception e)
120 {
121 throw new Exception("Caught exception processing byte arrays in SculptMap(): e: " + e.ToString());
122 }
123
124 width++;
125 height++;
126 }
127
128 public List<List<Coord>> ToRows(bool mirror)
129 {
130 int numRows = height;
131 int numCols = width;
132
133 List<List<Coord>> rows = new List<List<Coord>>(numRows);
134
135 float pixScale = 1.0f / 255;
136
137 int rowNdx, colNdx;
138 int smNdx = 0;
139
140 for (rowNdx = 0; rowNdx < numRows; rowNdx++)
141 {
142 List<Coord> row = new List<Coord>(numCols);
143 for (colNdx = 0; colNdx < numCols; colNdx++)
144 {
145 if (mirror)
146 row.Add(new Coord(-(redBytes[smNdx] * pixScale - 0.5f), (greenBytes[smNdx] * pixScale - 0.5f), blueBytes[smNdx] * pixScale - 0.5f));
147 else
148 row.Add(new Coord(redBytes[smNdx] * pixScale - 0.5f, greenBytes[smNdx] * pixScale - 0.5f, blueBytes[smNdx] * pixScale - 0.5f));
149
150 ++smNdx;
151 }
152 rows.Add(row);
153 }
154 return rows;
155 }
156
157 private Bitmap ScaleImage(Bitmap srcImage, int destWidth, int destHeight,
158 System.Drawing.Drawing2D.InterpolationMode interpMode)
159 {
160 Bitmap scaledImage = new Bitmap(srcImage, destWidth, destHeight);
161 scaledImage.SetResolution(96.0f, 96.0f);
162
163 Graphics grPhoto = Graphics.FromImage(scaledImage);
164 grPhoto.InterpolationMode = interpMode;
165
166 grPhoto.DrawImage(srcImage,
167 new Rectangle(0, 0, destWidth, destHeight),
168 new Rectangle(0, 0, srcImage.Width, srcImage.Height),
169 GraphicsUnit.Pixel);
170
171 grPhoto.Dispose();
172 return scaledImage;
173 }
174 }
175}
176#endif
diff --git a/OpenSim/Region/Physics/Meshing/SculptMesh.cs b/OpenSim/Region/Physics/Meshing/SculptMesh.cs
index 4dc6e2e..6aa8fe4 100644
--- a/OpenSim/Region/Physics/Meshing/SculptMesh.cs
+++ b/OpenSim/Region/Physics/Meshing/SculptMesh.cs
@@ -53,43 +53,6 @@ namespace PrimMesher
53 public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 }; 53 public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 };
54 54
55#if SYSTEM_DRAWING 55#if SYSTEM_DRAWING
56 // private Bitmap ScaleImage(Bitmap srcImage, float scale)
57 // {
58 // int sourceWidth = srcImage.Width;
59 // int sourceHeight = srcImage.Height;
60 // int sourceX = 0;
61 // int sourceY = 0;
62
63 // int destX = 0;
64 // int destY = 0;
65 // int destWidth = (int)(srcImage.Width * scale);
66 // int destHeight = (int)(srcImage.Height * scale);
67
68 // if (srcImage.PixelFormat == PixelFormat.Format32bppArgb)
69 // for (int y = 0; y < srcImage.Height; y++)
70 // for (int x = 0; x < srcImage.Width; x++)
71 // {
72 // Color c = srcImage.GetPixel(x, y);
73 // srcImage.SetPixel(x, y, Color.FromArgb(255, c.R, c.G, c.B));
74 // }
75
76 // Bitmap scaledImage = new Bitmap(destWidth, destHeight,
77 // PixelFormat.Format24bppRgb);
78
79 // scaledImage.SetResolution(96.0f, 96.0f);
80
81 // Graphics grPhoto = Graphics.FromImage(scaledImage);
82 // grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
83
84 // grPhoto.DrawImage(srcImage,
85 // new Rectangle(destX, destY, destWidth, destHeight),
86 // new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
87 // GraphicsUnit.Pixel);
88
89 // grPhoto.Dispose();
90 // return scaledImage;
91 // }
92
93 56
94 public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode) 57 public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode)
95 { 58 {
@@ -99,6 +62,7 @@ namespace PrimMesher
99 return sculptMesh; 62 return sculptMesh;
100 } 63 }
101 64
65
102 public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert) 66 public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert)
103 { 67 {
104 Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName); 68 Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName);
@@ -268,6 +232,11 @@ namespace PrimMesher
268 for (imageY = imageYStart; imageY < imageYEnd; imageY++) 232 for (imageY = imageYStart; imageY < imageYEnd; imageY++)
269 { 233 {
270 Color c = bitmap.GetPixel(imageX, imageY); 234 Color c = bitmap.GetPixel(imageX, imageY);
235 if (c.A != 255)
236 {
237 bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B));
238 c = bitmap.GetPixel(imageX, imageY);
239 }
271 rSum += c.R; 240 rSum += c.R;
272 gSum += c.G; 241 gSum += c.G;
273 bSum += c.B; 242 bSum += c.B;
@@ -284,30 +253,53 @@ namespace PrimMesher
284 return rows; 253 return rows;
285 } 254 }
286 255
287 256 private List<List<Coord>> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mirror)
288 void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
289 { 257 {
290 coords = new List<Coord>(); 258 int numRows = bitmap.Height / scale;
291 faces = new List<Face>(); 259 int numCols = bitmap.Width / scale;
292 normals = new List<Coord>(); 260 List<List<Coord>> rows = new List<List<Coord>>(numRows);
293 uvs = new List<UVCoord>();
294 261
295 sculptType = (SculptType)(((int)sculptType) & 0x07); 262 float pixScale = 1.0f / 256.0f;
296 263
297 if (mirror) 264 int imageX, imageY = 0;
298 if (sculptType == SculptType.plane) 265
299 invert = !invert; 266 int rowNdx, colNdx;
267
268 for (rowNdx = 0; rowNdx <= numRows; rowNdx++)
269 {
270 List<Coord> row = new List<Coord>(numCols);
271 imageY = rowNdx * scale;
272 if (rowNdx == numRows) imageY--;
273 for (colNdx = 0; colNdx <= numCols; colNdx++)
274 {
275 imageX = colNdx * scale;
276 if (colNdx == numCols) imageX--;
300 277
301 float sourceScaleFactor = (float)(lod) / (float)Math.Sqrt(sculptBitmap.Width * sculptBitmap.Height); 278 Color c = bitmap.GetPixel(imageX, imageY);
279 if (c.A != 255)
280 {
281 bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B));
282 c = bitmap.GetPixel(imageX, imageY);
283 }
302 284
303 int scale = (int)(1.0f / sourceScaleFactor); 285 if (mirror)
304 if (scale < 1) scale = 1; 286 row.Add(new Coord(-(c.R * pixScale - 0.5f), c.G * pixScale - 0.5f, c.B * pixScale - 0.5f));
287 else
288 row.Add(new Coord(c.R * pixScale - 0.5f, c.G * pixScale - 0.5f, c.B * pixScale - 0.5f));
305 289
306 _SculptMesh(bitmap2Coords(sculptBitmap, scale, mirror), sculptType, viewerMode, mirror, invert); 290 }
291 rows.Add(row);
292 }
293 return rows;
307 } 294 }
308#endif
309 295
310 296
297 void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
298 {
299 _SculptMesh(new SculptMap(sculptBitmap, lod).ToRows(mirror), sculptType, viewerMode, mirror, invert);
300 }
301#endif
302
311 void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) 303 void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert)
312 { 304 {
313 coords = new List<Coord>(); 305 coords = new List<Coord>();
@@ -331,8 +323,18 @@ namespace PrimMesher
331 323
332 if (sculptType != SculptType.plane) 324 if (sculptType != SculptType.plane)
333 { 325 {
334 for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++) 326 if (rows.Count % 2 == 0)
335 rows[rowNdx].Add(rows[rowNdx][0]); 327 {
328 for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++)
329 rows[rowNdx].Add(rows[rowNdx][0]);
330 }
331 else
332 {
333 int lastIndex = rows[0].Count - 1;
334
335 for (int i = 0; i < rows.Count; i++)
336 rows[i][0] = rows[i][lastIndex];
337 }
336 } 338 }
337 339
338 Coord topPole = rows[0][width / 2]; 340 Coord topPole = rows[0][width / 2];
@@ -340,23 +342,41 @@ namespace PrimMesher
340 342
341 if (sculptType == SculptType.sphere) 343 if (sculptType == SculptType.sphere)
342 { 344 {
343 int count = rows[0].Count; 345 if (rows.Count % 2 == 0)
344 List<Coord> topPoleRow = new List<Coord>(count); 346 {
345 List<Coord> bottomPoleRow = new List<Coord>(count); 347 int count = rows[0].Count;
348 List<Coord> topPoleRow = new List<Coord>(count);
349 List<Coord> bottomPoleRow = new List<Coord>(count);
346 350
347 for (int i = 0; i < count; i++) 351 for (int i = 0; i < count; i++)
352 {
353 topPoleRow.Add(topPole);
354 bottomPoleRow.Add(bottomPole);
355 }
356 rows.Insert(0, topPoleRow);
357 rows.Add(bottomPoleRow);
358 }
359 else
348 { 360 {
349 topPoleRow.Add(topPole); 361 int count = rows[0].Count;
350 bottomPoleRow.Add(bottomPole); 362
363 List<Coord> topPoleRow = rows[0];
364 List<Coord> bottomPoleRow = rows[rows.Count - 1];
365
366 for (int i = 0; i < count; i++)
367 {
368 topPoleRow[i] = topPole;
369 bottomPoleRow[i] = bottomPole;
370 }
351 } 371 }
352 rows.Insert(0, topPoleRow);
353 rows.Add(bottomPoleRow);
354 } 372 }
355 else if (sculptType == SculptType.torus) 373
374 if (sculptType == SculptType.torus)
356 rows.Add(rows[0]); 375 rows.Add(rows[0]);
357 376
358 int coordsDown = rows.Count; 377 int coordsDown = rows.Count;
359 int coordsAcross = rows[0].Count; 378 int coordsAcross = rows[0].Count;
379 int lastColumn = coordsAcross - 1;
360 380
361 float widthUnit = 1.0f / (coordsAcross - 1); 381 float widthUnit = 1.0f / (coordsAcross - 1);
362 float heightUnit = 1.0f / (coordsDown - 1); 382 float heightUnit = 1.0f / (coordsDown - 1);
diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs
index 2ab00a3..be7c348 100644
--- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs
+++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs
@@ -1575,11 +1575,11 @@ Console.WriteLine(" JointCreateFixed");
1575 { 1575 {
1576//Console.WriteLine("Move " + m_primName); 1576//Console.WriteLine("Move " + m_primName);
1577 if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body); // KF add 161009 1577 if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body); // KF add 161009
1578 /*
1579 // NON-'VEHICLES' are dealt with here 1578 // NON-'VEHICLES' are dealt with here
1580 if (d.BodyIsEnabled(Body) && !m_angularlock.ApproxEquals(Vector3.Zero, 0.003f)) 1579 if (d.BodyIsEnabled(Body) && !m_angularlock.ApproxEquals(Vector3.Zero, 0.003f))
1581 { 1580 {
1582 d.Vector3 avel2 = d.BodyGetAngularVel(Body); 1581 d.Vector3 avel2 = d.BodyGetAngularVel(Body);
1582 /*
1583 if (m_angularlock.X == 1) 1583 if (m_angularlock.X == 1)
1584 avel2.X = 0; 1584 avel2.X = 0;
1585 if (m_angularlock.Y == 1) 1585 if (m_angularlock.Y == 1)
@@ -1587,8 +1587,8 @@ Console.WriteLine(" JointCreateFixed");
1587 if (m_angularlock.Z == 1) 1587 if (m_angularlock.Z == 1)
1588 avel2.Z = 0; 1588 avel2.Z = 0;
1589 d.BodySetAngularVel(Body, avel2.X, avel2.Y, avel2.Z); 1589 d.BodySetAngularVel(Body, avel2.X, avel2.Y, avel2.Z);
1590 */
1590 } 1591 }
1591 */
1592 //float PID_P = 900.0f; 1592 //float PID_P = 900.0f;
1593 1593
1594 float m_mass = CalculateMass(); 1594 float m_mass = CalculateMass();
diff --git a/OpenSim/Region/RegionCombinerModule/RegionCombinerModule.cs b/OpenSim/Region/RegionCombinerModule/RegionCombinerModule.cs
index 0b8771c..b42d3bf 100644
--- a/OpenSim/Region/RegionCombinerModule/RegionCombinerModule.cs
+++ b/OpenSim/Region/RegionCombinerModule/RegionCombinerModule.cs
@@ -625,36 +625,37 @@ namespace OpenSim.Region.RegionCombinerModule
625 return; 625 return;
626 } 626 }
627 627
628 List<ScenePresence> avatars = connectiondata.RegionScene.GetAvatars();
629 List<Vector3> CoarseLocations = new List<Vector3>(); 628 List<Vector3> CoarseLocations = new List<Vector3>();
630 List<UUID> AvatarUUIDs = new List<UUID>(); 629 List<UUID> AvatarUUIDs = new List<UUID>();
631 for (int i = 0; i < avatars.Count; i++) 630 connectiondata.RegionScene.ForEachScenePresence(delegate(ScenePresence sp)
632 { 631 {
633 if (avatars[i].UUID != presence.UUID) 632 if (sp.IsChildAgent)
633 return;
634 if (sp.UUID != presence.UUID)
634 { 635 {
635 if (avatars[i].ParentID != 0) 636 if (sp.ParentID != 0)
636 { 637 {
637 // sitting avatar 638 // sitting avatar
638 SceneObjectPart sop = connectiondata.RegionScene.GetSceneObjectPart(avatars[i].ParentID); 639 SceneObjectPart sop = connectiondata.RegionScene.GetSceneObjectPart(sp.ParentID);
639 if (sop != null) 640 if (sop != null)
640 { 641 {
641 CoarseLocations.Add(sop.AbsolutePosition + avatars[i].AbsolutePosition); 642 CoarseLocations.Add(sop.AbsolutePosition + sp.AbsolutePosition);
642 AvatarUUIDs.Add(avatars[i].UUID); 643 AvatarUUIDs.Add(sp.UUID);
643 } 644 }
644 else 645 else
645 { 646 {
646 // we can't find the parent.. ! arg! 647 // we can't find the parent.. ! arg!
647 CoarseLocations.Add(avatars[i].AbsolutePosition); 648 CoarseLocations.Add(sp.AbsolutePosition);
648 AvatarUUIDs.Add(avatars[i].UUID); 649 AvatarUUIDs.Add(sp.UUID);
649 } 650 }
650 } 651 }
651 else 652 else
652 { 653 {
653 CoarseLocations.Add(avatars[i].AbsolutePosition); 654 CoarseLocations.Add(sp.AbsolutePosition);
654 AvatarUUIDs.Add(avatars[i].UUID); 655 AvatarUUIDs.Add(sp.UUID);
655 } 656 }
656 } 657 }
657 } 658 });
658 DistributeCourseLocationUpdates(CoarseLocations, AvatarUUIDs, connectiondata, presence); 659 DistributeCourseLocationUpdates(CoarseLocations, AvatarUUIDs, connectiondata, presence);
659 } 660 }
660 661
diff --git a/OpenSim/Region/ScriptEngine/Interfaces/IScriptInstance.cs b/OpenSim/Region/ScriptEngine/Interfaces/IScriptInstance.cs
index ae148a9..9f6ea35 100644
--- a/OpenSim/Region/ScriptEngine/Interfaces/IScriptInstance.cs
+++ b/OpenSim/Region/ScriptEngine/Interfaces/IScriptInstance.cs
@@ -81,6 +81,9 @@ namespace OpenSim.Region.ScriptEngine.Interfaces
81 81
82 void PostEvent(EventParams data); 82 void PostEvent(EventParams data);
83 83
84 void Suspend();
85 void Resume();
86
84 /// <summary> 87 /// <summary>
85 /// Process the next event queued for this script 88 /// Process the next event queued for this script
86 /// </summary> 89 /// </summary>
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs
index 9f829da..07cba60 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs
@@ -1,4 +1,31 @@
1using System; 1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
2using System.Reflection; 29using System.Reflection;
3using System.Collections; 30using System.Collections;
4using System.Collections.Generic; 31using System.Collections.Generic;
@@ -7,7 +34,7 @@ using OpenMetaverse;
7using Nini.Config; 34using Nini.Config;
8using OpenSim; 35using OpenSim;
9using OpenSim.Framework; 36using OpenSim.Framework;
10using OpenSim.Region.CoreModules.World.Meta7Windlight; 37using OpenSim.Region.CoreModules.World.LightShare;
11using OpenSim.Region.Framework.Interfaces; 38using OpenSim.Region.Framework.Interfaces;
12using OpenSim.Region.Framework.Scenes; 39using OpenSim.Region.Framework.Scenes;
13using OpenSim.Region.ScriptEngine.Shared; 40using OpenSim.Region.ScriptEngine.Shared;
@@ -92,7 +119,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
92 public LSL_List cmGetAvatarList() 119 public LSL_List cmGetAvatarList()
93 { 120 {
94 LSL_List result = new LSL_List(); 121 LSL_List result = new LSL_List();
95 foreach (ScenePresence avatar in World.GetAvatars()) 122 World.ForEachScenePresence(delegate (ScenePresence avatar)
96 { 123 {
97 if (avatar.UUID != m_host.OwnerID) 124 if (avatar.UUID != m_host.OwnerID)
98 { 125 {
@@ -103,7 +130,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
103 result.Add(avatar.Name); 130 result.Add(avatar.Name);
104 } 131 }
105 } 132 }
106 } 133 });
107 return result; 134 return result;
108 } 135 }
109 136
@@ -119,7 +146,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
119 return new LSL_List(); 146 return new LSL_List();
120 } 147 }
121 m_host.AddScriptLPS(1); 148 m_host.AddScriptLPS(1);
122 RegionMeta7WindlightData wl = m_host.ParentGroup.Scene.RegionInfo.WindlightSettings; 149 RegionLightShareData wl = m_host.ParentGroup.Scene.RegionInfo.WindlightSettings;
123 150
124 LSL_List values = new LSL_List(); 151 LSL_List values = new LSL_List();
125 int idx = 0; 152 int idx = 0;
@@ -253,9 +280,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
253 280
254 } 281 }
255 282
256 private RegionMeta7WindlightData getWindlightProfileFromRules(LSL_List rules) 283 private RegionLightShareData getWindlightProfileFromRules(LSL_List rules)
257 { 284 {
258 RegionMeta7WindlightData wl = (RegionMeta7WindlightData)m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.Clone(); 285 RegionLightShareData wl = (RegionLightShareData)m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.Clone();
259 286
260 LSL_List values = new LSL_List(); 287 LSL_List values = new LSL_List();
261 int idx = 0; 288 int idx = 0;
@@ -449,9 +476,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
449 } 476 }
450 int success = 0; 477 int success = 0;
451 m_host.AddScriptLPS(1); 478 m_host.AddScriptLPS(1);
452 if (Meta7WindlightModule.EnableWindlight) 479 if (LightShareModule.EnableWindlight)
453 { 480 {
454 RegionMeta7WindlightData wl = getWindlightProfileFromRules(rules); 481 RegionLightShareData wl = getWindlightProfileFromRules(rules);
455 m_host.ParentGroup.Scene.StoreWindlightProfile(wl); 482 m_host.ParentGroup.Scene.StoreWindlightProfile(wl);
456 success = 1; 483 success = 1;
457 } 484 }
@@ -481,9 +508,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
481 } 508 }
482 int success = 0; 509 int success = 0;
483 m_host.AddScriptLPS(1); 510 m_host.AddScriptLPS(1);
484 if (Meta7WindlightModule.EnableWindlight) 511 if (LightShareModule.EnableWindlight)
485 { 512 {
486 RegionMeta7WindlightData wl = getWindlightProfileFromRules(rules); 513 RegionLightShareData wl = getWindlightProfileFromRules(rules);
487 World.EventManager.TriggerOnSendNewWindlightProfileTargeted(wl, new UUID(target.m_string)); 514 World.EventManager.TriggerOnSendNewWindlightProfileTargeted(wl, new UUID(target.m_string));
488 success = 1; 515 success = 1;
489 } 516 }
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
index 75dd615..6ab3c62 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
@@ -39,7 +39,7 @@ using OpenMetaverse;
39using OpenMetaverse.Packets; 39using OpenMetaverse.Packets;
40using OpenSim; 40using OpenSim;
41using OpenSim.Framework; 41using OpenSim.Framework;
42using OpenSim.Framework.Communications.Cache; 42
43using OpenSim.Region.CoreModules; 43using OpenSim.Region.CoreModules;
44using OpenSim.Region.CoreModules.World.Land; 44using OpenSim.Region.CoreModules.World.Land;
45using OpenSim.Region.CoreModules.World.Terrain; 45using OpenSim.Region.CoreModules.World.Terrain;
@@ -53,9 +53,9 @@ using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
53using OpenSim.Region.ScriptEngine.Interfaces; 53using OpenSim.Region.ScriptEngine.Interfaces;
54using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; 54using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
55using OpenSim.Services.Interfaces; 55using OpenSim.Services.Interfaces;
56
57using PrimType = OpenSim.Region.Framework.Scenes.PrimType;
58using GridRegion = OpenSim.Services.Interfaces.GridRegion; 56using GridRegion = OpenSim.Services.Interfaces.GridRegion;
57using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
58using PrimType = OpenSim.Region.Framework.Scenes.PrimType;
59using AssetLandmark = OpenSim.Framework.AssetLandmark; 59using AssetLandmark = OpenSim.Framework.AssetLandmark;
60 60
61using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; 61using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
@@ -917,10 +917,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
917 public string resolveName(UUID objecUUID) 917 public string resolveName(UUID objecUUID)
918 { 918 {
919 // try avatar username surname 919 // try avatar username surname
920 CachedUserInfo profile = World.CommsManager.UserProfileCacheService.GetUserDetails(objecUUID); 920 UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, objecUUID);
921 if (profile != null && profile.UserProfile != null) 921 if (account != null)
922 { 922 {
923 string avatarname = profile.UserProfile.FirstName + " " + profile.UserProfile.SurName; 923 string avatarname = account.Name;
924 return avatarname; 924 return avatarname;
925 } 925 }
926 // try an scene object 926 // try an scene object
@@ -2033,14 +2033,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
2033 float ground = World.GetGroundHeight((float)targetPos.x, (float)targetPos.y); 2033 float ground = World.GetGroundHeight((float)targetPos.x, (float)targetPos.y);
2034 bool disable_underground_movement = m_ScriptEngine.Config.GetBoolean("DisableUndergroundMovement", true); 2034 bool disable_underground_movement = m_ScriptEngine.Config.GetBoolean("DisableUndergroundMovement", true);
2035 2035
2036 if (part.ParentGroup == null) 2036 if (part.ParentGroup.RootPart == part)
2037 {
2038 if ((targetPos.z < ground) && disable_underground_movement)
2039 targetPos.z = ground;
2040 LSL_Vector real_vec = SetPosAdjust(currentPos, targetPos);
2041 part.UpdateOffSet(new Vector3((float)real_vec.x, (float)real_vec.y, (float)real_vec.z));
2042 }
2043 else if (part.ParentGroup.RootPart == part)
2044 { 2037 {
2045 if ((targetPos.z < ground) && disable_underground_movement) 2038 if ((targetPos.z < ground) && disable_underground_movement)
2046 targetPos.z = ground; 2039 targetPos.z = ground;
@@ -2050,7 +2043,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
2050 } 2043 }
2051 else 2044 else
2052 { 2045 {
2053 //it's late... i think this is right ?
2054 if (llVecDist(new LSL_Vector(0,0,0), targetPos) <= 10.0f) 2046 if (llVecDist(new LSL_Vector(0,0,0), targetPos) <= 10.0f)
2055 { 2047 {
2056 part.OffsetPosition = new Vector3((float)targetPos.x, (float)targetPos.y, (float)targetPos.z); 2048 part.OffsetPosition = new Vector3((float)targetPos.x, (float)targetPos.y, (float)targetPos.z);
@@ -3080,9 +3072,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
3080 3072
3081 ScenePresence presence = World.GetScenePresence(m_host.OwnerID); 3073 ScenePresence presence = World.GetScenePresence(m_host.OwnerID);
3082 3074
3083 m_ScriptEngine.World.AttachObject(presence.ControllingClient, 3075 IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
3084 grp.LocalId, (uint)attachment, Quaternion.Identity, 3076 if (attachmentsModule != null)
3085 Vector3.Zero, false); 3077 attachmentsModule.AttachObject(
3078 presence.ControllingClient, grp.LocalId,
3079 (uint)attachment, Quaternion.Identity, Vector3.Zero, false);
3086 } 3080 }
3087 } 3081 }
3088 3082
@@ -3119,8 +3113,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
3119 3113
3120 ScenePresence presence = World.GetScenePresence(m_host.OwnerID); 3114 ScenePresence presence = World.GetScenePresence(m_host.OwnerID);
3121 3115
3122 m_ScriptEngine.World.DetachSingleAttachmentToInv(itemID, 3116 IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
3123 presence.ControllingClient); 3117 if (attachmentsModule != null)
3118 attachmentsModule.ShowDetachInUserInventory(itemID, presence.ControllingClient);
3124 } 3119 }
3125 } 3120 }
3126 3121
@@ -4002,9 +3997,30 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4002 throw new Exception(String.Format("The inventory object '{0}' could not be found", inventory)); 3997 throw new Exception(String.Format("The inventory object '{0}' could not be found", inventory));
4003 } 3998 }
4004 3999
4005 // check if destination is an avatar 4000 // check if destination is an object
4006 if (World.GetScenePresence(destId) != null) 4001 if (World.GetSceneObjectPart(destId) != null)
4002 {
4003 // destination is an object
4004 World.MoveTaskInventoryItem(destId, m_host, objId);
4005 }
4006 else
4007 { 4007 {
4008 ScenePresence presence = World.GetScenePresence(destId);
4009
4010 if (presence == null)
4011 {
4012 UserAccount account =
4013 World.UserAccountService.GetUserAccount(
4014 World.RegionInfo.ScopeID,
4015 destId);
4016
4017 if (account == null)
4018 {
4019 llSay(0, "Can't find destination "+destId.ToString());
4020 return;
4021 }
4022 }
4023
4008 // destination is an avatar 4024 // destination is an avatar
4009 InventoryItemBase agentItem = 4025 InventoryItemBase agentItem =
4010 World.MoveTaskInventoryItem(destId, UUID.Zero, m_host, objId); 4026 World.MoveTaskInventoryItem(destId, UUID.Zero, m_host, objId);
@@ -4034,12 +4050,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4034 //This delay should only occur when giving inventory to avatars. 4050 //This delay should only occur when giving inventory to avatars.
4035 ScriptSleep(3000); 4051 ScriptSleep(3000);
4036 } 4052 }
4037 else
4038 {
4039 // destination is an object
4040 World.MoveTaskInventoryItem(destId, m_host, objId);
4041 }
4042
4043 } 4053 }
4044 4054
4045 [DebuggerNonUserCode] 4055 [DebuggerNonUserCode]
@@ -4096,13 +4106,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4096 4106
4097 UUID uuid = (UUID)id; 4107 UUID uuid = (UUID)id;
4098 4108
4099 UserProfileData userProfile = 4109 UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, uuid);
4100 World.CommsManager.UserService.GetUserProfile(uuid);
4101 4110
4102 UserAgentData userAgent = 4111 PresenceInfo[] pinfos = World.PresenceService.GetAgents(new string[] { uuid.ToString() });
4103 World.CommsManager.UserService.GetAgentByUUID(uuid); 4112 PresenceInfo pinfo = PresenceInfo.GetOnlinePresence(pinfos);
4104 4113
4105 if (userProfile == null || userAgent == null) 4114 if (pinfo == null)
4106 return UUID.Zero.ToString(); 4115 return UUID.Zero.ToString();
4107 4116
4108 string reply = String.Empty; 4117 string reply = String.Empty;
@@ -4111,17 +4120,17 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4111 { 4120 {
4112 case 1: // DATA_ONLINE (0|1) 4121 case 1: // DATA_ONLINE (0|1)
4113 // TODO: implement fetching of this information 4122 // TODO: implement fetching of this information
4114 if (userProfile.CurrentAgent!=null && userProfile.CurrentAgent.AgentOnline) 4123 if (pinfo != null)
4115 reply = "1"; 4124 reply = "1";
4116 else 4125 else
4117 reply = "0"; 4126 reply = "0";
4118 break; 4127 break;
4119 case 2: // DATA_NAME (First Last) 4128 case 2: // DATA_NAME (First Last)
4120 reply = userProfile.FirstName + " " + userProfile.SurName; 4129 reply = account.FirstName + " " + account.LastName;
4121 break; 4130 break;
4122 case 3: // DATA_BORN (YYYY-MM-DD) 4131 case 3: // DATA_BORN (YYYY-MM-DD)
4123 DateTime born = new DateTime(1970, 1, 1, 0, 0, 0, 0); 4132 DateTime born = new DateTime(1970, 1, 1, 0, 0, 0, 0);
4124 born = born.AddSeconds(userProfile.Created); 4133 born = born.AddSeconds(account.Created);
4125 reply = born.ToString("yyyy-MM-dd"); 4134 reply = born.ToString("yyyy-MM-dd");
4126 break; 4135 break;
4127 case 4: // DATA_RATING (0,0,0,0,0,0) 4136 case 4: // DATA_RATING (0,0,0,0,0,0)
@@ -4220,10 +4229,34 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4220 ScriptSleep(5000); 4229 ScriptSleep(5000);
4221 } 4230 }
4222 4231
4223 public void llTextBox(string avatar, string message, int chat_channel) 4232 public void llTextBox(string agent, string message, int chatChannel)
4224 { 4233 {
4234 IDialogModule dm = World.RequestModuleInterface<IDialogModule>();
4235
4236 if (dm == null)
4237 return;
4238
4225 m_host.AddScriptLPS(1); 4239 m_host.AddScriptLPS(1);
4226 NotImplemented("llTextBox"); 4240 UUID av = new UUID();
4241 if (!UUID.TryParse(agent,out av))
4242 {
4243 LSLError("First parameter to llDialog needs to be a key");
4244 return;
4245 }
4246
4247 if (message == string.Empty)
4248 {
4249 ShoutError("Trying to use llTextBox with empty message.");
4250 }
4251 else if (message.Length > 512)
4252 {
4253 ShoutError("Trying to use llTextBox with message over 512 characters.");
4254 }
4255 else
4256 {
4257 dm.SendTextBoxToUser(av, message, chatChannel, m_host.Name, m_host.UUID, m_host.OwnerID);
4258 ScriptSleep(1000);
4259 }
4227 } 4260 }
4228 4261
4229 public void llModifyLand(int action, int brush) 4262 public void llModifyLand(int action, int brush)
@@ -4238,6 +4271,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
4238 4271
4239 public void llCollisionSound(string impact_sound, double impact_volume) 4272 public void llCollisionSound(string impact_sound, double impact_volume)
4240 { 4273 {
4274
4241 m_host.AddScriptLPS(1); 4275 m_host.AddScriptLPS(1);
4242 // TODO: Parameter check logic required. 4276 // TODO: Parameter check logic required.
4243 UUID soundId = UUID.Zero; 4277 UUID soundId = UUID.Zero;
@@ -9091,17 +9125,19 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
9091 landObject.SetMediaUrl(url); 9125 landObject.SetMediaUrl(url);
9092 9126
9093 // now send to all (non-child) agents 9127 // now send to all (non-child) agents
9094 List<ScenePresence> agents = World.GetAvatars(); 9128 World.ForEachScenePresence(delegate(ScenePresence sp)
9095 foreach (ScenePresence agent in agents)
9096 { 9129 {
9097 agent.ControllingClient.SendParcelMediaUpdate(landData.MediaURL, 9130 if (!sp.IsChildAgent)
9098 landData.MediaID, 9131 {
9099 landData.MediaAutoScale, 9132 sp.ControllingClient.SendParcelMediaUpdate(landData.MediaURL,
9100 mediaType, 9133 landData.MediaID,
9101 description, 9134 landData.MediaAutoScale,
9102 width, height, 9135 mediaType,
9103 loop); 9136 description,
9104 } 9137 width, height,
9138 loop);
9139 }
9140 });
9105 } 9141 }
9106 else if (!presence.IsChildAgent) 9142 else if (!presence.IsChildAgent)
9107 { 9143 {
@@ -9122,13 +9158,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
9122 if (presence == null) 9158 if (presence == null)
9123 { 9159 {
9124 // send to all (non-child) agents 9160 // send to all (non-child) agents
9125 List<ScenePresence> agents = World.GetAvatars(); 9161 World.ForEachScenePresence(delegate(ScenePresence sp)
9126 foreach (ScenePresence agent in agents)
9127 { 9162 {
9128 agent.ControllingClient.SendParcelMediaCommand(0x4, // TODO what is this? 9163 if (!sp.IsChildAgent)
9129 (ParcelMediaCommandEnum)commandToSend, 9164 {
9130 time); 9165 sp.ControllingClient.SendParcelMediaCommand(0x4, // TODO what is this?
9131 } 9166 (ParcelMediaCommandEnum)commandToSend,
9167 time);
9168 }
9169 });
9132 } 9170 }
9133 else if (!presence.IsChildAgent) 9171 else if (!presence.IsChildAgent)
9134 { 9172 {
@@ -10160,90 +10198,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
10160 10198
10161 Notecard nc = new Notecard(); 10199 Notecard nc = new Notecard();
10162 nc.lastRef = DateTime.Now; 10200 nc.lastRef = DateTime.Now;
10163 nc.text = ParseText(text.Replace("\r", "").Split('\n')); 10201 nc.text = SLUtil.ParseNotecardToList(text).ToArray();
10164 m_Notecards[assetID] = nc; 10202 m_Notecards[assetID] = nc;
10165 } 10203 }
10166 } 10204 }
10167 10205
10168 protected static string[] ParseText(string[] input)
10169 {
10170 int idx = 0;
10171 int level = 0;
10172 List<string> output = new List<string>();
10173 string[] words;
10174
10175 while (idx < input.Length)
10176 {
10177 if (input[idx] == "{")
10178 {
10179 level++;
10180 idx++;
10181 continue;
10182 }
10183
10184 if (input[idx]== "}")
10185 {
10186 level--;
10187 idx++;
10188 continue;
10189 }
10190
10191 switch (level)
10192 {
10193 case 0:
10194 words = input[idx].Split(' '); // Linden text ver
10195 // Notecards are created *really* empty. Treat that as "no text" (just like after saving an empty notecard)
10196 if (words.Length < 3)
10197 return new String[0];
10198
10199 int version = int.Parse(words[3]);
10200 if (version != 2)
10201 return new String[0];
10202 break;
10203 case 1:
10204 words = input[idx].Split(' ');
10205 if (words[0] == "LLEmbeddedItems")
10206 break;
10207 if (words[0] == "Text")
10208 {
10209 int len = int.Parse(words[2]);
10210 idx++;
10211
10212 int count = -1;
10213
10214 while (count < len)
10215 {
10216 // int l = input[idx].Length;
10217 string ln = input[idx];
10218
10219 int need = len-count-1;
10220 if (ln.Length > need)
10221 ln = ln.Substring(0, need);
10222
10223 output.Add(ln);
10224 count += ln.Length + 1;
10225 idx++;
10226 }
10227
10228 return output.ToArray();
10229 }
10230 break;
10231 case 2:
10232 words = input[idx].Split(' '); // count
10233 if (words[0] == "count")
10234 {
10235 int c = int.Parse(words[1]);
10236 if (c > 0)
10237 return new String[0];
10238 break;
10239 }
10240 break;
10241 }
10242 idx++;
10243 }
10244 return output.ToArray();
10245 }
10246
10247 public static bool IsCached(UUID assetID) 10206 public static bool IsCached(UUID assetID)
10248 { 10207 {
10249 lock (m_Notecards) 10208 lock (m_Notecards)
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
index 1ddba1e..9474bab 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
@@ -36,12 +36,11 @@ using OpenMetaverse;
36using Nini.Config; 36using Nini.Config;
37using OpenSim; 37using OpenSim;
38using OpenSim.Framework; 38using OpenSim.Framework;
39using OpenSim.Framework.Communications.Cache; 39
40using OpenSim.Framework.Console; 40using OpenSim.Framework.Console;
41using OpenSim.Region.CoreModules.Avatar.NPC; 41using OpenSim.Region.CoreModules.Avatar.NPC;
42using OpenSim.Region.Framework.Interfaces; 42using OpenSim.Region.Framework.Interfaces;
43using OpenSim.Region.Framework.Scenes; 43using OpenSim.Region.Framework.Scenes;
44using OpenSim.Region.Framework.Scenes.Hypergrid;
45using OpenSim.Region.ScriptEngine.Shared; 44using OpenSim.Region.ScriptEngine.Shared;
46using OpenSim.Region.ScriptEngine.Shared.Api.Plugins; 45using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
47using OpenSim.Region.ScriptEngine.Shared.ScriptBase; 46using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
@@ -607,21 +606,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
607 // and convert the regionName to the target region 606 // and convert the regionName to the target region
608 if (regionName.Contains(".") && regionName.Contains(":")) 607 if (regionName.Contains(".") && regionName.Contains(":"))
609 { 608 {
609 List<GridRegion> regions = World.GridService.GetRegionsByName(World.RegionInfo.ScopeID, regionName, 1);
610 // Try to link the region 610 // Try to link the region
611 IHyperlinkService hyperService = World.RequestModuleInterface<IHyperlinkService>(); 611 if (regions != null && regions.Count > 0)
612 if (hyperService != null)
613 { 612 {
614 GridRegion regInfo = hyperService.TryLinkRegion(presence.ControllingClient, 613 GridRegion regInfo = regions[0];
615 regionName); 614 regionName = regInfo.RegionName;
616 // Get the region name
617 if (regInfo != null)
618 {
619 regionName = regInfo.RegionName;
620 }
621 else
622 {
623 // Might need to ping the client here in case of failure??
624 }
625 } 615 }
626 } 616 }
627 presence.ControllingClient.SendTeleportLocationStart(); 617 presence.ControllingClient.SendTeleportLocationStart();
@@ -707,10 +697,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
707 CheckThreatLevel(ThreatLevel.None, "osGetAgents"); 697 CheckThreatLevel(ThreatLevel.None, "osGetAgents");
708 698
709 LSL_List result = new LSL_List(); 699 LSL_List result = new LSL_List();
710 foreach (ScenePresence avatar in World.GetAvatars()) 700 World.ForEachScenePresence(delegate(ScenePresence sp)
711 { 701 {
712 result.Add(avatar.Name); 702 if (!sp.IsChildAgent)
713 } 703 result.Add(sp.Name);
704 });
714 return result; 705 return result;
715 } 706 }
716 707
@@ -1482,7 +1473,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
1482 m_host.AddScriptLPS(1); 1473 m_host.AddScriptLPS(1);
1483 1474
1484 // Create new asset 1475 // Create new asset
1485 AssetBase asset = new AssetBase(UUID.Random(), notecardName, (sbyte)AssetType.Notecard); 1476 AssetBase asset = new AssetBase(UUID.Random(), notecardName, (sbyte)AssetType.Notecard, m_host.OwnerID.ToString());
1486 asset.Description = "Script Generated Notecard"; 1477 asset.Description = "Script Generated Notecard";
1487 string notecardData = String.Empty; 1478 string notecardData = String.Empty;
1488 1479
@@ -1695,15 +1686,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
1695 { 1686 {
1696 CheckThreatLevel(ThreatLevel.Low, "osAvatarName2Key"); 1687 CheckThreatLevel(ThreatLevel.Low, "osAvatarName2Key");
1697 1688
1698 CachedUserInfo userInfo = World.CommsManager.UserProfileCacheService.GetUserDetails(firstname, lastname); 1689 UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, firstname, lastname);
1699 1690 if (null == account)
1700 if (null == userInfo)
1701 { 1691 {
1702 return UUID.Zero.ToString(); 1692 return UUID.Zero.ToString();
1703 } 1693 }
1704 else 1694 else
1705 { 1695 {
1706 return userInfo.UserProfile.ID.ToString(); 1696 return account.PrincipalID.ToString();
1707 } 1697 }
1708 } 1698 }
1709 1699
@@ -1714,15 +1704,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
1714 1704
1715 if (UUID.TryParse(id, out key)) 1705 if (UUID.TryParse(id, out key))
1716 { 1706 {
1717 CachedUserInfo userInfo = World.CommsManager.UserProfileCacheService.GetUserDetails(key); 1707 UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, key);
1718 1708 if (null == account)
1719 if (null == userInfo)
1720 { 1709 {
1721 return ""; 1710 return "";
1722 } 1711 }
1723 else 1712 else
1724 { 1713 {
1725 return userInfo.UserProfile.Name; 1714 return account.Name;
1726 } 1715 }
1727 } 1716 }
1728 else 1717 else
@@ -2001,19 +1990,20 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
2001 CheckThreatLevel(ThreatLevel.Severe, "osKickAvatar"); 1990 CheckThreatLevel(ThreatLevel.Severe, "osKickAvatar");
2002 if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID)) 1991 if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID))
2003 { 1992 {
2004 foreach (ScenePresence presence in World.GetAvatars()) 1993 World.ForEachScenePresence(delegate(ScenePresence sp)
2005 { 1994 {
2006 if ((presence.Firstname == FirstName) && 1995 if (!sp.IsChildAgent &&
2007 presence.Lastname == SurName) 1996 sp.Firstname == FirstName &&
1997 sp.Lastname == SurName)
2008 { 1998 {
2009 // kick client... 1999 // kick client...
2010 if (alert != null) 2000 if (alert != null)
2011 presence.ControllingClient.Kick(alert); 2001 sp.ControllingClient.Kick(alert);
2012 2002
2013 // ...and close on our side 2003 // ...and close on our side
2014 presence.Scene.IncomingCloseAgent(presence.UUID); 2004 sp.Scene.IncomingCloseAgent(sp.UUID);
2015 } 2005 }
2016 } 2006 });
2017 } 2007 }
2018 } 2008 }
2019 2009
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs
index b75a2e4..d354fde 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs
@@ -29,7 +29,7 @@ using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30using OpenMetaverse; 30using OpenMetaverse;
31using OpenSim.Framework; 31using OpenSim.Framework;
32using OpenSim.Framework.Communications.Cache; 32
33using OpenSim.Region.Framework.Scenes; 33using OpenSim.Region.Framework.Scenes;
34using OpenSim.Region.ScriptEngine.Shared; 34using OpenSim.Region.ScriptEngine.Shared;
35using OpenSim.Region.ScriptEngine.Shared.Api; 35using OpenSim.Region.ScriptEngine.Shared.Api;
@@ -204,7 +204,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
204 // Is the sensor type is AGENT and not SCRIPTED then include agents 204 // Is the sensor type is AGENT and not SCRIPTED then include agents
205 if ((ts.type & AGENT) != 0 && (ts.type & SCRIPTED) == 0) 205 if ((ts.type & AGENT) != 0 && (ts.type & SCRIPTED) == 0)
206 { 206 {
207 sensedEntities.AddRange(doAgentSensor(ts)); 207 sensedEntities.AddRange(doAgentSensor(ts));
208 } 208 }
209 209
210 // If SCRIPTED or PASSIVE or ACTIVE check objects 210 // If SCRIPTED or PASSIVE or ACTIVE check objects
@@ -302,6 +302,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
302 float dz; 302 float dz;
303 303
304 Quaternion q = SensePoint.RotationOffset; 304 Quaternion q = SensePoint.RotationOffset;
305 if (SensePoint.ParentGroup.RootPart.IsAttachment)
306 {
307 // In attachments, the sensor cone always orients with the
308 // avatar rotation. This may include a nonzero elevation if
309 // in mouselook.
310
311 ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.RootPart.AttachedAvatar);
312 fromRegionPos = avatar.AbsolutePosition;
313 q = avatar.Rotation;
314 }
305 LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); 315 LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
306 LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); 316 LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
307 double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); 317 double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
@@ -404,70 +414,50 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
404 414
405 private List<SensedEntity> doAgentSensor(SenseRepeatClass ts) 415 private List<SensedEntity> doAgentSensor(SenseRepeatClass ts)
406 { 416 {
407 List<ScenePresence> presences;
408 List<SensedEntity> sensedEntities = new List<SensedEntity>(); 417 List<SensedEntity> sensedEntities = new List<SensedEntity>();
409 418
410 // If this is an avatar sense by key try to get them directly
411 // rather than getting a list to scan through
412 if (ts.keyID != UUID.Zero)
413 {
414 ScenePresence p = m_CmdManager.m_ScriptEngine.World.GetScenePresence(ts.keyID);
415 if (p == null)
416 return sensedEntities;
417 presences = new List<ScenePresence>();
418 presences.Add(p);
419 }
420 else
421 {
422 presences = new List<ScenePresence>(m_CmdManager.m_ScriptEngine.World.GetScenePresences());
423 }
424
425 // If nobody about quit fast 419 // If nobody about quit fast
426 if (presences.Count == 0) 420 if(m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0)
427 return sensedEntities; 421 return sensedEntities;
428 422
429 SceneObjectPart SensePoint = ts.host; 423 SceneObjectPart SensePoint = ts.host;
430
431 Vector3 fromRegionPos = SensePoint.AbsolutePosition; 424 Vector3 fromRegionPos = SensePoint.AbsolutePosition;
432
433 Quaternion q = SensePoint.RotationOffset; 425 Quaternion q = SensePoint.RotationOffset;
426 if (SensePoint.ParentGroup.RootPart.IsAttachment)
427 {
428 // In attachments, the sensor cone always orients with the
429 // avatar rotation. This may include a nonzero elevation if
430 // in mouselook.
431
432 ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.RootPart.AttachedAvatar);
433 fromRegionPos = avatar.AbsolutePosition;
434 q = avatar.Rotation;
435 }
434 LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); 436 LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
435 LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); 437 LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
436 double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); 438 double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
437
438 bool attached = (SensePoint.AttachmentPoint != 0); 439 bool attached = (SensePoint.AttachmentPoint != 0);
439 bool nameSearch = (ts.name != null && ts.name != "");
440 Vector3 toRegionPos; 440 Vector3 toRegionPos;
441 double dis; 441 double dis;
442 442
443 for (int i = 0; i < presences.Count; i++) 443 Action<ScenePresence> senseEntity = new Action<ScenePresence>(delegate(ScenePresence presence)
444 { 444 {
445 ScenePresence presence = presences[i]; 445 if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0)
446 bool keep = true; 446 return;
447
448 // if the object the script is in is attached and the avatar is the owner
449 // then this one is not wanted
450 if (attached && presence.UUID == SensePoint.OwnerID)
451 return;
447 452
448 if (presence.IsDeleted)
449 continue;
450
451 if (presence.IsChildAgent)
452 keep = false;
453 toRegionPos = presence.AbsolutePosition; 453 toRegionPos = presence.AbsolutePosition;
454
455 dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos)); 454 dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));
456 455
457 // are they in range 456 // are they in range
458 if (keep && dis <= ts.range) 457 if (dis <= ts.range)
459 { 458 {
460 // if the object the script is in is attached and the avatar is the owner
461 // then this one is not wanted
462 if (attached && presence.UUID == SensePoint.OwnerID)
463 keep = false;
464
465 // check the name if needed
466 if (keep && nameSearch && ts.name != presence.Name)
467 keep = false;
468
469 // Are they in the required angle of view 459 // Are they in the required angle of view
470 if (keep && ts.arc < Math.PI) 460 if (ts.arc < Math.PI)
471 { 461 {
472 // not omni-directional. Can you see it ? 462 // not omni-directional. Can you see it ?
473 // vec forward_dir = llRot2Fwd(llGetRot()) 463 // vec forward_dir = llRot2Fwd(llGetRot())
@@ -488,26 +478,40 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
488 catch 478 catch
489 { 479 {
490 } 480 }
491 if (ang_obj > ts.arc) keep = false; 481 if (ang_obj <= ts.arc)
482 {
483 sensedEntities.Add(new SensedEntity(dis, presence.UUID));
484 }
485 }
486 else
487 {
488 // If full circle is asked for, just add it
489 sensedEntities.Add(new SensedEntity(dis, presence.UUID));
492 } 490 }
493 } 491 }
494 else 492 });
495 {
496 keep = false;
497 }
498
499 // Do not report gods, not even minor ones
500 if (keep && presence.GodLevel > 0.0)
501 keep = false;
502
503 if (keep) // add to list with distance
504 {
505 sensedEntities.Add(new SensedEntity(dis, presence.UUID));
506 }
507 493
508 // If this is a search by name and we have just found it then no more to do 494 // If this is an avatar sense by key try to get them directly
509 if (nameSearch && ts.name == presence.Name) 495 // rather than getting a list to scan through
496 if (ts.keyID != UUID.Zero)
497 {
498 ScenePresence sp;
499 // Try direct lookup by UUID
500 if(!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp))
510 return sensedEntities; 501 return sensedEntities;
502 senseEntity(sp);
503 }
504 else if (ts.name != null && ts.name != "")
505 {
506 ScenePresence sp;
507 // Try lookup by name will return if/when found
508 if (!m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp))
509 return sensedEntities;
510 senseEntity(sp);
511 }
512 else
513 {
514 m_CmdManager.m_ScriptEngine.World.ForEachScenePresence(senseEntity);
511 } 515 }
512 return sensedEntities; 516 return sensedEntities;
513 } 517 }
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs
index 6239726..fba27f9 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs
@@ -1,4 +1,31 @@
1using System.Collections; 1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections;
2using OpenSim.Region.ScriptEngine.Interfaces; 29using OpenSim.Region.ScriptEngine.Interfaces;
3 30
4using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; 31using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Constants.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Constants.cs
index 522c020..f94ef4a 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Constants.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Constants.cs
@@ -70,7 +70,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
70 public const int WL_CLOUD_SCROLL_Y = 32; 70 public const int WL_CLOUD_SCROLL_Y = 32;
71 public const int WL_CLOUD_SCROLL_Y_LOCK = 33; 71 public const int WL_CLOUD_SCROLL_Y_LOCK = 33;
72 public const int WL_CLOUD_SCROLL_X_LOCK = 34; 72 public const int WL_CLOUD_SCROLL_X_LOCK = 34;
73 public const int WL_DRAW_CLASSIC_CLOUDS = 35; 73 public const int WL_DRAW_CLASSIC_CLOUDS = 35;
74 public const int WL_SUN_MOON_POSITION = 36; 74 public const int WL_SUN_MOON_POSITION = 36;
75 75
76 } 76 }
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs
index b3e4740..96f6486 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs
@@ -549,5 +549,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
549 public const int STATS_ACTIVE_SCRIPTS = 19; 549 public const int STATS_ACTIVE_SCRIPTS = 19;
550 public const int STATS_SCRIPT_LPS = 20; 550 public const int STATS_SCRIPT_LPS = 20;
551 551
552 public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED";
553 public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED";
552 } 554 }
553} 555}
diff --git a/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
index d8c0ba5..f719683 100644
--- a/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
@@ -261,13 +261,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
261 // } 261 // }
262 //} 262 //}
263 263
264 public object GetCompilerOutput(UUID assetID) 264 public string GetCompilerOutput(string assetID)
265 { 265 {
266 return Path.Combine(ScriptEnginesPath, Path.Combine( 266 return Path.Combine(ScriptEnginesPath, Path.Combine(
267 m_scriptEngine.World.RegionInfo.RegionID.ToString(), 267 m_scriptEngine.World.RegionInfo.RegionID.ToString(),
268 FilePrefix + "_compiled_" + assetID + ".dll")); 268 FilePrefix + "_compiled_" + assetID + ".dll"));
269 } 269 }
270 270
271 public string GetCompilerOutput(UUID assetID)
272 {
273 return GetCompilerOutput(assetID.ToString());
274 }
275
271 /// <summary> 276 /// <summary>
272 /// Converts script from LSL to CS and calls CompileFromCSText 277 /// Converts script from LSL to CS and calls CompileFromCSText
273 /// </summary> 278 /// </summary>
@@ -279,9 +284,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
279 linemap = null; 284 linemap = null;
280 m_warnings.Clear(); 285 m_warnings.Clear();
281 286
282 assembly = Path.Combine(ScriptEnginesPath, Path.Combine( 287 assembly = GetCompilerOutput(asset);
283 m_scriptEngine.World.RegionInfo.RegionID.ToString(),
284 FilePrefix + "_compiled_" + asset + ".dll"));
285 288
286 if (!Directory.Exists(ScriptEnginesPath)) 289 if (!Directory.Exists(ScriptEnginesPath))
287 { 290 {
diff --git a/OpenSim/Region/ScriptEngine/Shared/Instance/ScriptInstance.cs b/OpenSim/Region/ScriptEngine/Shared/Instance/ScriptInstance.cs
index 6ecafd4..b348403 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Instance/ScriptInstance.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Instance/ScriptInstance.cs
@@ -96,6 +96,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
96 private bool m_startedFromSavedState; 96 private bool m_startedFromSavedState;
97 private UUID m_CurrentStateHash; 97 private UUID m_CurrentStateHash;
98 private UUID m_RegionID; 98 private UUID m_RegionID;
99 private bool m_Suspended = false;
99 100
100 private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> 101 private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
101 m_LineMap; 102 m_LineMap;
@@ -640,158 +641,160 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
640 /// <returns></returns> 641 /// <returns></returns>
641 public object EventProcessor() 642 public object EventProcessor()
642 { 643 {
644 EventParams data = null;
643 645
644 EventParams data = null; 646 lock (m_EventQueue)
645
646 lock (m_EventQueue)
647 {
648 lock (m_Script)
649 { 647 {
650 data = (EventParams) m_EventQueue.Dequeue(); 648 if (m_Suspended)
651 if (data == null) // Shouldn't happen 649 return 0;
650
651 lock (m_Script)
652 { 652 {
653 if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown)) 653 data = (EventParams) m_EventQueue.Dequeue();
654 if (data == null) // Shouldn't happen
654 { 655 {
655 m_CurrentResult = m_Engine.QueueEventHandler(this); 656 if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
657 {
658 m_CurrentResult = m_Engine.QueueEventHandler(this);
659 }
660 else
661 {
662 m_CurrentResult = null;
663 }
664 return 0;
656 } 665 }
657 else 666
667 if (data.EventName == "timer")
668 m_TimerQueued = false;
669 if (data.EventName == "control")
658 { 670 {
659 m_CurrentResult = null; 671 if (m_ControlEventsInQueue > 0)
672 m_ControlEventsInQueue--;
660 } 673 }
661 return 0; 674 if (data.EventName == "collision")
662 } 675 m_CollisionInQueue = false;
663
664 if (data.EventName == "timer")
665 m_TimerQueued = false;
666 if (data.EventName == "control")
667 {
668 if (m_ControlEventsInQueue > 0)
669 m_ControlEventsInQueue--;
670 } 676 }
671 if (data.EventName == "collision")
672 m_CollisionInQueue = false;
673 } 677 }
674 } 678 lock(m_Script)
675 lock(m_Script) 679 {
676 { 680
677 681 //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
678 //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
679 682
680 m_DetectParams = data.DetectParams; 683 m_DetectParams = data.DetectParams;
681 684
682 if (data.EventName == "state") // Hardcoded state change 685 if (data.EventName == "state") // Hardcoded state change
683 {
684// m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
685// m_PrimName, m_ScriptName, data.Params[0].ToString());
686 m_State=data.Params[0].ToString();
687 AsyncCommandManager.RemoveScript(m_Engine,
688 m_LocalID, m_ItemID);
689
690 SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
691 m_LocalID);
692 if (part != null)
693 {
694 part.SetScriptEvents(m_ItemID,
695 (int)m_Script.GetStateEventFlags(State));
696 }
697 }
698 else
699 {
700 if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
701 data.EventName == "control") // Don't freeze avies!
702 { 686 {
687 // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
688 // m_PrimName, m_ScriptName, data.Params[0].ToString());
689 m_State=data.Params[0].ToString();
690 AsyncCommandManager.RemoveScript(m_Engine,
691 m_LocalID, m_ItemID);
692
703 SceneObjectPart part = m_Engine.World.GetSceneObjectPart( 693 SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
704 m_LocalID); 694 m_LocalID);
705 // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", 695 if (part != null)
706 // m_PrimName, m_ScriptName, data.EventName, m_State); 696 {
707 697 part.SetScriptEvents(m_ItemID,
708 try 698 (int)m_Script.GetStateEventFlags(State));
699 }
700 }
701 else
702 {
703 if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
704 data.EventName == "control") // Don't freeze avies!
709 { 705 {
710 m_CurrentEvent = data.EventName; 706 SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
711 m_EventStart = DateTime.Now; 707 m_LocalID);
712 m_InEvent = true; 708 // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
709 // m_PrimName, m_ScriptName, data.EventName, m_State);
713 710
714 m_Script.ExecuteEvent(State, data.EventName, data.Params); 711 try
712 {
713 m_CurrentEvent = data.EventName;
714 m_EventStart = DateTime.Now;
715 m_InEvent = true;
715 716
716 m_InEvent = false; 717 m_Script.ExecuteEvent(State, data.EventName, data.Params);
717 m_CurrentEvent = String.Empty;
718 718
719 if (m_SaveState) 719 m_InEvent = false;
720 { 720 m_CurrentEvent = String.Empty;
721 // This will be the very first event we deliver
722 // (state_entry) in default state
723 //
724 721
725 SaveState(m_Assembly); 722 if (m_SaveState)
723 {
724 // This will be the very first event we deliver
725 // (state_entry) in default state
726 //
726 727
727 m_SaveState = false; 728 SaveState(m_Assembly);
728 }
729 }
730 catch (Exception e)
731 {
732 // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
733 m_InEvent = false;
734 m_CurrentEvent = String.Empty;
735 729
736 if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException)) 730 m_SaveState = false;
731 }
732 }
733 catch (Exception e)
737 { 734 {
738 try 735 // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
736 m_InEvent = false;
737 m_CurrentEvent = String.Empty;
738
739 if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException))
739 { 740 {
740 // DISPLAY ERROR INWORLD 741 try
741 string text = FormatException(e); 742 {
742 743 // DISPLAY ERROR INWORLD
743 if (text.Length > 1000) 744 string text = FormatException(e);
744 text = text.Substring(0, 1000); 745
745 m_Engine.World.SimChat(Utils.StringToBytes(text), 746 if (text.Length > 1000)
746 ChatTypeEnum.DebugChannel, 2147483647, 747 text = text.Substring(0, 1000);
747 part.AbsolutePosition, 748 m_Engine.World.SimChat(Utils.StringToBytes(text),
748 part.Name, part.UUID, false); 749 ChatTypeEnum.DebugChannel, 2147483647,
750 part.AbsolutePosition,
751 part.Name, part.UUID, false);
752 }
753 catch (Exception)
754 {
755 }
756 // catch (Exception e2) // LEGIT: User Scripting
757 // {
758 // m_log.Error("[SCRIPT]: "+
759 // "Error displaying error in-world: " +
760 // e2.ToString());
761 // m_log.Error("[SCRIPT]: " +
762 // "Errormessage: Error compiling script:\r\n" +
763 // e.ToString());
764 // }
749 } 765 }
750 catch (Exception) 766 else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
751 { 767 {
768 m_InSelfDelete = true;
769 if (part != null && part.ParentGroup != null)
770 m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
771 }
772 else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
773 {
774 m_InSelfDelete = true;
775 if (part != null && part.ParentGroup != null)
776 part.Inventory.RemoveInventoryItem(m_ItemID);
752 } 777 }
753 // catch (Exception e2) // LEGIT: User Scripting
754 // {
755 // m_log.Error("[SCRIPT]: "+
756 // "Error displaying error in-world: " +
757 // e2.ToString());
758 // m_log.Error("[SCRIPT]: " +
759 // "Errormessage: Error compiling script:\r\n" +
760 // e.ToString());
761 // }
762 }
763 else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
764 {
765 m_InSelfDelete = true;
766 if (part != null && part.ParentGroup != null)
767 m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
768 }
769 else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
770 {
771 m_InSelfDelete = true;
772 if (part != null && part.ParentGroup != null)
773 part.Inventory.RemoveInventoryItem(m_ItemID);
774 } 778 }
775 } 779 }
776 } 780 }
777 }
778 781
779 lock (m_EventQueue) 782 lock (m_EventQueue)
780 {
781 if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
782 {
783 m_CurrentResult = m_Engine.QueueEventHandler(this);
784 }
785 else
786 { 783 {
787 m_CurrentResult = null; 784 if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
785 {
786 m_CurrentResult = m_Engine.QueueEventHandler(this);
787 }
788 else
789 {
790 m_CurrentResult = null;
791 }
788 } 792 }
789 }
790 793
791 m_DetectParams = null; 794 m_DetectParams = null;
792 795
793 return 0; 796 return 0;
794 } 797 }
795 } 798 }
796 799
797 public int EventTime() 800 public int EventTime()
@@ -1018,5 +1021,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
1018 { 1021 {
1019 get { return m_RegionID; } 1022 get { return m_RegionID; }
1020 } 1023 }
1024
1025 public void Suspend()
1026 {
1027 m_Suspended = true;
1028 }
1029
1030 public void Resume()
1031 {
1032 m_Suspended = false;
1033 }
1021 } 1034 }
1022} 1035}
diff --git a/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs b/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs
index 35d57d8..463b052 100644
--- a/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs
+++ b/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs
@@ -1570,5 +1570,23 @@ namespace OpenSim.Region.ScriptEngine.XEngine
1570 return new ArrayList(); 1570 return new ArrayList();
1571 } 1571 }
1572 } 1572 }
1573
1574 public void SuspendScript(UUID itemID)
1575 {
1576 IScriptInstance instance = GetInstance(itemID);
1577 if (instance == null)
1578 return;
1579
1580 instance.Suspend();
1581 }
1582
1583 public void ResumeScript(UUID itemID)
1584 {
1585 IScriptInstance instance = GetInstance(itemID);
1586 if (instance == null)
1587 return;
1588
1589 instance.Resume();
1590 }
1573 } 1591 }
1574} 1592}
diff --git a/OpenSim/Region/UserStatistics/ActiveConnectionsAJAX.cs b/OpenSim/Region/UserStatistics/ActiveConnectionsAJAX.cs
index 704b74f..dcbd717 100644
--- a/OpenSim/Region/UserStatistics/ActiveConnectionsAJAX.cs
+++ b/OpenSim/Region/UserStatistics/ActiveConnectionsAJAX.cs
@@ -68,17 +68,15 @@ namespace OpenSim.Region.UserStatistics
68 HTMLUtil.OL_O(ref output, ""); 68 HTMLUtil.OL_O(ref output, "");
69 foreach (Scene scene in all_scenes) 69 foreach (Scene scene in all_scenes)
70 { 70 {
71 ScenePresence[] avatarInScene = scene.GetScenePresences();
72
73 HTMLUtil.LI_O(ref output, String.Empty); 71 HTMLUtil.LI_O(ref output, String.Empty);
74 output.Append(scene.RegionInfo.RegionName); 72 output.Append(scene.RegionInfo.RegionName);
75 HTMLUtil.OL_O(ref output, String.Empty); 73 HTMLUtil.OL_O(ref output, String.Empty);
76 foreach (ScenePresence av in avatarInScene) 74 scene.ForEachScenePresence(delegate(ScenePresence av)
77 { 75 {
78 Dictionary<string,string> queues = new Dictionary<string, string>(); 76 Dictionary<string, string> queues = new Dictionary<string, string>();
79 if (av.ControllingClient is IStatsCollector) 77 if (av.ControllingClient is IStatsCollector)
80 { 78 {
81 IStatsCollector isClient = (IStatsCollector) av.ControllingClient; 79 IStatsCollector isClient = (IStatsCollector)av.ControllingClient;
82 queues = decodeQueueReport(isClient.Report()); 80 queues = decodeQueueReport(isClient.Report());
83 } 81 }
84 HTMLUtil.LI_O(ref output, String.Empty); 82 HTMLUtil.LI_O(ref output, String.Empty);
@@ -92,8 +90,8 @@ namespace OpenSim.Region.UserStatistics
92 else 90 else
93 { 91 {
94 output.Append(string.Format("<br /><NOBR>Position: <{0},{1},{2}></NOBR>", (int)av.AbsolutePosition.X, 92 output.Append(string.Format("<br /><NOBR>Position: <{0},{1},{2}></NOBR>", (int)av.AbsolutePosition.X,
95 (int) av.AbsolutePosition.Y, 93 (int)av.AbsolutePosition.Y,
96 (int) av.AbsolutePosition.Z)); 94 (int)av.AbsolutePosition.Z));
97 } 95 }
98 Dictionary<string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1)); 96 Dictionary<string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1));
99 97
@@ -124,7 +122,7 @@ namespace OpenSim.Region.UserStatistics
124 122
125 HTMLUtil.UL_C(ref output); 123 HTMLUtil.UL_C(ref output);
126 HTMLUtil.LI_C(ref output); 124 HTMLUtil.LI_C(ref output);
127 } 125 });
128 HTMLUtil.OL_C(ref output); 126 HTMLUtil.OL_C(ref output);
129 } 127 }
130 HTMLUtil.OL_C(ref output); 128 HTMLUtil.OL_C(ref output);