Compare commits

..

No commits in common. "master" and "BulletSim2017" have entirely different histories.

889 changed files with 111117 additions and 158163 deletions

View File

@ -1,35 +1,38 @@
# Building on Windows # Building on Windows
Steps: Steps:
* runprebuild.bat * runprebuild.bat
* Load OpenSim.sln into Visual Studio .NET and build the solution. * Load OpenSim.sln into Visual Studio .NET and build the solution.
* chdir bin * chdir bin
* copy OpenSim.ini.example to OpenSim.ini and other appropriate files in bin/config-include * copy OpenSim.ini.example to OpenSim.ini and other appropriate files in bin/config-include
* run OpenSim.exe * run OpenSim.exe
# Building on Linux / Mac # Building on Linux
Prereqs: Prereqs:
* Mono >= 2.4.3
* Mono > 5.0 * Nant >= 0.85
* On some Linux distributions you may need to install additional packages. * On some Linux distributions you may need to install additional packages.
* msbuild or xbuild if still supported by the mono version See http://opensimulator.org/wiki/Dependencies for more information.
* See http://opensimulator.org/wiki/Dependencies for more information. * May also use xbuild (included in mono distributions)
* May use Monodevelop, a cross-platform IDE
From the distribution type: From the distribution type:
* ./runprebuild.sh * ./runprebuild.sh
* type msbuild or xbuild * nant (or !* xbuild)
* cd bin * cd bin
* copy OpenSim.ini.example to OpenSim.ini and other appropriate files in bin/config-include * copy OpenSim.ini.example to OpenSim.ini and other appropriate files in bin/config-include
* review and change those ini files according to your needs * run mono OpenSim.exe
* windows: execute opensim.exe or opensim32.exe for small regions !* xbuild option switches
* linux: run ./opensim.sh !* clean: xbuild /target:clean
* msbuild (xbuild) option switches !* debug: (default) xbuild /property:Configuration=Debug
* clean: msbuild /target:clean !* release: xbuild /property:Configuration=Release
* debug: (default) msbuild /property:Configuration=Debug
* release: msbuild /property:Configuration=Release # Using Monodevelop
From the distribution type:
* ./runprebuild.sh
* type monodevelop OpenSim.sln
# References # References

View File

@ -4,9 +4,14 @@ The following people have contributed to OpenSim (Thank you for your effort!)
These folks represent the current core team for OpenSim, and are the These folks represent the current core team for OpenSim, and are the
people that make the day to day of OpenSim happen. people that make the day to day of OpenSim happen.
* justincc (OSVW Consulting, justincc.org)
* Melanie Thielker * Melanie Thielker
* Diva (Crista Lopes, University of California, Irvine) * Diva (Crista Lopes, University of California, Irvine)
* BlueWall (James Hughes)
* Nebadon Izumi (Michael Cerquoni, OSgrid)
* Snoopy Pfeffer
* Robert Adams (MisterBlue) * Robert Adams (MisterBlue)
* Oren Hurvitz (Kitely)
* Kevin Cozens * Kevin Cozens
* Leal Duarte (Ubit Umarov) * Leal Duarte (Ubit Umarov)
@ -15,8 +20,11 @@ Core developers who have temporarily (we hope) gone chasing the white rabbit.
They are in all similar to the active core developers, except that they haven't They are in all similar to the active core developers, except that they haven't
been that active lately, so their voting rights are awaiting their come back. been that active lately, so their voting rights are awaiting their come back.
* Nebadon Izumi (Michael Cerquoni, OSgrid) * Teravus (w3z)
* Alicia Raven * Arthur Rodrigo S Valadares (IBM)
* Dan Lake
* Marck
* Mic Bowman
= Past Open Sim Developers = = Past Open Sim Developers =
These folks are alumns of the OpenSim core group, but are now These folks are alumns of the OpenSim core group, but are now
@ -49,15 +57,7 @@ where we are today.
* John Hurliman * John Hurliman
* chi11ken (Genkii) * chi11ken (Genkii)
* dahlia * dahlia
* justincc (OSVW Consulting, justincc.org)
* Arthur Rodrigo S Valadares (IBM)
* BlueWall (James Hughes)
* Dan Lake
* Marck
* Mic Bowman
* Oren Hurvitz (Kitely)
* Snoopy Pfeffer
* Teravus (w3z)
= Additional OpenSim Contributors = = Additional OpenSim Contributors =
These folks have contributed code patches or content to OpenSimulator to help make it These folks have contributed code patches or content to OpenSimulator to help make it
@ -69,9 +69,9 @@ what it is today.
* alex_carnell * alex_carnell
* Alan Webb (IBM) * Alan Webb (IBM)
* Aleric * Aleric
* Alicia Raven
* Allen Kerensky * Allen Kerensky
* BigFootAg * BigFootAg
* Bill Blight
* BlueWall Slade * BlueWall Slade
* bobshaffer2 * bobshaffer2
* brianw/Sir_Ahzz * brianw/Sir_Ahzz
@ -131,7 +131,6 @@ what it is today.
* KittyLiu * KittyLiu
* Kurt Taylor (IBM) * Kurt Taylor (IBM)
* Lani Global * Lani Global
* lickx
* lillith_xue * lillith_xue
* lkalif * lkalif
* LuciusSirnah * LuciusSirnah
@ -143,7 +142,6 @@ what it is today.
* Mandarinka Tasty * Mandarinka Tasty
* MarcelEdward * MarcelEdward
* Matt Lehmann * Matt Lehmann
* mewtwo0641
* Mic Bowman * Mic Bowman
* Michelle Argus * Michelle Argus
* Michael Cortez (The Flotsam Project, http://osflotsam.org/) * Michael Cortez (The Flotsam Project, http://osflotsam.org/)
@ -151,7 +149,6 @@ what it is today.
* Micheil Merlin * Micheil Merlin
* Mike Osias (IBM) * Mike Osias (IBM)
* Mike Pitman (IBM) * Mike Pitman (IBM)
* Mike Rieker (Dreamnation)
* mikemig * mikemig
* mikkopa/_someone - RealXtend * mikkopa/_someone - RealXtend
* Misterblue * Misterblue
@ -185,20 +182,16 @@ what it is today.
* SpotOn3D * SpotOn3D
* Stefan_Boom / stoehr * Stefan_Boom / stoehr
* Steven Zielinski (MOSES) * Steven Zielinski (MOSES)
* Stolen Ruby
* Strawberry Fride * Strawberry Fride
* Talun * Talun
* TechplexEngineer (Blake Bourque) * TechplexEngineer (Blake Bourque)
* TBG Renfold * TBG Renfold
* Terry Ford
* tglion * tglion
* tlaukkan/Tommil (Tommi S. E. Laukkanen, Bubble Cloud) * tlaukkan/Tommil (Tommi S. E. Laukkanen, Bubble Cloud)
* TomDataWorks * TomDataWorks
* TomTheDragon (muckwaddle) * TomTheDragon (muckwaddle)
* tyre * tyre
* uriesk
* Vegaslon <vegaslon@gmail.com> * Vegaslon <vegaslon@gmail.com>
* Vincent Sylvester
* VikingErik * VikingErik
* Vytek * Vytek
* webmage (IBM) * webmage (IBM)

41
OpenSim/Addons/Groups/GroupsMessagingModule.cs Executable file → Normal file
View File

@ -252,7 +252,7 @@ namespace OpenSim.Groups
m_debugEnabled = verbose; m_debugEnabled = verbose;
MainConsole.Instance.Output("{0} verbose logging set to {1}", Name, m_debugEnabled); MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled);
} }
/// <summary> /// <summary>
@ -599,16 +599,13 @@ namespace OpenSim.Groups
{ {
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message"); if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message");
UUID fromAgent = new UUID(msg.fromAgentID);
// Force? open the group session dialog??? // Force? open the group session dialog???
// and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg); // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>(); IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
if (eq != null)
{
eq.ChatterboxInvitation( eq.ChatterboxInvitation(
GroupID GroupID
, groupInfo.GroupName , groupInfo.GroupName
, fromAgent , new UUID(msg.fromAgentID)
, msg.message , msg.message
, AgentID , AgentID
, msg.fromAgentName , msg.fromAgentName
@ -623,10 +620,15 @@ namespace OpenSim.Groups
, OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName) , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
); );
var update = new GroupChatListAgentUpdateData(AgentID); eq.ChatterBoxSessionAgentListUpdates(
var updates = new List<GroupChatListAgentUpdateData> { update }; new UUID(GroupID)
eq.ChatterBoxSessionAgentListUpdates(GroupID, new UUID(msg.toAgentID), updates); , AgentID
} , new UUID(msg.toAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
, true // Enter
);
} }
} }
} }
@ -661,12 +663,15 @@ namespace OpenSim.Groups
ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID); ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null) queue.ChatterBoxSessionAgentListUpdates(
{ GroupID
var update = new GroupChatListAgentUpdateData(AgentID); , AgentID
var updates = new List<GroupChatListAgentUpdateData> { update }; , new UUID(im.toAgentID)
queue.ChatterBoxSessionAgentListUpdates(GroupID, remoteClient.AgentId, updates); , false //canVoiceChat
} , false //isModerator
, false //text mute
, true
);
} }
} }
@ -708,7 +713,11 @@ namespace OpenSim.Groups
bodyMap.Add("session_info", sessionMap); bodyMap.Add("session_info", sessionMap);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
queue?.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
if (queue != null)
{
queue.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
}
} }
private void DebugGridInstantMessage(GridInstantMessage im) private void DebugGridInstantMessage(GridInstantMessage im)

232
OpenSim/Addons/Groups/GroupsModule.cs Executable file → Normal file
View File

@ -38,7 +38,7 @@ using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using PermissionMask = OpenSim.Framework.PermissionMask; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
namespace OpenSim.Groups namespace OpenSim.Groups
{ {
@ -127,7 +127,7 @@ namespace OpenSim.Groups
m_debugEnabled = verbose; m_debugEnabled = verbose;
MainConsole.Instance.Output("{0} verbose logging set to {1}", Name, m_debugEnabled); MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled);
} }
public void RegionLoaded(Scene scene) public void RegionLoaded(Scene scene)
@ -233,7 +233,7 @@ namespace OpenSim.Groups
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
//client.OnRequestAvatarProperties += OnRequestAvatarProperties; client.OnRequestAvatarProperties += OnRequestAvatarProperties;
} }
@ -249,7 +249,7 @@ namespace OpenSim.Groups
// There might be some problem with the thread we're generating this on but not // There might be some problem with the thread we're generating this on but not
// doing the update at this time causes problems (Mantis #7920 and #7915) // doing the update at this time causes problems (Mantis #7920 and #7915)
// TODO: move sending this update to a later time in the rootification of the client. // TODO: move sending this update to a later time in the rootification of the client.
if(!sp.m_haveGroupInformation) if(!sp.haveGroupInformation)
SendAgentGroupDataUpdate(sp.ControllingClient, false); SendAgentGroupDataUpdate(sp.ControllingClient, false);
} }
@ -261,7 +261,7 @@ namespace OpenSim.Groups
// Used for Notices and Group Invites/Accept/Reject // Used for Notices and Group Invites/Accept/Reject
sp.ControllingClient.OnInstantMessage -= OnInstantMessage; sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
} }
/*
private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{ {
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@ -269,7 +269,7 @@ namespace OpenSim.Groups
GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
} }
*/
private void OnClientClosed(UUID AgentId, Scene scene) private void OnClientClosed(UUID AgentId, Scene scene)
{ {
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@ -281,7 +281,7 @@ namespace OpenSim.Groups
if (client != null) if (client != null)
{ {
client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
//client.OnRequestAvatarProperties -= OnRequestAvatarProperties; client.OnRequestAvatarProperties -= OnRequestAvatarProperties;
// make child possible not called? // make child possible not called?
client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
client.OnInstantMessage -= OnInstantMessage; client.OnInstantMessage -= OnInstantMessage;
@ -344,24 +344,14 @@ namespace OpenSim.Groups
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{ {
if (m_debugEnabled) if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_log.DebugFormat("[Groups]: OnInstantMessage called");
if(remoteClient == null || !remoteClient.IsActive || remoteClient.AgentId == UUID.Zero)
return;
Scene scene = (Scene)remoteClient.Scene;
if (scene == null)
return;
string remoteAgentIDstr = remoteClient.AgentId.ToString();
//m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog); //m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog);
// Group invitations // Group invitations
if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
{ {
UUID inviteID = new UUID(im.imSessionID); UUID inviteID = new UUID(im.imSessionID);
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(remoteAgentIDstr, inviteID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
if (inviteInfo == null) if (inviteInfo == null)
{ {
@ -384,7 +374,7 @@ namespace OpenSim.Groups
// and the sessionid is the role // and the sessionid is the role
string reason = string.Empty; string reason = string.Empty;
if (!m_groupData.AddAgentToGroup(remoteAgentIDstr, invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason)) if (!m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason))
remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false); remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false);
else else
{ {
@ -411,155 +401,104 @@ namespace OpenSim.Groups
} }
} }
m_groupData.RemoveAgentToGroupInvite(remoteAgentIDstr, inviteID); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
} }
// Reject // Reject
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
{ {
if (m_debugEnabled) if (m_debugEnabled) m_log.DebugFormat("[Groups]: Received a reject invite notice.");
m_log.DebugFormat("[Groups]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
m_groupData.RemoveAgentToGroupInvite(remoteAgentIDstr, inviteID); m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID);
m_groupData.RemoveAgentFromGroup(remoteAgentIDstr, inviteInfo.AgentID, inviteInfo.GroupID);
} }
} }
} }
// Group notices // Group notices
else if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
{ {
if (!m_groupNoticesEnabled) if (!m_groupNoticesEnabled)
{
return; return;
}
UUID GroupID = new UUID(im.toAgentID); UUID GroupID = new UUID(im.toAgentID);
GroupMembershipData grpMemberData = m_groupData.GetAgentGroupMembership(remoteAgentIDstr, remoteAgentIDstr, GroupID); if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null) != null)
if (grpMemberData == null)
{ {
remoteClient.SendAgentAlertMessage("Group membership not found", false);
return;
}
if ((grpMemberData.GroupPowers & (ulong)GroupPowers.SendNotices) == 0)
{
remoteClient.SendAgentAlertMessage("No permission to send notice to group", false);
return;
}
int index = im.message.IndexOf('|');
if (index < 0)
return;
string Subject = im.message.Substring(0, index);
string Message = im.message.Substring(index + 1);
UUID NoticeID = UUID.Random(); UUID NoticeID = UUID.Random();
string Subject = im.message.Substring(0, im.message.IndexOf('|'));
string Message = im.message.Substring(Subject.Length + 1);
InventoryItemBase item = null; InventoryItemBase item = null;
bool hasAttachment = false; bool hasAttachment = false;
if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0)
{ {
UUID itemID = UUID.Zero;
UUID ownerID = UUID.Zero;
try
{
string binBucket = Utils.BytesToString(im.binaryBucket);
binBucket = binBucket.Substring(15); // remove extra LLSD pre header
OSDMap binBucketMAP = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket);
itemID = binBucketMAP["item_id"].AsUUID();
ownerID = binBucketMAP["owner_id"].AsUUID();
}
catch
{
m_log.DebugFormat("[GROUPS]: failed to decode group notice bucket");
return;
}
if (itemID != UUID.Zero && ownerID != UUID.Zero)
{
item = scene.InventoryService.GetItem(ownerID, itemID);
if(item != null)
{
if ((item.CurrentPermissions & (uint)(PermissionMask.Transfer | PermissionMask.Copy)) !=
(uint)(PermissionMask.Transfer | PermissionMask.Copy))
{
remoteClient.SendAgentAlertMessage("Item must be have Copy and Transfer rights to attach to group notice", false);
return;
}
}
hasAttachment = true; hasAttachment = true;
string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket);
binBucket = binBucket.Remove(0, 14).Trim();
OSD binBucketOSD = OSDParser.DeserializeLLSDXml(binBucket);
if (binBucketOSD is OSDMap)
{
OSDMap binBucketMap = (OSDMap)binBucketOSD;
UUID itemID = binBucketMap["item_id"].AsUUID();
UUID ownerID = binBucketMap["owner_id"].AsUUID();
item = m_sceneList[0].InventoryService.GetItem(ownerID, itemID);
} }
else
m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType());
} }
if (m_groupData.AddGroupNotice(remoteAgentIDstr, GroupID, NoticeID, im.fromAgentName, Subject, Message, if (m_groupData.AddGroupNotice(GetRequestingAgentIDStr(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message,
hasAttachment, hasAttachment,
(byte)(item == null ? 0 : item.AssetType), (byte)(item == null ? 0 : item.AssetType),
item == null ? null : item.Name, item == null ? null : item.Name,
item == null ? UUID.Zero : item.ID, item == null ? UUID.Zero : item.ID,
item == null ? UUID.Zero.ToString() : item.Owner.ToString())) item == null ? UUID.Zero.ToString() : item.Owner.ToString()))
{ {
OnNewGroupNotice?.Invoke(GroupID, NoticeID); if (OnNewGroupNotice != null)
{
OnNewGroupNotice(GroupID, NoticeID);
}
// Send notice out to everyone that wants notices // Send notice out to everyone that wants notices
foreach (GroupMembersData member in m_groupData.GetGroupMembers(remoteAgentIDstr, GroupID)) foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), GroupID))
{ {
GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)InstantMessageDialog.GroupNotice);
if (member.AcceptNotices) if (member.AcceptNotices)
{ {
// Build notice IIM, one of reach, because the sending may be async // Build notice IIM, one of reach, because the sending may be async
GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice);
msg.toAgentID = member.AgentID.Guid; msg.toAgentID = member.AgentID.Guid;
OutgoingInstantMessage(msg, member.AgentID); OutgoingInstantMessage(msg, member.AgentID);
} }
} }
} }
} }
}
if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted)
{ {
if (!m_groupNoticesEnabled) if (im.binaryBucket.Length < 16) // Invalid
return; return;
//// 16 bytes are the UUID. Maybe.
// UUID folderID = new UUID(im.binaryBucket, 0);
UUID noticeID = new UUID(im.imSessionID); UUID noticeID = new UUID(im.imSessionID);
if (m_debugEnabled) GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteClient.AgentId.ToString(), noticeID);
m_log.DebugFormat("[xmlGROUPS]: Accepted notice {0} for {1}", noticeID, remoteClient.AgentId); if (notice != null)
if (noticeID == UUID.Zero)
return;
UUID folderID = UUID.Zero;
try
{ {
if (im.binaryBucket != null && im.binaryBucket.Length >= 16)
folderID = new UUID(im.binaryBucket, 0);
}
catch
{
m_log.DebugFormat("[xmlGROUPS]: GroupNoticeInventoryAccepted failed to decode target folder");
return;
}
GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteAgentIDstr, noticeID);
if (notice == null)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.",
noticeID, remoteClient.AgentId);
return;
}
string tmp;
UUID giver = new UUID(im.toAgentID); UUID giver = new UUID(im.toAgentID);
string tmp = string.Empty;
Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp); Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp);
m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId);
string message;
string message = "Could not find group notice attached item"; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId,
InventoryItemBase itemCopy = scene.GiveInventoryItem(remoteClient.AgentId, giver, notice.noticeData.AttachmentItemID, out message);
giver, notice.noticeData.AttachmentItemID, folderID, out message);
if (itemCopy == null) if (itemCopy == null)
{ {
@ -569,79 +508,14 @@ namespace OpenSim.Groups
remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
} }
else if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryDeclined)
{
if (!m_groupNoticesEnabled)
return;
UUID noticeID = new UUID(im.imSessionID);
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS]: Accepted notice {0} for {1}", noticeID, remoteAgentIDstr);
if (noticeID == UUID.Zero)
return;
UUID remoteAgentID = remoteClient.AgentId;
GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteAgentIDstr, noticeID);
if (notice == null)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.",
noticeID, remoteClient.AgentId);
return;
} }
string giver = notice.noticeData.AttachmentOwnerID;
UUID attachmentUUID = notice.noticeData.AttachmentItemID;
if (attachmentUUID == null ||
attachmentUUID == UUID.Zero ||
giver == null ||
giver == UUID.Zero.ToString()
)
return;
if (m_debugEnabled)
m_log.DebugFormat("[xmlGroups]: Deny inventory from {0} to {1}", giver, remoteAgentIDstr);
string message = String.Empty;
InventoryItemBase itemCopy = scene.InventoryService.GetItem(remoteAgentID, attachmentUUID);
if (itemCopy == null)
return;
InventoryFolderBase trash = scene.InventoryService.GetFolderForType(remoteAgentID, FolderType.Trash);
if (trash == null)
{
m_log.DebugFormat("[GROUPS]: failed to find trash folder for {0} ", remoteAgentID);
return;
}
if (itemCopy.Folder == trash.ID || remoteAgentIDstr == notice.noticeData.AttachmentOwnerID)
return;
itemCopy.Folder = trash.ID;
scene.InventoryService.MoveItems(itemCopy.Owner, new List<InventoryItemBase>() { itemCopy });
if (itemCopy == null)
{
remoteClient.SendAgentAlertMessage(message, false);
return;
}
remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
}
// Interop, received special 210 code for ejecting a group member // Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid // this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presense server of some kind to find out where the // TODO:FIXME: Use a presense server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them, // client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue // or provide the notification via xmlrpc update queue
else if ((im.dialog == 210)) if ((im.dialog == 210))
{ {
// This is sent from the region that the ejectee was ejected from // This is sent from the region that the ejectee was ejected from
// if it's being delivered here, then the ejectee is here // if it's being delivered here, then the ejectee is here
@ -1075,7 +949,6 @@ namespace OpenSim.Groups
bucket = new byte[19 + name.Length]; bucket = new byte[19 + name.Length];
bucket[0] = 1; // has attachment? bucket[0] = 1; // has attachment?
bucket[1] = info.noticeData.AttachmentType; // attachment type bucket[1] = info.noticeData.AttachmentType; // attachment type
info.GroupID.ToBytes(bucket, 2);
name.CopyTo(bucket, 18); name.CopyTo(bucket, 18);
} }
else else
@ -1086,6 +959,7 @@ namespace OpenSim.Groups
bucket[18] = 0; // null terminated bucket[18] = 0; // null terminated
} }
info.GroupID.ToBytes(bucket, 2);
msg.binaryBucket = bucket; msg.binaryBucket = bucket;
} }
else else
@ -1334,7 +1208,7 @@ namespace OpenSim.Groups
public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query)
{ {
return m_groupData.FindGroups(remoteClient.AgentId.ToString(), query); return m_groupData.FindGroups(GetRequestingAgentIDStr(remoteClient), query);
} }
#endregion #endregion

View File

@ -246,9 +246,9 @@ namespace OpenSim.Groups
return null; return null;
} }
public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search) public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{ {
return m_LocalGroupsConnector.FindGroups(RequestingAgentIDstr, search); return m_LocalGroupsConnector.FindGroups(AgentUUI(RequestingAgentID), search);
} }
public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID) public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)
@ -605,8 +605,14 @@ namespace OpenSim.Groups
private string AgentUUI(string AgentIDStr) private string AgentUUI(string AgentIDStr)
{ {
UUID AgentID = UUID.Zero; UUID AgentID = UUID.Zero;
if (!UUID.TryParse(AgentIDStr, out AgentID) || AgentID == UUID.Zero) try
return UUID.Zero.ToString(); {
AgentID = new UUID(AgentIDStr);
}
catch (FormatException)
{
return AgentID.ToString();
}
if (m_UserManagement.IsLocalGridUser(AgentID)) if (m_UserManagement.IsLocalGridUser(AgentID))
return AgentID.ToString(); return AgentID.ToString();
@ -630,8 +636,14 @@ namespace OpenSim.Groups
private string AgentUUIForOutside(string AgentIDStr) private string AgentUUIForOutside(string AgentIDStr)
{ {
UUID AgentID = UUID.Zero; UUID AgentID = UUID.Zero;
if (!UUID.TryParse(AgentIDStr, out AgentID) || AgentID == UUID.Zero) try
return UUID.Zero.ToString(); {
AgentID = new UUID(AgentIDStr);
}
catch (FormatException)
{
return AgentID.ToString();
}
AgentCircuitData agent = null; AgentCircuitData agent = null;
foreach (Scene scene in m_Scenes) foreach (Scene scene in m_Scenes)

View File

@ -39,7 +39,7 @@ namespace OpenSim.Groups
bool UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee,
bool openEnrollment, bool allowPublish, bool maturePublish, out string reason); bool openEnrollment, bool allowPublish, bool maturePublish, out string reason);
ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string GroupName); ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string GroupName);
List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search); List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search);
List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID); List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID);
bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason); bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason);

View File

@ -173,9 +173,9 @@ namespace OpenSim.Groups
return null; return null;
} }
public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search) public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{ {
return m_GroupsService.FindGroups(RequestingAgentIDstr, search); return m_GroupsService.FindGroups(RequestingAgentID, search);
} }
public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID) public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)

View File

@ -153,7 +153,7 @@ namespace OpenSim.Groups
return GroupsDataUtils.GroupRecord((Dictionary<string, object>)ret["RESULT"]); return GroupsDataUtils.GroupRecord((Dictionary<string, object>)ret["RESULT"]);
} }
public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string query) public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string query)
{ {
List<DirGroupsReplyData> hits = new List<DirGroupsReplyData>(); List<DirGroupsReplyData> hits = new List<DirGroupsReplyData>();
if (string.IsNullOrEmpty(query)) if (string.IsNullOrEmpty(query))
@ -161,7 +161,7 @@ namespace OpenSim.Groups
Dictionary<string, object> sendData = new Dictionary<string, object>(); Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["Query"] = query; sendData["Query"] = query;
sendData["RequestingAgentID"] = RequestingAgentIDstr; sendData["RequestingAgentID"] = RequestingAgentID;
Dictionary<string, object> ret = MakeRequest("FINDGROUPS", sendData); Dictionary<string, object> ret = MakeRequest("FINDGROUPS", sendData);

View File

@ -192,10 +192,10 @@ namespace OpenSim.Groups
}); });
} }
public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search) public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{ {
// TODO! // TODO!
return m_GroupsService.FindGroups(RequestingAgentIDstr, search); return m_GroupsService.FindGroups(RequestingAgentID, search);
} }
public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason) public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason)

View File

@ -43,8 +43,7 @@ namespace OpenSim.Groups
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const GroupPowers DefaultEveryonePowers = public const GroupPowers DefaultEveryonePowers = GroupPowers.AllowSetHome |
GroupPowers.AllowSetHome |
GroupPowers.Accountable | GroupPowers.Accountable |
GroupPowers.JoinChat | GroupPowers.JoinChat |
GroupPowers.AllowVoiceChat | GroupPowers.AllowVoiceChat |
@ -52,23 +51,31 @@ namespace OpenSim.Groups
GroupPowers.StartProposal | GroupPowers.StartProposal |
GroupPowers.VoteOnProposal; GroupPowers.VoteOnProposal;
public const GroupPowers OfficersPowers = DefaultEveryonePowers | public const GroupPowers OwnerPowers = GroupPowers.Accountable |
GroupPowers.AllowEditLand |
GroupPowers.AllowFly | GroupPowers.AllowFly |
GroupPowers.AllowLandmark | GroupPowers.AllowLandmark |
GroupPowers.AllowRez | GroupPowers.AllowRez |
GroupPowers.AllowSetHome |
GroupPowers.AllowVoiceChat |
GroupPowers.AssignMember |
GroupPowers.AssignMemberLimited | GroupPowers.AssignMemberLimited |
GroupPowers.ChangeActions |
GroupPowers.ChangeIdentity | GroupPowers.ChangeIdentity |
GroupPowers.ChangeMedia | GroupPowers.ChangeMedia |
GroupPowers.ChangeOptions | GroupPowers.ChangeOptions |
GroupPowers.CreateRole |
GroupPowers.DeedObject | GroupPowers.DeedObject |
GroupPowers.DeleteRole |
GroupPowers.Eject | GroupPowers.Eject |
GroupPowers.FindPlaces | GroupPowers.FindPlaces |
GroupPowers.HostEvent |
GroupPowers.Invite | GroupPowers.Invite |
GroupPowers.JoinChat |
GroupPowers.LandChangeIdentity | GroupPowers.LandChangeIdentity |
GroupPowers.LandDeed | GroupPowers.LandDeed |
GroupPowers.LandDivideJoin | GroupPowers.LandDivideJoin |
GroupPowers.LandEdit | GroupPowers.LandEdit |
GroupPowers.AllowEnvironment |
GroupPowers.LandEjectAndFreeze | GroupPowers.LandEjectAndFreeze |
GroupPowers.LandGardening | GroupPowers.LandGardening |
GroupPowers.LandManageAllowed | GroupPowers.LandManageAllowed |
@ -77,29 +84,19 @@ namespace OpenSim.Groups
GroupPowers.LandOptions | GroupPowers.LandOptions |
GroupPowers.LandRelease | GroupPowers.LandRelease |
GroupPowers.LandSetSale | GroupPowers.LandSetSale |
GroupPowers.MemberVisible |
GroupPowers.ModerateChat | GroupPowers.ModerateChat |
GroupPowers.ObjectManipulate | GroupPowers.ObjectManipulate |
GroupPowers.ObjectSetForSale | GroupPowers.ObjectSetForSale |
GroupPowers.ReceiveNotices |
GroupPowers.RemoveMember |
GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupOwned |
GroupPowers.ReturnGroupSet | GroupPowers.ReturnGroupSet |
GroupPowers.ReturnNonGroup | GroupPowers.ReturnNonGroup |
GroupPowers.RoleProperties | GroupPowers.RoleProperties |
GroupPowers.SendNotices | GroupPowers.SendNotices |
GroupPowers.SetLandingPoint; GroupPowers.SetLandingPoint |
GroupPowers.StartProposal |
public const GroupPowers OwnerPowers = OfficersPowers | GroupPowers.VoteOnProposal;
GroupPowers.Accountable |
GroupPowers.AllowEditLand |
GroupPowers.AssignMember |
GroupPowers.ChangeActions |
GroupPowers.CreateRole |
GroupPowers.DeleteRole |
GroupPowers.ExperienceAdmin |
GroupPowers.ExperienceCreator |
GroupPowers.GroupBanAccess |
GroupPowers.HostEvent |
GroupPowers.RemoveMember;
#region Daily Cleanup #region Daily Cleanup
@ -154,25 +151,20 @@ namespace OpenSim.Groups
data.Data["ShowInList"] = showInList ? "1" : "0"; data.Data["ShowInList"] = showInList ? "1" : "0";
data.Data["AllowPublish"] = allowPublish ? "1" : "0"; data.Data["AllowPublish"] = allowPublish ? "1" : "0";
data.Data["MaturePublish"] = maturePublish ? "1" : "0"; data.Data["MaturePublish"] = maturePublish ? "1" : "0";
UUID ownerRoleID = UUID.Random(); UUID roleID = UUID.Random();
data.Data["OwnerRoleID"] = ownerRoleID.ToString(); data.Data["OwnerRoleID"] = roleID.ToString();
if (!m_Database.StoreGroup(data)) if (!m_Database.StoreGroup(data))
return UUID.Zero; return UUID.Zero;
// Create Everyone role // Create Everyone role
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, UUID.Zero, "Everyone", "Everyone in the group is in the everyone role.", "Member of " + name, (ulong)DefaultEveryonePowers, true); _AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, UUID.Zero, "Everyone", "Everyone in the group", "Member of " + name, (ulong)DefaultEveryonePowers, true);
// Create Officers role
UUID officersRoleID = UUID.Random();
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, officersRoleID, "Officers", "The officers of the group, with more powers than regular members.", "Officer of " + name, (ulong)OfficersPowers, true);
// Create Owner role // Create Owner role
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, ownerRoleID, "Owners", "Owners of the group", "Owner of " + name, (ulong)OwnerPowers, true); _AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, roleID, "Owners", "Owners of the group", "Owner of " + name, (ulong)OwnerPowers, true);
// Add founder to group // Add founder to group
_AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, ownerRoleID); _AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, roleID);
_AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, officersRoleID);
return data.GroupID; return data.GroupID;
} }
@ -231,22 +223,15 @@ namespace OpenSim.Groups
if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty) if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty)
continue; continue;
int nmembers = m_Database.MemberCount(d.GroupID);
if(nmembers == 0)
continue;
DirGroupsReplyData g = new DirGroupsReplyData(); DirGroupsReplyData g = new DirGroupsReplyData();
g.groupID = d.GroupID;
if (d.Data.ContainsKey("Name")) if (d.Data.ContainsKey("Name"))
g.groupName = d.Data["Name"]; g.groupName = d.Data["Name"];
else else
{
m_log.DebugFormat("[Groups]: Key Name not found"); m_log.DebugFormat("[Groups]: Key Name not found");
continue;
}
g.groupID = d.GroupID; g.members = m_Database.MemberCount(d.GroupID);
g.members = nmembers;
groups.Add(g); groups.Add(g);
} }
@ -500,7 +485,7 @@ namespace OpenSim.Groups
// check permissions // check permissions
bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited); bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited);
bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) || IsOwner(RequestingAgentID, GroupID); bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) | IsOwner(RequestingAgentID, GroupID);
if (!limited && !unlimited) if (!limited && !unlimited)
{ {
m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID); m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID);
@ -858,7 +843,7 @@ namespace OpenSim.Groups
return false; return false;
} }
if (!add && data == null) // it doesn't exist, can't update if (!add && data == null) // it deosn't exist, can't update
{ {
m_log.DebugFormat("[Groups]: Group {0} doesn't exist. Can't update it", groupID); m_log.DebugFormat("[Groups]: Group {0} doesn't exist. Can't update it", groupID);
return false; return false;

View File

@ -114,6 +114,7 @@ namespace OpenSim.OfflineIM
scene.ForEachClient(delegate(IClientAPI client) scene.ForEachClient(delegate(IClientAPI client)
{ {
client.OnRetrieveInstantMessages -= RetrieveInstantMessages; client.OnRetrieveInstantMessages -= RetrieveInstantMessages;
client.OnMuteListRequest -= OnMuteListRequest;
}); });
} }
@ -161,6 +162,7 @@ namespace OpenSim.OfflineIM
private void OnNewClient(IClientAPI client) private void OnNewClient(IClientAPI client)
{ {
client.OnRetrieveInstantMessages += RetrieveInstantMessages; client.OnRetrieveInstantMessages += RetrieveInstantMessages;
client.OnMuteListRequest += OnMuteListRequest;
} }
private void RetrieveInstantMessages(IClientAPI client) private void RetrieveInstantMessages(IClientAPI client)
@ -192,6 +194,20 @@ namespace OpenSim.OfflineIM
} }
} }
// Apparently this is needed in order for the viewer to request the IMs.
private void OnMuteListRequest(IClientAPI client, uint crc)
{
m_log.DebugFormat("[OfflineIM.V2] Got mute list request for crc {0}", crc);
string filename = "mutes" + client.AgentId.ToString();
IXfer xfer = client.Scene.RequestModuleInterface<IXfer>();
if (xfer != null)
{
xfer.AddNewFile(filename, new Byte[0]);
client.SendMuteListUpdate(filename);
}
}
private void UndeliveredMessage(GridInstantMessage im) private void UndeliveredMessage(GridInstantMessage im)
{ {
if (im.dialog != (byte)InstantMessageDialog.MessageFromObject && if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&

View File

@ -110,8 +110,9 @@ namespace OpenSim.OfflineIM
{ {
m_serializer.Serialize(writer, im); m_serializer.Serialize(writer, im);
writer.Flush(); writer.Flush();
imXml = Util.UTF8NoBomEncoding.GetString(mstream.ToArray());
} }
imXml = Util.UTF8NoBomEncoding.GetString(mstream.ToArray());
} }
OfflineIMData data = new OfflineIMData(); OfflineIMData data = new OfflineIMData();

View File

@ -122,7 +122,7 @@ namespace OpenSim.ApplicationPlugins.LoadRegions
throw ex; throw ex;
} }
if (regionCount > 0 || allowRegionless) if (regionCount > 0 | allowRegionless)
return regionInfos; return regionInfos;
m_log.Debug("[WEBLOADER]: Request yielded no regions."); m_log.Debug("[WEBLOADER]: Request yielded no regions.");

View File

@ -1934,7 +1934,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
GetSceneFromRegionParams(requestData, responseData, out scene); GetSceneFromRegionParams(requestData, responseData, out scene);
health = scene.GetHealth(out flags, out text); health = scene.GetHealth(out flags, out text);
} }
catch catch (Exception e)
{ {
responseData["error"] = null; responseData["error"] = null;
} }

View File

@ -28,7 +28,6 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
@ -50,9 +49,9 @@ namespace OpenSim.Framework.Capabilities
/// </summary> /// </summary>
public delegate IClientAPI GetClientDelegate(UUID agentID); public delegate IClientAPI GetClientDelegate(UUID agentID);
public class Caps : IDisposable public class Caps
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_httpListenerHostName; private string m_httpListenerHostName;
private uint m_httpListenPort; private uint m_httpListenPort;
@ -65,8 +64,8 @@ namespace OpenSim.Framework.Capabilities
private CapsHandlers m_capsHandlers; private CapsHandlers m_capsHandlers;
private ConcurrentDictionary<string, PollServiceEventArgs> m_pollServiceHandlers private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers
= new ConcurrentDictionary<string, PollServiceEventArgs>(); = new Dictionary<string, PollServiceEventArgs>();
private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>(); private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>();
@ -120,19 +119,6 @@ namespace OpenSim.Framework.Capabilities
get { return m_externalCapsHandlers; } get { return m_externalCapsHandlers; }
} }
[Flags]
public enum CapsFlags:uint
{
None = 0,
SentSeeds = 1,
ObjectAnim = 0x100,
WLEnv = 0x200,
AdvEnv = 0x400
}
public CapsFlags Flags { get; set;}
public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath, public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
UUID agent, string regionName) UUID agent, string regionName)
{ {
@ -152,35 +138,12 @@ namespace OpenSim.Framework.Capabilities
m_agentID = agent; m_agentID = agent;
m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort); m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort);
m_regionName = regionName; m_regionName = regionName;
Flags = CapsFlags.None;
m_capsActive.Reset(); m_capsActive.Reset();
} }
~Caps() ~Caps()
{
Flags = CapsFlags.None;
if (m_capsActive!= null)
{ {
m_capsActive.Dispose(); m_capsActive.Dispose();
m_capsActive = null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
Flags = CapsFlags.None;
if (m_capsActive != null)
{
DeregisterHandlers();
m_capsActive.Dispose();
m_capsActive = null;
}
} }
/// <summary> /// <summary>
@ -194,27 +157,15 @@ namespace OpenSim.Framework.Capabilities
m_capsHandlers[capName] = handler; m_capsHandlers[capName] = handler;
} }
public void RegisterSimpleHandler(string capName, ISimpleStreamHandler handler, bool addToListener = true)
{
//m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
m_capsHandlers.AddSimpleHandler(capName, handler, addToListener);
}
public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler) public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler)
{ {
// m_log.DebugFormat( // m_log.DebugFormat(
// "[CAPS]: Registering handler with name {0}, url {1} for {2}", // "[CAPS]: Registering handler with name {0}, url {1} for {2}",
// capName, pollServiceHandler.Url, m_agentID, m_regionName); // capName, pollServiceHandler.Url, m_agentID, m_regionName);
if(!m_pollServiceHandlers.TryAdd(capName, pollServiceHandler)) m_pollServiceHandlers.Add(capName, pollServiceHandler);
{
m_log.ErrorFormat(
"[CAPS]: Handler with name {0} already registered (ulr {1}, agent {2}, region {3}",
capName, pollServiceHandler.Url, m_agentID, m_regionName);
return;
}
m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler); m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler);
// uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; // uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
// string protocol = "http"; // string protocol = "http";
@ -254,9 +205,8 @@ namespace OpenSim.Framework.Capabilities
foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values) foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values)
{ {
m_httpListener.RemovePollServiceHTTPHandler(handler.Url); m_httpListener.RemovePollServiceHTTPHandler("", handler.Url);
} }
m_pollServiceHandlers.Clear();
} }
public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler) public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler)
@ -295,6 +245,9 @@ namespace OpenSim.Framework.Capabilities
port = MainServer.Instance.SSLPort; port = MainServer.Instance.SSLPort;
protocol = "https"; protocol = "https";
} }
//
// caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url); caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url);
} }
} }
@ -308,7 +261,6 @@ namespace OpenSim.Framework.Capabilities
caps[kvp.Key] = kvp.Value; caps[kvp.Key] = kvp.Value;
} }
return caps; return caps;
} }

View File

@ -27,7 +27,6 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Concurrent;
using OpenSim.Framework.Servers; using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
@ -41,7 +40,6 @@ namespace OpenSim.Framework.Capabilities
public class CapsHandlers public class CapsHandlers
{ {
private Dictionary<string, IRequestHandler> m_capsHandlers = new Dictionary<string, IRequestHandler>(); private Dictionary<string, IRequestHandler> m_capsHandlers = new Dictionary<string, IRequestHandler>();
private ConcurrentDictionary<string, ISimpleStreamHandler> m_capsSimpleHandlers = new ConcurrentDictionary<string, ISimpleStreamHandler>();
private IHttpServer m_httpListener; private IHttpServer m_httpListener;
private string m_httpListenerHostName; private string m_httpListenerHostName;
private uint m_httpListenerPort; private uint m_httpListenerPort;
@ -74,36 +72,18 @@ namespace OpenSim.Framework.Capabilities
public void Remove(string capsName) public void Remove(string capsName)
{ {
lock (m_capsHandlers) lock (m_capsHandlers)
{
if(m_capsHandlers.ContainsKey(capsName))
{ {
m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[capsName].Path); m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[capsName].Path);
m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[capsName].Path); m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[capsName].Path);
m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[capsName].Path); m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[capsName].Path);
m_httpListener.RemoveStreamHandler("DELETE", m_capsHandlers[capsName].Path);
m_capsHandlers.Remove(capsName); m_capsHandlers.Remove(capsName);
} }
} }
if(m_capsSimpleHandlers.TryRemove(capsName, out ISimpleStreamHandler hdr))
{
m_httpListener.RemoveSimpleStreamHandler(hdr.Path);
}
}
public void AddSimpleHandler(string capName, ISimpleStreamHandler handler, bool addToListener = true)
{
if(ContainsCap(capName))
Remove(capName);
if(m_capsSimpleHandlers.TryAdd(capName, handler) && addToListener)
m_httpListener.AddSimpleStreamHandler(handler);
}
public bool ContainsCap(string cap) public bool ContainsCap(string cap)
{ {
lock (m_capsHandlers) lock (m_capsHandlers)
if (m_capsHandlers.ContainsKey(cap)) return m_capsHandlers.ContainsKey(cap);
return true;
return m_capsSimpleHandlers.ContainsKey(cap);
} }
/// <summary> /// <summary>
@ -130,9 +110,6 @@ namespace OpenSim.Framework.Capabilities
if (m_capsHandlers.ContainsKey(idx)) if (m_capsHandlers.ContainsKey(idx))
{ {
m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[idx].Path); m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[idx].Path);
m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[idx].Path);
m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[idx].Path);
m_httpListener.RemoveStreamHandler("DELETE", m_capsHandlers[idx].Path);
m_capsHandlers.Remove(idx); m_capsHandlers.Remove(idx);
} }
@ -154,9 +131,8 @@ namespace OpenSim.Framework.Capabilities
{ {
lock (m_capsHandlers) lock (m_capsHandlers)
{ {
string[] __keys = new string[m_capsHandlers.Keys.Count + m_capsSimpleHandlers.Keys.Count]; string[] __keys = new string[m_capsHandlers.Keys.Count];
m_capsHandlers.Keys.CopyTo(__keys, 0); m_capsHandlers.Keys.CopyTo(__keys, 0);
m_capsSimpleHandlers.Keys.CopyTo(__keys, m_capsHandlers.Keys.Count);
return __keys; return __keys;
} }
} }
@ -170,39 +146,24 @@ namespace OpenSim.Framework.Capabilities
public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps) public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps)
{ {
Hashtable caps = new Hashtable(); Hashtable caps = new Hashtable();
string protocol = "http://";
if (m_useSSL)
protocol = "https://";
string protocol = m_useSSL ? "https://" : "http://";
string baseUrl = protocol + m_httpListenerHostName + ":" + m_httpListenerPort.ToString(); string baseUrl = protocol + m_httpListenerHostName + ":" + m_httpListenerPort.ToString();
if (requestedCaps == null)
{
lock (m_capsHandlers) lock (m_capsHandlers)
{ {
foreach (KeyValuePair<string, ISimpleStreamHandler> kvp in m_capsSimpleHandlers) foreach (string capsName in m_capsHandlers.Keys)
caps[kvp.Key] = baseUrl + kvp.Value.Path;
foreach (KeyValuePair<string, IRequestHandler> kvp in m_capsHandlers)
caps[kvp.Key] = baseUrl + kvp.Value.Path;
}
return caps;
}
lock (m_capsHandlers)
{ {
for(int i = 0; i < requestedCaps.Count; ++i)
{
string capsName = requestedCaps[i];
if (excludeSeed && "SEED" == capsName) if (excludeSeed && "SEED" == capsName)
continue; continue;
if (m_capsSimpleHandlers.TryGetValue(capsName, out ISimpleStreamHandler shdr)) if (requestedCaps != null && !requestedCaps.Contains(capsName))
{
caps[capsName] = baseUrl + shdr.Path;
continue; continue;
}
if (m_capsHandlers.TryGetValue(capsName, out IRequestHandler chdr)) caps[capsName] = baseUrl + m_capsHandlers[capsName].Path;
{
caps[capsName] = baseUrl + chdr.Path;
}
} }
} }

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Web;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
//using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Capabilities.Handlers
{
public class AvatarPickerSearchHandler : BaseStreamHandler
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IPeople m_PeopleService;
public AvatarPickerSearchHandler(string path, IPeople peopleService, string name, string description)
: base("GET", path, name, description)
{
m_PeopleService = peopleService;
}
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// Try to parse the texture ID from the request URL
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
string names = query.GetOne("names");
string psize = query.GetOne("page_size");
string pnumber = query.GetOne("page");
if (m_PeopleService == null)
return FailureResponse(names, (int)System.Net.HttpStatusCode.InternalServerError, httpResponse);
if (string.IsNullOrEmpty(names) || names.Length < 3)
return FailureResponse(names, (int)System.Net.HttpStatusCode.BadRequest, httpResponse);
m_log.DebugFormat("[AVATAR PICKER SEARCH]: search for {0}", names);
int page_size = (string.IsNullOrEmpty(psize) ? 500 : Int32.Parse(psize));
int page_number = (string.IsNullOrEmpty(pnumber) ? 1 : Int32.Parse(pnumber));
// Full content request
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
//httpResponse.ContentLength = ??;
httpResponse.ContentType = "application/llsd+xml";
List<UserData> users = m_PeopleService.GetUserData(names, page_size, page_number);
LLSDAvatarPicker osdReply = new LLSDAvatarPicker();
osdReply.next_page_url = httpRequest.RawUrl;
foreach (UserData u in users)
osdReply.agents.Array.Add(ConvertUserData(u));
string reply = LLSDHelpers.SerialiseLLSDReply(osdReply);
return System.Text.Encoding.UTF8.GetBytes(reply);
}
private LLSDPerson ConvertUserData(UserData user)
{
LLSDPerson p = new LLSDPerson();
p.legacy_first_name = user.FirstName;
p.legacy_last_name = user.LastName;
p.display_name = user.FirstName + " " + user.LastName;
if (user.LastName.StartsWith("@"))
p.username = user.FirstName.ToLower() + user.LastName.ToLower();
else
p.username = user.FirstName.ToLower() + "." + user.LastName.ToLower();
p.id = user.Id;
p.is_display_name_default = false;
return p;
}
private byte[] FailureResponse(string names, int statuscode, IOSHttpResponse httpResponse)
{
m_log.Error("[AVATAR PICKER SEARCH]: Error searching for " + names);
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return System.Text.Encoding.UTF8.GetBytes(string.Empty);
}
}
}

View File

@ -29,12 +29,9 @@ using System;
using Nini.Config; using Nini.Config;
using OpenSim.Server.Base; using OpenSim.Server.Base;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base; using OpenSim.Server.Handlers.Base;
using OpenMetaverse; using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Capabilities.Handlers namespace OpenSim.Capabilities.Handlers
{ {
@ -70,16 +67,16 @@ namespace OpenSim.Capabilities.Handlers
m_LibraryService = m_LibraryService =
ServerUtils.LoadPlugin<ILibraryService>(libService, args); ServerUtils.LoadPlugin<ILibraryService>(libService, args);
ExpiringKey<UUID> m_badRequests = new ExpiringKey<UUID>(30000);
FetchInvDescHandler webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService, null); FetchInvDescHandler webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService, null);
ISimpleStreamHandler reqHandler IRequestHandler reqHandler
= new SimpleStreamHandler("/CAPS/WebFetchInvDesc/", delegate(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) = new RestStreamHandler(
{ "POST",
webFetchHandler.FetchInventoryDescendentsRequest(httpRequest, httpResponse, m_badRequests); "/CAPS/WebFetchInvDesc/" /*+ UUID.Random()*/,
}); webFetchHandler.FetchInventoryDescendentsRequest,
"FetchInvDescendents",
server.AddSimpleStreamHandler(reqHandler); null);
server.AddStreamHandler(reqHandler);
} }
} }
} }

View File

@ -25,12 +25,11 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Net;
using System.Reflection; using System.Reflection;
using System.Text;
using OpenMetaverse; using OpenMetaverse;
using OpenMetaverse.StructuredData; using OpenMetaverse.StructuredData;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using OSDArray = OpenMetaverse.StructuredData.OSDArray; using OSDArray = OpenMetaverse.StructuredData.OSDArray;
@ -60,6 +59,9 @@ namespace OpenSim.Capabilities.Handlers
OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request)); OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
OSDArray itemsRequested = (OSDArray)requestmap["items"]; OSDArray itemsRequested = (OSDArray)requestmap["items"];
string reply;
LLSDFetchInventory llsdReply = new LLSDFetchInventory();
UUID[] itemIDs = new UUID[itemsRequested.Count]; UUID[] itemIDs = new UUID[itemsRequested.Count];
int i = 0; int i = 0;
@ -73,6 +75,15 @@ namespace OpenSim.Capabilities.Handlers
if (m_agentID != UUID.Zero) if (m_agentID != UUID.Zero)
{ {
items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs); items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs);
if (items == null)
{
// OMG!!! One by one!!! This is fallback code, in case the backend isn't updated
m_log.WarnFormat("[FETCH INVENTORY HANDLER]: GetMultipleItems failed. Falling back to fetching inventory items one by one.");
items = new InventoryItemBase[itemsRequested.Count];
foreach (UUID id in itemIDs)
items[i++] = m_inventoryService.GetItem(m_agentID, id);
}
} }
else else
{ {
@ -81,86 +92,55 @@ namespace OpenSim.Capabilities.Handlers
items[i++] = m_inventoryService.GetItem(UUID.Zero, id); items[i++] = m_inventoryService.GetItem(UUID.Zero, id);
} }
StringBuilder lsl = LLSDxmlEncode.Start(4096);
LLSDxmlEncode.AddMap(lsl);
if(m_agentID == UUID.Zero && items.Length > 0)
LLSDxmlEncode.AddElem("agent_id", items[0].Owner, lsl);
else
LLSDxmlEncode.AddElem("agent_id", m_agentID, lsl);
if(items == null || items.Length == 0)
{
LLSDxmlEncode.AddEmptyArray("items", lsl);
}
else
{
LLSDxmlEncode.AddArray("items", lsl);
foreach (InventoryItemBase item in items) foreach (InventoryItemBase item in items)
{ {
if (item != null) if (item != null)
item.ToLLSDxml(lsl, 0xff);
}
LLSDxmlEncode.AddEndArray(lsl);
}
LLSDxmlEncode.AddEndMap(lsl);
return LLSDxmlEncode.End(lsl);
}
public void FetchInventorySimpleRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap requestmap, ExpiringKey<UUID> BadRequests)
{ {
//m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capability request {0}", request); // We don't know the agent that this request belongs to so we'll use the agent id of the item
// which will be the same for all items.
if(BadRequests == null) llsdReply.agent_id = item.Owner;
{ llsdReply.items.Array.Add(ConvertInventoryItem(item));
httpResponse.StatusCode = (int)HttpStatusCode.NotFound; }
return;
} }
OSDArray itemsRequested = (OSDArray)requestmap["items"]; reply = LLSDHelpers.SerialiseLLSDReply(llsdReply);
UUID[] itemIDs = new UUID[itemsRequested.Count]; return reply;
int i = 0;
foreach (OSDMap osdItemId in itemsRequested)
{
UUID id = osdItemId["item_id"].AsUUID();
if(!BadRequests.ContainsKey(id))
itemIDs[i++] = id;
} }
InventoryItemBase[] items = null; /// <summary>
try /// Convert an internal inventory item object into an LLSD object.
/// </summary>
/// <param name="invItem"></param>
/// <returns></returns>
private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
{ {
// badrequests still not filled LLSDInventoryItem llsdItem = new LLSDInventoryItem();
items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs); llsdItem.asset_id = invItem.AssetID;
} llsdItem.created_at = invItem.CreationDate;
catch{ } llsdItem.desc = invItem.Description;
llsdItem.flags = ((int)invItem.Flags) & 0xff;
llsdItem.item_id = invItem.ID;
llsdItem.name = invItem.Name;
llsdItem.parent_id = invItem.Folder;
llsdItem.type = invItem.AssetType;
llsdItem.inv_type = invItem.InvType;
StringBuilder lsl = LLSDxmlEncode.Start(4096); llsdItem.permissions = new LLSDPermissions();
LLSDxmlEncode.AddMap(lsl); llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid;
llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
llsdItem.permissions.group_id = invItem.GroupID;
llsdItem.permissions.group_mask = (int)invItem.GroupPermissions;
llsdItem.permissions.is_owner_group = invItem.GroupOwned;
llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
llsdItem.permissions.owner_id = invItem.Owner;
llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
llsdItem.sale_info = new LLSDSaleInfo();
llsdItem.sale_info.sale_price = invItem.SalePrice;
llsdItem.sale_info.sale_type = invItem.SaleType;
LLSDxmlEncode.AddElem("agent_id", m_agentID, lsl); return llsdItem;
if (items == null || items.Length == 0)
{
LLSDxmlEncode.AddEmptyArray("items", lsl);
}
else
{
LLSDxmlEncode.AddArray("items", lsl);
foreach (InventoryItemBase item in items)
{
if (item != null)
item.ToLLSDxml(lsl, 0xff);
}
LLSDxmlEncode.AddEndArray(lsl);
}
LLSDxmlEncode.AddEndMap(lsl);
httpResponse.RawBuffer = Util.UTF8.GetBytes(LLSDxmlEncode.End(lsl));
httpResponse.StatusCode = (int)HttpStatusCode.OK;
} }
} }
} }

View File

@ -28,7 +28,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.IO; using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using log4net; using log4net;
using log4net.Config; using log4net.Config;
@ -46,7 +46,7 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
[TestFixture] [TestFixture]
public class FetchInventoryDescendents2HandlerTests : OpenSimTestCase public class FetchInventoryDescendents2HandlerTests : OpenSimTestCase
{ {
private UUID m_userID = new UUID("00000000-0000-0000-0000-000000000001"); private UUID m_userID = UUID.Zero;
private Scene m_scene; private Scene m_scene;
private UUID m_rootFolderID; private UUID m_rootFolderID;
private int m_rootDescendents; private int m_rootDescendents;
@ -103,7 +103,6 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
// Add a folder // Add a folder
InventoryFolderBase folder = new InventoryFolderBase(new UUID("f0000000-0000-0000-0000-00000000000f"), "Test Folder", m_userID, m_rootFolderID); InventoryFolderBase folder = new InventoryFolderBase(new UUID("f0000000-0000-0000-0000-00000000000f"), "Test Folder", m_userID, m_rootFolderID);
folder.Type = (short)FolderType.None;
m_scene.InventoryService.AddFolder(folder); m_scene.InventoryService.AddFolder(folder);
// Add a link to notecard 2 in Test Folder // Add a link to notecard 2 in Test Folder
@ -127,19 +126,6 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
Console.WriteLine("Number of descendents: " + m_rootDescendents); Console.WriteLine("Number of descendents: " + m_rootDescendents);
} }
private string dorequest(FetchInvDescHandler handler, string request)
{
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
using(ExpiringKey<UUID> bad = new ExpiringKey<UUID>(5000)) // bad but this is test
using (MemoryStream ms = new MemoryStream(Utils.StringToBytes(request), false))
{
req.InputStream = ms;
handler.FetchInventoryDescendentsRequest(req, resp, bad);
}
return Util.UTF8.GetString(resp.RawBuffer);
}
[Test] [Test]
public void Test_001_SimpleFolder() public void Test_001_SimpleFolder()
{ {
@ -148,18 +134,18 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
Init(); Init();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID; request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
request += m_userID.ToString();
request += "</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = dorequest(handler, request); string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Assert.That(llsdresponse != null, Is.True, "Incorrect null response"); Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response"); Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");
Assert.That(llsdresponse.Contains(m_userID.ToString()), Is.True, "Response should contain userID"); Assert.That(llsdresponse.Contains("00000000-0000-0000-0000-000000000000"), Is.True, "Response should contain userID");
string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>"; string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>";
Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents"); Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents");
@ -172,17 +158,19 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
TestHelpers.InMethod(); TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array>"; string request = "<llsd><map><key>folders</key><array>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID; request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_notecardsFolder; request += m_notecardsFolder;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "</array></map></llsd>"; request += "</array></map></llsd>";
string llsdresponse = dorequest(handler, request); string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse); Console.WriteLine(llsdresponse);
string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>"; string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>";
@ -200,12 +188,14 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
TestHelpers.InMethod(); TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += "f0000000-0000-0000-0000-00000000000f"; request += "f0000000-0000-0000-0000-00000000000f";
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = dorequest(handler, request); string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse); Console.WriteLine(llsdresponse);
string descendents = "descendents</key><integer>2</integer>"; string descendents = "descendents</key><integer>2</integer>";
@ -242,6 +232,8 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
TestHelpers.InMethod(); TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array>"; string request = "<llsd><map><key>folders</key><array>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
@ -258,7 +250,7 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "</array></map></llsd>"; request += "</array></map></llsd>";
string llsdresponse = dorequest(handler, request); string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse); Console.WriteLine(llsdresponse);
string root_folder = "<key>folder_id</key><uuid>" + m_rootFolderID + "</uuid>"; string root_folder = "<key>folder_id</key><uuid>" + m_rootFolderID + "</uuid>";
@ -275,26 +267,27 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
[Test] [Test]
public void Test_005_FolderZero() public void Test_005_FolderZero()
{ {
TestHelpers.InMethod(); TestHelpers.InMethod();
Init(); Init();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += UUID.Zero; request += UUID.Zero;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = dorequest(handler, request); string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Assert.That(llsdresponse != null, Is.True, "Incorrect null response"); Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response"); Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");
// we do return a answer now Assert.That(llsdresponse.Contains("bad_folders</key><array><uuid>00000000-0000-0000-0000-000000000000"), Is.True, "Folder Zero should be a bad folder");
//Assert.That(llsdresponse.Contains("bad_folders</key><array><uuid>00000000-0000-0000-0000-000000000000"), Is.True, "Folder Zero should be a bad folder");
Console.WriteLine(llsdresponse); Console.WriteLine(llsdresponse);
} }
} }
} }

View File

@ -1,190 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Capabilities.Handlers
{
public class GetAssetsHandler
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Dictionary<string, AssetType> queryTypes = new Dictionary<string, AssetType>()
{
{"texture_id", AssetType.Texture},
{"sound_id", AssetType.Sound},
{"callcard_id", AssetType.CallingCard},
{"landmark_id", AssetType.Landmark},
{"script_id", AssetType.LSLText},
{"clothing_id", AssetType.Clothing},
{"object_id", AssetType.Object},
{"notecard_id", AssetType.Notecard},
{"lsltext_id", AssetType.LSLText},
{"lslbyte_id", AssetType.LSLBytecode},
{"txtr_tga_id", AssetType.TextureTGA},
{"bodypart_id", AssetType.Bodypart},
{"snd_wav_id", AssetType.SoundWAV},
{"img_tga_id", AssetType.ImageTGA},
{"jpeg_id", AssetType.ImageJPEG},
{"animatn_id", AssetType.Animation},
{"gesture_id", AssetType.Gesture},
{"mesh_id", AssetType.Mesh},
{"settings_id", AssetType.Settings}
};
private IAssetService m_assetService;
public GetAssetsHandler(IAssetService assService)
{
m_assetService = assService;
}
public void Handle(OSHttpRequest req, OSHttpResponse response)
{
response.ContentType = "text/plain";
if (m_assetService == null)
{
response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
response.KeepAlive = false;
return;
}
response.StatusCode = (int)HttpStatusCode.BadRequest;
var queries = req.QueryAsDictionary;
if(queries.Count == 0)
return;
AssetType type = AssetType.Unknown;
string assetStr = string.Empty;
foreach (KeyValuePair<string,string> kvp in queries)
{
if (queryTypes.ContainsKey(kvp.Key))
{
type = queryTypes[kvp.Key];
assetStr = kvp.Value;
break;
}
}
if(type == AssetType.Unknown)
{
//m_log.Warn("[GETASSET]: Unknown type: " + query);
m_log.Warn("[GETASSET]: Unknown type");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (String.IsNullOrEmpty(assetStr))
return;
UUID assetID = UUID.Zero;
if(!UUID.TryParse(assetStr, out assetID))
return;
AssetBase asset = m_assetService.Get(assetID.ToString());
if(asset == null)
{
// m_log.Warn("[GETASSET]: not found: " + query + " " + assetStr);
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (asset.Type != (sbyte)type)
return;
int len = asset.Data.Length;
string range = null;
if (req.Headers["Range"] != null)
range = req.Headers["Range"];
else if (req.Headers["range"] != null)
range = req.Headers["range"];
// range request
int start, end;
if (Util.TryParseHttpRange(range, out start, out end))
{
// Before clamping start make sure we can satisfy it in order to avoid
// sending back the last byte instead of an error status
if (start >= asset.Data.Length)
{
response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
return;
}
if (end == -1)
end = asset.Data.Length - 1;
else
end = Utils.Clamp(end, 0, asset.Data.Length - 1);
start = Utils.Clamp(start, 0, end);
len = end - start + 1;
//m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, asset.Data.Length));
response.StatusCode = (int)HttpStatusCode.PartialContent;
response.RawBufferStart = start;
}
else
response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = asset.Metadata.ContentType;
response.RawBuffer = asset.Data;
response.RawBufferLen = len;
if (type == AssetType.Mesh || type == AssetType.Texture)
{
if(len > 8196)
{
//if(type == AssetType.Texture && ((asset.Flags & AssetFlags.AvatarBake)!= 0))
// responsedata["prio"] = 1;
//else
response.Priority = 2;
}
else
response.Priority = 1;
}
else
response.Priority = -1;
}
}
}

View File

@ -0,0 +1,117 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.IO;
using System.Web;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
namespace OpenSim.Capabilities.Handlers
{
public class GetDisplayNamesHandler : BaseStreamHandler
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IUserManagement m_UserManagement;
public GetDisplayNamesHandler(string path, IUserManagement umService, string name, string description)
: base("GET", path, name, description)
{
m_UserManagement = umService;
}
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// m_log.DebugFormat("[GET_DISPLAY_NAMES]: called {0}", httpRequest.Url.Query);
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
string[] ids = query.GetValues("ids");
if (m_UserManagement == null)
{
m_log.Error("[GET_DISPLAY_NAMES]: Cannot fetch display names without a user management component");
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
return new byte[0];
}
Dictionary<UUID,string> names = m_UserManagement.GetUsersNames(ids);
OSDMap osdReply = new OSDMap();
OSDArray agents = new OSDArray();
osdReply["agents"] = agents;
foreach (KeyValuePair<UUID,string> kvp in names)
{
if (string.IsNullOrEmpty(kvp.Value))
continue;
if(kvp.Key == UUID.Zero)
continue;
string[] parts = kvp.Value.Split(new char[] {' '});
OSDMap osdname = new OSDMap();
if(parts[0] == "Unknown")
{
osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddHours(1));
osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddHours(2));
}
else
{
osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddDays(8));
osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddMonths(1));
}
osdname["display_name"] = OSD.FromString(kvp.Value);
osdname["legacy_first_name"] = parts[0];
osdname["legacy_last_name"] = parts[1];
osdname["username"] = OSD.FromString(kvp.Value);
osdname["id"] = OSD.FromUUID(kvp.Key);
osdname["is_display_name_default"] = OSD.FromBoolean(true);
agents.Add(osdname);
}
// Full content request
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
//httpResponse.ContentLength = ??;
httpResponse.ContentType = "application/llsd+xml";
string reply = OSDParser.SerializeLLSDXmlString(osdReply);
return System.Text.Encoding.UTF8.GetBytes(reply);
}
}
}

View File

@ -29,35 +29,41 @@ using System;
using Nini.Config; using Nini.Config;
using OpenSim.Server.Base; using OpenSim.Server.Base;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base; using OpenSim.Server.Handlers.Base;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.GridUser namespace OpenSim.Capabilities.Handlers
{ {
public class MuteListServiceConnector : ServiceConnector public class GetDisplayNamesServerConnector : ServiceConnector
{ {
private IMuteListService m_MuteListService; private IUserManagement m_UserManagement;
private string m_ConfigName = "MuteListService"; private string m_ConfigName = "CapsService";
public MuteListServiceConnector(IConfigSource config, IHttpServer server, string configName) : public GetDisplayNamesServerConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName) base(config, server, configName)
{ {
if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName]; IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string service = serverConfig.GetString("LocalServiceModule", String.Empty); string umService = serverConfig.GetString("AssetService", String.Empty);
if (service == String.Empty) if (umService == String.Empty)
throw new Exception("LocalServiceModule not present in MuteListService config file MuteListService section"); throw new Exception("No AssetService in config file");
Object[] args = new Object[] { config }; Object[] args = new Object[] { config };
m_MuteListService = ServerUtils.LoadPlugin<IMuteListService>(service, args); m_UserManagement =
ServerUtils.LoadPlugin<IUserManagement>(umService, args);
IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); if (m_UserManagement == null)
throw new Exception(String.Format("Failed to load UserManagement from {0}; config is {1}", umService, m_ConfigName));
server.AddStreamHandler(new MuteListServerPostHandler(m_MuteListService, auth)); server.AddStreamHandler(
new GetDisplayNamesHandler("/CAPS/agents/", m_UserManagement, "GetDisplayNames", null));
} }
} }
} }

View File

@ -41,6 +41,9 @@ using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps; using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Capabilities.Handlers namespace OpenSim.Capabilities.Handlers
{ {
public class GetMeshHandler public class GetMeshHandler
@ -58,98 +61,211 @@ namespace OpenSim.Capabilities.Handlers
} }
public Hashtable Handle(Hashtable request) public Hashtable Handle(Hashtable request)
{ {
return ProcessGetMesh(request, UUID.Zero, null); ; Hashtable ret = new Hashtable();
ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
ret["content_type"] = "text/plain";
ret["keepalive"] = false;
ret["reusecontext"] = false;
ret["int_bytes"] = 0;
ret["int_lod"] = 0;
string MeshStr = (string)request["mesh_id"];
//m_log.DebugFormat("[GETMESH]: called {0}", MeshStr);
if (m_assetService == null)
{
m_log.Error("[GETMESH]: Cannot fetch mesh " + MeshStr + " without an asset service");
} }
UUID meshID;
if (!String.IsNullOrEmpty(MeshStr) && UUID.TryParse(MeshStr, out meshID))
{
// m_log.DebugFormat("[GETMESH]: Received request for mesh id {0}", meshID);
ret = ProcessGetMesh(request, UUID.Zero, null);
}
else
{
m_log.Warn("[GETMESH]: Failed to parse a mesh_id from GetMesh request: " + (string)request["uri"]);
}
return ret;
}
public Hashtable ProcessGetMesh(Hashtable request, UUID AgentId, Caps cap) public Hashtable ProcessGetMesh(Hashtable request, UUID AgentId, Caps cap)
{ {
Hashtable responsedata = new Hashtable(); Hashtable responsedata = new Hashtable();
if (m_assetService == null) responsedata["int_response_code"] = 400; //501; //410; //404;
{
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.ServiceUnavailable;
responsedata["str_response_string"] = "The asset service is unavailable";
responsedata["keepalive"] = false;
return responsedata;
}
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.BadRequest;
responsedata["content_type"] = "text/plain"; responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Request wasn't what was expected";
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 0;
responsedata["int_bytes"] = 0; responsedata["int_bytes"] = 0;
string meshStr = string.Empty; string meshStr = string.Empty;
if (request.ContainsKey("mesh_id")) if (request.ContainsKey("mesh_id"))
meshStr = request["mesh_id"].ToString(); meshStr = request["mesh_id"].ToString();
if (String.IsNullOrEmpty(meshStr))
return responsedata;
UUID meshID = UUID.Zero; UUID meshID = UUID.Zero;
if(!UUID.TryParse(meshStr, out meshID)) if (!String.IsNullOrEmpty(meshStr) && UUID.TryParse(meshStr, out meshID))
{
if (m_assetService == null)
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "The asset service is unavailable. So is your mesh.";
responsedata["reusecontext"] = false;
return responsedata; return responsedata;
}
AssetBase mesh = m_assetService.Get(meshID.ToString()); AssetBase mesh = m_assetService.Get(meshID.ToString());
if(mesh == null)
{
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
responsedata["str_response_string"] = "Mesh not found.";
return responsedata;
}
if (mesh.Type != (SByte)AssetType.Mesh) if (mesh != null)
{ {
responsedata["str_response_string"] = "Asset isn't a mesh."; if (mesh.Type == (SByte)AssetType.Mesh)
return responsedata; {
}
Hashtable headers = new Hashtable();
responsedata["headers"] = headers;
string range = String.Empty; string range = String.Empty;
if (((Hashtable)request["headers"])["range"] != null) if (((Hashtable)request["headers"])["range"] != null)
range = (string)((Hashtable)request["headers"])["range"]; range = (string)((Hashtable)request["headers"])["range"];
else if (((Hashtable)request["headers"])["Range"] != null) else if (((Hashtable)request["headers"])["Range"] != null)
range = (string)((Hashtable)request["headers"])["Range"]; range = (string)((Hashtable)request["headers"])["Range"];
responsedata["content_type"] = "application/vnd.ll.mesh"; if (!String.IsNullOrEmpty(range)) // Mesh Asset LOD // Physics
if (String.IsNullOrEmpty(range))
{ {
// full mesh // Range request
responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data);
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.OK;
return responsedata;
}
// range request
int start, end; int start, end;
if (Util.TryParseHttpRange(range, out start, out end)) if (TryParseRange(range, out start, out end))
{ {
// Before clamping start make sure we can satisfy it in order to avoid // Before clamping start make sure we can satisfy it in order to avoid
// sending back the last byte instead of an error status // sending back the last byte instead of an error status
if (start >= mesh.Data.Length) if (start >= mesh.Data.Length)
{ {
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "This range doesnt exist."; responsedata["str_response_string"] = "This range doesnt exist.";
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 3;
return responsedata; return responsedata;
} }
else
{
end = Utils.Clamp(end, 0, mesh.Data.Length - 1); end = Utils.Clamp(end, 0, mesh.Data.Length - 1);
start = Utils.Clamp(start, 0, end); start = Utils.Clamp(start, 0, end);
int len = end - start + 1; int len = end - start + 1;
//m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
Hashtable headers = new Hashtable();
headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, mesh.Data.Length); if (start > 20000)
responsedata["headers"] = headers; {
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent; responsedata["int_lod"] = 3;
}
else if (start < 4097)
{
responsedata["int_lod"] = 1;
}
else
{
responsedata["int_lod"] = 2;
}
if (start == 0 && len == mesh.Data.Length) // well redudante maybe
{
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.OK;
responsedata["bin_response_data"] = mesh.Data;
responsedata["int_bytes"] = mesh.Data.Length;
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 3;
}
else
{
responsedata["int_response_code"] =
(int)System.Net.HttpStatusCode.PartialContent;
headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end,
mesh.Data.Length);
byte[] d = new byte[len]; byte[] d = new byte[len];
Array.Copy(mesh.Data, start, d, 0, len); Array.Copy(mesh.Data, start, d, 0, len);
responsedata["bin_response_data"] = d; responsedata["bin_response_data"] = d;
responsedata["int_bytes"] = len; responsedata["int_bytes"] = len;
return responsedata; responsedata["reusecontext"] = false;
} }
}
}
else
{
m_log.Warn("[GETMESH]: Failed to parse a range from GetMesh request, sending full asset: " + (string)request["uri"]); m_log.Warn("[GETMESH]: Failed to parse a range from GetMesh request, sending full asset: " + (string)request["uri"]);
responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data); responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data);
responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.OK; responsedata["content_type"] = "application/vnd.ll.mesh";
responsedata["int_response_code"] = 200;
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 3;
}
}
else
{
responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data);
responsedata["content_type"] = "application/vnd.ll.mesh";
responsedata["int_response_code"] = 200;
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 3;
}
}
// Optionally add additional mesh types here
else
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Unfortunately, this asset isn't a mesh.";
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 1;
return responsedata; return responsedata;
} }
} }
else
{
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Your Mesh wasn't found. Sorry!";
responsedata["reusecontext"] = false;
responsedata["int_lod"] = 0;
return responsedata;
}
}
return responsedata;
}
private bool TryParseRange(string header, out int start, out int end)
{
if (header.StartsWith("bytes="))
{
string[] rangeValues = header.Substring(6).Split('-');
if (rangeValues.Length == 2)
{
if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
return true;
}
}
start = end = 0;
return false;
}
}
} }

View File

@ -68,7 +68,7 @@ namespace OpenSim.Capabilities.Handlers
IRequestHandler reqHandler IRequestHandler reqHandler
= new RestHTTPHandler( = new RestHTTPHandler(
"GET", "GET",
"/" + UUID.Random(), "/CAPS/" + UUID.Random(),
httpMethod => gmeshHandler.ProcessGetMesh(httpMethod, UUID.Zero, null), httpMethod => gmeshHandler.ProcessGetMesh(httpMethod, UUID.Zero, null),
"GetMesh", "GetMesh",
null); null);

View File

@ -66,6 +66,8 @@ namespace OpenSim.Capabilities.Handlers
Hashtable ret = new Hashtable(); Hashtable ret = new Hashtable();
ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound; ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
ret["content_type"] = "text/plain"; ret["content_type"] = "text/plain";
ret["keepalive"] = false;
ret["reusecontext"] = false;
ret["int_bytes"] = 0; ret["int_bytes"] = 0;
string textureStr = (string)request["texture_id"]; string textureStr = (string)request["texture_id"];
string format = (string)request["format"]; string format = (string)request["format"];
@ -110,6 +112,8 @@ namespace OpenSim.Capabilities.Handlers
ret["error_status_text"] = "not found"; ret["error_status_text"] = "not found";
ret["str_response_string"] = "not found"; ret["str_response_string"] = "not found";
ret["content_type"] = "text/plain"; ret["content_type"] = "text/plain";
ret["keepalive"] = false;
ret["reusecontext"] = false;
ret["int_bytes"] = 0; ret["int_bytes"] = 0;
} }
} }
@ -210,7 +214,7 @@ namespace OpenSim.Capabilities.Handlers
{ {
// Range request // Range request
int start, end; int start, end;
if (Util.TryParseHttpRange(range, out start, out end)) if (TryParseRange(range, out start, out end))
{ {
// Before clamping start make sure we can satisfy it in order to avoid // Before clamping start make sure we can satisfy it in order to avoid
// sending back the last byte instead of an error status // sending back the last byte instead of an error status
@ -249,6 +253,15 @@ namespace OpenSim.Capabilities.Handlers
// m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
response["content-type"] = texture.Metadata.ContentType; response["content-type"] = texture.Metadata.ContentType;
if (start == 0 && len == texture.Data.Length) // well redudante maybe
{
response["int_response_code"] = (int)System.Net.HttpStatusCode.OK;
response["bin_response_data"] = texture.Data;
response["int_bytes"] = texture.Data.Length;
}
else
{
response["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent; response["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent;
headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length); headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length);
@ -257,6 +270,8 @@ namespace OpenSim.Capabilities.Handlers
response["bin_response_data"] = d; response["bin_response_data"] = d;
response["int_bytes"] = len; response["int_bytes"] = len;
} }
// response.Body.Write(texture.Data, start, len);
}
} }
else else
{ {
@ -289,6 +304,50 @@ namespace OpenSim.Capabilities.Handlers
// texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
} }
/// <summary>
/// Parse a range header.
/// </summary>
/// <remarks>
/// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html,
/// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-).
/// Where there is no value, -1 is returned.
/// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1
/// for start.</remarks>
/// <returns></returns>
/// <param name='header'></param>
/// <param name='start'>Start of the range. Undefined if this was not a number.</param>
/// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param>
private bool TryParseRange(string header, out int start, out int end)
{
start = end = 0;
if (header.StartsWith("bytes="))
{
string[] rangeValues = header.Substring(6).Split('-');
if (rangeValues.Length == 2)
{
if (!Int32.TryParse(rangeValues[0], out start))
return false;
string rawEnd = rangeValues[1];
if (rawEnd == "")
{
end = -1;
return true;
}
else if (Int32.TryParse(rawEnd, out end))
{
return true;
}
}
}
start = end = 0;
return false;
}
private byte[] ConvertTextureData(AssetBase texture, string format) private byte[] ConvertTextureData(AssetBase texture, string format)
{ {
m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);

View File

@ -32,7 +32,6 @@ using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.Reflection; using System.Reflection;
using System.IO; using System.IO;
using System.Net;
using System.Web; using System.Web;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
@ -132,18 +131,49 @@ namespace OpenSim.Capabilities.Handlers
/// <returns>False for "caller try another codec"; true otherwise</returns> /// <returns>False for "caller try another codec"; true otherwise</returns>
private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format)
{ {
// m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
if(!String.IsNullOrEmpty(m_RedirectURL)) AssetBase texture;
string fullID = textureID.ToString();
if (format != DefaultFormat)
fullID = fullID + "-" + format;
if (!String.IsNullOrEmpty(m_RedirectURL))
{ {
string textureUrl = m_RedirectURL + "?texture_id=" + textureID.ToString(); // Only try to fetch locally cached textures. Misses are redirected
m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); texture = m_assetService.GetCached(fullID);
httpResponse.StatusCode = (int)HttpStatusCode.Moved;
httpResponse.AddHeader("Location:", textureUrl); if (texture != null)
{
if (texture.Type != (sbyte)AssetType.Texture)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true; return true;
} }
WriteTextureData(httpRequest, httpResponse, texture, format);
return true;
}
else
{
string textureUrl = m_RedirectURL + "?texture_id="+ textureID.ToString();
m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
httpResponse.StatusCode = (int)OSHttpStatusCode.RedirectMovedPermanently;
httpResponse.RedirectLocation = textureUrl;
return true;
}
}
else // no redirect
{
// try the cache
texture = m_assetService.GetCached(fullID);
if (texture == null)
{
// m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache");
// Fetch locally or remotely. Misses return a 404
texture = m_assetService.Get(textureID.ToString());
// Fetch, Misses or invalid return a 404
AssetBase texture = m_assetService.Get(textureID.ToString());
if (texture != null) if (texture != null)
{ {
if (texture.Type != (sbyte)AssetType.Texture) if (texture.Type != (sbyte)AssetType.Texture)
@ -156,8 +186,8 @@ namespace OpenSim.Capabilities.Handlers
WriteTextureData(httpRequest, httpResponse, texture, format); WriteTextureData(httpRequest, httpResponse, texture, format);
return true; return true;
} }
else
// need to convert format {
AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
newTexture.Data = ConvertTextureData(texture, format); newTexture.Data = ConvertTextureData(texture, format);
if (newTexture.Data.Length == 0) if (newTexture.Data.Length == 0)
@ -166,12 +196,22 @@ namespace OpenSim.Capabilities.Handlers
newTexture.Flags = AssetFlags.Collectable; newTexture.Flags = AssetFlags.Collectable;
newTexture.Temporary = true; newTexture.Temporary = true;
newTexture.Local = true; newTexture.Local = true;
m_assetService.Store(newTexture);
WriteTextureData(httpRequest, httpResponse, newTexture, format); WriteTextureData(httpRequest, httpResponse, newTexture, format);
return true; return true;
} }
}
}
else // it was on the cache
{
// m_log.DebugFormat("[GETTEXTURE]: texture was in the cache");
WriteTextureData(httpRequest, httpResponse, texture, format);
return true;
}
}
// not found // not found
// m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return true; return true;
} }
@ -239,9 +279,8 @@ namespace OpenSim.Capabilities.Handlers
response.ContentLength = len; response.ContentLength = len;
response.ContentType = texture.Metadata.ContentType; response.ContentType = texture.Metadata.ContentType;
response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
response.RawBuffer = texture.Data;
response.RawBufferStart = start; response.Body.Write(texture.Data, start, len);
response.RawBufferLen = len;
} }
} }
else else
@ -259,19 +298,17 @@ namespace OpenSim.Capabilities.Handlers
response.ContentType = texture.Metadata.ContentType; response.ContentType = texture.Metadata.ContentType;
else else
response.ContentType = "image/" + format; response.ContentType = "image/" + format;
response.RawBuffer = texture.Data; response.Body.Write(texture.Data, 0, texture.Data.Length);
response.RawBufferStart = 0;
response.RawBufferLen = texture.Data.Length;
} }
// if (response.StatusCode < 200 || response.StatusCode > 299) // if (response.StatusCode < 200 || response.StatusCode > 299)
// m_log.WarnFormat( // m_log.WarnFormat(
// "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
// texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
// else // else
// m_log.DebugFormat( // m_log.DebugFormat(
// "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
// texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
} }
/// <summary> /// <summary>

View File

@ -66,7 +66,7 @@ namespace OpenSim.Capabilities.Handlers
string rurl = serverConfig.GetString("GetTextureRedirectURL"); string rurl = serverConfig.GetString("GetTextureRedirectURL");
; ;
server.AddStreamHandler( server.AddStreamHandler(
new GetTextureRobustHandler("/CAPS/GetTexture", m_AssetService, "GetTexture", null, rurl)); new GetTextureRobustHandler("/CAPS/GetTexture/", m_AssetService, "GetTexture", null, rurl));
} }
} }
} }

View File

@ -0,0 +1,171 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Capabilities.Handlers
{
public class UploadBakedTextureHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Caps m_HostCapsObj;
private IAssetService m_assetService;
public UploadBakedTextureHandler(Caps caps, IAssetService assetService)
{
m_HostCapsObj = caps;
m_assetService = assetService;
}
/// <summary>
/// Handle a request from the client for a Uri to upload a baked texture.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns>The upload response if the request is successful, null otherwise.</returns>
public string UploadBakedTexture(
string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
try
{
string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
BakedTextureUploader uploader =
new BakedTextureUploader(capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_HostCapsObj.AgentID);
uploader.OnUpLoad += BakedTextureUploaded;
m_HostCapsObj.HttpListener.AddStreamHandler(
new BinaryStreamHandler(
"POST", capsBase + uploaderPath, uploader.uploaderCaps, "UploadBakedTexture", null));
string protocol = "http://";
if (m_HostCapsObj.SSLCaps)
protocol = "https://";
string uploaderURL = protocol + m_HostCapsObj.HostName + ":" +
m_HostCapsObj.Port.ToString() + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
catch (Exception e)
{
m_log.ErrorFormat("[UPLOAD BAKED TEXTURE HANDLER]: {0}{1}", e.Message, e.StackTrace);
}
return null;
}
/// <summary>
/// Called when a baked texture has been successfully uploaded by a client.
/// </summary>
/// <param name="assetID"></param>
/// <param name="data"></param>
private void BakedTextureUploaded(UUID assetID, byte[] data)
{
m_log.DebugFormat("[UPLOAD BAKED TEXTURE HANDLER]: Received baked texture {0}", assetID.ToString());
AssetBase asset;
asset = new AssetBase(assetID, "Baked Texture", (sbyte)AssetType.Texture, m_HostCapsObj.AgentID.ToString());
asset.Data = data;
asset.Temporary = true;
asset.Local = true;
m_assetService.Store(asset);
}
}
class BakedTextureUploader
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event Action<UUID, byte[]> OnUpLoad;
private string uploaderPath = String.Empty;
private UUID newAssetID;
private IHttpServer httpListener;
private UUID AgentId = UUID.Zero;
public BakedTextureUploader(string path, IHttpServer httpServer, UUID uUID)
{
newAssetID = UUID.Random();
uploaderPath = path;
httpListener = httpServer;
AgentId = uUID;
// m_log.InfoFormat("[CAPS] baked texture upload starting for {0}",newAssetID);
}
/// <summary>
/// Handle raw uploaded baked texture data.
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
Action<UUID, byte[]> handlerUpLoad = OnUpLoad;
// Don't do this asynchronously, otherwise it's possible for the client to send set appearance information
// on another thread which might send out avatar updates before the asset has been put into the asset
// service.
if (handlerUpLoad != null)
handlerUpLoad(newAssetID, data);
string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = newAssetID.ToString();
uploadComplete.new_inventory_item = UUID.Zero;
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
// m_log.DebugFormat("[BAKED TEXTURE UPLOADER]: baked texture upload completed for {0}", newAssetID);
return res;
}
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Nini.Config;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using OpenMetaverse;
namespace OpenSim.Capabilities.Handlers
{
public class UploadBakedTextureServerConnector : ServiceConnector
{
private IAssetService m_AssetService;
private string m_ConfigName = "CapsService";
public UploadBakedTextureServerConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string assetService = serverConfig.GetString("AssetService", String.Empty);
if (assetService == String.Empty)
throw new Exception("No AssetService in config file");
Object[] args = new Object[] { config };
m_AssetService =
ServerUtils.LoadPlugin<IAssetService>(assetService, args);
if (m_AssetService == null)
throw new Exception(String.Format("Failed to load AssetService from {0}; config is {1}", assetService, m_ConfigName));
// NEED TO FIX THIS
OpenSim.Framework.Capabilities.Caps caps = new OpenSim.Framework.Capabilities.Caps(server, "", server.Port, "", UUID.Zero, "");
server.AddStreamHandler(new RestStreamHandler(
"POST",
"/CAPS/UploadBakedTexture/",
new UploadBakedTextureHandler(caps, m_AssetService).UploadBakedTexture,
"UploadBakedTexture",
"Upload Baked Texture Capability"));
}
}
}

View File

@ -107,18 +107,18 @@ namespace OpenSim.Framework.Capabilities
/// <returns></returns> /// <returns></returns>
public static byte[] LLSDSerialize(object obj) public static byte[] LLSDSerialize(object obj)
{ {
using(StringWriter sw = new StringWriter()) StringWriter sw = new StringWriter();
using(XmlTextWriter writer = new XmlTextWriter(sw)) XmlTextWriter writer = new XmlTextWriter(sw);
{
writer.Formatting = Formatting.None; writer.Formatting = Formatting.None;
writer.WriteStartElement(String.Empty, "llsd", String.Empty); writer.WriteStartElement(String.Empty, "llsd", String.Empty);
LLSDWriteOne(writer, obj); LLSDWriteOne(writer, obj);
writer.WriteEndElement(); writer.WriteEndElement();
writer.Flush();
writer.Close();
return Util.UTF8.GetBytes(sw.ToString()); return Util.UTF8.GetBytes(sw.ToString());
} }
}
/// <summary> /// <summary>
/// ///

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
namespace OpenSim.Framework.Capabilities
{
[OSDMap]
public class LLSDEnvironmentRequest
{
public UUID messageID;
public UUID regionID;
}
[OSDMap]
public class LLSDEnvironmentSetResponse
{
public UUID regionID;
public UUID messageID;
public Boolean success;
public String fail_reason;
}
public class EnvironmentSettings
{
/// <summary>
/// generates a empty llsd settings response for viewer
/// </summary>
/// <param name="messageID">the message UUID</param>
/// <param name="regionID">the region UUID</param>
public static string EmptySettings(UUID messageID, UUID regionID)
{
OSDArray arr = new OSDArray();
LLSDEnvironmentRequest msg = new LLSDEnvironmentRequest();
msg.messageID = messageID;
msg.regionID = regionID;
arr.Array.Add(msg);
return LLSDHelpers.SerialiseLLSDReply(arr);
}
}
}

View File

@ -30,7 +30,6 @@ using System.Collections;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Xml; using System.Xml;
using OpenMetaverse;
namespace OpenSim.Framework.Capabilities namespace OpenSim.Framework.Capabilities
{ {
@ -41,33 +40,18 @@ namespace OpenSim.Framework.Capabilities
public static string SerialiseLLSDReply(object obj) public static string SerialiseLLSDReply(object obj)
{ {
using(StringWriter sw = new StringWriter()) StringWriter sw = new StringWriter();
using(XmlTextWriter writer = new XmlTextWriter(sw)) XmlTextWriter writer = new XmlTextWriter(sw);
{
writer.Formatting = Formatting.None; writer.Formatting = Formatting.None;
writer.WriteStartElement(String.Empty, "llsd", String.Empty); writer.WriteStartElement(String.Empty, "llsd", String.Empty);
SerializeOSDType(writer, obj); SerializeOSDType(writer, obj);
writer.WriteEndElement(); writer.WriteEndElement();
writer.Flush(); writer.Close();
//m_log.DebugFormat("[LLSD Helpers]: Generated serialized LLSD reply {0}", sw.ToString()); //m_log.DebugFormat("[LLSD Helpers]: Generated serialized LLSD reply {0}", sw.ToString());
return sw.ToString(); return sw.ToString();
} }
}
public static string SerialiseLLSDReplyNoHeader(object obj)
{
using(StringWriter sw = new StringWriter())
using(XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.None;
SerializeOSDType(writer, obj);
writer.Flush();
//m_log.DebugFormat("[LLSD Helpers]: Generated serialized LLSD reply {0}", sw.ToString());
return sw.ToString();
}
}
private static void SerializeOSDType(XmlTextWriter writer, object obj) private static void SerializeOSDType(XmlTextWriter writer, object obj)
{ {
@ -176,18 +160,7 @@ namespace OpenSim.Framework.Capabilities
else if(enumerator.Value is Boolean && field.FieldType == typeof(int) ) else if(enumerator.Value is Boolean && field.FieldType == typeof(int) )
{ {
int i = (bool)enumerator.Value ? 1 : 0; int i = (bool)enumerator.Value ? 1 : 0;
field.SetValue(obj, i); field.SetValue(obj, (object)i);
}
else if(field.FieldType == typeof(bool) && enumerator.Value is int)
{
bool b = (int)enumerator.Value != 0;
field.SetValue(obj, b);
}
else if(field.FieldType == typeof(UUID) && enumerator.Value is string)
{
UUID u;
UUID.TryParse((string)enumerator.Value, out u);
field.SetValue(obj, u);
} }
else else
{ {

View File

@ -37,6 +37,5 @@ namespace OpenSim.Framework.Capabilities
public string name; public string name;
public int type; public int type;
public int preferred_type; public int preferred_type;
public int version;
} }
} }

View File

@ -27,15 +27,15 @@
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Framework namespace OpenSim.Framework.Capabilities
{ {
public class MuteData [OSDMap]
public class LLSDItemUpdate
{ {
public UUID AgentID; public UUID item_id;
public UUID MuteID;
public string MuteName; public LLSDItemUpdate()
public int MuteType; {
public int MuteFlags; }
public int Stamp;
} }
} }

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System.Collections;
namespace OpenSim.Framework.Capabilities
{
[OSDMap]
public class LLSDParcelVoiceInfoResponse
{
public int parcel_local_id;
public string region_name;
public Hashtable voice_credentials;
public LLSDParcelVoiceInfoResponse()
{
}
public LLSDParcelVoiceInfoResponse(string region, int localID, Hashtable creds)
{
region_name = region;
parcel_local_id = localID;
voice_credentials = creds;
}
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using OpenMetaverse;
namespace OpenSim.Framework.Capabilities
{
[LLSDType("MAP")]
public class LLSDRemoteParcelResponse
{
public UUID parcel_id;
public LLSDRemoteParcelResponse()
{
}
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
namespace OpenSim.Framework.Capabilities
{
[OSDMap]
public class LLSDTaskScriptUpdate
{
/// <summary>
/// The item containing the script to update
/// </summary>
public UUID item_id;
/// <summary>
/// The task containing the script
/// </summary>
public UUID task_id;
/// <summary>
/// Signals whether the script is currently active
/// </summary>
public int is_script_running;
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace OpenSim.Framework.Capabilities
{
[OSDMap]
public class LLSDVoiceAccountResponse
{
public string username;
public string password;
public string voice_sip_uri_hostname;
public string voice_account_server_name;
public LLSDVoiceAccountResponse()
{
}
public LLSDVoiceAccountResponse(string user, string pass)
{
username = user;
password = pass;
}
public LLSDVoiceAccountResponse(string user, string pass, string sipUriHost, string accountServer)
{
username = user;
password = pass;
voice_sip_uri_hostname = sipUriHost;
voice_account_server_name = accountServer;
}
}
}

View File

@ -80,7 +80,7 @@ namespace OpenSim.ConsoleClient
while (m_Server.Running) while (m_Server.Running)
{ {
System.Threading.Thread.Sleep(500); System.Threading.Thread.Sleep(500);
MainConsole.Instance.Prompt(); // MainConsole.Instance.Prompt();
} }
if (pidFile != String.Empty) if (pidFile != String.Empty)

View File

@ -47,25 +47,24 @@ namespace OpenSim.Data
if ((id == null) || (id == DBNull.Value)) if ((id == null) || (id == DBNull.Value))
return UUID.Zero; return UUID.Zero;
Type idtype = id.GetType(); if (id.GetType() == typeof(Guid))
if (idtype == typeof(Guid))
return new UUID((Guid)id); return new UUID((Guid)id);
if (id.GetType() == typeof(string)) if (id.GetType() == typeof(byte[]))
{ {
Guid gg; if (((byte[])id).Length == 0)
if (Guid.TryParse((string)id, out gg))
return new UUID(gg);
return UUID.Zero;
}
if (idtype == typeof(byte[]))
{
if (((byte[])id).Length < 16)
return UUID.Zero; return UUID.Zero;
else if (((byte[])id).Length == 16)
return new UUID((byte[])id, 0); return new UUID((byte[])id, 0);
} }
else if (id.GetType() == typeof(string))
{
if (((string)id).Length == 0)
return UUID.Zero;
else if (((string)id).Length == 36)
return new UUID((string)id);
}
throw new Exception("Failed to convert db value to UUID: " + id.ToString()); throw new Exception("Failed to convert db value to UUID: " + id.ToString());
} }
} }

View File

@ -71,8 +71,6 @@ namespace OpenSim.Data
{ {
RegionData Get(UUID regionID, UUID ScopeID); RegionData Get(UUID regionID, UUID ScopeID);
List<RegionData> Get(string regionName, UUID ScopeID); List<RegionData> Get(string regionName, UUID ScopeID);
RegionData GetSpecific(string regionName, UUID ScopeID);
RegionData Get(int x, int y, UUID ScopeID); RegionData Get(int x, int y, UUID ScopeID);
List<RegionData> Get(int xStart, int yStart, int xEnd, int yEnd, UUID ScopeID); List<RegionData> Get(int xStart, int yStart, int xEnd, int yEnd, UUID ScopeID);

View File

@ -285,7 +285,7 @@ namespace OpenSim.Data.MySQL
using (MySqlCommand cmd = dbcon.CreateCommand()) using (MySqlCommand cmd = dbcon.CreateCommand())
{ {
cmd.CommandText = "select * from estateban where EstateID = ?EstateID"; cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID); cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
using (IDataReader r = cmd.ExecuteReader()) using (IDataReader r = cmd.ExecuteReader())
@ -293,11 +293,13 @@ namespace OpenSim.Data.MySQL
while (r.Read()) while (r.Read())
{ {
EstateBan eb = new EstateBan(); EstateBan eb = new EstateBan();
eb.BannedUserID = DBGuid.FromDB(r["bannedUUID"]); ;
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0";
eb.BanningUserID = DBGuid.FromDB(r["banningUUID"]);
eb.BanTime = Convert.ToInt32(r["banTime"]);
es.AddBan(eb); es.AddBan(eb);
} }
} }
@ -321,14 +323,12 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask, banningUUID, banTime) values ( ?EstateID, ?bannedUUID, '', '', '', ?banningUUID, ?banTime)"; cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans) foreach (EstateBan b in es.EstateBans)
{ {
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
cmd.Parameters.AddWithValue("?banningUUID", b.BanningUserID.ToString());
cmd.Parameters.AddWithValue("?banTime", b.BanTime);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); cmd.Parameters.Clear();

View File

@ -29,9 +29,11 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Reflection; using System.Reflection;
using System.Text; using log4net;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MySQL namespace OpenSim.Data.MySQL
{ {
@ -117,39 +119,7 @@ namespace OpenSim.Data.MySQL
public virtual T[] Get(string field, string key) public virtual T[] Get(string field, string key)
{ {
using (MySqlCommand cmd = new MySqlCommand()) return Get(new string[] { field }, new string[] { key });
{
cmd.Parameters.AddWithValue(field, key);
cmd.CommandText = string.Format("select * from {0} where `{1}` = ?{1}", m_Realm, field);
return DoQuery(cmd);
}
}
public virtual T[] Get(string field, string[] keys)
{
int flen = keys.Length;
if(flen == 0)
return new T[0];
int flast = flen - 1;
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select * from {0} where {1} IN (?", m_Realm, field);
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < flen ; i++)
{
string fname = field + i.ToString();
cmd.Parameters.AddWithValue(fname, keys[i]);
sb.Append(fname);
if(i < flast)
sb.Append(",?");
else
sb.Append(")");
}
cmd.CommandText = sb.ToString();
return DoQuery(cmd);
}
} }
public virtual T[] Get(string[] fields, string[] keys) public virtual T[] Get(string[] fields, string[] keys)
@ -159,27 +129,25 @@ namespace OpenSim.Data.MySQL
public virtual T[] Get(string[] fields, string[] keys, string options) public virtual T[] Get(string[] fields, string[] keys, string options)
{ {
int flen = fields.Length; if (fields.Length != keys.Length)
if (flen == 0 || flen != keys.Length)
return new T[0]; return new T[0];
int flast = flen - 1; List<string> terms = new List<string>();
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select * from {0} where ", m_Realm);
using (MySqlCommand cmd = new MySqlCommand()) using (MySqlCommand cmd = new MySqlCommand())
{ {
for (int i = 0 ; i < flen ; i++) for (int i = 0 ; i < fields.Length ; i++)
{ {
cmd.Parameters.AddWithValue(fields[i], keys[i]); cmd.Parameters.AddWithValue(fields[i], keys[i]);
if(i < flast) terms.Add("`" + fields[i] + "` = ?" + fields[i]);
sb.AppendFormat("`{0}` = ?{0} and ", fields[i]);
else
sb.AppendFormat("`{0}` = ?{0} ", fields[i]);
} }
sb.Append(options); string where = String.Join(" and ", terms.ToArray());
cmd.CommandText = sb.ToString();
string query = String.Format("select * from {0} where {1} {2}",
m_Realm, where, options);
cmd.CommandText = query;
return DoQuery(cmd); return DoQuery(cmd);
} }
@ -236,7 +204,7 @@ namespace OpenSim.Data.MySQL
if (m_Fields[name].FieldType == typeof(bool)) if (m_Fields[name].FieldType == typeof(bool))
{ {
int v = Convert.ToInt32(reader[name]); int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0); m_Fields[name].SetValue(row, v != 0 ? true : false);
} }
else if (m_Fields[name].FieldType == typeof(UUID)) else if (m_Fields[name].FieldType == typeof(UUID))
{ {
@ -355,26 +323,25 @@ namespace OpenSim.Data.MySQL
// "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}", // "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}",
// string.Join(",", fields), string.Join(",", keys)); // string.Join(",", fields), string.Join(",", keys));
int flen = fields.Length; if (fields.Length != keys.Length)
if (flen == 0 || flen != keys.Length)
return false; return false;
int flast = flen - 1; List<string> terms = new List<string>();
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("delete from {0} where ", m_Realm);
using (MySqlCommand cmd = new MySqlCommand()) using (MySqlCommand cmd = new MySqlCommand())
{ {
for (int i = 0 ; i < flen ; i++) for (int i = 0 ; i < fields.Length ; i++)
{ {
cmd.Parameters.AddWithValue(fields[i], keys[i]); cmd.Parameters.AddWithValue(fields[i], keys[i]);
if(i < flast) terms.Add("`" + fields[i] + "` = ?" + fields[i]);
sb.AppendFormat("`{0}` = ?{0} and ", fields[i]);
else
sb.AppendFormat("`{0}` = ?{0}", fields[i]);
} }
cmd.CommandText = sb.ToString(); string where = String.Join(" and ", terms.ToArray());
string query = String.Format("delete from {0} where {1}", m_Realm, where);
cmd.CommandText = query;
return ExecuteNonQuery(cmd) > 0; return ExecuteNonQuery(cmd) > 0;
} }
} }
@ -386,27 +353,27 @@ namespace OpenSim.Data.MySQL
public long GetCount(string[] fields, string[] keys) public long GetCount(string[] fields, string[] keys)
{ {
int flen = fields.Length; if (fields.Length != keys.Length)
if (flen == 0 || flen != keys.Length)
return 0; return 0;
int flast = flen - 1; List<string> terms = new List<string>();
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select count(*) from {0} where ", m_Realm);
using (MySqlCommand cmd = new MySqlCommand()) using (MySqlCommand cmd = new MySqlCommand())
{ {
for (int i = 0 ; i < flen ; i++) for (int i = 0; i < fields.Length; i++)
{ {
cmd.Parameters.AddWithValue(fields[i], keys[i]); cmd.Parameters.AddWithValue(fields[i], keys[i]);
if(i < flast) terms.Add("`" + fields[i] + "` = ?" + fields[i]);
sb.AppendFormat("`{0}` = ?{0} and ", fields[i]);
else
sb.AppendFormat("`{0}` = ?{0}", fields[i]);
} }
cmd.CommandText = sb.ToString(); string where = String.Join(" and ", terms.ToArray());
object result = DoQueryScalar(cmd);
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result); return Convert.ToInt64(result);
} }
@ -436,7 +403,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open(); dbcon.Open();
cmd.Connection = dbcon; cmd.Connection = dbcon;
object ret = cmd.ExecuteScalar(); Object ret = cmd.ExecuteScalar();
cmd.Connection = null; cmd.Connection = null;
dbcon.Close(); dbcon.Close();
return ret; return ret;

View File

@ -90,7 +90,7 @@ namespace OpenSim.Data.MySQL
else else
pattern = string.Format("Name LIKE '%{0}%'", MySqlHelper.EscapeString(pattern)); pattern = string.Format("Name LIKE '%{0}%'", MySqlHelper.EscapeString(pattern));
return m_Groups.Get(string.Format("ShowInList=1 AND ({0})", pattern)); return m_Groups.Get(string.Format("ShowInList=1 AND ({0}) ORDER BY Name LIMIT 100", pattern));
} }
public bool DeleteGroup(UUID groupID) public bool DeleteGroup(UUID groupID)

View File

@ -81,15 +81,17 @@ namespace OpenSim.Data.MySQL
} }
} }
public RegionData GetSpecific(string regionName, UUID scopeID) public RegionData Get(int posX, int posY, UUID scopeID)
{ {
string command = "select * from `" + m_Realm + "` where regionName = ?regionName"; /* fixed size regions
string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY";
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command)) using (MySqlCommand cmd = new MySqlCommand(command))
{ {
cmd.Parameters.AddWithValue("?regionName", regionName); cmd.Parameters.AddWithValue("?posX", posX.ToString());
cmd.Parameters.AddWithValue("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd); List<RegionData> ret = RunCommand(cmd);
@ -98,11 +100,8 @@ namespace OpenSim.Data.MySQL
return ret[0]; return ret[0];
} }
*/
} // extend database search for maximum region size area
public RegionData Get(int posX, int posY, UUID scopeID)
{
string command = "select * from `" + m_Realm + "` where locX between ?startX and ?endX and locY between ?startY and ?endY"; string command = "select * from `" + m_Realm + "` where locX between ?startX and ?endX and locY between ?startY and ?endY";
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";

View File

@ -29,13 +29,16 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading;
using log4net; using log4net;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Data;
namespace OpenSim.Data.MySQL namespace OpenSim.Data.MySQL
{ {
@ -127,6 +130,10 @@ namespace OpenSim.Data.MySQL
// Eligibility check // Eligibility check
// //
// PrimFlags.Temporary is not used in OpenSim code and cannot
// be guaranteed to always be clear. Don't check it.
// if ((flags & (uint)PrimFlags.Temporary) != 0)
// return;
if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0) if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)
return; return;
@ -147,15 +154,16 @@ namespace OpenSim.Data.MySQL
"Name, Text, Description, " + "Name, Text, Description, " +
"SitName, TouchName, ObjectFlags, " + "SitName, TouchName, ObjectFlags, " +
"OwnerMask, NextOwnerMask, GroupMask, " + "OwnerMask, NextOwnerMask, GroupMask, " +
"EveryoneMask, BaseMask, " + "EveryoneMask, BaseMask, PositionX, " +
"PositionX, PositionY, PositionZ, " + "PositionY, PositionZ, GroupPositionX, " +
"GroupPositionX, GroupPositionY, GroupPositionZ, " + "GroupPositionY, GroupPositionZ, VelocityX, " +
"VelocityX, VelocityY, VelocityZ, " + "VelocityY, VelocityZ, AngularVelocityX, " +
"AngularVelocityX, AngularVelocityY, AngularVelocityZ, " + "AngularVelocityY, AngularVelocityZ, " +
"AccelerationX, AccelerationY, AccelerationZ, " + "AccelerationX, AccelerationY, " +
"standtargetx, standtargety, standtargetz, " + "AccelerationZ, RotationX, " +
"RotationX, RotationY, RotationZ, RotationW, " + "RotationY, RotationZ, " +
"SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, " + "RotationW, SitTargetOffsetX, " +
"SitTargetOffsetY, SitTargetOffsetZ, " +
"SitTargetOrientW, SitTargetOrientX, " + "SitTargetOrientW, SitTargetOrientX, " +
"SitTargetOrientY, SitTargetOrientZ, " + "SitTargetOrientY, SitTargetOrientZ, " +
"RegionUUID, CreatorID, " + "RegionUUID, CreatorID, " +
@ -181,19 +189,20 @@ namespace OpenSim.Data.MySQL
"AttachedPosY, AttachedPosZ, " + "AttachedPosY, AttachedPosZ, " +
"PhysicsShapeType, Density, GravityModifier, " + "PhysicsShapeType, Density, GravityModifier, " +
"Friction, Restitution, Vehicle, PhysInertia, DynAttrs, " + "Friction, Restitution, Vehicle, PhysInertia, DynAttrs, " +
"RotationAxisLocks, sopanims, sitactrange, pseudocrc" + "RotationAxisLocks" +
") values (" + "?UUID, " + ") values (" + "?UUID, " +
"?CreationDate, ?Name, ?Text, " + "?CreationDate, ?Name, ?Text, " +
"?Description, ?SitName, ?TouchName, " + "?Description, ?SitName, ?TouchName, " +
"?ObjectFlags, ?OwnerMask, ?NextOwnerMask, " + "?ObjectFlags, ?OwnerMask, ?NextOwnerMask, " +
"?GroupMask, ?EveryoneMask, ?BaseMask, " + "?GroupMask, ?EveryoneMask, ?BaseMask, " +
"?PositionX, ?PositionY, ?PositionZ, " + "?PositionX, ?PositionY, ?PositionZ, " +
"?GroupPositionX, ?GroupPositionY, ?GroupPositionZ, " + "?GroupPositionX, ?GroupPositionY, " +
"?VelocityX, ?VelocityY, ?VelocityZ, "+ "?GroupPositionZ, ?VelocityX, " +
"?AngularVelocityX, ?AngularVelocityY, ?AngularVelocityZ, " + "?VelocityY, ?VelocityZ, ?AngularVelocityX, " +
"?AccelerationX, ?AccelerationY, ?AccelerationZ, " + "?AngularVelocityY, ?AngularVelocityZ, " +
"?standtargetx, ?standtargety, ?standtargetz, " + "?AccelerationX, ?AccelerationY, " +
"?RotationX, ?RotationY, ?RotationZ, " + "?AccelerationZ, ?RotationX, " +
"?RotationY, ?RotationZ, " +
"?RotationW, ?SitTargetOffsetX, " + "?RotationW, ?SitTargetOffsetX, " +
"?SitTargetOffsetY, ?SitTargetOffsetZ, " + "?SitTargetOffsetY, ?SitTargetOffsetZ, " +
"?SitTargetOrientW, ?SitTargetOrientX, " + "?SitTargetOrientW, ?SitTargetOrientX, " +
@ -217,7 +226,7 @@ namespace OpenSim.Data.MySQL
"?AttachedPosY, ?AttachedPosZ, " + "?AttachedPosY, ?AttachedPosZ, " +
"?PhysicsShapeType, ?Density, ?GravityModifier, " + "?PhysicsShapeType, ?Density, ?GravityModifier, " +
"?Friction, ?Restitution, ?Vehicle, ?PhysInertia, ?DynAttrs," + "?Friction, ?Restitution, ?Vehicle, ?PhysInertia, ?DynAttrs," +
"?RotationAxisLocks, ?sopanims, ?sitactrange, ?pseudocrc)"; "?RotationAxisLocks)";
FillPrimCommand(cmd, prim, obj.UUID, regionUUID); FillPrimCommand(cmd, prim, obj.UUID, regionUUID);
@ -589,7 +598,7 @@ namespace OpenSim.Data.MySQL
// Legacy entry point for when terrain was always a 256x256 hieghtmap // Legacy entry point for when terrain was always a 256x256 hieghtmap
public void StoreTerrain(double[,] ter, UUID regionID) public void StoreTerrain(double[,] ter, UUID regionID)
{ {
StoreTerrain(new TerrainData(ter), regionID); StoreTerrain(new HeightmapTerrainData(ter), regionID);
} }
public void StoreTerrain(TerrainData terrData, UUID regionID) public void StoreTerrain(TerrainData terrData, UUID regionID)
@ -821,7 +830,7 @@ namespace OpenSim.Data.MySQL
"UserLookAtX, UserLookAtY, UserLookAtZ, " + "UserLookAtX, UserLookAtY, UserLookAtZ, " +
"AuthbuyerID, OtherCleanTime, Dwell, MediaType, MediaDescription, " + "AuthbuyerID, OtherCleanTime, Dwell, MediaType, MediaDescription, " +
"MediaSize, MediaLoop, ObscureMusic, ObscureMedia, " + "MediaSize, MediaLoop, ObscureMusic, ObscureMedia, " +
"SeeAVs, AnyAVSounds, GroupAVSounds, environment) values (" + "SeeAVs, AnyAVSounds, GroupAVSounds) values (" +
"?UUID, ?RegionUUID, " + "?UUID, ?RegionUUID, " +
"?LocalLandID, ?Bitmap, ?Name, ?Description, " + "?LocalLandID, ?Bitmap, ?Name, ?Description, " +
"?OwnerUUID, ?IsGroupOwned, ?Area, ?AuctionID, " + "?OwnerUUID, ?IsGroupOwned, ?Area, ?AuctionID, " +
@ -833,7 +842,7 @@ namespace OpenSim.Data.MySQL
"?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " + "?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " +
"?AuthbuyerID, ?OtherCleanTime, ?Dwell, ?MediaType, ?MediaDescription, "+ "?AuthbuyerID, ?OtherCleanTime, ?Dwell, ?MediaType, ?MediaDescription, "+
"CONCAT(?MediaWidth, ',', ?MediaHeight), ?MediaLoop, ?ObscureMusic, ?ObscureMedia, " + "CONCAT(?MediaWidth, ',', ?MediaHeight), ?MediaLoop, ?ObscureMusic, ?ObscureMedia, " +
"?SeeAVs, ?AnyAVSounds, ?GroupAVSounds, ?environment)"; "?SeeAVs, ?AnyAVSounds, ?GroupAVSounds)";
FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID); FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID);
@ -860,6 +869,107 @@ namespace OpenSim.Data.MySQL
} }
} }
public virtual RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
{
RegionLightShareData nWP = new RegionLightShareData();
nWP.OnSave += StoreRegionWindlightSettings;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
string command = "select * from `regionwindlight` where region_id = ?regionID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Connection = dbcon;
cmd.Parameters.AddWithValue("?regionID", regionUUID.ToString());
using(IDataReader result = ExecuteReader(cmd))
{
if(!result.Read())
{
//No result, so store our default windlight profile and return it
nWP.regionID = regionUUID;
// StoreRegionWindlightSettings(nWP);
return nWP;
}
else
{
nWP.regionID = DBGuid.FromDB(result["region_id"]);
nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]);
nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]);
nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]);
nWP.waterFogDensityExponent = Convert.ToSingle(result["water_fog_density_exponent"]);
nWP.underwaterFogModifier = Convert.ToSingle(result["underwater_fog_modifier"]);
nWP.reflectionWaveletScale.X = Convert.ToSingle(result["reflection_wavelet_scale_1"]);
nWP.reflectionWaveletScale.Y = Convert.ToSingle(result["reflection_wavelet_scale_2"]);
nWP.reflectionWaveletScale.Z = Convert.ToSingle(result["reflection_wavelet_scale_3"]);
nWP.fresnelScale = Convert.ToSingle(result["fresnel_scale"]);
nWP.fresnelOffset = Convert.ToSingle(result["fresnel_offset"]);
nWP.refractScaleAbove = Convert.ToSingle(result["refract_scale_above"]);
nWP.refractScaleBelow = Convert.ToSingle(result["refract_scale_below"]);
nWP.blurMultiplier = Convert.ToSingle(result["blur_multiplier"]);
nWP.bigWaveDirection.X = Convert.ToSingle(result["big_wave_direction_x"]);
nWP.bigWaveDirection.Y = Convert.ToSingle(result["big_wave_direction_y"]);
nWP.littleWaveDirection.X = Convert.ToSingle(result["little_wave_direction_x"]);
nWP.littleWaveDirection.Y = Convert.ToSingle(result["little_wave_direction_y"]);
UUID.TryParse(result["normal_map_texture"].ToString(),out nWP.normalMapTexture);
nWP.horizon.X = Convert.ToSingle(result["horizon_r"]);
nWP.horizon.Y = Convert.ToSingle(result["horizon_g"]);
nWP.horizon.Z = Convert.ToSingle(result["horizon_b"]);
nWP.horizon.W = Convert.ToSingle(result["horizon_i"]);
nWP.hazeHorizon = Convert.ToSingle(result["haze_horizon"]);
nWP.blueDensity.X = Convert.ToSingle(result["blue_density_r"]);
nWP.blueDensity.Y = Convert.ToSingle(result["blue_density_g"]);
nWP.blueDensity.Z = Convert.ToSingle(result["blue_density_b"]);
nWP.blueDensity.W = Convert.ToSingle(result["blue_density_i"]);
nWP.hazeDensity = Convert.ToSingle(result["haze_density"]);
nWP.densityMultiplier = Convert.ToSingle(result["density_multiplier"]);
nWP.distanceMultiplier = Convert.ToSingle(result["distance_multiplier"]);
nWP.maxAltitude = Convert.ToUInt16(result["max_altitude"]);
nWP.sunMoonColor.X = Convert.ToSingle(result["sun_moon_color_r"]);
nWP.sunMoonColor.Y = Convert.ToSingle(result["sun_moon_color_g"]);
nWP.sunMoonColor.Z = Convert.ToSingle(result["sun_moon_color_b"]);
nWP.sunMoonColor.W = Convert.ToSingle(result["sun_moon_color_i"]);
nWP.sunMoonPosition = Convert.ToSingle(result["sun_moon_position"]);
nWP.ambient.X = Convert.ToSingle(result["ambient_r"]);
nWP.ambient.Y = Convert.ToSingle(result["ambient_g"]);
nWP.ambient.Z = Convert.ToSingle(result["ambient_b"]);
nWP.ambient.W = Convert.ToSingle(result["ambient_i"]);
nWP.eastAngle = Convert.ToSingle(result["east_angle"]);
nWP.sunGlowFocus = Convert.ToSingle(result["sun_glow_focus"]);
nWP.sunGlowSize = Convert.ToSingle(result["sun_glow_size"]);
nWP.sceneGamma = Convert.ToSingle(result["scene_gamma"]);
nWP.starBrightness = Convert.ToSingle(result["star_brightness"]);
nWP.cloudColor.X = Convert.ToSingle(result["cloud_color_r"]);
nWP.cloudColor.Y = Convert.ToSingle(result["cloud_color_g"]);
nWP.cloudColor.Z = Convert.ToSingle(result["cloud_color_b"]);
nWP.cloudColor.W = Convert.ToSingle(result["cloud_color_i"]);
nWP.cloudXYDensity.X = Convert.ToSingle(result["cloud_x"]);
nWP.cloudXYDensity.Y = Convert.ToSingle(result["cloud_y"]);
nWP.cloudXYDensity.Z = Convert.ToSingle(result["cloud_density"]);
nWP.cloudCoverage = Convert.ToSingle(result["cloud_coverage"]);
nWP.cloudScale = Convert.ToSingle(result["cloud_scale"]);
nWP.cloudDetailXYDensity.X = Convert.ToSingle(result["cloud_detail_x"]);
nWP.cloudDetailXYDensity.Y = Convert.ToSingle(result["cloud_detail_y"]);
nWP.cloudDetailXYDensity.Z = Convert.ToSingle(result["cloud_detail_density"]);
nWP.cloudScrollX = Convert.ToSingle(result["cloud_scroll_x"]);
nWP.cloudScrollXLock = Convert.ToBoolean(result["cloud_scroll_x_lock"]);
nWP.cloudScrollY = Convert.ToSingle(result["cloud_scroll_y"]);
nWP.cloudScrollYLock = Convert.ToBoolean(result["cloud_scroll_y_lock"]);
nWP.drawClassicClouds = Convert.ToBoolean(result["draw_classic_clouds"]);
nWP.valid = true;
}
}
}
dbcon.Close();
}
return nWP;
}
public virtual RegionSettings LoadRegionSettings(UUID regionUUID) public virtual RegionSettings LoadRegionSettings(UUID regionUUID)
{ {
RegionSettings rs = null; RegionSettings rs = null;
@ -905,6 +1015,127 @@ namespace OpenSim.Data.MySQL
return rs; return rs;
} }
public virtual void StoreRegionWindlightSettings(RegionLightShareData wl)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "REPLACE INTO `regionwindlight` (`region_id`, `water_color_r`, `water_color_g`, "
+ "`water_color_b`, `water_fog_density_exponent`, `underwater_fog_modifier`, "
+ "`reflection_wavelet_scale_1`, `reflection_wavelet_scale_2`, `reflection_wavelet_scale_3`, "
+ "`fresnel_scale`, `fresnel_offset`, `refract_scale_above`, `refract_scale_below`, "
+ "`blur_multiplier`, `big_wave_direction_x`, `big_wave_direction_y`, `little_wave_direction_x`, "
+ "`little_wave_direction_y`, `normal_map_texture`, `horizon_r`, `horizon_g`, `horizon_b`, "
+ "`horizon_i`, `haze_horizon`, `blue_density_r`, `blue_density_g`, `blue_density_b`, "
+ "`blue_density_i`, `haze_density`, `density_multiplier`, `distance_multiplier`, `max_altitude`, "
+ "`sun_moon_color_r`, `sun_moon_color_g`, `sun_moon_color_b`, `sun_moon_color_i`, `sun_moon_position`, "
+ "`ambient_r`, `ambient_g`, `ambient_b`, `ambient_i`, `east_angle`, `sun_glow_focus`, `sun_glow_size`, "
+ "`scene_gamma`, `star_brightness`, `cloud_color_r`, `cloud_color_g`, `cloud_color_b`, `cloud_color_i`, "
+ "`cloud_x`, `cloud_y`, `cloud_density`, `cloud_coverage`, `cloud_scale`, `cloud_detail_x`, "
+ "`cloud_detail_y`, `cloud_detail_density`, `cloud_scroll_x`, `cloud_scroll_x_lock`, `cloud_scroll_y`, "
+ "`cloud_scroll_y_lock`, `draw_classic_clouds`) VALUES (?region_id, ?water_color_r, "
+ "?water_color_g, ?water_color_b, ?water_fog_density_exponent, ?underwater_fog_modifier, ?reflection_wavelet_scale_1, "
+ "?reflection_wavelet_scale_2, ?reflection_wavelet_scale_3, ?fresnel_scale, ?fresnel_offset, ?refract_scale_above, "
+ "?refract_scale_below, ?blur_multiplier, ?big_wave_direction_x, ?big_wave_direction_y, ?little_wave_direction_x, "
+ "?little_wave_direction_y, ?normal_map_texture, ?horizon_r, ?horizon_g, ?horizon_b, ?horizon_i, ?haze_horizon, "
+ "?blue_density_r, ?blue_density_g, ?blue_density_b, ?blue_density_i, ?haze_density, ?density_multiplier, "
+ "?distance_multiplier, ?max_altitude, ?sun_moon_color_r, ?sun_moon_color_g, ?sun_moon_color_b, "
+ "?sun_moon_color_i, ?sun_moon_position, ?ambient_r, ?ambient_g, ?ambient_b, ?ambient_i, ?east_angle, "
+ "?sun_glow_focus, ?sun_glow_size, ?scene_gamma, ?star_brightness, ?cloud_color_r, ?cloud_color_g, "
+ "?cloud_color_b, ?cloud_color_i, ?cloud_x, ?cloud_y, ?cloud_density, ?cloud_coverage, ?cloud_scale, "
+ "?cloud_detail_x, ?cloud_detail_y, ?cloud_detail_density, ?cloud_scroll_x, ?cloud_scroll_x_lock, "
+ "?cloud_scroll_y, ?cloud_scroll_y_lock, ?draw_classic_clouds)"
;
cmd.Parameters.AddWithValue("region_id", wl.regionID);
cmd.Parameters.AddWithValue("water_color_r", wl.waterColor.X);
cmd.Parameters.AddWithValue("water_color_g", wl.waterColor.Y);
cmd.Parameters.AddWithValue("water_color_b", wl.waterColor.Z);
cmd.Parameters.AddWithValue("water_fog_density_exponent", wl.waterFogDensityExponent);
cmd.Parameters.AddWithValue("underwater_fog_modifier", wl.underwaterFogModifier);
cmd.Parameters.AddWithValue("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X);
cmd.Parameters.AddWithValue("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y);
cmd.Parameters.AddWithValue("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z);
cmd.Parameters.AddWithValue("fresnel_scale", wl.fresnelScale);
cmd.Parameters.AddWithValue("fresnel_offset", wl.fresnelOffset);
cmd.Parameters.AddWithValue("refract_scale_above", wl.refractScaleAbove);
cmd.Parameters.AddWithValue("refract_scale_below", wl.refractScaleBelow);
cmd.Parameters.AddWithValue("blur_multiplier", wl.blurMultiplier);
cmd.Parameters.AddWithValue("big_wave_direction_x", wl.bigWaveDirection.X);
cmd.Parameters.AddWithValue("big_wave_direction_y", wl.bigWaveDirection.Y);
cmd.Parameters.AddWithValue("little_wave_direction_x", wl.littleWaveDirection.X);
cmd.Parameters.AddWithValue("little_wave_direction_y", wl.littleWaveDirection.Y);
cmd.Parameters.AddWithValue("normal_map_texture", wl.normalMapTexture);
cmd.Parameters.AddWithValue("horizon_r", wl.horizon.X);
cmd.Parameters.AddWithValue("horizon_g", wl.horizon.Y);
cmd.Parameters.AddWithValue("horizon_b", wl.horizon.Z);
cmd.Parameters.AddWithValue("horizon_i", wl.horizon.W);
cmd.Parameters.AddWithValue("haze_horizon", wl.hazeHorizon);
cmd.Parameters.AddWithValue("blue_density_r", wl.blueDensity.X);
cmd.Parameters.AddWithValue("blue_density_g", wl.blueDensity.Y);
cmd.Parameters.AddWithValue("blue_density_b", wl.blueDensity.Z);
cmd.Parameters.AddWithValue("blue_density_i", wl.blueDensity.W);
cmd.Parameters.AddWithValue("haze_density", wl.hazeDensity);
cmd.Parameters.AddWithValue("density_multiplier", wl.densityMultiplier);
cmd.Parameters.AddWithValue("distance_multiplier", wl.distanceMultiplier);
cmd.Parameters.AddWithValue("max_altitude", wl.maxAltitude);
cmd.Parameters.AddWithValue("sun_moon_color_r", wl.sunMoonColor.X);
cmd.Parameters.AddWithValue("sun_moon_color_g", wl.sunMoonColor.Y);
cmd.Parameters.AddWithValue("sun_moon_color_b", wl.sunMoonColor.Z);
cmd.Parameters.AddWithValue("sun_moon_color_i", wl.sunMoonColor.W);
cmd.Parameters.AddWithValue("sun_moon_position", wl.sunMoonPosition);
cmd.Parameters.AddWithValue("ambient_r", wl.ambient.X);
cmd.Parameters.AddWithValue("ambient_g", wl.ambient.Y);
cmd.Parameters.AddWithValue("ambient_b", wl.ambient.Z);
cmd.Parameters.AddWithValue("ambient_i", wl.ambient.W);
cmd.Parameters.AddWithValue("east_angle", wl.eastAngle);
cmd.Parameters.AddWithValue("sun_glow_focus", wl.sunGlowFocus);
cmd.Parameters.AddWithValue("sun_glow_size", wl.sunGlowSize);
cmd.Parameters.AddWithValue("scene_gamma", wl.sceneGamma);
cmd.Parameters.AddWithValue("star_brightness", wl.starBrightness);
cmd.Parameters.AddWithValue("cloud_color_r", wl.cloudColor.X);
cmd.Parameters.AddWithValue("cloud_color_g", wl.cloudColor.Y);
cmd.Parameters.AddWithValue("cloud_color_b", wl.cloudColor.Z);
cmd.Parameters.AddWithValue("cloud_color_i", wl.cloudColor.W);
cmd.Parameters.AddWithValue("cloud_x", wl.cloudXYDensity.X);
cmd.Parameters.AddWithValue("cloud_y", wl.cloudXYDensity.Y);
cmd.Parameters.AddWithValue("cloud_density", wl.cloudXYDensity.Z);
cmd.Parameters.AddWithValue("cloud_coverage", wl.cloudCoverage);
cmd.Parameters.AddWithValue("cloud_scale", wl.cloudScale);
cmd.Parameters.AddWithValue("cloud_detail_x", wl.cloudDetailXYDensity.X);
cmd.Parameters.AddWithValue("cloud_detail_y", wl.cloudDetailXYDensity.Y);
cmd.Parameters.AddWithValue("cloud_detail_density", wl.cloudDetailXYDensity.Z);
cmd.Parameters.AddWithValue("cloud_scroll_x", wl.cloudScrollX);
cmd.Parameters.AddWithValue("cloud_scroll_x_lock", wl.cloudScrollXLock);
cmd.Parameters.AddWithValue("cloud_scroll_y", wl.cloudScrollY);
cmd.Parameters.AddWithValue("cloud_scroll_y_lock", wl.cloudScrollYLock);
cmd.Parameters.AddWithValue("draw_classic_clouds", wl.drawClassicClouds);
ExecuteNonQuery(cmd);
}
dbcon.Close();
}
}
public virtual void RemoveRegionWindlightSettings(UUID regionID)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "delete from `regionwindlight` where `region_id`=?regionID";
cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
ExecuteNonQuery(cmd);
}
dbcon.Close();
}
}
#region RegionEnvironmentSettings #region RegionEnvironmentSettings
public string LoadRegionEnvironmentSettings(UUID regionUUID) public string LoadRegionEnvironmentSettings(UUID regionUUID)
{ {
@ -1000,7 +1231,7 @@ namespace OpenSim.Data.MySQL
"covenant, covenant_datetime, Sandbox, sunvectorx, sunvectory, " + "covenant, covenant_datetime, Sandbox, sunvectorx, sunvectory, " +
"sunvectorz, loaded_creation_datetime, " + "sunvectorz, loaded_creation_datetime, " +
"loaded_creation_id, map_tile_ID, block_search, casino, " + "loaded_creation_id, map_tile_ID, block_search, casino, " +
"TelehubObject, parcel_tile_ID, cacheID) " + "TelehubObject, parcel_tile_ID) " +
"values (?RegionUUID, ?BlockTerraform, " + "values (?RegionUUID, ?BlockTerraform, " +
"?BlockFly, ?AllowDamage, ?RestrictPushing, " + "?BlockFly, ?AllowDamage, ?RestrictPushing, " +
"?AllowLandResell, ?AllowLandJoinDivide, " + "?AllowLandResell, ?AllowLandJoinDivide, " +
@ -1017,7 +1248,7 @@ namespace OpenSim.Data.MySQL
"?SunVectorX, ?SunVectorY, ?SunVectorZ, " + "?SunVectorX, ?SunVectorY, ?SunVectorZ, " +
"?LoadedCreationDateTime, ?LoadedCreationID, " + "?LoadedCreationDateTime, ?LoadedCreationID, " +
"?TerrainImageID, ?block_search, ?casino, " + "?TerrainImageID, ?block_search, ?casino, " +
"?TelehubObject, ?ParcelImageID, ?cacheID)"; "?TelehubObject, ?ParcelImageID)";
FillRegionSettingsCommand(cmd, rs); FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
@ -1121,57 +1352,49 @@ namespace OpenSim.Data.MySQL
// Vectors // Vectors
prim.OffsetPosition = new Vector3( prim.OffsetPosition = new Vector3(
(float)row["PositionX"], (float)(double)row["PositionX"],
(float)row["PositionY"], (float)(double)row["PositionY"],
(float)row["PositionZ"] (float)(double)row["PositionZ"]
); );
prim.GroupPosition = new Vector3( prim.GroupPosition = new Vector3(
(float)row["GroupPositionX"], (float)(double)row["GroupPositionX"],
(float)row["GroupPositionY"], (float)(double)row["GroupPositionY"],
(float)row["GroupPositionZ"] (float)(double)row["GroupPositionZ"]
); );
prim.Velocity = new Vector3( prim.Velocity = new Vector3(
(float)row["VelocityX"], (float)(double)row["VelocityX"],
(float)row["VelocityY"], (float)(double)row["VelocityY"],
(float)row["VelocityZ"] (float)(double)row["VelocityZ"]
); );
prim.AngularVelocity = new Vector3( prim.AngularVelocity = new Vector3(
(float)row["AngularVelocityX"], (float)(double)row["AngularVelocityX"],
(float)row["AngularVelocityY"], (float)(double)row["AngularVelocityY"],
(float)row["AngularVelocityZ"] (float)(double)row["AngularVelocityZ"]
); );
prim.Acceleration = new Vector3( prim.Acceleration = new Vector3(
(float)row["AccelerationX"], (float)(double)row["AccelerationX"],
(float)row["AccelerationY"], (float)(double)row["AccelerationY"],
(float)row["AccelerationZ"] (float)(double)row["AccelerationZ"]
); );
// quaternions // quaternions
prim.RotationOffset = new Quaternion( prim.RotationOffset = new Quaternion(
(float)row["RotationX"], (float)(double)row["RotationX"],
(float)row["RotationY"], (float)(double)row["RotationY"],
(float)row["RotationZ"], (float)(double)row["RotationZ"],
(float)row["RotationW"] (float)(double)row["RotationW"]
); );
prim.SitTargetPositionLL = new Vector3( prim.SitTargetPositionLL = new Vector3(
(float)row["SitTargetOffsetX"], (float)(double)row["SitTargetOffsetX"],
(float)row["SitTargetOffsetY"], (float)(double)row["SitTargetOffsetY"],
(float)row["SitTargetOffsetZ"] (float)(double)row["SitTargetOffsetZ"]
); );
prim.SitTargetOrientationLL = new Quaternion( prim.SitTargetOrientationLL = new Quaternion(
(float)row["SitTargetOrientX"], (float)(double)row["SitTargetOrientX"],
(float)row["SitTargetOrientY"], (float)(double)row["SitTargetOrientY"],
(float)row["SitTargetOrientZ"], (float)(double)row["SitTargetOrientZ"],
(float)row["SitTargetOrientW"] (float)(double)row["SitTargetOrientW"]
); );
prim.StandOffset = new Vector3(
(float)row["standtargetx"],
(float)row["standtargety"],
(float)row["standtargetz"]
);
prim.SitActiveRange = (float)row["sitactrange"];
prim.PayPrice[0] = (int)row["PayPrice"]; prim.PayPrice[0] = (int)row["PayPrice"];
prim.PayPrice[1] = (int)row["PayButton1"]; prim.PayPrice[1] = (int)row["PayButton1"];
prim.PayPrice[2] = (int)row["PayButton2"]; prim.PayPrice[2] = (int)row["PayButton2"];
@ -1179,11 +1402,8 @@ namespace OpenSim.Data.MySQL
prim.PayPrice[4] = (int)row["PayButton4"]; prim.PayPrice[4] = (int)row["PayButton4"];
prim.Sound = DBGuid.FromDB(row["LoopedSound"].ToString()); prim.Sound = DBGuid.FromDB(row["LoopedSound"].ToString());
prim.SoundGain = (float)row["LoopedSoundGain"]; prim.SoundGain = (float)(double)row["LoopedSoundGain"];
if (prim.Sound != UUID.Zero)
prim.SoundFlags = 1; // If it's persisted at all, it's looped prim.SoundFlags = 1; // If it's persisted at all, it's looped
else
prim.SoundFlags = 0;
if (!(row["TextureAnimation"] is DBNull)) if (!(row["TextureAnimation"] is DBNull))
prim.TextureAnimation = (byte[])row["TextureAnimation"]; prim.TextureAnimation = (byte[])row["TextureAnimation"];
@ -1191,21 +1411,21 @@ namespace OpenSim.Data.MySQL
prim.ParticleSystem = (byte[])row["ParticleSystem"]; prim.ParticleSystem = (byte[])row["ParticleSystem"];
prim.AngularVelocity = new Vector3( prim.AngularVelocity = new Vector3(
(float)row["OmegaX"], (float)(double)row["OmegaX"],
(float)row["OmegaY"], (float)(double)row["OmegaY"],
(float)row["OmegaZ"] (float)(double)row["OmegaZ"]
); );
prim.SetCameraEyeOffset(new Vector3( prim.SetCameraEyeOffset(new Vector3(
(float)row["CameraEyeOffsetX"], (float)(double)row["CameraEyeOffsetX"],
(float)row["CameraEyeOffsetY"], (float)(double)row["CameraEyeOffsetY"],
(float)row["CameraEyeOffsetZ"] (float)(double)row["CameraEyeOffsetZ"]
)); ));
prim.SetCameraAtOffset(new Vector3( prim.SetCameraAtOffset(new Vector3(
(float)row["CameraAtOffsetX"], (float)(double)row["CameraAtOffsetX"],
(float)row["CameraAtOffsetY"], (float)(double)row["CameraAtOffsetY"],
(float)row["CameraAtOffsetZ"] (float)(double)row["CameraAtOffsetZ"]
)); ));
prim.SetForceMouselook((sbyte)row["ForceMouselook"] != 0); prim.SetForceMouselook((sbyte)row["ForceMouselook"] != 0);
@ -1234,16 +1454,16 @@ namespace OpenSim.Data.MySQL
if (!(row["AttachedPosX"] is System.DBNull)) if (!(row["AttachedPosX"] is System.DBNull))
{ {
prim.AttachedPos = new Vector3( prim.AttachedPos = new Vector3(
(float)row["AttachedPosX"], (float)(double)row["AttachedPosX"],
(float)row["AttachedPosY"], (float)(double)row["AttachedPosY"],
(float)row["AttachedPosZ"] (float)(double)row["AttachedPosZ"]
); );
} }
if (!(row["DynAttrs"] is System.DBNull)) if (!(row["DynAttrs"] is System.DBNull))
prim.DynAttrs = DAMap.FromXml((string)row["DynAttrs"]); prim.DynAttrs = DAMap.FromXml((string)row["DynAttrs"]);
else else
prim.DynAttrs = null; prim.DynAttrs = new DAMap();
if (!(row["KeyframeMotion"] is DBNull)) if (!(row["KeyframeMotion"] is DBNull))
{ {
@ -1259,10 +1479,10 @@ namespace OpenSim.Data.MySQL
} }
prim.PhysicsShapeType = (byte)Convert.ToInt32(row["PhysicsShapeType"].ToString()); prim.PhysicsShapeType = (byte)Convert.ToInt32(row["PhysicsShapeType"].ToString());
prim.Density = (float)row["Density"]; prim.Density = (float)(double)row["Density"];
prim.GravityModifier = (float)row["GravityModifier"]; prim.GravityModifier = (float)(double)row["GravityModifier"];
prim.Friction = (float)row["Friction"]; prim.Friction = (float)(double)row["Friction"];
prim.Restitution = (float)row["Restitution"]; prim.Restitution = (float)(double)row["Restitution"];
prim.RotationAxisLocks = (byte)Convert.ToInt32(row["RotationAxisLocks"].ToString()); prim.RotationAxisLocks = (byte)Convert.ToInt32(row["RotationAxisLocks"].ToString());
SOPVehicle vehicle = null; SOPVehicle vehicle = null;
@ -1279,25 +1499,6 @@ namespace OpenSim.Data.MySQL
pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString()); pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString());
prim.PhysicsInertia = pdata; prim.PhysicsInertia = pdata;
if (!(row["sopanims"] is DBNull))
{
Byte[] data = (byte[])row["sopanims"];
if (data.Length > 0)
prim.DeSerializeAnimations(data);
else
prim.Animations = null;
}
else
{
prim.Animations = null;
}
prim.SitActiveRange = (float)row["sitactrange"];
int pseudocrc = (int)row["pseudocrc"];
if(pseudocrc != 0)
prim.PseudoCRC = pseudocrc;
return prim; return prim;
} }
@ -1402,10 +1603,6 @@ namespace OpenSim.Data.MySQL
newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]); newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]);
newSettings.Casino = Convert.ToBoolean(row["casino"]); newSettings.Casino = Convert.ToBoolean(row["casino"]);
if (!(row["cacheID"] is DBNull))
newSettings.CacheID = DBGuid.FromDB(row["cacheID"]);
return newSettings; return newSettings;
} }
@ -1489,34 +1686,6 @@ namespace OpenSim.Data.MySQL
if (!(row["GroupAVSounds"] is System.DBNull)) if (!(row["GroupAVSounds"] is System.DBNull))
newData.GroupAVSounds = Convert.ToInt32(row["GroupAVSounds"]) != 0 ? true : false; newData.GroupAVSounds = Convert.ToInt32(row["GroupAVSounds"]) != 0 ? true : false;
if (row["environment"] is DBNull)
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
string env = (string)row["environment"];
if(string.IsNullOrEmpty(env))
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
try
{
ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
newData.Environment = VEnv;
newData.EnvironmentVersion = VEnv.version;
}
catch
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
}
}
return newData; return newData;
} }
@ -1571,43 +1740,38 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("EveryoneMask", prim.EveryoneMask); cmd.Parameters.AddWithValue("EveryoneMask", prim.EveryoneMask);
cmd.Parameters.AddWithValue("BaseMask", prim.BaseMask); cmd.Parameters.AddWithValue("BaseMask", prim.BaseMask);
// vectors // vectors
cmd.Parameters.AddWithValue("PositionX", prim.OffsetPosition.X); cmd.Parameters.AddWithValue("PositionX", (double)prim.OffsetPosition.X);
cmd.Parameters.AddWithValue("PositionY", prim.OffsetPosition.Y); cmd.Parameters.AddWithValue("PositionY", (double)prim.OffsetPosition.Y);
cmd.Parameters.AddWithValue("PositionZ", prim.OffsetPosition.Z); cmd.Parameters.AddWithValue("PositionZ", (double)prim.OffsetPosition.Z);
cmd.Parameters.AddWithValue("GroupPositionX", prim.GroupPosition.X); cmd.Parameters.AddWithValue("GroupPositionX", (double)prim.GroupPosition.X);
cmd.Parameters.AddWithValue("GroupPositionY", prim.GroupPosition.Y); cmd.Parameters.AddWithValue("GroupPositionY", (double)prim.GroupPosition.Y);
cmd.Parameters.AddWithValue("GroupPositionZ", prim.GroupPosition.Z); cmd.Parameters.AddWithValue("GroupPositionZ", (double)prim.GroupPosition.Z);
cmd.Parameters.AddWithValue("VelocityX", prim.Velocity.X); cmd.Parameters.AddWithValue("VelocityX", (double)prim.Velocity.X);
cmd.Parameters.AddWithValue("VelocityY", prim.Velocity.Y); cmd.Parameters.AddWithValue("VelocityY", (double)prim.Velocity.Y);
cmd.Parameters.AddWithValue("VelocityZ", prim.Velocity.Z); cmd.Parameters.AddWithValue("VelocityZ", (double)prim.Velocity.Z);
cmd.Parameters.AddWithValue("AngularVelocityX", prim.AngularVelocity.X); cmd.Parameters.AddWithValue("AngularVelocityX", (double)prim.AngularVelocity.X);
cmd.Parameters.AddWithValue("AngularVelocityY", prim.AngularVelocity.Y); cmd.Parameters.AddWithValue("AngularVelocityY", (double)prim.AngularVelocity.Y);
cmd.Parameters.AddWithValue("AngularVelocityZ", prim.AngularVelocity.Z); cmd.Parameters.AddWithValue("AngularVelocityZ", (double)prim.AngularVelocity.Z);
cmd.Parameters.AddWithValue("AccelerationX", prim.Acceleration.X); cmd.Parameters.AddWithValue("AccelerationX", (double)prim.Acceleration.X);
cmd.Parameters.AddWithValue("AccelerationY", prim.Acceleration.Y); cmd.Parameters.AddWithValue("AccelerationY", (double)prim.Acceleration.Y);
cmd.Parameters.AddWithValue("AccelerationZ", prim.Acceleration.Z); cmd.Parameters.AddWithValue("AccelerationZ", (double)prim.Acceleration.Z);
cmd.Parameters.AddWithValue("standtargetx", prim.StandOffset.X);
cmd.Parameters.AddWithValue("standtargety", prim.StandOffset.Y);
cmd.Parameters.AddWithValue("standtargetz", prim.StandOffset.Z);
// quaternions // quaternions
cmd.Parameters.AddWithValue("RotationX", prim.RotationOffset.X); cmd.Parameters.AddWithValue("RotationX", (double)prim.RotationOffset.X);
cmd.Parameters.AddWithValue("RotationY", prim.RotationOffset.Y); cmd.Parameters.AddWithValue("RotationY", (double)prim.RotationOffset.Y);
cmd.Parameters.AddWithValue("RotationZ", prim.RotationOffset.Z); cmd.Parameters.AddWithValue("RotationZ", (double)prim.RotationOffset.Z);
cmd.Parameters.AddWithValue("RotationW", prim.RotationOffset.W); cmd.Parameters.AddWithValue("RotationW", (double)prim.RotationOffset.W);
// Sit target // Sit target
Vector3 sitTargetPos = prim.SitTargetPositionLL; Vector3 sitTargetPos = prim.SitTargetPositionLL;
cmd.Parameters.AddWithValue("SitTargetOffsetX", sitTargetPos.X); cmd.Parameters.AddWithValue("SitTargetOffsetX", (double)sitTargetPos.X);
cmd.Parameters.AddWithValue("SitTargetOffsetY", sitTargetPos.Y); cmd.Parameters.AddWithValue("SitTargetOffsetY", (double)sitTargetPos.Y);
cmd.Parameters.AddWithValue("SitTargetOffsetZ", sitTargetPos.Z); cmd.Parameters.AddWithValue("SitTargetOffsetZ", (double)sitTargetPos.Z);
Quaternion sitTargetOrient = prim.SitTargetOrientationLL; Quaternion sitTargetOrient = prim.SitTargetOrientationLL;
cmd.Parameters.AddWithValue("SitTargetOrientW", sitTargetOrient.W); cmd.Parameters.AddWithValue("SitTargetOrientW", (double)sitTargetOrient.W);
cmd.Parameters.AddWithValue("SitTargetOrientX", sitTargetOrient.X); cmd.Parameters.AddWithValue("SitTargetOrientX", (double)sitTargetOrient.X);
cmd.Parameters.AddWithValue("SitTargetOrientY", sitTargetOrient.Y); cmd.Parameters.AddWithValue("SitTargetOrientY", (double)sitTargetOrient.Y);
cmd.Parameters.AddWithValue("SitTargetOrientZ", sitTargetOrient.Z); cmd.Parameters.AddWithValue("SitTargetOrientZ", (double)sitTargetOrient.Z);
cmd.Parameters.AddWithValue("PayPrice", prim.PayPrice[0]); cmd.Parameters.AddWithValue("PayPrice", prim.PayPrice[0]);
cmd.Parameters.AddWithValue("PayButton1", prim.PayPrice[1]); cmd.Parameters.AddWithValue("PayButton1", prim.PayPrice[1]);
@ -1618,7 +1782,7 @@ namespace OpenSim.Data.MySQL
if ((prim.SoundFlags & 1) != 0) // Looped if ((prim.SoundFlags & 1) != 0) // Looped
{ {
cmd.Parameters.AddWithValue("LoopedSound", prim.Sound.ToString()); cmd.Parameters.AddWithValue("LoopedSound", prim.Sound.ToString());
cmd.Parameters.AddWithValue("LoopedSoundGain", (float)prim.SoundGain); cmd.Parameters.AddWithValue("LoopedSoundGain", prim.SoundGain);
} }
else else
{ {
@ -1629,17 +1793,17 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("TextureAnimation", prim.TextureAnimation); cmd.Parameters.AddWithValue("TextureAnimation", prim.TextureAnimation);
cmd.Parameters.AddWithValue("ParticleSystem", prim.ParticleSystem); cmd.Parameters.AddWithValue("ParticleSystem", prim.ParticleSystem);
cmd.Parameters.AddWithValue("OmegaX", prim.AngularVelocity.X); cmd.Parameters.AddWithValue("OmegaX", (double)prim.AngularVelocity.X);
cmd.Parameters.AddWithValue("OmegaY", prim.AngularVelocity.Y); cmd.Parameters.AddWithValue("OmegaY", (double)prim.AngularVelocity.Y);
cmd.Parameters.AddWithValue("OmegaZ", prim.AngularVelocity.Z); cmd.Parameters.AddWithValue("OmegaZ", (double)prim.AngularVelocity.Z);
cmd.Parameters.AddWithValue("CameraEyeOffsetX", prim.GetCameraEyeOffset().X); cmd.Parameters.AddWithValue("CameraEyeOffsetX", (double)prim.GetCameraEyeOffset().X);
cmd.Parameters.AddWithValue("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y); cmd.Parameters.AddWithValue("CameraEyeOffsetY", (double)prim.GetCameraEyeOffset().Y);
cmd.Parameters.AddWithValue("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z); cmd.Parameters.AddWithValue("CameraEyeOffsetZ", (double)prim.GetCameraEyeOffset().Z);
cmd.Parameters.AddWithValue("CameraAtOffsetX", prim.GetCameraAtOffset().X); cmd.Parameters.AddWithValue("CameraAtOffsetX", (double)prim.GetCameraAtOffset().X);
cmd.Parameters.AddWithValue("CameraAtOffsetY", prim.GetCameraAtOffset().Y); cmd.Parameters.AddWithValue("CameraAtOffsetY", (double)prim.GetCameraAtOffset().Y);
cmd.Parameters.AddWithValue("CameraAtOffsetZ", prim.GetCameraAtOffset().Z); cmd.Parameters.AddWithValue("CameraAtOffsetZ", (double)prim.GetCameraAtOffset().Z);
if (prim.GetForceMouselook()) if (prim.GetForceMouselook())
cmd.Parameters.AddWithValue("ForceMouselook", 1); cmd.Parameters.AddWithValue("ForceMouselook", 1);
@ -1683,9 +1847,9 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("MediaURL", prim.MediaUrl); cmd.Parameters.AddWithValue("MediaURL", prim.MediaUrl);
if (prim.AttachedPos != null) if (prim.AttachedPos != null)
{ {
cmd.Parameters.AddWithValue("AttachedPosX", prim.AttachedPos.X); cmd.Parameters.AddWithValue("AttachedPosX", (double)prim.AttachedPos.X);
cmd.Parameters.AddWithValue("AttachedPosY", prim.AttachedPos.Y); cmd.Parameters.AddWithValue("AttachedPosY", (double)prim.AttachedPos.Y);
cmd.Parameters.AddWithValue("AttachedPosZ", prim.AttachedPos.Z); cmd.Parameters.AddWithValue("AttachedPosZ", (double)prim.AttachedPos.Z);
} }
if (prim.KeyframeMotion != null) if (prim.KeyframeMotion != null)
@ -1703,25 +1867,17 @@ namespace OpenSim.Data.MySQL
else else
cmd.Parameters.AddWithValue("Vehicle", String.Empty); cmd.Parameters.AddWithValue("Vehicle", String.Empty);
if (prim.DynAttrs != null && prim.DynAttrs.CountNamespaces > 0) if (prim.DynAttrs.CountNamespaces > 0)
cmd.Parameters.AddWithValue("DynAttrs", prim.DynAttrs.ToXml()); cmd.Parameters.AddWithValue("DynAttrs", prim.DynAttrs.ToXml());
else else
cmd.Parameters.AddWithValue("DynAttrs", null); cmd.Parameters.AddWithValue("DynAttrs", null);
cmd.Parameters.AddWithValue("PhysicsShapeType", prim.PhysicsShapeType); cmd.Parameters.AddWithValue("PhysicsShapeType", prim.PhysicsShapeType);
cmd.Parameters.AddWithValue("Density", prim.Density); cmd.Parameters.AddWithValue("Density", (double)prim.Density);
cmd.Parameters.AddWithValue("GravityModifier", prim.GravityModifier); cmd.Parameters.AddWithValue("GravityModifier", (double)prim.GravityModifier);
cmd.Parameters.AddWithValue("Friction", prim.Friction); cmd.Parameters.AddWithValue("Friction", (double)prim.Friction);
cmd.Parameters.AddWithValue("Restitution", prim.Restitution); cmd.Parameters.AddWithValue("Restitution", (double)prim.Restitution);
cmd.Parameters.AddWithValue("RotationAxisLocks", prim.RotationAxisLocks); cmd.Parameters.AddWithValue("RotationAxisLocks", prim.RotationAxisLocks);
if (prim.Animations!= null)
cmd.Parameters.AddWithValue("sopanims", prim.SerializeAnimations());
else
cmd.Parameters.AddWithValue("sopanims", null);
cmd.Parameters.AddWithValue("sitactrange", prim.SitActiveRange);
cmd.Parameters.AddWithValue("pseudocrc", prim.PseudoCRC);
} }
/// <summary> /// <summary>
@ -1805,7 +1961,6 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("ParcelImageID", settings.ParcelImageID); cmd.Parameters.AddWithValue("ParcelImageID", settings.ParcelImageID);
cmd.Parameters.AddWithValue("TelehubObject", settings.TelehubObject); cmd.Parameters.AddWithValue("TelehubObject", settings.TelehubObject);
cmd.Parameters.AddWithValue("cacheID", settings.CacheID);
} }
/// <summary> /// <summary>
@ -1863,19 +2018,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("SeeAVs", land.SeeAVs ? 1 : 0); cmd.Parameters.AddWithValue("SeeAVs", land.SeeAVs ? 1 : 0);
cmd.Parameters.AddWithValue("AnyAVSounds", land.AnyAVSounds ? 1 : 0); cmd.Parameters.AddWithValue("AnyAVSounds", land.AnyAVSounds ? 1 : 0);
cmd.Parameters.AddWithValue("GroupAVSounds", land.GroupAVSounds ? 1 : 0); cmd.Parameters.AddWithValue("GroupAVSounds", land.GroupAVSounds ? 1 : 0);
if (land.Environment == null)
cmd.Parameters.AddWithValue("environment", "");
else
{
try
{
cmd.Parameters.AddWithValue("environment", ViewerEnvironment.ToOSDString(land.Environment));
}
catch
{
cmd.Parameters.AddWithValue("environment", "");
}
}
} }
/// <summary> /// <summary>

View File

@ -112,7 +112,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA] GetClassifiedRecords exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": UserAccount exception {0}", e.Message);
} }
n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("classifieduuid", OSD.FromUUID(Id));
n.Add("name", OSD.FromString(Name)); n.Add("name", OSD.FromString(Name));
@ -233,7 +234,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdateClassifiedRecord exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": ClassifiedesUpdate exception {0}", e.Message);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -260,7 +262,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: DeleteClassifiedRecord exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteClassifiedRecord exception {0}", e.Message);
return false; return false;
} }
return true; return true;
@ -307,7 +310,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetClassifiedInfo exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
} }
return true; return true;
} }
@ -349,7 +353,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarPicks exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarPicks exception {0}", e.Message);
} }
return data; return data;
} }
@ -402,7 +407,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetPickInfo exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
} }
return pick; return pick;
} }
@ -466,7 +472,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdatePicksRecord exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false; return false;
} }
return true; return true;
@ -493,7 +500,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: DeletePicksRecord exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteUserPickRecord exception {0}", e.Message);
return false; return false;
} }
return true; return true;
@ -533,7 +541,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarNotes exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
} }
return true; return true;
} }
@ -580,7 +589,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarNotes exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false; return false;
} }
return true; return true;
@ -701,7 +711,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarProperties exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": Requst properties exception {0}", e.Message);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -736,7 +747,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarProperties exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentPropertiesUpdate exception {0}", e.Message);
return false; return false;
} }
@ -775,7 +787,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarInterests exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -836,7 +849,7 @@ namespace OpenSim.Data.MySQL
const string queryB = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id"; const string queryB = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id";
using (MySqlCommand cmd = new MySqlCommand(queryB, dbcon)) using (MySqlCommand cmd = new MySqlCommand(string.Format (queryB,"`userpicks`"), dbcon))
{ {
cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); cmd.Parameters.AddWithValue("?Id", avatarId.ToString());
@ -857,7 +870,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetUserImageAssets exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
} }
return data; return data;
} }
@ -907,7 +921,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetUserPreferences exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": Get preferences exception {0}", e.Message);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -939,7 +954,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: UpdateUserPreferences exception {0} {1}", e.Message, e.InnerException); m_log.ErrorFormat("[PROFILES_DATA]" +
": UserPreferencesUpdate exception {0} {1}", e.Message, e.InnerException);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -990,7 +1006,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: GetUserAppData exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": Requst application data exception {0}", e.Message);
result = e.Message; result = e.Message;
return false; return false;
} }
@ -1020,7 +1037,8 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[PROFILES_DATA]: SetUserAppData exception {0}", e.Message); m_log.ErrorFormat("[PROFILES_DATA]" +
": SetUserData exception {0}", e.Message);
return false; return false;
} }
return true; return true;

View File

@ -58,6 +58,11 @@ namespace OpenSim.Data.MySQL
private bool m_enableCompression = false; private bool m_enableCompression = false;
private string m_connectionString; private string m_connectionString;
/// <summary>
/// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
/// </summary>
private HashAlgorithm hasher = new SHA256CryptoServiceProvider();
#region IPlugin Members #region IPlugin Members
public string Version { get { return "1.0.0.0"; } } public string Version { get { return "1.0.0.0"; } }
@ -245,9 +250,7 @@ namespace OpenSim.Data.MySQL
} }
} }
byte[] hash; byte[] hash = hasher.ComputeHash(asset.Data);
using (HashAlgorithm hasher = new SHA256CryptoServiceProvider())
hash = hasher.ComputeHash(asset.Data);
// m_log.DebugFormat( // m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}", // "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",

View File

@ -69,15 +69,3 @@ CREATE TABLE IF NOT EXISTS `estateban` (
COMMIT; COMMIT;
:VERSION 35
BEGIN;
ALTER TABLE `estateban`
ADD COLUMN `banningUUID` varchar(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
ADD COLUMN `banTime` int(11) NOT NULL DEFAULT 0;
COMMIT;
:VERSION 36
BEGIN;
ALTER TABLE `estate_settings`
ADD COLUMN `AllowEnviromentOverride` tinyint(4) NOT NULL DEFAULT '0';
COMMIT;

View File

@ -16,9 +16,3 @@ CREATE TABLE `hg_traveling_data` (
COMMIT; COMMIT;
:VERSION 2 # --------------------------
ALTER TABLE `hg_traveling_data` MODIFY `TMStamp` timestamp NOT NULL default CURRENT_TIMESTAMP;
COMMIT;

View File

@ -1,16 +0,0 @@
:VERSION 1
BEGIN;
CREATE TABLE `MuteList` (
`AgentID` char(36) NOT NULL,
`MuteID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
`MuteName` varchar(64) NOT NULL DEFAULT '',
`MuteType` int(11) NOT NULL DEFAULT '1',
`MuteFlags` int(11) NOT NULL DEFAULT '0',
`Stamp` int(11) NOT NULL,
UNIQUE KEY `AgentID_2` (`AgentID`,`MuteID`,`MuteName`),
KEY `AgentID` (`AgentID`)
);
COMMIT;

View File

@ -467,86 +467,3 @@ COMMIT;
BEGIN; BEGIN;
ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL; ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
COMMIT; COMMIT;
:VERSION 58 #----- Add sop animations
BEGIN;
ALTER TABLE `prims` ADD COLUMN `sopanims` blob default NULL;
COMMIT;
:VERSION 59 #----- Add standtarget and sit range
BEGIN;
ALTER TABLE `prims`
ADD COLUMN `standtargetx` float DEFAULT '0.0',
ADD COLUMN `standtargety` float DEFAULT '0.0',
ADD COLUMN `standtargetz` float DEFAULT '0.0',
ADD COLUMN `sitactrange` float DEFAULT '0.0';
COMMIT;
:VERSION 60 #----- don't store float on double
BEGIN;
ALTER TABLE `prims`
MODIFY `PositionX` float DEFAULT '0.0',
MODIFY `PositionY` float DEFAULT '0.0',
MODIFY `PositionZ` float DEFAULT '0.0',
MODIFY `GroupPositionX` float DEFAULT '0.0',
MODIFY `GroupPositionY` float DEFAULT '0.0',
MODIFY `GroupPositionZ` float DEFAULT '0.0',
MODIFY `VelocityX` float DEFAULT '0.0',
MODIFY `VelocityY` float DEFAULT '0.0',
MODIFY `VelocityZ` float DEFAULT '0.0',
MODIFY `AngularVelocityX` float DEFAULT '0.0',
MODIFY `AngularVelocityY` float DEFAULT '0.0',
MODIFY `AngularVelocityZ` float DEFAULT '0.0',
MODIFY `AccelerationX` float DEFAULT '0.0',
MODIFY `AccelerationY` float DEFAULT '0.0',
MODIFY `AccelerationZ` float DEFAULT '0.0',
MODIFY `RotationX` float DEFAULT '0.0',
MODIFY `RotationY` float DEFAULT '0.0',
MODIFY `RotationZ` float DEFAULT '0.0',
MODIFY `RotationW` float DEFAULT '0.0',
MODIFY `SitTargetOffsetX` float DEFAULT '0.0',
MODIFY `SitTargetOffsetY` float DEFAULT '0.0',
MODIFY `SitTargetOffsetZ` float DEFAULT '0.0',
MODIFY `SitTargetOrientX` float DEFAULT '0.0',
MODIFY `SitTargetOrientY` float DEFAULT '0.0',
MODIFY `SitTargetOrientZ` float DEFAULT '0.0',
MODIFY `SitTargetOrientW` float DEFAULT '0.0',
MODIFY `OmegaX` float DEFAULT '0.0',
MODIFY `OmegaY` float DEFAULT '0.0',
MODIFY `OmegaZ` float DEFAULT '0.0',
MODIFY `CameraEyeOffsetX` float DEFAULT '0.0',
MODIFY `CameraEyeOffsetY` float DEFAULT '0.0',
MODIFY `CameraEyeOffsetZ` float DEFAULT '0.0',
MODIFY `CameraAtOffsetX` float DEFAULT '0.0',
MODIFY `CameraAtOffsetY` float DEFAULT '0.0',
MODIFY `CameraAtOffsetZ` float DEFAULT '0.0',
MODIFY `Density` float DEFAULT '1000.0',
MODIFY `GravityModifier` float DEFAULT '1.0',
MODIFY `Friction` float DEFAULT '0.6',
MODIFY `Restitution` float DEFAULT '0.5',
MODIFY `AttachedPosX` float DEFAULT '0',
MODIFY `AttachedPosY` float DEFAULT '0',
MODIFY `AttachedPosZ` float DEFAULT '0',
MODIFY `LoopedSoundGain` float DEFAULT '0';
COMMIT;
:VERSION 61 #----- Add pseudo CRC and region cache id
BEGIN;
ALTER TABLE `prims` ADD COLUMN `pseudocrc` int DEFAULT '0';
ALTER TABLE `regionsettings` ADD COLUMN `cacheID` char(36) DEFAULT NULL;
COMMIT;
:VERSION 62 #----- increase size of environment settings
BEGIN;
ALTER TABLE `regionenvironment` MODIFY `llsd_settings` MEDIUMTEXT;
COMMIT;
:VERSION 63 #----- parcel environment store
BEGIN;
ALTER TABLE `land` ADD COLUMN `environment` MEDIUMTEXT default NULL;
COMMIT;

View File

@ -113,11 +113,3 @@ DROP TABLE `diva_groups_principals`;
DELETE FROM `migrations` WHERE name='diva_im_Store'; DELETE FROM `migrations` WHERE name='diva_im_Store';
COMMIT; COMMIT;
:VERSION 3 # --------------------------
ALTER TABLE `os_groups_invites`
MODIFY `TMStamp` timestamp NOT NULL default CURRENT_TIMESTAMP;
COMMIT;

View File

@ -42,47 +42,6 @@ namespace OpenSim.Data.Null
/// </summary> /// </summary>
public class NullGenericDataHandler public class NullGenericDataHandler
{ {
protected List<T> Get<T>(string field, string val, List<T> inputEntities)
{
List<T> entities = inputEntities;
entities
= entities.Where(
e =>
{
FieldInfo fi = typeof(T).GetField(field);
if (fi == null)
throw new NotImplementedException(string.Format("No field {0} for val {1}", field, val));
return fi.GetValue(e).ToString() == val;
}
).ToList();
return entities;
}
protected List<T> Get<T>(string field, string[] vals, List<T> inputEntities)
{
List<T> entities = new List<T>();
for (int i = 0; i < vals.Length; i++)
{
entities.AddRange (inputEntities.Where(
e =>
{
FieldInfo fi = typeof(T).GetField(field);
if (fi == null)
throw new NotImplementedException(string.Format("No field {0} for val {1}", field, vals[i]));
return fi.GetValue(e).ToString() == vals[i];
}
).ToList()
);
}
return entities;
}
protected List<T> Get<T>(string[] fields, string[] vals, List<T> inputEntities) protected List<T> Get<T>(string[] fields, string[] vals, List<T> inputEntities)
{ {
List<T> entities = inputEntities; List<T> entities = inputEntities;

View File

@ -68,34 +68,12 @@ namespace OpenSim.Data.Null
private delegate bool Matcher(string value); private delegate bool Matcher(string value);
public RegionData GetSpecific(string regionName, UUID scopeID)
{
if (m_useStaticInstance && Instance != this)
return Instance.GetSpecific(regionName, scopeID);
string cleanName = regionName.ToLower();
Matcher queryMatch;
queryMatch = delegate (string s) { return s.Equals(cleanName); };
lock (m_regionData)
{
foreach (RegionData r in m_regionData.Values)
{
// m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower());
if (queryMatch(r.RegionName.ToLower()))
return(r);
}
}
return null;
}
public List<RegionData> Get(string regionName, UUID scopeID) public List<RegionData> Get(string regionName, UUID scopeID)
{ {
if (m_useStaticInstance && Instance != this) if (m_useStaticInstance && Instance != this)
return Instance.Get(regionName, scopeID); return Instance.Get(regionName, scopeID);
// m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID); // m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID);
string cleanName = regionName.ToLower(); string cleanName = regionName.ToLower();

View File

@ -151,7 +151,7 @@ namespace OpenSim.Data.Null
// Legacy. Just don't do this. // Legacy. Just don't do this.
public void StoreTerrain(double[,] ter, UUID regionID) public void StoreTerrain(double[,] ter, UUID regionID)
{ {
TerrainData terrData = new TerrainData(ter); TerrainData terrData = new HeightmapTerrainData(ter);
StoreTerrain(terrData, regionID); StoreTerrain(terrData, regionID);
} }

View File

@ -286,7 +286,7 @@ namespace OpenSim.Data.PGSQL
{ {
es.ClearBans(); es.ClearBans();
string sql = "select * from estateban where \"EstateID\" = :EstateID"; string sql = "select \"bannedUUID\" from estateban where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
@ -302,8 +302,6 @@ namespace OpenSim.Data.PGSQL
EstateBan eb = new EstateBan(); EstateBan eb = new EstateBan();
eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid; eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid;
eb.BanningUserID = new UUID((Guid)reader["banningUUID"]); //uuid;
eb.BanTime = Convert.ToInt32(reader["banTime"]);
eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb); es.AddBan(eb);
@ -348,15 +346,11 @@ namespace OpenSim.Data.PGSQL
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
//Insert after //Insert after
cmd.CommandText = "insert into estateban (\"EstateID\", \"bannedUUID\",\"bannedIp\", \"bannedIpHostMask\", \"bannedNameMask\", \"banningUUID\",\"banTime\" ) values ( :EstateID, :bannedUUID, '','','', :banningUUID, :banTime )"; cmd.CommandText = "insert into estateban (\"EstateID\", \"bannedUUID\",\"bannedIp\", \"bannedIpHostMask\", \"bannedNameMask\") values ( :EstateID, :bannedUUID, '','','' )";
cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty); cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty);
foreach (EstateBan b in es.EstateBans) foreach (EstateBan b in es.EstateBans)
{ {
cmd.Parameters["EstateID"].Value = b.EstateID;
cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid; cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid;
cmd.Parameters["banningUUID"].Value = b.BanningUserID.Guid;
cmd.Parameters["banTime"].Value = b.BanTime;
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
} }

View File

@ -1,316 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Data;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using log4net;
using OpenMetaverse;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLFSAssetData : IFSAssetDataPlugin
{
private const string _migrationStore = "FSAssetStore";
private static string m_Table = "fsassets";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private long m_ticksToEpoch;
private PGSQLManager m_database;
private string m_connectionString;
public PGSQLFSAssetData()
{
}
public void Initialise(string connect, string realm, int UpdateAccessTime)
{
DaysBetweenAccessTimeUpdates = UpdateAccessTime;
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
m_connectionString = connect;
m_database = new PGSQLManager(m_connectionString);
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
}
public void Initialise()
{
throw new NotImplementedException();
}
/// <summary>
/// Number of days that must pass before we update the access time on an asset when it has been fetched
/// Config option to change this is "DaysBetweenAccessTimeUpdates"
/// </summary>
private int DaysBetweenAccessTimeUpdates = 0;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
public string Version { get { return "1.0.0.0"; } }
public void Dispose() { }
public string Name
{
get { return "PGSQL FSAsset storage engine"; }
}
#endregion
#region IFSAssetDataPlugin Members
public AssetMetadata Get(string id, out string hash)
{
hash = String.Empty;
AssetMetadata meta = null;
UUID uuid = new UUID(id);
string query = String.Format("select \"id\", \"type\", \"hash\", \"create_time\", \"access_time\", \"asset_flags\" from {0} where \"id\" = :id", m_Table);
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
cmd.Parameters.Add(m_database.CreateParameter("id", uuid));
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
{
if (reader.Read())
{
meta = new AssetMetadata();
hash = reader["hash"].ToString();
meta.ID = id;
meta.FullID = uuid;
meta.Name = String.Empty;
meta.Description = String.Empty;
meta.Type = (sbyte)Convert.ToInt32(reader["type"]);
meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type);
meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"]));
meta.Flags = (AssetFlags)Convert.ToInt32(reader["asset_flags"]);
int atime = Convert.ToInt32(reader["access_time"]);
UpdateAccessTime(atime, uuid);
}
}
}
return meta;
}
private void UpdateAccessTime(int AccessTime, UUID id)
{
// Reduce DB work by only updating access time if asset hasn't recently been accessed
// 0 By Default, Config option is "DaysBetweenAccessTimeUpdates"
if (DaysBetweenAccessTimeUpdates > 0 && (DateTime.UtcNow - Utils.UnixTimeToDateTime(AccessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
return;
string query = String.Format("UPDATE {0} SET \"access_time\" = :access_time WHERE \"id\" = :id", m_Table);
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
cmd.Parameters.Add(m_database.CreateParameter("id", id));
cmd.Parameters.Add(m_database.CreateParameter("access_time", now));
cmd.ExecuteNonQuery();
}
}
public bool Store(AssetMetadata meta, string hash)
{
try
{
bool found = false;
string oldhash;
AssetMetadata existingAsset = Get(meta.ID, out oldhash);
string query = String.Format("UPDATE {0} SET \"access_time\" = :access_time WHERE \"id\" = :id", m_Table);
if (existingAsset == null)
{
query = String.Format("insert into {0} (\"id\", \"type\", \"hash\", \"asset_flags\", \"create_time\", \"access_time\") values ( :id, :type, :hash, :asset_flags, :create_time, :access_time)", m_Table);
found = true;
}
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
cmd.Parameters.Add(m_database.CreateParameter("id", meta.FullID));
cmd.Parameters.Add(m_database.CreateParameter("type", meta.Type));
cmd.Parameters.Add(m_database.CreateParameter("hash", hash));
cmd.Parameters.Add(m_database.CreateParameter("asset_flags", Convert.ToInt32(meta.Flags)));
cmd.Parameters.Add(m_database.CreateParameter("create_time", now));
cmd.Parameters.Add(m_database.CreateParameter("access_time", now));
cmd.ExecuteNonQuery();
}
return found;
}
catch(Exception e)
{
m_log.Error("[PGSQL FSASSETS] Failed to store asset with ID " + meta.ID);
m_log.Error(e.ToString());
return false;
}
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The asset UUID's</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exists = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string query = string.Format("select \"id\" from {1} where id in ({0})", ids, m_Table);
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
{
while (reader.Read())
{
UUID id = DBGuid.FromDB(reader["id"]);;
exists.Add(id);
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exists.Contains(uuids[i]);
return results;
}
public int Count()
{
int count = 0;
string query = String.Format("select count(*) as count from {0}", m_Table);
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
IDataReader reader = cmd.ExecuteReader();
reader.Read();
count = Convert.ToInt32(reader["count"]);
reader.Close();
}
return count;
}
public bool Delete(string id)
{
string query = String.Format("delete from {0} where \"id\" = :id", m_Table);
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
dbcon.Open();
cmd.Parameters.Add(m_database.CreateParameter("id", new UUID(id)));
cmd.ExecuteNonQuery();
}
return true;
}
public void Import(string conn, string table, int start, int count, bool force, FSStoreDelegate store)
{
int imported = 0;
string limit = String.Empty;
if(count != -1)
{
limit = String.Format(" limit {0} offset {1}", start, count);
}
string query = String.Format("select * from {0}{1}", table, limit);
try
{
using (NpgsqlConnection remote = new NpgsqlConnection(conn))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, remote))
{
remote.Open();
MainConsole.Instance.Output("Querying database");
MainConsole.Instance.Output("Reading data");
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
{
while (reader.Read())
{
if ((imported % 100) == 0)
{
MainConsole.Instance.Output(String.Format("{0} assets imported so far", imported));
}
AssetBase asset = new AssetBase();
AssetMetadata meta = new AssetMetadata();
meta.ID = reader["id"].ToString();
meta.FullID = new UUID(meta.ID);
meta.Name = String.Empty;
meta.Description = String.Empty;
meta.Type = (sbyte)Convert.ToInt32(reader["assetType"]);
meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type);
meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"]));
asset.Metadata = meta;
asset.Data = (byte[])reader["data"];
store(asset, force);
imported++;
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PGSQL FSASSETS]: Error importing assets: {0}",
e.Message.ToString());
return;
}
MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported));
}
#endregion
}
}

View File

@ -180,54 +180,7 @@ namespace OpenSim.Data.PGSQL
public virtual T[] Get(string field, string key) public virtual T[] Get(string field, string key)
{ {
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) return Get(new string[] { field }, new string[] { key });
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
if ( m_FieldTypes.ContainsKey(field) )
cmd.Parameters.Add(m_database.CreateParameter(field, key, m_FieldTypes[field]));
else
cmd.Parameters.Add(m_database.CreateParameter(field, key));
string query = String.Format("SELECT * FROM {0} WHERE \"{1}\" = :{1}", m_Realm, field, field);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
public virtual T[] Get(string field, string[] keys)
{
int flen = keys.Length;
if(flen == 0)
return new T[0];
int flast = flen - 1;
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select * from {0} where {1} IN ('", m_Realm, field);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0 ; i < flen ; i++)
{
sb.Append(keys[i]);
if(i < flast)
sb.Append("','");
else
sb.Append("')");
}
string query = sb.ToString();
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
} }
public virtual T[] Get(string[] fields, string[] keys) public virtual T[] Get(string[] fields, string[] keys)

View File

@ -86,13 +86,13 @@ namespace OpenSim.Data.PGSQL
if (string.IsNullOrEmpty(pattern)) // True for where clause if (string.IsNullOrEmpty(pattern)) // True for where clause
{ {
pattern = "1"; pattern = " 1 ORDER BY lower(\"Name\") LIMIT 100";
return m_Groups.Get(pattern); return m_Groups.Get(pattern);
} }
else else
{ {
pattern = " \"ShowInList\" = 1 AND lower(\"Name\") LIKE lower('%" + pattern + "%')"; pattern = " \"ShowInList\" = 1 AND lower(\"Name\") LIKE lower('%" + pattern + "%') ORDER BY lower(\"Name\") LIMIT 100";
return m_Groups.Get(pattern, new NpgsqlParameter("pattern", pattern)); return m_Groups.Get(pattern, new NpgsqlParameter("pattern", pattern));
} }

View File

@ -114,27 +114,6 @@ namespace OpenSim.Data.PGSQL
} }
} }
public RegionData GetSpecific(string regionName, UUID scopeID)
{
string sql = "select * from " + m_Realm + " where lower(\"regionName\") = lower(:regionName) ";
if (scopeID != UUID.Zero)
sql += " and \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
if (scopeID != UUID.Zero)
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public RegionData Get(int posX, int posY, UUID scopeID) public RegionData Get(int posX, int posY, UUID scopeID)
{ {
// extend database search for maximum region size area // extend database search for maximum region size area

View File

@ -353,10 +353,8 @@ namespace OpenSim.Data.PGSQL
""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution, ""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution,
""PassCollisions"" = :PassCollisions, ""RotationAxisLocks"" = :RotationAxisLocks, ""RezzerID"" = :RezzerID, ""PassCollisions"" = :PassCollisions, ""RotationAxisLocks"" = :RotationAxisLocks, ""RezzerID"" = :RezzerID,
""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches, ""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches,
""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs, ""Vehicle"" = :Vehicle, ""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs,
""PhysInertia"" = :PhysInertia, ""standtargetx"" =:standtargetx, ""standtargety"" =:standtargety, ""standtargetz"" =:standtargetz, ""PhysInertia"" = :PhysInertia
""sitactrange"" =:sitactrange, ""pseudocrc"" = :pseudocrc
WHERE ""UUID"" = :UUID ; WHERE ""UUID"" = :UUID ;
INSERT INTO INSERT INTO
@ -370,8 +368,7 @@ namespace OpenSim.Data.PGSQL
""OmegaY"", ""OmegaZ"", ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"", ""OmegaY"", ""OmegaZ"", ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"",
""ForceMouselook"", ""ScriptAccessPin"", ""AllowedDrop"", ""DieAtEdge"", ""SalePrice"", ""SaleType"", ""ColorR"", ""ColorG"", ""ColorB"", ""ColorA"", ""ForceMouselook"", ""ScriptAccessPin"", ""AllowedDrop"", ""DieAtEdge"", ""SalePrice"", ""SaleType"", ""ColorR"", ""ColorG"", ""ColorB"", ""ColorA"",
""ParticleSystem"", ""ClickAction"", ""Material"", ""CollisionSound"", ""CollisionSoundVolume"", ""PassTouches"", ""LinkNumber"", ""MediaURL"", ""DynAttrs"", ""ParticleSystem"", ""ClickAction"", ""Material"", ""CollisionSound"", ""CollisionSoundVolume"", ""PassTouches"", ""LinkNumber"", ""MediaURL"", ""DynAttrs"",
""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""Vehicle"", ""PhysInertia"", ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""PhysInertia""
""standtargetx"", ""standtargety"", ""standtargetz"", ""sitactrange"", ""pseudocrc""
) Select ) Select
:UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask, :UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask,
:EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX, :EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX,
@ -382,8 +379,7 @@ namespace OpenSim.Data.PGSQL
:OmegaY, :OmegaZ, :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ, :OmegaY, :OmegaZ, :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ,
:ForceMouselook, :ScriptAccessPin, :AllowedDrop, :DieAtEdge, :SalePrice, :SaleType, :ColorR, :ColorG, :ColorB, :ColorA, :ForceMouselook, :ScriptAccessPin, :AllowedDrop, :DieAtEdge, :SalePrice, :SaleType, :ColorR, :ColorG, :ColorB, :ColorA,
:ParticleSystem, :ClickAction, :Material, :CollisionSound, :CollisionSoundVolume, :PassTouches, :LinkNumber, :MediaURL, :DynAttrs, :ParticleSystem, :ClickAction, :Material, :CollisionSound, :CollisionSoundVolume, :PassTouches, :LinkNumber, :MediaURL, :DynAttrs,
:PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :Vehicle, :PhysInertia, :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :PhysInertia
:standtargetx, :standtargety, :standtargetz,:sitactrange, :pseudocrc
where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID); where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID);
"; ";
@ -614,7 +610,7 @@ namespace OpenSim.Data.PGSQL
// Legacy entry point for when terrain was always a 256x256 heightmap // Legacy entry point for when terrain was always a 256x256 heightmap
public void StoreTerrain(double[,] terrain, UUID regionID) public void StoreTerrain(double[,] terrain, UUID regionID)
{ {
StoreTerrain(new TerrainData(terrain), regionID); StoreTerrain(new HeightmapTerrainData(terrain), regionID);
} }
/// <summary> /// <summary>
@ -770,14 +766,13 @@ namespace OpenSim.Data.PGSQL
(""UUID"",""RegionUUID"",""LocalLandID"",""Bitmap"",""Name"",""Description"",""OwnerUUID"",""IsGroupOwned"",""Area"",""AuctionID"",""Category"",""ClaimDate"",""ClaimPrice"", (""UUID"",""RegionUUID"",""LocalLandID"",""Bitmap"",""Name"",""Description"",""OwnerUUID"",""IsGroupOwned"",""Area"",""AuctionID"",""Category"",""ClaimDate"",""ClaimPrice"",
""GroupUUID"",""SalePrice"",""LandStatus"",""LandFlags"",""LandingType"",""MediaAutoScale"",""MediaTextureUUID"",""MediaURL"",""MusicURL"",""PassHours"",""PassPrice"", ""GroupUUID"",""SalePrice"",""LandStatus"",""LandFlags"",""LandingType"",""MediaAutoScale"",""MediaTextureUUID"",""MediaURL"",""MusicURL"",""PassHours"",""PassPrice"",
""SnapshotUUID"",""UserLocationX"",""UserLocationY"",""UserLocationZ"",""UserLookAtX"",""UserLookAtY"",""UserLookAtZ"",""AuthbuyerID"",""OtherCleanTime"",""Dwell"", ""SnapshotUUID"",""UserLocationX"",""UserLocationY"",""UserLocationZ"",""UserLookAtX"",""UserLookAtY"",""UserLookAtZ"",""AuthbuyerID"",""OtherCleanTime"",""Dwell"",
""MediaType"",""MediaDescription"",""MediaSize"",""MediaLoop"",""ObscureMusic"",""ObscureMedia"",""SeeAVs"",""AnyAVSounds"",""GroupAVSounds"", ""MediaType"",""MediaDescription"",""MediaSize"",""MediaLoop"",""ObscureMusic"",""ObscureMedia"",""SeeAVs"",""AnyAVSounds"",""GroupAVSounds"")
""environment"")
VALUES VALUES
(:UUID,:RegionUUID,:LocalLandID,:Bitmap,:Name,:Description,:OwnerUUID,:IsGroupOwned,:Area,:AuctionID,:Category,:ClaimDate,:ClaimPrice, (:UUID,:RegionUUID,:LocalLandID,:Bitmap,:Name,:Description,:OwnerUUID,:IsGroupOwned,:Area,:AuctionID,:Category,:ClaimDate,:ClaimPrice,
:GroupUUID,:SalePrice,:LandStatus,:LandFlags,:LandingType,:MediaAutoScale,:MediaTextureUUID,:MediaURL,:MusicURL,:PassHours,:PassPrice, :GroupUUID,:SalePrice,:LandStatus,:LandFlags,:LandingType,:MediaAutoScale,:MediaTextureUUID,:MediaURL,:MusicURL,:PassHours,:PassPrice,
:SnapshotUUID,:UserLocationX,:UserLocationY,:UserLocationZ,:UserLookAtX,:UserLookAtY,:UserLookAtZ,:AuthbuyerID,:OtherCleanTime,:Dwell, :SnapshotUUID,:UserLocationX,:UserLocationY,:UserLocationZ,:UserLookAtX,:UserLookAtY,:UserLookAtZ,:AuthbuyerID,:OtherCleanTime,:Dwell,
:MediaType,:MediaDescription,:MediaWidth::text || ',' || :MediaHeight::text,:MediaLoop,:ObscureMusic,:ObscureMedia,:SeeAVs::int::smallint, :MediaType,:MediaDescription,:MediaWidth::text || ',' || :MediaHeight::text,:MediaLoop,:ObscureMusic,:ObscureMedia,:SeeAVs::int::smallint,
:AnyAVSounds::int::smallint,:GroupAVSounds::int::smallint,:environment)"; :AnyAVSounds::int::smallint,:GroupAVSounds::int::smallint)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
@ -826,6 +821,477 @@ namespace OpenSim.Data.PGSQL
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
} }
public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
{
RegionLightShareData nWP = new RegionLightShareData();
nWP.OnSave += StoreRegionWindlightSettings;
string sql = @"select * from regionwindlight where ""region_id"" = :regionID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("regionID", regionUUID.ToString() ));
conn.Open();
using (NpgsqlDataReader result = cmd.ExecuteReader())
{
if (!result.Read())
{
//No result, so store our default windlight profile and return it
nWP.regionID = regionUUID;
StoreRegionWindlightSettings(nWP);
return nWP;
}
else
{
nWP.regionID = DBGuid.FromDB(result["region_id"]);
nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]);
nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]);
nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]);
nWP.waterFogDensityExponent = Convert.ToSingle(result["water_fog_density_exponent"]);
nWP.underwaterFogModifier = Convert.ToSingle(result["underwater_fog_modifier"]);
nWP.reflectionWaveletScale.X = Convert.ToSingle(result["reflection_wavelet_scale_1"]);
nWP.reflectionWaveletScale.Y = Convert.ToSingle(result["reflection_wavelet_scale_2"]);
nWP.reflectionWaveletScale.Z = Convert.ToSingle(result["reflection_wavelet_scale_3"]);
nWP.fresnelScale = Convert.ToSingle(result["fresnel_scale"]);
nWP.fresnelOffset = Convert.ToSingle(result["fresnel_offset"]);
nWP.refractScaleAbove = Convert.ToSingle(result["refract_scale_above"]);
nWP.refractScaleBelow = Convert.ToSingle(result["refract_scale_below"]);
nWP.blurMultiplier = Convert.ToSingle(result["blur_multiplier"]);
nWP.bigWaveDirection.X = Convert.ToSingle(result["big_wave_direction_x"]);
nWP.bigWaveDirection.Y = Convert.ToSingle(result["big_wave_direction_y"]);
nWP.littleWaveDirection.X = Convert.ToSingle(result["little_wave_direction_x"]);
nWP.littleWaveDirection.Y = Convert.ToSingle(result["little_wave_direction_y"]);
UUID.TryParse(result["normal_map_texture"].ToString(), out nWP.normalMapTexture);
nWP.horizon.X = Convert.ToSingle(result["horizon_r"]);
nWP.horizon.Y = Convert.ToSingle(result["horizon_g"]);
nWP.horizon.Z = Convert.ToSingle(result["horizon_b"]);
nWP.horizon.W = Convert.ToSingle(result["horizon_i"]);
nWP.hazeHorizon = Convert.ToSingle(result["haze_horizon"]);
nWP.blueDensity.X = Convert.ToSingle(result["blue_density_r"]);
nWP.blueDensity.Y = Convert.ToSingle(result["blue_density_g"]);
nWP.blueDensity.Z = Convert.ToSingle(result["blue_density_b"]);
nWP.blueDensity.W = Convert.ToSingle(result["blue_density_i"]);
nWP.hazeDensity = Convert.ToSingle(result["haze_density"]);
nWP.densityMultiplier = Convert.ToSingle(result["density_multiplier"]);
nWP.distanceMultiplier = Convert.ToSingle(result["distance_multiplier"]);
nWP.maxAltitude = Convert.ToUInt16(result["max_altitude"]);
nWP.sunMoonColor.X = Convert.ToSingle(result["sun_moon_color_r"]);
nWP.sunMoonColor.Y = Convert.ToSingle(result["sun_moon_color_g"]);
nWP.sunMoonColor.Z = Convert.ToSingle(result["sun_moon_color_b"]);
nWP.sunMoonColor.W = Convert.ToSingle(result["sun_moon_color_i"]);
nWP.sunMoonPosition = Convert.ToSingle(result["sun_moon_position"]);
nWP.ambient.X = Convert.ToSingle(result["ambient_r"]);
nWP.ambient.Y = Convert.ToSingle(result["ambient_g"]);
nWP.ambient.Z = Convert.ToSingle(result["ambient_b"]);
nWP.ambient.W = Convert.ToSingle(result["ambient_i"]);
nWP.eastAngle = Convert.ToSingle(result["east_angle"]);
nWP.sunGlowFocus = Convert.ToSingle(result["sun_glow_focus"]);
nWP.sunGlowSize = Convert.ToSingle(result["sun_glow_size"]);
nWP.sceneGamma = Convert.ToSingle(result["scene_gamma"]);
nWP.starBrightness = Convert.ToSingle(result["star_brightness"]);
nWP.cloudColor.X = Convert.ToSingle(result["cloud_color_r"]);
nWP.cloudColor.Y = Convert.ToSingle(result["cloud_color_g"]);
nWP.cloudColor.Z = Convert.ToSingle(result["cloud_color_b"]);
nWP.cloudColor.W = Convert.ToSingle(result["cloud_color_i"]);
nWP.cloudXYDensity.X = Convert.ToSingle(result["cloud_x"]);
nWP.cloudXYDensity.Y = Convert.ToSingle(result["cloud_y"]);
nWP.cloudXYDensity.Z = Convert.ToSingle(result["cloud_density"]);
nWP.cloudCoverage = Convert.ToSingle(result["cloud_coverage"]);
nWP.cloudScale = Convert.ToSingle(result["cloud_scale"]);
nWP.cloudDetailXYDensity.X = Convert.ToSingle(result["cloud_detail_x"]);
nWP.cloudDetailXYDensity.Y = Convert.ToSingle(result["cloud_detail_y"]);
nWP.cloudDetailXYDensity.Z = Convert.ToSingle(result["cloud_detail_density"]);
nWP.cloudScrollX = Convert.ToSingle(result["cloud_scroll_x"]);
nWP.cloudScrollXLock = Convert.ToBoolean(result["cloud_scroll_x_lock"]);
nWP.cloudScrollY = Convert.ToSingle(result["cloud_scroll_y"]);
nWP.cloudScrollYLock = Convert.ToBoolean(result["cloud_scroll_y_lock"]);
nWP.drawClassicClouds = Convert.ToBoolean(result["draw_classic_clouds"]);
nWP.valid = true;
}
}
}
return nWP;
}
public void RemoveRegionWindlightSettings(UUID regionID)
{
string sql = @"delete from regionwindlight where ""region_id"" = :region_id";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.Add(_Database.CreateParameter("region_id", regionID.ToString()));
cmd.ExecuteNonQuery();
}
}
public void StoreRegionWindlightSettings(RegionLightShareData wl)
{
string sql = @"select region_id from regionwindlight where ""region_id"" = :region_id limit 1;";
bool exists = false;
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID.ToString() ));
NpgsqlDataReader dr = cmd.ExecuteReader();
exists = dr.Read();
}
}
if (exists)
{
RemoveRegionWindlightSettings(wl.regionID);
}
// sql insert
sql = @"INSERT INTO regionwindlight
(region_id
,water_color_r
,water_color_g
,water_color_b
,water_fog_density_exponent
,underwater_fog_modifier
,reflection_wavelet_scale_1
,reflection_wavelet_scale_2
,reflection_wavelet_scale_3
,fresnel_scale
,fresnel_offset
,refract_scale_above
,refract_scale_below
,blur_multiplier
,big_wave_direction_x
,big_wave_direction_y
,little_wave_direction_x
,little_wave_direction_y
,normal_map_texture
,horizon_r
,horizon_g
,horizon_b
,horizon_i
,haze_horizon
,blue_density_r
,blue_density_g
,blue_density_b
,blue_density_i
,haze_density
,density_multiplier
,distance_multiplier
,max_altitude
,sun_moon_color_r
,sun_moon_color_g
,sun_moon_color_b
,sun_moon_color_i
,sun_moon_position
,ambient_r
,ambient_g
,ambient_b
,ambient_i
,east_angle
,sun_glow_focus
,sun_glow_size
,scene_gamma
,star_brightness
,cloud_color_r
,cloud_color_g
,cloud_color_b
,cloud_color_i
,cloud_x
,cloud_y
,cloud_density
,cloud_coverage
,cloud_scale
,cloud_detail_x
,cloud_detail_y
,cloud_detail_density
,cloud_scroll_x
,cloud_scroll_x_lock
,cloud_scroll_y
,cloud_scroll_y_lock
,draw_classic_clouds)
VALUES
(:region_id
,:water_color_r
,:water_color_g
,:water_color_b
,:water_fog_density_exponent
,:underwater_fog_modifier
,:reflection_wavelet_scale_1
,:reflection_wavelet_scale_2
,:reflection_wavelet_scale_3
,:fresnel_scale
,:fresnel_offset
,:refract_scale_above
,:refract_scale_below
,:blur_multiplier
,:big_wave_direction_x
,:big_wave_direction_y
,:little_wave_direction_x
,:little_wave_direction_y
,:normal_map_texture
,:horizon_r
,:horizon_g
,:horizon_b
,:horizon_i
,:haze_horizon
,:blue_density_r
,:blue_density_g
,:blue_density_b
,:blue_density_i
,:haze_density
,:density_multiplier
,:distance_multiplier
,:max_altitude
,:sun_moon_color_r
,:sun_moon_color_g
,:sun_moon_color_b
,:sun_moon_color_i
,:sun_moon_position
,:ambient_r
,:ambient_g
,:ambient_b
,:ambient_i
,:east_angle
,:sun_glow_focus
,:sun_glow_size
,:scene_gamma
,:star_brightness
,:cloud_color_r
,:cloud_color_g
,:cloud_color_b
,:cloud_color_i
,:cloud_x
,:cloud_y
,:cloud_density
,:cloud_coverage
,:cloud_scale
,:cloud_detail_x
,:cloud_detail_y
,:cloud_detail_density
,:cloud_scroll_x
,:cloud_scroll_x_lock
,:cloud_scroll_y
,:cloud_scroll_y_lock
,:draw_classic_clouds);";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID.ToString()));
cmd.Parameters.Add(_Database.CreateParameter("water_color_r", wl.waterColor.X));
cmd.Parameters.Add(_Database.CreateParameter("water_color_g", wl.waterColor.Y));
cmd.Parameters.Add(_Database.CreateParameter("water_color_b", wl.waterColor.Z));
cmd.Parameters.Add(_Database.CreateParameter("water_fog_density_exponent", wl.waterFogDensityExponent));
cmd.Parameters.Add(_Database.CreateParameter("underwater_fog_modifier", wl.underwaterFogModifier));
cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X));
cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y));
cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z));
cmd.Parameters.Add(_Database.CreateParameter("fresnel_scale", wl.fresnelScale));
cmd.Parameters.Add(_Database.CreateParameter("fresnel_offset", wl.fresnelOffset));
cmd.Parameters.Add(_Database.CreateParameter("refract_scale_above", wl.refractScaleAbove));
cmd.Parameters.Add(_Database.CreateParameter("refract_scale_below", wl.refractScaleBelow));
cmd.Parameters.Add(_Database.CreateParameter("blur_multiplier", wl.blurMultiplier));
cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_x", wl.bigWaveDirection.X));
cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_y", wl.bigWaveDirection.Y));
cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_x", wl.littleWaveDirection.X));
cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_y", wl.littleWaveDirection.Y));
cmd.Parameters.Add(_Database.CreateParameter("normal_map_texture", wl.normalMapTexture.ToString()));
cmd.Parameters.Add(_Database.CreateParameter("horizon_r", wl.horizon.X));
cmd.Parameters.Add(_Database.CreateParameter("horizon_g", wl.horizon.Y));
cmd.Parameters.Add(_Database.CreateParameter("horizon_b", wl.horizon.Z));
cmd.Parameters.Add(_Database.CreateParameter("horizon_i", wl.horizon.W));
cmd.Parameters.Add(_Database.CreateParameter("haze_horizon", wl.hazeHorizon));
cmd.Parameters.Add(_Database.CreateParameter("blue_density_r", wl.blueDensity.X));
cmd.Parameters.Add(_Database.CreateParameter("blue_density_g", wl.blueDensity.Y));
cmd.Parameters.Add(_Database.CreateParameter("blue_density_b", wl.blueDensity.Z));
cmd.Parameters.Add(_Database.CreateParameter("blue_density_i", wl.blueDensity.W));
cmd.Parameters.Add(_Database.CreateParameter("haze_density", wl.hazeDensity));
cmd.Parameters.Add(_Database.CreateParameter("density_multiplier", wl.densityMultiplier));
cmd.Parameters.Add(_Database.CreateParameter("distance_multiplier", wl.distanceMultiplier));
cmd.Parameters.Add(_Database.CreateParameter("max_altitude", wl.maxAltitude));
cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_r", wl.sunMoonColor.X));
cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_g", wl.sunMoonColor.Y));
cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_b", wl.sunMoonColor.Z));
cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_i", wl.sunMoonColor.W));
cmd.Parameters.Add(_Database.CreateParameter("sun_moon_position", wl.sunMoonPosition));
cmd.Parameters.Add(_Database.CreateParameter("ambient_r", wl.ambient.X));
cmd.Parameters.Add(_Database.CreateParameter("ambient_g", wl.ambient.Y));
cmd.Parameters.Add(_Database.CreateParameter("ambient_b", wl.ambient.Z));
cmd.Parameters.Add(_Database.CreateParameter("ambient_i", wl.ambient.W));
cmd.Parameters.Add(_Database.CreateParameter("east_angle", wl.eastAngle));
cmd.Parameters.Add(_Database.CreateParameter("sun_glow_focus", wl.sunGlowFocus));
cmd.Parameters.Add(_Database.CreateParameter("sun_glow_size", wl.sunGlowSize));
cmd.Parameters.Add(_Database.CreateParameter("scene_gamma", wl.sceneGamma));
cmd.Parameters.Add(_Database.CreateParameter("star_brightness", wl.starBrightness));
cmd.Parameters.Add(_Database.CreateParameter("cloud_color_r", wl.cloudColor.X));
cmd.Parameters.Add(_Database.CreateParameter("cloud_color_g", wl.cloudColor.Y));
cmd.Parameters.Add(_Database.CreateParameter("cloud_color_b", wl.cloudColor.Z));
cmd.Parameters.Add(_Database.CreateParameter("cloud_color_i", wl.cloudColor.W));
cmd.Parameters.Add(_Database.CreateParameter("cloud_x", wl.cloudXYDensity.X));
cmd.Parameters.Add(_Database.CreateParameter("cloud_y", wl.cloudXYDensity.Y));
cmd.Parameters.Add(_Database.CreateParameter("cloud_density", wl.cloudXYDensity.Z));
cmd.Parameters.Add(_Database.CreateParameter("cloud_coverage", wl.cloudCoverage));
cmd.Parameters.Add(_Database.CreateParameter("cloud_scale", wl.cloudScale));
cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_x", wl.cloudDetailXYDensity.X));
cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_y", wl.cloudDetailXYDensity.Y));
cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_density", wl.cloudDetailXYDensity.Z));
cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x", wl.cloudScrollX));
cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x_lock", wl.cloudScrollXLock));
cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y", wl.cloudScrollY));
cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y_lock", wl.cloudScrollYLock));
cmd.Parameters.Add(_Database.CreateParameter("draw_classic_clouds", wl.drawClassicClouds));
cmd.ExecuteNonQuery();
}
}
#region update
// }
// else
// {
// // sql update
// sql = @"UPDATE [OpenSim].[dbo].[regionwindlight]
// SET [region_id] = @region_id
// ,[water_color_r] = @water_color_r
// ,[water_color_g] = @water_color_g
// ,[water_color_b] = @water_color_b
// ,[water_fog_density_exponent] = @water_fog_density_exponent
// ,[underwater_fog_modifier] = @underwater_fog_modifier
// ,[reflection_wavelet_scale_1] = @reflection_wavelet_scale_1
// ,[reflection_wavelet_scale_2] = @reflection_wavelet_scale_2
// ,[reflection_wavelet_scale_3] = @reflection_wavelet_scale_3
// ,[fresnel_scale] = @fresnel_scale
// ,[fresnel_offset] = @fresnel_offset
// ,[refract_scale_above] = @refract_scale_above
// ,[refract_scale_below] = @refract_scale_below
// ,[blur_multiplier] = @blur_multiplier
// ,[big_wave_direction_x] = @big_wave_direction_x
// ,[big_wave_direction_y] = @big_wave_direction_y
// ,[little_wave_direction_x] = @little_wave_direction_x
// ,[little_wave_direction_y] = @little_wave_direction_y
// ,[normal_map_texture] = @normal_map_texture
// ,[horizon_r] = @horizon_r
// ,[horizon_g] = @horizon_g
// ,[horizon_b] = @horizon_b
// ,[horizon_i] = @horizon_i
// ,[haze_horizon] = @haze_horizon
// ,[blue_density_r] = @blue_density_r
// ,[blue_density_g] = @blue_density_g
// ,[blue_density_b] = @blue_density_b
// ,[blue_density_i] = @blue_density_i
// ,[haze_density] = @haze_density
// ,[density_multiplier] = @density_multiplier
// ,[distance_multiplier] = @distance_multiplier
// ,[max_altitude] = @max_altitude
// ,[sun_moon_color_r] = @sun_moon_color_r
// ,[sun_moon_color_g] = @sun_moon_color_g
// ,[sun_moon_color_b] = @sun_moon_color_b
// ,[sun_moon_color_i] = @sun_moon_color_i
// ,[sun_moon_position] = @sun_moon_position
// ,[ambient_r] = @ambient_r
// ,[ambient_g] = @ambient_g
// ,[ambient_b] = @ambient_b
// ,[ambient_i] = @ambient_i
// ,[east_angle] = @east_angle
// ,[sun_glow_focus] = @sun_glow_focus
// ,[sun_glow_size] = @sun_glow_size
// ,[scene_gamma] = @scene_gamma
// ,[star_brightness] = @star_brightness
// ,[cloud_color_r] = @cloud_color_r
// ,[cloud_color_g] = @cloud_color_g
// ,[cloud_color_b] = @cloud_color_b
// ,[cloud_color_i] = @cloud_color_i
// ,[cloud_x] = @cloud_x
// ,[cloud_y] = @cloud_y
// ,[cloud_density] = @cloud_density
// ,[cloud_coverage] = @cloud_coverage
// ,[cloud_scale] = @cloud_scale
// ,[cloud_detail_x] = @cloud_detail_x
// ,[cloud_detail_y] = @cloud_detail_y
// ,[cloud_detail_density] = @cloud_detail_density
// ,[cloud_scroll_x] = @cloud_scroll_x
// ,[cloud_scroll_x_lock] = @cloud_scroll_x_lock
// ,[cloud_scroll_y] = @cloud_scroll_y
// ,[cloud_scroll_y_lock] = @cloud_scroll_y_lock
// ,[draw_classic_clouds] = @draw_classic_clouds
// WHERE region_id = @region_id";
// using (SqlConnection conn = new SqlConnection(m_connectionString))
// {
// conn.Open();
// using (SqlCommand cmd = new SqlCommand(sql, conn))
// {
// cmd.Parameters.AddWithValue("region_id", wl.regionID);
// cmd.Parameters.AddWithValue("water_color_r", wl.waterColor.X);
// cmd.Parameters.AddWithValue("water_color_g", wl.waterColor.Y);
// cmd.Parameters.AddWithValue("water_color_b", wl.waterColor.Z);
// cmd.Parameters.AddWithValue("water_fog_density_exponent", wl.waterFogDensityExponent);
// cmd.Parameters.AddWithValue("underwater_fog_modifier", wl.underwaterFogModifier);
// cmd.Parameters.AddWithValue("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X);
// cmd.Parameters.AddWithValue("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y);
// cmd.Parameters.AddWithValue("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z);
// cmd.Parameters.AddWithValue("fresnel_scale", wl.fresnelScale);
// cmd.Parameters.AddWithValue("fresnel_offset", wl.fresnelOffset);
// cmd.Parameters.AddWithValue("refract_scale_above", wl.refractScaleAbove);
// cmd.Parameters.AddWithValue("refract_scale_below", wl.refractScaleBelow);
// cmd.Parameters.AddWithValue("blur_multiplier", wl.blurMultiplier);
// cmd.Parameters.AddWithValue("big_wave_direction_x", wl.bigWaveDirection.X);
// cmd.Parameters.AddWithValue("big_wave_direction_y", wl.bigWaveDirection.Y);
// cmd.Parameters.AddWithValue("little_wave_direction_x", wl.littleWaveDirection.X);
// cmd.Parameters.AddWithValue("little_wave_direction_y", wl.littleWaveDirection.Y);
// cmd.Parameters.AddWithValue("normal_map_texture", wl.normalMapTexture);
// cmd.Parameters.AddWithValue("horizon_r", wl.horizon.X);
// cmd.Parameters.AddWithValue("horizon_g", wl.horizon.Y);
// cmd.Parameters.AddWithValue("horizon_b", wl.horizon.Z);
// cmd.Parameters.AddWithValue("horizon_i", wl.horizon.W);
// cmd.Parameters.AddWithValue("haze_horizon", wl.hazeHorizon);
// cmd.Parameters.AddWithValue("blue_density_r", wl.blueDensity.X);
// cmd.Parameters.AddWithValue("blue_density_g", wl.blueDensity.Y);
// cmd.Parameters.AddWithValue("blue_density_b", wl.blueDensity.Z);
// cmd.Parameters.AddWithValue("blue_density_i", wl.blueDensity.W);
// cmd.Parameters.AddWithValue("haze_density", wl.hazeDensity);
// cmd.Parameters.AddWithValue("density_multiplier", wl.densityMultiplier);
// cmd.Parameters.AddWithValue("distance_multiplier", wl.distanceMultiplier);
// cmd.Parameters.AddWithValue("max_altitude", wl.maxAltitude);
// cmd.Parameters.AddWithValue("sun_moon_color_r", wl.sunMoonColor.X);
// cmd.Parameters.AddWithValue("sun_moon_color_g", wl.sunMoonColor.Y);
// cmd.Parameters.AddWithValue("sun_moon_color_b", wl.sunMoonColor.Z);
// cmd.Parameters.AddWithValue("sun_moon_color_i", wl.sunMoonColor.W);
// cmd.Parameters.AddWithValue("sun_moon_position", wl.sunMoonPosition);
// cmd.Parameters.AddWithValue("ambient_r", wl.ambient.X);
// cmd.Parameters.AddWithValue("ambient_g", wl.ambient.Y);
// cmd.Parameters.AddWithValue("ambient_b", wl.ambient.Z);
// cmd.Parameters.AddWithValue("ambient_i", wl.ambient.W);
// cmd.Parameters.AddWithValue("east_angle", wl.eastAngle);
// cmd.Parameters.AddWithValue("sun_glow_focus", wl.sunGlowFocus);
// cmd.Parameters.AddWithValue("sun_glow_size", wl.sunGlowSize);
// cmd.Parameters.AddWithValue("scene_gamma", wl.sceneGamma);
// cmd.Parameters.AddWithValue("star_brightness", wl.starBrightness);
// cmd.Parameters.AddWithValue("cloud_color_r", wl.cloudColor.X);
// cmd.Parameters.AddWithValue("cloud_color_g", wl.cloudColor.Y);
// cmd.Parameters.AddWithValue("cloud_color_b", wl.cloudColor.Z);
// cmd.Parameters.AddWithValue("cloud_color_i", wl.cloudColor.W);
// cmd.Parameters.AddWithValue("cloud_x", wl.cloudXYDensity.X);
// cmd.Parameters.AddWithValue("cloud_y", wl.cloudXYDensity.Y);
// cmd.Parameters.AddWithValue("cloud_density", wl.cloudXYDensity.Z);
// cmd.Parameters.AddWithValue("cloud_coverage", wl.cloudCoverage);
// cmd.Parameters.AddWithValue("cloud_scale", wl.cloudScale);
// cmd.Parameters.AddWithValue("cloud_detail_x", wl.cloudDetailXYDensity.X);
// cmd.Parameters.AddWithValue("cloud_detail_y", wl.cloudDetailXYDensity.Y);
// cmd.Parameters.AddWithValue("cloud_detail_density", wl.cloudDetailXYDensity.Z);
// cmd.Parameters.AddWithValue("cloud_scroll_x", wl.cloudScrollX);
// cmd.Parameters.AddWithValue("cloud_scroll_x_lock", wl.cloudScrollXLock);
// cmd.Parameters.AddWithValue("cloud_scroll_y", wl.cloudScrollY);
// cmd.Parameters.AddWithValue("cloud_scroll_y_lock", wl.cloudScrollYLock);
// cmd.Parameters.AddWithValue("draw_classic_clouds", wl.drawClassicClouds);
// cmd.ExecuteNonQuery();
// }
// }
// }
#endregion
}
#region Environment Settings #region Environment Settings
public string LoadRegionEnvironmentSettings(UUID regionUUID) public string LoadRegionEnvironmentSettings(UUID regionUUID)
@ -966,7 +1432,7 @@ namespace OpenSim.Data.PGSQL
,terrain_lower_limit = :terrain_lower_limit ,use_estate_sun = :use_estate_sun ,fixed_sun = :fixed_sun ,sun_position = :sun_position ,terrain_lower_limit = :terrain_lower_limit ,use_estate_sun = :use_estate_sun ,fixed_sun = :fixed_sun ,sun_position = :sun_position
,covenant = :covenant ,covenant_datetime = :covenant_datetime, sunvectorx = :sunvectorx, sunvectory = :sunvectory, sunvectorz = :sunvectorz, ,covenant = :covenant ,covenant_datetime = :covenant_datetime, sunvectorx = :sunvectorx, sunvectory = :sunvectory, sunvectorz = :sunvectorz,
""Sandbox"" = :Sandbox, loaded_creation_datetime = :loaded_creation_datetime, loaded_creation_id = :loaded_creation_id, ""map_tile_ID"" = :TerrainImageID, ""Sandbox"" = :Sandbox, loaded_creation_datetime = :loaded_creation_datetime, loaded_creation_id = :loaded_creation_id, ""map_tile_ID"" = :TerrainImageID,
""TelehubObject"" = :telehubobject, ""parcel_tile_ID"" = :ParcelImageID, ""cacheID"" = :cacheID ""TelehubObject"" = :telehubobject, ""parcel_tile_ID"" = :ParcelImageID
WHERE ""regionUUID"" = :regionUUID"; WHERE ""regionUUID"" = :regionUUID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
@ -1081,8 +1547,6 @@ namespace OpenSim.Data.PGSQL
newSettings.ParcelImageID = new UUID((Guid)row["parcel_tile_ID"]); newSettings.ParcelImageID = new UUID((Guid)row["parcel_tile_ID"]);
newSettings.TelehubObject = new UUID((Guid)row["TelehubObject"]); newSettings.TelehubObject = new UUID((Guid)row["TelehubObject"]);
if (!(row["cacheID"] is DBNull))
newSettings.CacheID = new UUID((Guid)row["cacheID"]);
return newSettings; return newSettings;
} }
@ -1138,6 +1602,7 @@ namespace OpenSim.Data.PGSQL
newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
newData.Dwell = Convert.ToSingle(row["Dwell"]); newData.Dwell = Convert.ToSingle(row["Dwell"]);
try try
{ {
newData.UserLocation = newData.UserLocation =
@ -1167,35 +1632,6 @@ namespace OpenSim.Data.PGSQL
newData.AnyAVSounds = Convert.ToBoolean(row["AnyAVSounds"]); newData.AnyAVSounds = Convert.ToBoolean(row["AnyAVSounds"]);
newData.GroupAVSounds = Convert.ToBoolean(row["GroupAVSounds"]); newData.GroupAVSounds = Convert.ToBoolean(row["GroupAVSounds"]);
if (row["environment"] is DBNull)
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
string env = (string)row["environment"];
if (string.IsNullOrEmpty(env))
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
try
{
ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
newData.Environment = VEnv;
newData.EnvironmentVersion = VEnv.version;
}
catch
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
}
}
return newData; return newData;
} }
@ -1292,20 +1728,12 @@ namespace OpenSim.Data.PGSQL
Convert.ToSingle(primRow["SitTargetOffsetY"]), Convert.ToSingle(primRow["SitTargetOffsetY"]),
Convert.ToSingle(primRow["SitTargetOffsetZ"])); Convert.ToSingle(primRow["SitTargetOffsetZ"]));
prim.SitTargetOrientationLL = new Quaternion( prim.SitTargetOrientationLL = new Quaternion(
Convert.ToSingle(primRow["SitTargetOrientX"]), Convert.ToSingle(primRow["SitTargetOrientX"]),
Convert.ToSingle(primRow["SitTargetOrientY"]), Convert.ToSingle(primRow["SitTargetOrientY"]),
Convert.ToSingle(primRow["SitTargetOrientZ"]), Convert.ToSingle(primRow["SitTargetOrientZ"]),
Convert.ToSingle(primRow["SitTargetOrientW"])); Convert.ToSingle(primRow["SitTargetOrientW"]));
prim.StandOffset = new Vector3(
Convert.ToSingle(primRow["standtargetx"]),
Convert.ToSingle(primRow["standtargety"]),
Convert.ToSingle(primRow["standtargetz"]));
prim.SitActiveRange = Convert.ToSingle(primRow["sitactrange"]);
prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]); prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]);
prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]); prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]);
prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]); prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]);
@ -1314,10 +1742,7 @@ namespace OpenSim.Data.PGSQL
prim.Sound = new UUID((Guid)primRow["LoopedSound"]); prim.Sound = new UUID((Guid)primRow["LoopedSound"]);
prim.SoundGain = Convert.ToSingle(primRow["LoopedSoundGain"]); prim.SoundGain = Convert.ToSingle(primRow["LoopedSoundGain"]);
if (prim.Sound != UUID.Zero)
prim.SoundFlags = 1; // If it's persisted at all, it's looped prim.SoundFlags = 1; // If it's persisted at all, it's looped
else
prim.SoundFlags = 0;
if (!(primRow["TextureAnimation"] is DBNull)) if (!(primRow["TextureAnimation"] is DBNull))
prim.TextureAnimation = (Byte[])primRow["TextureAnimation"]; prim.TextureAnimation = (Byte[])primRow["TextureAnimation"];
@ -1372,7 +1797,7 @@ namespace OpenSim.Data.PGSQL
if (!(primRow["DynAttrs"] is System.DBNull) && (string)primRow["DynAttrs"] != "") if (!(primRow["DynAttrs"] is System.DBNull) && (string)primRow["DynAttrs"] != "")
prim.DynAttrs = DAMap.FromXml((string)primRow["DynAttrs"]); prim.DynAttrs = DAMap.FromXml((string)primRow["DynAttrs"]);
else else
prim.DynAttrs = null; prim.DynAttrs = new DAMap();
prim.PhysicsShapeType = Convert.ToByte(primRow["PhysicsShapeType"]); prim.PhysicsShapeType = Convert.ToByte(primRow["PhysicsShapeType"]);
prim.Density = Convert.ToSingle(primRow["Density"]); prim.Density = Convert.ToSingle(primRow["Density"]);
@ -1381,23 +1806,12 @@ namespace OpenSim.Data.PGSQL
prim.Restitution = Convert.ToSingle(primRow["Restitution"]); prim.Restitution = Convert.ToSingle(primRow["Restitution"]);
prim.RotationAxisLocks = Convert.ToByte(primRow["RotationAxisLocks"]); prim.RotationAxisLocks = Convert.ToByte(primRow["RotationAxisLocks"]);
SOPVehicle vehicle = null;
if (!(primRow["Vehicle"] is System.DBNull))
{
vehicle = SOPVehicle.FromXml2(primRow["Vehicle"].ToString());
if (vehicle != null)
prim.VehicleParams = vehicle;
}
PhysicsInertiaData pdata = null; PhysicsInertiaData pdata = null;
if (!(primRow["PhysInertia"] is System.DBNull)) if (!(primRow["PhysInertia"] is System.DBNull))
pdata = PhysicsInertiaData.FromXml2(primRow["PhysInertia"].ToString()); pdata = PhysicsInertiaData.FromXml2(primRow["PhysInertia"].ToString());
prim.PhysicsInertia = pdata; prim.PhysicsInertia = pdata;
int pseudocrc = Convert.ToInt32(primRow["pseudocrc"]);
if(pseudocrc != 0)
prim.PseudoCRC = pseudocrc;
return prim; return prim;
} }
@ -1584,8 +1998,6 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("ParcelImageID", settings.ParcelImageID)); parameters.Add(_Database.CreateParameter("ParcelImageID", settings.ParcelImageID));
parameters.Add(_Database.CreateParameter("TelehubObject", settings.TelehubObject)); parameters.Add(_Database.CreateParameter("TelehubObject", settings.TelehubObject));
parameters.Add(_Database.CreateParameter("cacheID", settings.CacheID));
return parameters.ToArray(); return parameters.ToArray();
} }
@ -1647,20 +2059,6 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("AnyAVSounds", land.AnyAVSounds)); parameters.Add(_Database.CreateParameter("AnyAVSounds", land.AnyAVSounds));
parameters.Add(_Database.CreateParameter("GroupAVSounds", land.GroupAVSounds)); parameters.Add(_Database.CreateParameter("GroupAVSounds", land.GroupAVSounds));
if (land.Environment == null)
parameters.Add(_Database.CreateParameter("environment", ""));
else
{
try
{
parameters.Add(_Database.CreateParameter("environment", ViewerEnvironment.ToOSDString(land.Environment)));
}
catch
{
parameters.Add(_Database.CreateParameter("environment", ""));
}
}
return parameters.ToArray(); return parameters.ToArray();
} }
@ -1754,13 +2152,6 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y)); parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y));
parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z)); parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z));
Vector3 standTargetPos = prim.StandOffset;
parameters.Add(_Database.CreateParameter("standtargetx", standTargetPos.X));
parameters.Add(_Database.CreateParameter("standtargety", standTargetPos.Y));
parameters.Add(_Database.CreateParameter("standtargetz", standTargetPos.Z));
parameters.Add(_Database.CreateParameter("sitactrange", prim.SitActiveRange));
parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0])); parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0]));
parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1])); parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1]));
parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2])); parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2]));
@ -1824,6 +2215,7 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("PassTouches", (bool)prim.PassTouches)); parameters.Add(_Database.CreateParameter("PassTouches", (bool)prim.PassTouches));
parameters.Add(_Database.CreateParameter("PassCollisions", (bool)prim.PassCollisions)); parameters.Add(_Database.CreateParameter("PassCollisions", (bool)prim.PassCollisions));
if (prim.PassTouches) if (prim.PassTouches)
parameters.Add(_Database.CreateParameter("PassTouches", true)); parameters.Add(_Database.CreateParameter("PassTouches", true));
else else
@ -1837,17 +2229,13 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum)); parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum));
parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl)); parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl));
if (prim.VehicleParams != null)
parameters.Add(_Database.CreateParameter("Vehicle", prim.VehicleParams.ToXml2()));
else
parameters.Add(_Database.CreateParameter("Vehicle", String.Empty));
if (prim.PhysicsInertia != null) if (prim.PhysicsInertia != null)
parameters.Add(_Database.CreateParameter("PhysInertia", prim.PhysicsInertia.ToXml2())); parameters.Add(_Database.CreateParameter("PhysInertia", prim.PhysicsInertia.ToXml2()));
else else
parameters.Add(_Database.CreateParameter("PhysInertia", String.Empty)); parameters.Add(_Database.CreateParameter("PhysInertia", String.Empty));
if (prim.DynAttrs != null && prim.DynAttrs.CountNamespaces > 0)
if (prim.DynAttrs.CountNamespaces > 0)
parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml())); parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml()));
else else
parameters.Add(_Database.CreateParameter("DynAttrs", null)); parameters.Add(_Database.CreateParameter("DynAttrs", null));
@ -1859,8 +2247,6 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution)); parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution));
parameters.Add(_Database.CreateParameter("RotationAxisLocks", prim.RotationAxisLocks)); parameters.Add(_Database.CreateParameter("RotationAxisLocks", prim.RotationAxisLocks));
parameters.Add(_Database.CreateParameter("pseudocrc", prim.PseudoCRC));
return parameters.ToArray(); return parameters.ToArray();
} }

View File

@ -845,7 +845,7 @@ namespace OpenSim.Data.PGSQL
query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id"; query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id";
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon))
{ {
cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId));

View File

@ -110,32 +110,3 @@ CREATE INDEX IF NOT EXISTS "ix_estateban" ON "public"."estateban" USING btree("
COMMIT; COMMIT;
:VERSION 13
BEGIN TRASACTION;
-- ----------------------------
-- SEQUENCE estate_settings_id
-- ----------------------------
CREATE SEQUENCE IF NOT EXISTS "public"."estate_settings_id"
INCREMENT 100
MINVALUE 1
MAXVALUE 9223372036854775807
START 100
CACHE 1;
COMMIT;
:VERSION 14
BEGIN TRANSACTION;
ALTER TABLE "public"."estateban"
ADD COLUMN "banningUUID" uuid NOT NULL,
ADD COLUMN "banTime" int4 NOT NULL DEFAULT 0;
COMMIT;
:VERSION 15
BEGIN TRANSACTION;
ALTER TABLE "public"."estate_settings"
ADD COLUMN "AllowEnviromentOverride" bool NOT NULL;
COMMIT;

View File

@ -1,14 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE fsassets (
"id" uuid NOT NULL PRIMARY KEY,
"type" integer NOT NULL,
"hash" char(64) NOT NULL,
"create_time" integer NOT NULL DEFAULT '0',
"access_time" integer NOT NULL DEFAULT '0',
"asset_flags" integer NOT NULL DEFAULT '0'
);
COMMIT;

View File

@ -1225,33 +1225,3 @@ ALTER TABLE "public"."prims"
ELSE NULL ELSE NULL
END; END;
COMMIT; COMMIT;
:VERSION 48 #---- field Vehicle to table prims
BEGIN TRANSACTION;
ALTER TABLE prims ADD "Vehicle" TEXT;
COMMIT;
:VERSION 49 #----- Add standtarget and sit range
BEGIN;
ALTER TABLE `prims`
ADD COLUMN `standtargetx` real DEFAULT '0.0',
ADD COLUMN `standtargety` real DEFAULT '0.0',
ADD COLUMN `standtargetz` real DEFAULT '0.0',
ADD COLUMN `sitactrange` real DEFAULT '0.0';
COMMIT;
:VERSION 50 #----- Add pseudo CRC and region cache id
BEGIN;
ALTER TABLE `prims` ADD COLUMN `pseudocrc` integer DEFAULT '0';
ALTER TABLE `regionsettings` ADD COLUMN `cacheID` uuid DEFAULT NULL;
COMMIT;
:VERSION 51 #----- parcel environment store
BEGIN;
ALTER TABLE `land` ADD COLUMN `environment` varchar default NULL;
COMMIT;

View File

@ -63,21 +63,7 @@ CREATE TABLE IF NOT EXISTS estateban (
bannedIpHostMask varchar(16) NOT NULL, bannedIpHostMask varchar(16) NOT NULL,
bannedNameMask varchar(64) default NULL bannedNameMask varchar(64) default NULL
); );
CREATE INDEX estate_ban_estate_id on estateban(EstateID); CREATE INDEX estate_ban_estate_id on estateban(EstateID);
COMMIT; COMMIT;
:VERSION 11
BEGIN;
ALTER TABLE `estateban` ADD COLUMN `banningUUID` varchar(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
ALTER TABLE `estateban` ADD COLUMN `banTime` integer NOT NULL DEFAULT 0;
COMMIT;
:VERSION 12
BEGIN;
ALTER TABLE `estate_settings`
ADD COLUMN `AllowEnviromentOverride` tinyint not null default 0;
COMMIT;

View File

@ -1,16 +0,0 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE MuteList (
AgentID char(36) NOT NULL,
MuteID char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
MuteName varchar(64) NOT NULL DEFAULT '',
MuteType int(11) NOT NULL DEFAULT '1',
MuteFlags int(11) NOT NULL DEFAULT '0',
Stamp int(11) NOT NULL,
UNIQUE (AgentID, MuteID, MuteName),
PRIMARY KEY(AgentID)
);
COMMIT;

View File

@ -377,25 +377,3 @@ COMMIT;
BEGIN; BEGIN;
ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL; ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
COMMIT; COMMIT;
:VERSION 37 #----- Add standtarget and sit range
BEGIN;
ALTER TABLE `prims` ADD COLUMN `standtargetx` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `standtargety` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `standtargetz` float NOT NULL DEFAULT '0.0';
ALTER TABLE `prims` ADD COLUMN `sitactrange` float NOT NULL DEFAULT '0.0';
COMMIT;
:VERSION 38 #----- Add pseudo CRC and region cache id
BEGIN;
ALTER TABLE `prims` ADD COLUMN `pseudocrc` integer DEFAULT '0';
ALTER TABLE `regionsettings` ADD COLUMN `cacheID` char(36) DEFAULT NULL;
COMMIT;
:VERSION 39 #----- parcel environment store
BEGIN;
ALTER TABLE `land` ADD COLUMN `environment` TEXT default NULL;
COMMIT;

View File

@ -186,10 +186,13 @@ namespace OpenSim.Data.SQLite
private void DoCreate(EstateSettings es) private void DoCreate(EstateSettings es)
{ {
List<string> names = new List<string>(FieldList); List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
IDataReader r = null;
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
names.Remove("EstateID");
string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")"; string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.CommandText = sql; cmd.CommandText = sql;
@ -214,12 +217,17 @@ namespace OpenSim.Data.SQLite
cmd.CommandText = "select LAST_INSERT_ROWID() as id"; cmd.CommandText = "select LAST_INSERT_ROWID() as id";
cmd.Parameters.Clear(); cmd.Parameters.Clear();
using(IDataReader r = cmd.ExecuteReader())
{ r = cmd.ExecuteReader();
}
r.Read(); r.Read();
es.EstateID = Convert.ToUInt32(r["id"]); es.EstateID = Convert.ToUInt32(r["id"]);
}
} r.Close();
es.Save();
} }
public void StoreEstateSettings(EstateSettings es) public void StoreEstateSettings(EstateSettings es)
@ -232,10 +240,11 @@ namespace OpenSim.Data.SQLite
foreach (string f in fields) foreach (string f in fields)
terms.Add(f+" = :"+f); terms.Add(f+" = :"+f);
string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
cmd.CommandText = "update estate_settings set " + String.Join(", ", terms.ToArray()) + " where EstateID = :EstateID"; ; cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
foreach (string name in FieldList) foreach (string name in FieldList)
{ {
@ -269,7 +278,7 @@ namespace OpenSim.Data.SQLite
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
cmd.CommandText = "select * from estateban where EstateID = :EstateID"; cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID); cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
r = cmd.ExecuteReader(); r = cmd.ExecuteReader();
@ -279,11 +288,12 @@ namespace OpenSim.Data.SQLite
{ {
EstateBan eb = new EstateBan(); EstateBan eb = new EstateBan();
eb.BannedUserID = DBGuid.FromDB(r["bannedUUID"]); ; UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0";
eb.BanningUserID = DBGuid.FromDB(r["banningUUID"]);
eb.BanTime = Convert.ToInt32(r["banTime"]);
es.AddBan(eb); es.AddBan(eb);
} }
r.Close(); r.Close();
@ -300,14 +310,12 @@ namespace OpenSim.Data.SQLite
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask, banningUUID, banTime) values ( :EstateID, :bannedUUID, '', '', '', :banningUUID, :banTime )"; cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans) foreach (EstateBan b in es.EstateBans)
{ {
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString()); cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString());
cmd.Parameters.AddWithValue(":banningUUID", b.BanningUserID.ToString());
cmd.Parameters.AddWithValue(":banTime", b.BanTime);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); cmd.Parameters.Clear();
@ -463,8 +471,8 @@ namespace OpenSim.Data.SQLite
public bool LinkRegion(UUID regionID, int estateID) public bool LinkRegion(UUID regionID, int estateID)
{ {
using(SqliteTransaction transaction = m_connection.BeginTransaction()) SqliteTransaction transaction = m_connection.BeginTransaction();
{
// Delete any existing estate mapping for this region. // Delete any existing estate mapping for this region.
using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
@ -494,7 +502,6 @@ namespace OpenSim.Data.SQLite
} }
} }
} }
}
public List<UUID> GetRegions(int estateID) public List<UUID> GetRegions(int estateID)
{ {

View File

@ -429,6 +429,75 @@ namespace OpenSim.Data.SQLite
} }
} }
/// <summary>
/// Load windlight settings from region storage
/// </summary>
/// <param name="regionUUID">RegionID</param>
public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
{
RegionLightShareData wl = null;
lock (ds)
{
DataTable windlightTable = ds.Tables["regionwindlight"];
DataRow windlightRow = windlightTable.Rows.Find(regionUUID.ToString());
if (windlightRow == null)
{
wl = new RegionLightShareData();
wl.regionID = regionUUID;
StoreRegionWindlightSettings(wl);
return wl;
}
wl = buildRegionWindlight(windlightRow);
return wl;
}
}
/// <summary>
/// Remove windlight settings from region storage
/// </summary>
/// <param name="regionID">RegionID</param>
public void RemoveRegionWindlightSettings(UUID regionID)
{
lock (ds)
{
DataTable windlightTable = ds.Tables["regionwindlight"];
DataRow windlightRow = windlightTable.Rows.Find(regionID.ToString());
if (windlightRow != null)
{
windlightRow.Delete();
}
}
Commit();
}
/// <summary>
/// Adds an windlight into region storage
/// </summary>
/// <param name="wl">RegionLightShareData</param>
public void StoreRegionWindlightSettings(RegionLightShareData wl)
{
lock (ds)
{
DataTable windlightTable = ds.Tables["regionwindlight"];
DataRow windlightRow = windlightTable.Rows.Find(wl.regionID.ToString());
if (windlightRow == null)
{
windlightRow = windlightTable.NewRow();
fillRegionWindlightRow(windlightRow, wl);
windlightTable.Rows.Add(windlightRow);
}
else
{
fillRegionWindlightRow(windlightRow, wl);
}
Commit();
}
}
#region Region Environment Settings #region Region Environment Settings
public string LoadRegionEnvironmentSettings(UUID regionUUID) public string LoadRegionEnvironmentSettings(UUID regionUUID)
{ {
@ -557,13 +626,10 @@ namespace OpenSim.Data.SQLite
// m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID); // m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
addPrim(prim, obj.UUID, regionUUID); addPrim(prim, obj.UUID, regionUUID);
} }
primDa.Update(ds, "prims");
shapeDa.Update(ds, "primshapes");
itemsDa.Update(ds, "primitems");
ds.AcceptChanges();
} }
// m_log.Info("[Dump of prims]: " + ds.GetXml()); Commit();
// m_log.Info("[Dump of prims]: " + ds.GetXml());
} }
/// <summary> /// <summary>
@ -757,7 +823,7 @@ namespace OpenSim.Data.SQLite
// Legacy entry point for when terrain was always a 256x256 hieghtmap // Legacy entry point for when terrain was always a 256x256 hieghtmap
public void StoreTerrain(double[,] ter, UUID regionID) public void StoreTerrain(double[,] ter, UUID regionID)
{ {
StoreTerrain(new TerrainData(ter), regionID); StoreTerrain(new HeightmapTerrainData(ter), regionID);
} }
/// <summary> /// <summary>
@ -769,7 +835,8 @@ namespace OpenSim.Data.SQLite
{ {
lock (ds) lock (ds)
{ {
using (SqliteCommand cmd = new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID", m_conn)) using (
SqliteCommand cmd = new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID", m_conn))
{ {
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
@ -991,9 +1058,12 @@ namespace OpenSim.Data.SQLite
if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString()) if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString())
rowsToDelete.Add(rowToCheck); rowsToDelete.Add(rowToCheck);
} }
for (int iter = 0; iter < rowsToDelete.Count; ++iter) for (int iter = 0; iter < rowsToDelete.Count; iter++)
{
rowsToDelete[iter].Delete(); rowsToDelete[iter].Delete();
landaccesslist.Rows.Remove(rowsToDelete[iter]);
}
rowsToDelete.Clear();
foreach (LandAccessEntry entry in parcel.LandData.ParcelAccessList) foreach (LandAccessEntry entry in parcel.LandData.ParcelAccessList)
{ {
DataRow newAccessRow = landaccesslist.NewRow(); DataRow newAccessRow = landaccesslist.NewRow();
@ -1243,21 +1313,6 @@ namespace OpenSim.Data.SQLite
createCol(prims, "KeyframeMotion", typeof(Byte[])); createCol(prims, "KeyframeMotion", typeof(Byte[]));
createCol(prims, "PassTouches", typeof(bool));
createCol(prims, "PassCollisions", typeof(bool));
createCol(prims, "Vehicle", typeof(string));
createCol(prims, "RotationAxisLocks", typeof(byte));
createCol(prims, "PhysInertia", typeof(string));
createCol(prims, "standtargetx", typeof(float));
createCol(prims, "standtargety", typeof(float));
createCol(prims, "standtargetz", typeof(float));
createCol(prims, "sitactrange", typeof(float));
createCol(prims, "pseudocrc", typeof(int));
// Add in contraints // Add in contraints
prims.PrimaryKey = new DataColumn[] { prims.Columns["UUID"] }; prims.PrimaryKey = new DataColumn[] { prims.Columns["UUID"] };
@ -1300,7 +1355,6 @@ namespace OpenSim.Data.SQLite
createCol(shapes, "ProfileCurve", typeof(Int32)); createCol(shapes, "ProfileCurve", typeof(Int32));
createCol(shapes, "ProfileHollow", typeof(Int32)); createCol(shapes, "ProfileHollow", typeof(Int32));
createCol(shapes, "State", typeof(Int32)); createCol(shapes, "State", typeof(Int32));
createCol(shapes, "LastAttachPoint", typeof(Int32));
// text TODO: this isn't right, but I'm not sure the right // text TODO: this isn't right, but I'm not sure the right
// way to specify this as a blob atm // way to specify this as a blob atm
createCol(shapes, "Texture", typeof(Byte[])); createCol(shapes, "Texture", typeof(Byte[]));
@ -1402,7 +1456,6 @@ namespace OpenSim.Data.SQLite
createCol(land, "SeeAVs", typeof(Boolean)); createCol(land, "SeeAVs", typeof(Boolean));
createCol(land, "AnyAVSounds", typeof(Boolean)); createCol(land, "AnyAVSounds", typeof(Boolean));
createCol(land, "GroupAVSounds", typeof(Boolean)); createCol(land, "GroupAVSounds", typeof(Boolean));
createCol(land, "environment", typeof(string));
land.PrimaryKey = new DataColumn[] { land.Columns["UUID"] }; land.PrimaryKey = new DataColumn[] { land.Columns["UUID"] };
@ -1467,9 +1520,6 @@ namespace OpenSim.Data.SQLite
createCol(regionsettings, "map_tile_ID", typeof(String)); createCol(regionsettings, "map_tile_ID", typeof(String));
createCol(regionsettings, "TelehubObject", typeof(String)); createCol(regionsettings, "TelehubObject", typeof(String));
createCol(regionsettings, "parcel_tile_ID", typeof(String)); createCol(regionsettings, "parcel_tile_ID", typeof(String));
createCol(regionsettings, "block_search", typeof(Boolean));
createCol(regionsettings, "casino", typeof(Boolean));
createCol(regionsettings, "cacheID", typeof(string));
regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] }; regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] };
return regionsettings; return regionsettings;
} }
@ -1675,18 +1725,14 @@ namespace OpenSim.Data.SQLite
Convert.ToSingle(row["SitTargetOffsetY"]), Convert.ToSingle(row["SitTargetOffsetY"]),
Convert.ToSingle(row["SitTargetOffsetZ"])); Convert.ToSingle(row["SitTargetOffsetZ"]));
prim.SitTargetOrientationLL = new Quaternion( prim.SitTargetOrientationLL = new Quaternion(
Convert.ToSingle(row["SitTargetOrientX"]), Convert.ToSingle(
Convert.ToSingle(row["SitTargetOrientY"]), row["SitTargetOrientX"]),
Convert.ToSingle(row["SitTargetOrientZ"]), Convert.ToSingle(
Convert.ToSingle(row["SitTargetOrientW"])); row["SitTargetOrientY"]),
Convert.ToSingle(
prim.StandOffset = new Vector3( row["SitTargetOrientZ"]),
Convert.ToSingle(row["standtargetx"]), Convert.ToSingle(
Convert.ToSingle(row["standtargety"]), row["SitTargetOrientW"]));
Convert.ToSingle(row["standtargetz"])
);
prim.SitActiveRange = Convert.ToSingle(row["sitactrange"]);
prim.ClickAction = Convert.ToByte(row["ClickAction"]); prim.ClickAction = Convert.ToByte(row["ClickAction"]);
prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]); prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]);
@ -1697,10 +1743,7 @@ namespace OpenSim.Data.SQLite
prim.Sound = new UUID(row["LoopedSound"].ToString()); prim.Sound = new UUID(row["LoopedSound"].ToString());
prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]); prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]);
if (prim.Sound != UUID.Zero)
prim.SoundFlags = 1; // If it's persisted at all, it's looped prim.SoundFlags = 1; // If it's persisted at all, it's looped
else
prim.SoundFlags = 0;
if (!row.IsNull("TextureAnimation")) if (!row.IsNull("TextureAnimation"))
prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString()); prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString());
@ -1766,7 +1809,7 @@ namespace OpenSim.Data.SQLite
} }
else else
{ {
prim.DynAttrs = null; prim.DynAttrs = new DAMap();
} }
prim.PhysicsShapeType = Convert.ToByte(row["PhysicsShapeType"]); prim.PhysicsShapeType = Convert.ToByte(row["PhysicsShapeType"]);
@ -1806,10 +1849,6 @@ namespace OpenSim.Data.SQLite
pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString()); pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString());
prim.PhysicsInertia = pdata; prim.PhysicsInertia = pdata;
int pseudocrc = Convert.ToInt32(row["pseudocrc"]);
if(pseudocrc != 0)
prim.PseudoCRC = pseudocrc;
return prim; return prim;
} }
@ -1921,36 +1960,6 @@ namespace OpenSim.Data.SQLite
newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
if (row["environment"] is DBNull)
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
string env = (string)row["environment"];
if (string.IsNullOrEmpty(env))
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
else
{
try
{
ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
newData.Environment = VEnv;
newData.EnvironmentVersion = VEnv.version;
}
catch
{
newData.Environment = null;
newData.EnvironmentVersion = -1;
}
}
}
return newData; return newData;
} }
@ -2003,12 +2012,86 @@ namespace OpenSim.Data.SQLite
newSettings.ParcelImageID = new UUID((String)row["parcel_tile_ID"]); newSettings.ParcelImageID = new UUID((String)row["parcel_tile_ID"]);
newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]); newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]);
newSettings.Casino = Convert.ToBoolean(row["casino"]); newSettings.Casino = Convert.ToBoolean(row["casino"]);
if (!(row["cacheID"] is System.DBNull))
newSettings.CacheID = new UUID((String)row["cacheID"]);
return newSettings; return newSettings;
} }
/// <summary>
/// Build a windlight entry from the persisted data.
/// </summary>
/// <param name="row"></param>
/// <returns>RegionLightShareData</returns>
private RegionLightShareData buildRegionWindlight(DataRow row)
{
RegionLightShareData windlight = new RegionLightShareData();
windlight.regionID = new UUID((string)row["region_id"]);
windlight.waterColor.X = Convert.ToSingle(row["water_color_r"]);
windlight.waterColor.Y = Convert.ToSingle(row["water_color_g"]);
windlight.waterColor.Z = Convert.ToSingle(row["water_color_b"]);
//windlight.waterColor.W = Convert.ToSingle(row["water_color_i"]); //not implemented
windlight.waterFogDensityExponent = Convert.ToSingle(row["water_fog_density_exponent"]);
windlight.underwaterFogModifier = Convert.ToSingle(row["underwater_fog_modifier"]);
windlight.reflectionWaveletScale.X = Convert.ToSingle(row["reflection_wavelet_scale_1"]);
windlight.reflectionWaveletScale.Y = Convert.ToSingle(row["reflection_wavelet_scale_2"]);
windlight.reflectionWaveletScale.Z = Convert.ToSingle(row["reflection_wavelet_scale_3"]);
windlight.fresnelScale = Convert.ToSingle(row["fresnel_scale"]);
windlight.fresnelOffset = Convert.ToSingle(row["fresnel_offset"]);
windlight.refractScaleAbove = Convert.ToSingle(row["refract_scale_above"]);
windlight.refractScaleBelow = Convert.ToSingle(row["refract_scale_below"]);
windlight.blurMultiplier = Convert.ToSingle(row["blur_multiplier"]);
windlight.bigWaveDirection.X = Convert.ToSingle(row["big_wave_direction_x"]);
windlight.bigWaveDirection.Y = Convert.ToSingle(row["big_wave_direction_y"]);
windlight.littleWaveDirection.X = Convert.ToSingle(row["little_wave_direction_x"]);
windlight.littleWaveDirection.Y = Convert.ToSingle(row["little_wave_direction_y"]);
windlight.normalMapTexture = new UUID((string)row["normal_map_texture"]);
windlight.horizon.X = Convert.ToSingle(row["horizon_r"]);
windlight.horizon.Y = Convert.ToSingle(row["horizon_g"]);
windlight.horizon.Z = Convert.ToSingle(row["horizon_b"]);
windlight.horizon.W = Convert.ToSingle(row["horizon_i"]);
windlight.hazeHorizon = Convert.ToSingle(row["haze_horizon"]);
windlight.blueDensity.X = Convert.ToSingle(row["blue_density_r"]);
windlight.blueDensity.Y = Convert.ToSingle(row["blue_density_g"]);
windlight.blueDensity.Z = Convert.ToSingle(row["blue_density_b"]);
windlight.blueDensity.W = Convert.ToSingle(row["blue_density_i"]);
windlight.hazeDensity = Convert.ToSingle(row["haze_density"]);
windlight.densityMultiplier = Convert.ToSingle(row["density_multiplier"]);
windlight.distanceMultiplier = Convert.ToSingle(row["distance_multiplier"]);
windlight.maxAltitude = Convert.ToUInt16(row["max_altitude"]);
windlight.sunMoonColor.X = Convert.ToSingle(row["sun_moon_color_r"]);
windlight.sunMoonColor.Y = Convert.ToSingle(row["sun_moon_color_g"]);
windlight.sunMoonColor.Z = Convert.ToSingle(row["sun_moon_color_b"]);
windlight.sunMoonColor.W = Convert.ToSingle(row["sun_moon_color_i"]);
windlight.sunMoonPosition = Convert.ToSingle(row["sun_moon_position"]);
windlight.ambient.X = Convert.ToSingle(row["ambient_r"]);
windlight.ambient.Y = Convert.ToSingle(row["ambient_g"]);
windlight.ambient.Z = Convert.ToSingle(row["ambient_b"]);
windlight.ambient.W = Convert.ToSingle(row["ambient_i"]);
windlight.eastAngle = Convert.ToSingle(row["east_angle"]);
windlight.sunGlowFocus = Convert.ToSingle(row["sun_glow_focus"]);
windlight.sunGlowSize = Convert.ToSingle(row["sun_glow_size"]);
windlight.sceneGamma = Convert.ToSingle(row["scene_gamma"]);
windlight.starBrightness = Convert.ToSingle(row["star_brightness"]);
windlight.cloudColor.X = Convert.ToSingle(row["cloud_color_r"]);
windlight.cloudColor.Y = Convert.ToSingle(row["cloud_color_g"]);
windlight.cloudColor.Z = Convert.ToSingle(row["cloud_color_b"]);
windlight.cloudColor.W = Convert.ToSingle(row["cloud_color_i"]);
windlight.cloudXYDensity.X = Convert.ToSingle(row["cloud_x"]);
windlight.cloudXYDensity.Y = Convert.ToSingle(row["cloud_y"]);
windlight.cloudXYDensity.Z = Convert.ToSingle(row["cloud_density"]);
windlight.cloudCoverage = Convert.ToSingle(row["cloud_coverage"]);
windlight.cloudScale = Convert.ToSingle(row["cloud_scale"]);
windlight.cloudDetailXYDensity.X = Convert.ToSingle(row["cloud_detail_x"]);
windlight.cloudDetailXYDensity.Y = Convert.ToSingle(row["cloud_detail_y"]);
windlight.cloudDetailXYDensity.Z = Convert.ToSingle(row["cloud_detail_density"]);
windlight.cloudScrollX = Convert.ToSingle(row["cloud_scroll_x"]);
windlight.cloudScrollXLock = Convert.ToBoolean(row["cloud_scroll_x_lock"]);
windlight.cloudScrollY = Convert.ToSingle(row["cloud_scroll_y"]);
windlight.cloudScrollYLock = Convert.ToBoolean(row["cloud_scroll_y_lock"]);
windlight.drawClassicClouds = Convert.ToBoolean(row["draw_classic_clouds"]);
return windlight;
}
/// <summary> /// <summary>
/// Build a land access entry from the persisted data. /// Build a land access entry from the persisted data.
/// </summary> /// </summary>
@ -2089,14 +2172,6 @@ namespace OpenSim.Data.SQLite
row["SitTargetOrientX"] = sitTargetOrient.X; row["SitTargetOrientX"] = sitTargetOrient.X;
row["SitTargetOrientY"] = sitTargetOrient.Y; row["SitTargetOrientY"] = sitTargetOrient.Y;
row["SitTargetOrientZ"] = sitTargetOrient.Z; row["SitTargetOrientZ"] = sitTargetOrient.Z;
Vector3 standTarget = prim.StandOffset;
row["standtargetx"] = standTarget.X;
row["standtargety"] = standTarget.Y;
row["standtargetz"] = standTarget.Z;
row["sitactrange"] = prim.SitActiveRange;
row["ColorR"] = Convert.ToInt32(prim.Color.R); row["ColorR"] = Convert.ToInt32(prim.Color.R);
row["ColorG"] = Convert.ToInt32(prim.Color.G); row["ColorG"] = Convert.ToInt32(prim.Color.G);
row["ColorB"] = Convert.ToInt32(prim.Color.B); row["ColorB"] = Convert.ToInt32(prim.Color.B);
@ -2122,6 +2197,7 @@ namespace OpenSim.Data.SQLite
row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y; row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y;
row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z; row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z;
if ((prim.SoundFlags & 1) != 0) // Looped if ((prim.SoundFlags & 1) != 0) // Looped
{ {
row["LoopedSound"] = prim.Sound.ToString(); row["LoopedSound"] = prim.Sound.ToString();
@ -2171,7 +2247,7 @@ namespace OpenSim.Data.SQLite
row["AttachedPosY"] = prim.AttachedPos.Y; row["AttachedPosY"] = prim.AttachedPos.Y;
row["AttachedPosZ"] = prim.AttachedPos.Z; row["AttachedPosZ"] = prim.AttachedPos.Z;
if (prim.DynAttrs!= null && prim.DynAttrs.CountNamespaces > 0) if (prim.DynAttrs.CountNamespaces > 0)
row["DynAttrs"] = prim.DynAttrs.ToXml(); row["DynAttrs"] = prim.DynAttrs.ToXml();
else else
row["DynAttrs"] = null; row["DynAttrs"] = null;
@ -2201,7 +2277,6 @@ namespace OpenSim.Data.SQLite
else else
row["PhysInertia"] = String.Empty; row["PhysInertia"] = String.Empty;
row["pseudocrc"] = prim.PseudoCRC;
} }
/// <summary> /// <summary>
@ -2289,20 +2364,6 @@ namespace OpenSim.Data.SQLite
row["AnyAVSounds"] = land.AnyAVSounds; row["AnyAVSounds"] = land.AnyAVSounds;
row["GroupAVSounds"] = land.GroupAVSounds; row["GroupAVSounds"] = land.GroupAVSounds;
if (land.Environment == null)
row["environment"] = "";
else
{
try
{
row["environment"] = ViewerEnvironment.ToOSDString(land.Environment);
}
catch
{
row["environment"] = "";
}
}
} }
/// <summary> /// <summary>
@ -2363,7 +2424,79 @@ namespace OpenSim.Data.SQLite
row["parcel_tile_ID"] = settings.ParcelImageID.ToString(); row["parcel_tile_ID"] = settings.ParcelImageID.ToString();
row["block_search"] = settings.GodBlockSearch; row["block_search"] = settings.GodBlockSearch;
row["casino"] = settings.Casino; row["casino"] = settings.Casino;
row["cacheID"] = settings.CacheID; }
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="windlight"></param>
private static void fillRegionWindlightRow(DataRow row, RegionLightShareData windlight)
{
row["region_id"] = windlight.regionID.ToString();
row["water_color_r"] = windlight.waterColor.X;
row["water_color_g"] = windlight.waterColor.Y;
row["water_color_b"] = windlight.waterColor.Z;
row["water_color_i"] = 1; //windlight.waterColor.W; //not implemented
row["water_fog_density_exponent"] = windlight.waterFogDensityExponent;
row["underwater_fog_modifier"] = windlight.underwaterFogModifier;
row["reflection_wavelet_scale_1"] = windlight.reflectionWaveletScale.X;
row["reflection_wavelet_scale_2"] = windlight.reflectionWaveletScale.Y;
row["reflection_wavelet_scale_3"] = windlight.reflectionWaveletScale.Z;
row["fresnel_scale"] = windlight.fresnelScale;
row["fresnel_offset"] = windlight.fresnelOffset;
row["refract_scale_above"] = windlight.refractScaleAbove;
row["refract_scale_below"] = windlight.refractScaleBelow;
row["blur_multiplier"] = windlight.blurMultiplier;
row["big_wave_direction_x"] = windlight.bigWaveDirection.X;
row["big_wave_direction_y"] = windlight.bigWaveDirection.Y;
row["little_wave_direction_x"] = windlight.littleWaveDirection.X;
row["little_wave_direction_y"] = windlight.littleWaveDirection.Y;
row["normal_map_texture"] = windlight.normalMapTexture.ToString();
row["horizon_r"] = windlight.horizon.X;
row["horizon_g"] = windlight.horizon.Y;
row["horizon_b"] = windlight.horizon.Z;
row["horizon_i"] = windlight.horizon.W;
row["haze_horizon"] = windlight.hazeHorizon;
row["blue_density_r"] = windlight.blueDensity.X;
row["blue_density_g"] = windlight.blueDensity.Y;
row["blue_density_b"] = windlight.blueDensity.Z;
row["blue_density_i"] = windlight.blueDensity.W;
row["haze_density"] = windlight.hazeDensity;
row["density_multiplier"] = windlight.densityMultiplier;
row["distance_multiplier"] = windlight.distanceMultiplier;
row["max_altitude"] = windlight.maxAltitude;
row["sun_moon_color_r"] = windlight.sunMoonColor.X;
row["sun_moon_color_g"] = windlight.sunMoonColor.Y;
row["sun_moon_color_b"] = windlight.sunMoonColor.Z;
row["sun_moon_color_i"] = windlight.sunMoonColor.W;
row["sun_moon_position"] = windlight.sunMoonPosition;
row["ambient_r"] = windlight.ambient.X;
row["ambient_g"] = windlight.ambient.Y;
row["ambient_b"] = windlight.ambient.Z;
row["ambient_i"] = windlight.ambient.W;
row["east_angle"] = windlight.eastAngle;
row["sun_glow_focus"] = windlight.sunGlowFocus;
row["sun_glow_size"] = windlight.sunGlowSize;
row["scene_gamma"] = windlight.sceneGamma;
row["star_brightness"] = windlight.starBrightness;
row["cloud_color_r"] = windlight.cloudColor.X;
row["cloud_color_g"] = windlight.cloudColor.Y;
row["cloud_color_b"] = windlight.cloudColor.Z;
row["cloud_color_i"] = windlight.cloudColor.W;
row["cloud_x"] = windlight.cloudXYDensity.X;
row["cloud_y"] = windlight.cloudXYDensity.Y;
row["cloud_density"] = windlight.cloudXYDensity.Z;
row["cloud_coverage"] = windlight.cloudCoverage;
row["cloud_scale"] = windlight.cloudScale;
row["cloud_detail_x"] = windlight.cloudDetailXYDensity.X;
row["cloud_detail_y"] = windlight.cloudDetailXYDensity.Y;
row["cloud_detail_density"] = windlight.cloudDetailXYDensity.Z;
row["cloud_scroll_x"] = windlight.cloudScrollX;
row["cloud_scroll_x_lock"] = windlight.cloudScrollXLock;
row["cloud_scroll_y"] = windlight.cloudScrollY;
row["cloud_scroll_y_lock"] = windlight.cloudScrollYLock;
row["draw_classic_clouds"] = windlight.drawClassicClouds;
} }
/// <summary> /// <summary>

View File

@ -926,7 +926,7 @@ namespace OpenSim.Data.SQLite
{ {
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
cmd.CommandText = string.Format(query, "\"classifieds\""); cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
@ -940,7 +940,7 @@ namespace OpenSim.Data.SQLite
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{ {
cmd.CommandText = string.Format(query, "\"userpicks\""); cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))

View File

@ -495,6 +495,10 @@ namespace OpenSim.Data.Tests
Assert.AreEqual(pricePerMeter, estateSettings.PricePerMeter); Assert.AreEqual(pricePerMeter, estateSettings.PricePerMeter);
Assert.AreEqual(redirectGridX, estateSettings.RedirectGridX); Assert.AreEqual(redirectGridX, estateSettings.RedirectGridX);
Assert.AreEqual(redirectGridY, estateSettings.RedirectGridY); Assert.AreEqual(redirectGridY, estateSettings.RedirectGridY);
Assert.AreEqual(useGlobalTime, estateSettings.UseGlobalTime);
Assert.AreEqual(fixedSun, estateSettings.FixedSun);
DataTestUtil.AssertDoubleEqualsWithTolerance(sunPosition, estateSettings.SunPosition);
Assert.AreEqual(allowVoice, estateSettings.AllowVoice); Assert.AreEqual(allowVoice, estateSettings.AllowVoice);
Assert.AreEqual(allowDirectTeleport, estateSettings.AllowDirectTeleport); Assert.AreEqual(allowDirectTeleport, estateSettings.AllowDirectTeleport);

View File

@ -269,12 +269,12 @@ namespace OpenSim.Data.Tests
random.NextBytes(partsys); random.NextBytes(partsys);
DateTime expires = new DateTime(2008, 12, 20); DateTime expires = new DateTime(2008, 12, 20);
DateTime rezzed = new DateTime(2009, 07, 15); DateTime rezzed = new DateTime(2009, 07, 15);
Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(1),random.Next(1),random.Next(1),random.Next(1)); Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
string description = name; string description = name;
Color color = Color.FromArgb(255, 165, 50, 100); Color color = Color.FromArgb(255, 165, 50, 100);
string text = "All Your Base Are Belong to Us"; string text = "All Your Base Are Belong to Us";
@ -289,7 +289,7 @@ namespace OpenSim.Data.Tests
pbshap.ProfileBegin = ushort.MaxValue; pbshap.ProfileBegin = ushort.MaxValue;
pbshap.ProfileEnd = ushort.MaxValue; pbshap.ProfileEnd = ushort.MaxValue;
pbshap.ProfileHollow = ushort.MaxValue; pbshap.ProfileHollow = ushort.MaxValue;
Vector3 scale = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 scale = new Vector3(random.Next(),random.Next(),random.Next());
RegionInfo regionInfo = new RegionInfo(); RegionInfo regionInfo = new RegionInfo();
regionInfo.RegionID = region3; regionInfo.RegionID = region3;
@ -378,9 +378,9 @@ namespace OpenSim.Data.Tests
SceneObjectPart p = sogs[0].RootPart; SceneObjectPart p = sogs[0].RootPart;
Assert.That(regionh,Is.EqualTo(p.RegionHandle), "Assert.That(regionh,Is.EqualTo(p.RegionHandle))"); Assert.That(regionh,Is.EqualTo(p.RegionHandle), "Assert.That(regionh,Is.EqualTo(p.RegionHandle))");
//Assert.That(localid,Is.EqualTo(p.LocalId), "Assert.That(localid,Is.EqualTo(p.LocalId))"); //Assert.That(localid,Is.EqualTo(p.LocalId), "Assert.That(localid,Is.EqualTo(p.LocalId))");
Assert.That(groupos, Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))"); Assert.That(groupos,Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))");
Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))"); Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
Assert.That(rotoff, Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))"); Assert.That(rotoff,Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))");
Assert.That(uuid,Is.EqualTo(p.UUID), "Assert.That(uuid,Is.EqualTo(p.UUID))"); Assert.That(uuid,Is.EqualTo(p.UUID), "Assert.That(uuid,Is.EqualTo(p.UUID))");
Assert.That(creator,Is.EqualTo(p.CreatorID), "Assert.That(creator,Is.EqualTo(p.CreatorID))"); Assert.That(creator,Is.EqualTo(p.CreatorID), "Assert.That(creator,Is.EqualTo(p.CreatorID))");
//Assert.That(iserial,Is.EqualTo(p.InventorySerial), "Assert.That(iserial,Is.EqualTo(p.InventorySerial))"); //Assert.That(iserial,Is.EqualTo(p.InventorySerial), "Assert.That(iserial,Is.EqualTo(p.InventorySerial))");
@ -443,12 +443,12 @@ namespace OpenSim.Data.Tests
random.NextBytes(partsys); random.NextBytes(partsys);
DateTime expires = new DateTime(2010, 12, 20); DateTime expires = new DateTime(2010, 12, 20);
DateTime rezzed = new DateTime(2005, 07, 15); DateTime rezzed = new DateTime(2005, 07, 15);
Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(100000),random.Next(100000),random.Next(100000),random.Next(100000)); Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
string description = name; string description = name;
Color color = Color.FromArgb(255, 255, 255, 0); Color color = Color.FromArgb(255, 255, 255, 0);
string text = "What You Say?{]\vz~"; string text = "What You Say?{]\vz~";
@ -536,12 +536,12 @@ namespace OpenSim.Data.Tests
{ {
UUID tmp = UUID.Random(); UUID tmp = UUID.Random();
SceneObjectPart sop = NewSOP(("Test SOP " + i.ToString()),tmp); SceneObjectPart sop = NewSOP(("Test SOP " + i.ToString()),tmp);
Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(100000),random.Next(100000),random.Next(100000),random.Next(100000)); Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000)); Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
sop.GroupPosition = groupos; sop.GroupPosition = groupos;
sop.RotationOffset = rotoff; sop.RotationOffset = rotoff;
@ -648,13 +648,11 @@ namespace OpenSim.Data.Tests
[Test] [Test]
public void T020_PrimInventoryEmpty() public void T020_PrimInventoryEmpty()
{ {
/*
TestHelpers.InMethod(); TestHelpers.InMethod();
SceneObjectGroup sog = GetMySOG("object1"); SceneObjectGroup sog = GetMySOG("object1");
TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1);
Assert.That(t, Is.Null); Assert.That(t, Is.Null);
*/
} }
// TODO: Is there any point to call StorePrimInventory on a list, rather than on the prim itself? // TODO: Is there any point to call StorePrimInventory on a list, rather than on the prim itself?
@ -674,7 +672,6 @@ namespace OpenSim.Data.Tests
[Test] [Test]
public void T021_PrimInventoryBasic() public void T021_PrimInventoryBasic()
{ {
/*
TestHelpers.InMethod(); TestHelpers.InMethod();
SceneObjectGroup sog = GetMySOG("object1"); SceneObjectGroup sog = GetMySOG("object1");
@ -710,13 +707,11 @@ namespace OpenSim.Data.Tests
sog = FindSOG("object1", region1); sog = FindSOG("object1", region1);
t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); t = sog.GetInventoryItem(sog.RootPart.LocalId, item1);
Assert.That(t, Is.Null); Assert.That(t, Is.Null);
*/
} }
[Test] [Test]
public void T025_PrimInventoryPersistency() public void T025_PrimInventoryPersistency()
{ {
/*
TestHelpers.InMethod(); TestHelpers.InMethod();
InventoryItemBase i = new InventoryItemBase(); InventoryItemBase i = new InventoryItemBase();
@ -784,14 +779,12 @@ namespace OpenSim.Data.Tests
// Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 16), "Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8))"); // Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 16), "Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8))");
Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID), "Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID))"); Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID), "Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID))");
Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID), "Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID))"); Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID), "Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID))");
*/
} }
/*
[Test] [Test]
[ExpectedException(typeof(ArgumentException))] [ExpectedException(typeof(ArgumentException))]
public void T026_PrimInventoryMany() public void T026_PrimInventoryMany()
{ {
TestHelpers.InMethod(); TestHelpers.InMethod();
UUID i1,i2,i3,i4; UUID i1,i2,i3,i4;
@ -819,9 +812,8 @@ namespace OpenSim.Data.Tests
Assert.That(t3.Name, Is.EqualTo(ib3.Name), "Assert.That(t3.Name, Is.EqualTo(ib3.Name))"); Assert.That(t3.Name, Is.EqualTo(ib3.Name), "Assert.That(t3.Name, Is.EqualTo(ib3.Name))");
TaskInventoryItem t4 = sog.GetInventoryItem(sog.RootPart.LocalId, i4); TaskInventoryItem t4 = sog.GetInventoryItem(sog.RootPart.LocalId, i4);
Assert.That(t4, Is.Null); Assert.That(t4, Is.Null);
} }
*/
[Test] [Test]
public void T052_RemoveObject() public void T052_RemoveObject()
{ {
@ -869,6 +861,7 @@ namespace OpenSim.Data.Tests
double terrainlower = random.Next(); double terrainlower = random.Next();
Vector3 sunvector = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); Vector3 sunvector = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5));
UUID terimgid = UUID.Random(); UUID terimgid = UUID.Random();
double sunpos = random.Next();
UUID cov = UUID.Random(); UUID cov = UUID.Random();
RegionSettings r1 = db.LoadRegionSettings(region1); RegionSettings r1 = db.LoadRegionSettings(region1);
@ -902,8 +895,10 @@ namespace OpenSim.Data.Tests
r1.TerrainLowerLimit = terrainlower; r1.TerrainLowerLimit = terrainlower;
r1.UseEstateSun = false; r1.UseEstateSun = false;
r1.Sandbox = true; r1.Sandbox = true;
r1.SunVector = sunvector;
r1.TerrainImageID = terimgid; r1.TerrainImageID = terimgid;
r1.FixedSun = true; r1.FixedSun = true;
r1.SunPosition = sunpos;
r1.Covenant = cov; r1.Covenant = cov;
db.StoreRegionSettings(r1); db.StoreRegionSettings(r1);
@ -938,8 +933,12 @@ namespace OpenSim.Data.Tests
Assert.That(r1a.WaterHeight,Is.EqualTo(waterh), "Assert.That(r1a.WaterHeight,Is.EqualTo(waterh))"); Assert.That(r1a.WaterHeight,Is.EqualTo(waterh), "Assert.That(r1a.WaterHeight,Is.EqualTo(waterh))");
Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise), "Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise))"); Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise), "Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise))");
Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower), "Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower))"); Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower), "Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower))");
Assert.That(r1a.UseEstateSun,Is.False);
Assert.That(r1a.Sandbox,Is.True); Assert.That(r1a.Sandbox,Is.True);
Assert.That(r1a.SunVector,Is.EqualTo(sunvector), "Assert.That(r1a.SunVector,Is.EqualTo(sunvector))");
//Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid), "Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid))"); //Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid), "Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid))");
Assert.That(r1a.FixedSun,Is.True);
Assert.That(r1a.SunPosition, Is.EqualTo(sunpos), "Assert.That(r1a.SunPosition, Is.EqualTo(sunpos))");
Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))"); Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))");
} }
@ -963,7 +962,7 @@ namespace OpenSim.Data.Tests
db.StoreTerrain(t1, region1); db.StoreTerrain(t1, region1);
// store terrain is async // store terrain is async
Thread.Sleep(500); Thread.Sleep(1000);
Assert.That(db.LoadTerrain(zero), Is.Null); Assert.That(db.LoadTerrain(zero), Is.Null);
Assert.That(db.LoadTerrain(region1), Is.Not.Null); Assert.That(db.LoadTerrain(region1), Is.Not.Null);
@ -993,7 +992,7 @@ namespace OpenSim.Data.Tests
db.StoreTerrain(baseterrain2, region1); db.StoreTerrain(baseterrain2, region1);
// store terrain is async // store terrain is async
Thread.Sleep(500); Thread.Sleep(1000);
double[,] t1 = db.LoadTerrain(region1); double[,] t1 = db.LoadTerrain(region1);
Assert.That(CompareTerrain(t1, baseterrain1), Is.False); Assert.That(CompareTerrain(t1, baseterrain1), Is.False);
@ -1079,6 +1078,7 @@ namespace OpenSim.Data.Tests
sop.Shape = PrimitiveBaseShape.Default; sop.Shape = PrimitiveBaseShape.Default;
SceneObjectGroup sog = new SceneObjectGroup(sop); SceneObjectGroup sog = new SceneObjectGroup(sop);
// sog.SetScene(scene);
return sog; return sog;
} }

View File

@ -173,7 +173,6 @@ namespace OpenSim.Framework
/// Position the Agent's Avatar starts in the region /// Position the Agent's Avatar starts in the region
/// </summary> /// </summary>
public Vector3 startpos; public Vector3 startpos;
public float startfar = -1.0f;
public Dictionary<string, object> ServiceURLs; public Dictionary<string, object> ServiceURLs;
@ -220,8 +219,6 @@ namespace OpenSim.Framework
args["channel"] = OSD.FromString(Channel); args["channel"] = OSD.FromString(Channel);
args["mac"] = OSD.FromString(Mac); args["mac"] = OSD.FromString(Mac);
args["id0"] = OSD.FromString(Id0); args["id0"] = OSD.FromString(Id0);
if(startfar > 0)
args["far"] = OSD.FromReal(startfar);
if (Appearance != null) if (Appearance != null)
{ {
@ -267,17 +264,16 @@ namespace OpenSim.Framework
/// <param name="args"></param> /// <param name="args"></param>
public void UnpackAgentCircuitData(OSDMap args) public void UnpackAgentCircuitData(OSDMap args)
{ {
OSD tmpOSD; if (args["agent_id"] != null)
if (args.TryGetValue("agent_id", out tmpOSD)) AgentID = args["agent_id"].AsUUID();
AgentID = tmpOSD.AsUUID(); if (args["base_folder"] != null)
if (args.TryGetValue("base_folder", out tmpOSD)) BaseFolder = args["base_folder"].AsUUID();
BaseFolder =tmpOSD.AsUUID(); if (args["caps_path"] != null)
if (args.TryGetValue("caps_path", out tmpOSD)) CapsPath = args["caps_path"].AsString();
CapsPath = tmpOSD.AsString();
if ((args.TryGetValue("children_seeds", out tmpOSD) && tmpOSD is OSDArray)) if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array))
{ {
OSDArray childrenSeeds = (OSDArray)tmpOSD; OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
ChildrenCapSeeds = new Dictionary<ulong, string>(); ChildrenCapSeeds = new Dictionary<ulong, string>();
foreach (OSD o in childrenSeeds) foreach (OSD o in childrenSeeds)
{ {
@ -286,59 +282,50 @@ namespace OpenSim.Framework
ulong handle = 0; ulong handle = 0;
string seed = ""; string seed = "";
OSDMap pair = (OSDMap)o; OSDMap pair = (OSDMap)o;
if (pair.TryGetValue("handle", out tmpOSD)) if (pair["handle"] != null)
{ if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
if (!UInt64.TryParse(tmpOSD.AsString(), out handle))
continue; continue;
} if (pair["seed"] != null)
seed = pair["seed"].AsString();
if (!ChildrenCapSeeds.ContainsKey(handle)) if (!ChildrenCapSeeds.ContainsKey(handle))
{
if (pair.TryGetValue("seed", out tmpOSD))
{
seed = tmpOSD.AsString();
ChildrenCapSeeds.Add(handle, seed); ChildrenCapSeeds.Add(handle, seed);
} }
} }
} }
}
}
else else
ChildrenCapSeeds = new Dictionary<ulong, string>(); ChildrenCapSeeds = new Dictionary<ulong, string>();
if (args.TryGetValue("child", out tmpOSD)) if (args["child"] != null)
child = tmpOSD.AsBoolean(); child = args["child"].AsBoolean();
if (args.TryGetValue("circuit_code", out tmpOSD)) if (args["circuit_code"] != null)
UInt32.TryParse(tmpOSD.AsString(), out circuitcode); UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode);
if (args.TryGetValue("first_name", out tmpOSD)) if (args["first_name"] != null)
firstname = tmpOSD.AsString(); firstname = args["first_name"].AsString();
if (args.TryGetValue("last_name", out tmpOSD)) if (args["last_name"] != null)
lastname = tmpOSD.AsString(); lastname = args["last_name"].AsString();
if (args.TryGetValue("inventory_folder", out tmpOSD)) if (args["inventory_folder"] != null)
InventoryFolder = tmpOSD.AsUUID(); InventoryFolder = args["inventory_folder"].AsUUID();
if (args.TryGetValue("secure_session_id", out tmpOSD)) if (args["secure_session_id"] != null)
SecureSessionID = tmpOSD.AsUUID(); SecureSessionID = args["secure_session_id"].AsUUID();
if (args.TryGetValue("session_id", out tmpOSD)) if (args["session_id"] != null)
SessionID = tmpOSD.AsUUID(); SessionID = args["session_id"].AsUUID();
if (args.TryGetValue("service_session_id", out tmpOSD)) if (args["service_session_id"] != null)
ServiceSessionID = tmpOSD.AsString(); ServiceSessionID = args["service_session_id"].AsString();
if (args.TryGetValue("client_ip", out tmpOSD)) if (args["client_ip"] != null)
IPAddress = tmpOSD.AsString(); IPAddress = args["client_ip"].AsString();
if (args.TryGetValue("viewer", out tmpOSD)) if (args["viewer"] != null)
Viewer = tmpOSD.AsString(); Viewer = args["viewer"].AsString();
if (args.TryGetValue("channel", out tmpOSD)) if (args["channel"] != null)
Channel = tmpOSD.AsString(); Channel = args["channel"].AsString();
if (args.TryGetValue("mac", out tmpOSD)) if (args["mac"] != null)
Mac = tmpOSD.AsString(); Mac = args["mac"].AsString();
if (args.TryGetValue("id0", out tmpOSD)) if (args["id0"] != null)
Id0 = tmpOSD.AsString(); Id0 = args["id0"].AsString();
if (args.TryGetValue("teleport_flags", out tmpOSD)) if (args["teleport_flags"] != null)
teleportFlags = tmpOSD.AsUInteger(); teleportFlags = args["teleport_flags"].AsUInteger();
if (args.TryGetValue("start_pos", out tmpOSD)) if (args["start_pos"] != null)
Vector3.TryParse(tmpOSD.AsString(), out startpos); Vector3.TryParse(args["start_pos"].AsString(), out startpos);
if(args.TryGetValue("far", out tmpOSD))
startfar = (float)tmpOSD.AsReal();
//m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos); //m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos);
@ -349,12 +336,12 @@ namespace OpenSim.Framework
// Eventually this code should be deprecated, use full appearance // Eventually this code should be deprecated, use full appearance
// packing in packed_appearance // packing in packed_appearance
if (args.TryGetValue("appearance_serial", out tmpOSD)) if (args["appearance_serial"] != null)
Appearance.Serial = tmpOSD.AsInteger(); Appearance.Serial = args["appearance_serial"].AsInteger();
if (args.TryGetValue("packed_appearance", out tmpOSD) && (tmpOSD is OSDMap)) if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map))
{ {
Appearance.Unpack((OSDMap)tmpOSD); Appearance.Unpack((OSDMap)args["packed_appearance"]);
// m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance"); // m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance");
} }
else else
@ -369,29 +356,31 @@ namespace OpenSim.Framework
ServiceURLs = new Dictionary<string, object>(); ServiceURLs = new Dictionary<string, object>();
// Try parse the new way, OSDMap // Try parse the new way, OSDMap
if (args.TryGetValue("serviceurls", out tmpOSD) && (tmpOSD is OSDMap)) if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map)
{ {
OSDMap urls = (OSDMap)tmpOSD; OSDMap urls = (OSDMap)(args["serviceurls"]);
foreach (KeyValuePair<String, OSD> kvp in urls) foreach (KeyValuePair<String, OSD> kvp in urls)
{ {
ServiceURLs[kvp.Key] = kvp.Value; ServiceURLs[kvp.Key] = kvp.Value.AsString();
//System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]);
} }
} }
// else try the old way, OSDArray // else try the old way, OSDArray
// OBSOLETE -- soon to be deleted // OBSOLETE -- soon to be deleted
else if (args.TryGetValue("service_urls", out tmpOSD) && (tmpOSD is OSDArray)) else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array)
{ {
OSDArray urls = (OSDArray)tmpOSD; OSDArray urls = (OSDArray)(args["service_urls"]);
OSD tmpOSDb; for (int i = 0; i < urls.Count / 2; i++)
for (int i = 0; i < urls.Count - 1; i += 2)
{ {
tmpOSD = urls[i]; ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString();
tmpOSDb = urls[i + 1];
ServiceURLs[tmpOSD.AsString()] = tmpOSDb.AsString();
//System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString());
} }
} }
} }
} }
} }

View File

@ -26,7 +26,6 @@
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Concurrent;
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Framework namespace OpenSim.Framework
@ -42,18 +41,26 @@ namespace OpenSim.Framework
/// <remarks> /// <remarks>
/// We lock this for operations both on this dictionary and on m_agentCircuitsByUUID /// We lock this for operations both on this dictionary and on m_agentCircuitsByUUID
/// </remarks> /// </remarks>
private ConcurrentDictionary<uint, AgentCircuitData> m_agentCircuits = new ConcurrentDictionary<uint, AgentCircuitData>(); private Dictionary<uint, AgentCircuitData> m_agentCircuits = new Dictionary<uint, AgentCircuitData>();
/// <summary> /// <summary>
/// Agent circuits indexed by agent UUID. /// Agent circuits indexed by agent UUID.
/// </summary> /// </summary>
private ConcurrentDictionary<UUID, AgentCircuitData> m_agentCircuitsByUUID = new ConcurrentDictionary<UUID, AgentCircuitData>(); private Dictionary<UUID, AgentCircuitData> m_agentCircuitsByUUID = new Dictionary<UUID, AgentCircuitData>();
public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode) public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode)
{ {
AgentCircuitData validcircuit = null;
lock (m_agentCircuits)
{
if (m_agentCircuits.ContainsKey(circuitcode))
validcircuit = m_agentCircuits[circuitcode];
}
AuthenticateResponse user = new AuthenticateResponse(); AuthenticateResponse user = new AuthenticateResponse();
if (!m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData validcircuit) || validcircuit == null)
if (validcircuit == null)
{ {
//don't have this circuit code in our list //don't have this circuit code in our list
user.Authorised = false; user.Authorised = false;
@ -72,13 +79,13 @@ namespace OpenSim.Framework
user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder; user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder;
user.LoginInfo.BaseFolder = validcircuit.BaseFolder; user.LoginInfo.BaseFolder = validcircuit.BaseFolder;
user.LoginInfo.StartPos = validcircuit.startpos; user.LoginInfo.StartPos = validcircuit.startpos;
user.LoginInfo.StartFar = (float)validcircuit.startfar;
} }
else else
{ {
// Invalid // Invalid
user.Authorised = false; user.Authorised = false;
} }
return user; return user;
} }
@ -89,39 +96,65 @@ namespace OpenSim.Framework
/// <param name="agentData"></param> /// <param name="agentData"></param>
public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData) public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData)
{ {
RemoveCircuit(agentData.AgentID); // no duplications lock (m_agentCircuits)
{
if (m_agentCircuits.ContainsKey(circuitCode))
{
m_agentCircuits[circuitCode] = agentData; m_agentCircuits[circuitCode] = agentData;
m_agentCircuitsByUUID[agentData.AgentID] = agentData; m_agentCircuitsByUUID[agentData.AgentID] = agentData;
} }
else
{
m_agentCircuits.Add(circuitCode, agentData);
m_agentCircuitsByUUID[agentData.AgentID] = agentData;
}
}
}
public virtual void RemoveCircuit(uint circuitCode) public virtual void RemoveCircuit(uint circuitCode)
{ {
if (m_agentCircuits.TryRemove(circuitCode, out AgentCircuitData ac)) lock (m_agentCircuits)
{ {
m_agentCircuitsByUUID.TryRemove(ac.AgentID, out AgentCircuitData dummy); if (m_agentCircuits.ContainsKey(circuitCode))
{
UUID agentID = m_agentCircuits[circuitCode].AgentID;
m_agentCircuits.Remove(circuitCode);
m_agentCircuitsByUUID.Remove(agentID);
}
} }
} }
public virtual void RemoveCircuit(UUID agentID) public virtual void RemoveCircuit(UUID agentID)
{ {
if (m_agentCircuitsByUUID.TryRemove(agentID, out AgentCircuitData ac)) lock (m_agentCircuits)
{ {
m_agentCircuits.TryRemove(ac.circuitcode, out AgentCircuitData dummy); if (m_agentCircuitsByUUID.ContainsKey(agentID))
{
uint circuitCode = m_agentCircuitsByUUID[agentID].circuitcode;
m_agentCircuits.Remove(circuitCode);
m_agentCircuitsByUUID.Remove(agentID);
}
} }
} }
public AgentCircuitData GetAgentCircuitData(uint circuitCode) public AgentCircuitData GetAgentCircuitData(uint circuitCode)
{ {
if(m_agentCircuits.TryGetValue(circuitCode, out AgentCircuitData agentCircuit)) AgentCircuitData agentCircuit = null;
lock (m_agentCircuits)
m_agentCircuits.TryGetValue(circuitCode, out agentCircuit);
return agentCircuit; return agentCircuit;
return null;
} }
public AgentCircuitData GetAgentCircuitData(UUID agentID) public AgentCircuitData GetAgentCircuitData(UUID agentID)
{ {
if(m_agentCircuitsByUUID.TryGetValue(agentID, out AgentCircuitData agentCircuit)) AgentCircuitData agentCircuit = null;
lock (m_agentCircuits)
m_agentCircuitsByUUID.TryGetValue(agentID, out agentCircuit);
return agentCircuit; return agentCircuit;
return null;
} }
/// <summary> /// <summary>
@ -136,16 +169,20 @@ namespace OpenSim.Framework
public void UpdateAgentData(AgentCircuitData agentData) public void UpdateAgentData(AgentCircuitData agentData)
{ {
if (m_agentCircuits.TryGetValue(agentData.circuitcode, out AgentCircuitData ac)) lock (m_agentCircuits)
{ {
ac.firstname = agentData.firstname; if (m_agentCircuits.ContainsKey((uint) agentData.circuitcode))
ac.lastname = agentData.lastname; {
ac.startpos = agentData.startpos; m_agentCircuits[(uint) agentData.circuitcode].firstname = agentData.firstname;
ac.startfar = agentData.startfar; m_agentCircuits[(uint) agentData.circuitcode].lastname = agentData.lastname;
m_agentCircuits[(uint) agentData.circuitcode].startpos = agentData.startpos;
// Updated for when we don't know them before calling Scene.NewUserConnection // Updated for when we don't know them before calling Scene.NewUserConnection
ac.SecureSessionID = agentData.SecureSessionID; m_agentCircuits[(uint) agentData.circuitcode].SecureSessionID = agentData.SecureSessionID;
ac.SessionID = agentData.SessionID; m_agentCircuits[(uint) agentData.circuitcode].SessionID = agentData.SessionID;
// m_log.Debug("update user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z);
}
} }
} }
@ -154,30 +191,38 @@ namespace OpenSim.Framework
/// </summary> /// </summary>
/// <param name="circuitcode"></param> /// <param name="circuitcode"></param>
/// <param name="newcircuitcode"></param> /// <param name="newcircuitcode"></param>
public bool TryChangeCircuitCode(uint circuitcode, uint newcircuitcode) public bool TryChangeCiruitCode(uint circuitcode, uint newcircuitcode)
{ {
if(m_agentCircuits.ContainsKey(newcircuitcode)) lock (m_agentCircuits)
return false;
if (m_agentCircuits.TryRemove(circuitcode, out AgentCircuitData agentData))
{ {
if (m_agentCircuits.ContainsKey((uint)circuitcode) && !m_agentCircuits.ContainsKey((uint)newcircuitcode))
{
AgentCircuitData agentData = m_agentCircuits[(uint)circuitcode];
agentData.circuitcode = newcircuitcode; agentData.circuitcode = newcircuitcode;
m_agentCircuits.TryAdd(newcircuitcode, agentData);
m_agentCircuitsByUUID[agentData.AgentID] = agentData; m_agentCircuits.Remove((uint)circuitcode);
m_agentCircuits.Add(newcircuitcode, agentData);
return true; return true;
} }
}
return false; return false;
} }
public void UpdateAgentChildStatus(uint circuitcode, bool childstatus) public void UpdateAgentChildStatus(uint circuitcode, bool childstatus)
{ {
if (m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData ac)) lock (m_agentCircuits)
ac.child = childstatus; if (m_agentCircuits.ContainsKey(circuitcode))
m_agentCircuits[circuitcode].child = childstatus;
} }
public bool GetAgentChildStatus(uint circuitcode) public bool GetAgentChildStatus(uint circuitcode)
{ {
if (m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData ac)) lock (m_agentCircuits)
return ac.child; if (m_agentCircuits.ContainsKey(circuitcode))
return m_agentCircuits[circuitcode].child;
return false; return false;
} }
} }

View File

@ -83,7 +83,6 @@ namespace OpenSim.Framework
public bool UseClientAgentPosition; public bool UseClientAgentPosition;
public bool NeedsCameraCollision; public bool NeedsCameraCollision;
public uint lastpacketSequence; public uint lastpacketSequence;
public double lastUpdateTS;
public AgentUpdateArgs() public AgentUpdateArgs()
{ {

View File

@ -112,13 +112,12 @@ namespace OpenSim.Framework
/// <param name="args"></param> /// <param name="args"></param>
public void UnpackUpdateMessage(OSDMap args) public void UnpackUpdateMessage(OSDMap args)
{ {
OSD tmp; if (args["animation"] != null)
if (args.TryGetValue("animation", out tmp)) animID = args["animation"].AsUUID();
animID = tmp.AsUUID(); if (args["object_id"] != null)
if (args.TryGetValue("object_id", out tmp)) objectID = args["object_id"].AsUUID();
objectID = tmp.AsUUID(); if (args["seq_num"] != null)
if (args.TryGetValue("seq_num", out tmp)) sequenceNum = args["seq_num"].AsInteger();
sequenceNum = tmp.AsInteger();
} }
public override bool Equals(object obj) public override bool Equals(object obj)

View File

@ -34,13 +34,12 @@ using OpenMetaverse;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
[Flags] [Flags]
// this enum is stuck, can not be changed or will break compatibilty with any version older than that change
public enum AssetFlags : int public enum AssetFlags : int
{ {
Normal = 0, // Immutable asset Normal = 0, // Immutable asset
Maptile = 1, // What it says Maptile = 1, // What it says
Rewritable = 2, // Content can be rewritten Rewritable = 2, // Content can be rewritten
Collectable = 4, // Can be GC'ed after some time Collectable = 4 // Can be GC'ed after some time
} }
/// <summary> /// <summary>

View File

@ -42,13 +42,11 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
public class AssetLoaderFileSystem : IAssetLoader public class AssetLoaderFileSystem : IAssetLoader
{ {
private static readonly UUID LIBRARY_OWNER_ID = new UUID("11111111-1111-0000-0000-000100bba000"); private static readonly UUID LIBRARY_OWNER_ID = new UUID("11111111-1111-0000-0000-000100bba000");
private static readonly string LIBRARY_OWNER_IDstr = "11111111-1111-0000-0000-000100bba000";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type) protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type)
{ {
AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, LIBRARY_OWNER_IDstr); AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, LIBRARY_OWNER_ID.ToString());
if (!String.IsNullOrEmpty(path)) if (!String.IsNullOrEmpty(path))
{ {

View File

@ -51,28 +51,27 @@ namespace OpenSim.Framework
// this is viewer capabilities and weared things dependent // this is viewer capabilities and weared things dependent
// should be only used as initial default value ( V1 viewers ) // should be only used as initial default value ( V1 viewers )
public const int VISUALPARAM_COUNT = 218; public readonly static int VISUALPARAM_COUNT = 218;
// regions and viewer compatibility // public readonly static int TEXTURE_COUNT = 21
public readonly static int TEXTURE_COUNT = 45; // 21 bad, make it be updated as libovm gets update
public const int TEXTURE_COUNT_PV7 = 29; // also keeping in sync with it
public const int BAKES_COUNT_PV7 = 6; public readonly static int TEXTURE_COUNT = Primitive.TextureEntry.MAX_FACES;
public const int MAXWEARABLE_PV7 = 16;
public const int MAXWEARABLE_LEGACY = 15;
public readonly static byte[] BAKE_INDICES = new byte[] { 8, 9, 10, 11, 19, 20, 40, 41, 42, 43, 44 }; public readonly static byte[] BAKE_INDICES = new byte[] { 8, 9, 10, 11, 19, 20 };
protected int m_serial = 0; protected int m_serial = 0;
protected byte[] m_visualparams; protected byte[] m_visualparams;
protected Primitive.TextureEntry m_texture; protected Primitive.TextureEntry m_texture;
protected AvatarWearable[] m_wearables; protected AvatarWearable[] m_wearables;
protected Dictionary<int, List<AvatarAttachment>> m_attachments; protected Dictionary<int, List<AvatarAttachment>> m_attachments;
protected WearableCacheItem[] m_cacheitems; protected float m_avatarHeight = 0;
protected Vector3 m_avatarSize = new Vector3(0.45f, 0.6f, 1.9f); // sl Z cloud value protected Vector3 m_avatarSize = new Vector3(0.45f, 0.6f, 1.9f); // sl Z cloud value
protected Vector3 m_avatarBoxSize = new Vector3(0.45f, 0.6f, 1.9f); protected Vector3 m_avatarBoxSize = new Vector3(0.45f, 0.6f, 1.9f);
protected float m_avatarHeight = 0;
protected float m_avatarFeetOffset = 0; protected float m_avatarFeetOffset = 0;
protected float m_avatarAnimOffset = 0; protected float m_avatarAnimOffset = 0;
protected WearableCacheItem[] m_cacheitems;
protected bool m_cacheItemsDirty = true;
public virtual int Serial public virtual int Serial
{ {
@ -129,7 +128,11 @@ namespace OpenSim.Framework
set { m_cacheitems = value; } set { m_cacheitems = value; }
} }
public virtual float AvatarPreferencesHoverZ { get; set; } public virtual bool WearableCacheItemsDirty
{
get { return m_cacheItemsDirty; }
set { m_cacheItemsDirty = value; }
}
public AvatarAppearance() public AvatarAppearance()
{ {
@ -201,14 +204,12 @@ namespace OpenSim.Framework
SetDefaultParams(); SetDefaultParams();
// SetHeight(); // SetHeight();
SetSize(new Vector3(0.45f, 0.6f, 1.9f)); SetSize(new Vector3(0.45f, 0.6f, 1.9f));
AvatarPreferencesHoverZ = 0;
m_attachments = new Dictionary<int, List<AvatarAttachment>>(); m_attachments = new Dictionary<int, List<AvatarAttachment>>();
return; return;
} }
m_serial = appearance.Serial; m_serial = appearance.Serial;
AvatarPreferencesHoverZ = appearance.AvatarPreferencesHoverZ;
if (copyWearables && (appearance.Wearables != null)) if (copyWearables && (appearance.Wearables != null))
{ {
@ -227,7 +228,7 @@ namespace OpenSim.Framework
m_texture = null; m_texture = null;
if (appearance.Texture != null) if (appearance.Texture != null)
{ {
byte[] tbytes = appearance.Texture.GetBakesBytes(); byte[] tbytes = appearance.Texture.GetBytes();
m_texture = new Primitive.TextureEntry(tbytes,0,tbytes.Length); m_texture = new Primitive.TextureEntry(tbytes,0,tbytes.Length);
if (copyBaked && appearance.m_cacheitems != null) if (copyBaked && appearance.m_cacheitems != null)
m_cacheitems = (WearableCacheItem[])appearance.m_cacheitems.Clone(); m_cacheitems = (WearableCacheItem[])appearance.m_cacheitems.Clone();
@ -294,7 +295,6 @@ namespace OpenSim.Framework
m_serial = 0; m_serial = 0;
SetDefaultTexture(); SetDefaultTexture();
AvatarPreferencesHoverZ = 0;
//for (int i = 0; i < BAKE_INDICES.Length; i++) //for (int i = 0; i < BAKE_INDICES.Length; i++)
// { // {
@ -330,6 +330,9 @@ namespace OpenSim.Framework
protected virtual void SetDefaultTexture() protected virtual void SetDefaultTexture()
{ {
m_texture = new Primitive.TextureEntry(new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE)); m_texture = new Primitive.TextureEntry(new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE));
// for (uint i = 0; i < TEXTURE_COUNT; i++)
// m_texture.CreateFace(i).TextureID = new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE);
} }
/// <summary> /// <summary>
@ -344,31 +347,31 @@ namespace OpenSim.Framework
if (textureEntry == null) if (textureEntry == null)
return false; return false;
// There are much simpler versions of this copy that could be
// made. We determine if any of the textures actually
// changed to know if the appearance should be saved later
bool changed = false; bool changed = false;
Primitive.TextureEntryFace newface; for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++)
Primitive.TextureEntryFace tmpFace; {
Primitive.TextureEntryFace newface = textureEntry.FaceTextures[i];
Primitive.TextureEntryFace oldface = m_texture.FaceTextures[i];
//make sure textureEntry.DefaultTexture is the unused one(DEFAULT_AVATAR_TEXTURE). if (newface == null)
Primitive.TextureEntry converted = new Primitive.TextureEntry(AppearanceManager.DEFAULT_AVATAR_TEXTURE);
for (uint i = 0; i < TEXTURE_COUNT; ++i)
{ {
newface = textureEntry.GetFace(i); if (oldface == null)
if (newface.TextureID != AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue;
{
tmpFace = converted.GetFace(i);
tmpFace.TextureID = newface.TextureID; // we need a full high level copy, assuming all other parameters are the same.
if (m_texture.FaceTextures[i] == null || newface.TextureID != m_texture.FaceTextures[i].TextureID)
changed = true;
} }
else else
{ if (m_texture.FaceTextures[i] == null) {
if (oldface != null && oldface.TextureID == newface.TextureID)
continue; continue;
if(m_texture.FaceTextures[i].TextureID != AppearanceManager.DEFAULT_AVATAR_TEXTURE) }
changed = true; changed = true;
} }
}
if(changed) m_texture = textureEntry;
m_texture = converted;
return changed; return changed;
} }
@ -733,72 +736,42 @@ namespace OpenSim.Framework
data["serial"] = OSD.FromInteger(m_serial); data["serial"] = OSD.FromInteger(m_serial);
data["height"] = OSD.FromReal(m_avatarHeight); data["height"] = OSD.FromReal(m_avatarHeight);
data["aphz"] = OSD.FromReal(AvatarPreferencesHoverZ);
if (m_texture == null)
return data;
bool sendPV8 = false;
// Wearables // Wearables
OSDArray wears; //
int count; // This will send as many or as few wearables as we have, unless a count
if (ctx == null) // is given. Used for legacy (pre 0.4) versions.
count = MAXWEARABLE_LEGACY; int count = ctx.WearablesCount;
else if (ctx.WearablesCount == -1)
{
if(ctx.OutboundVersion >= 0.8)
{
sendPV8 = true;
count = m_wearables.Length; count = m_wearables.Length;
} OSDArray wears = new OSDArray(count);
else if (ctx.OutboundVersion >= 0.6) for (int i = 0; i < count; i++)
count = MAXWEARABLE_PV7;
else
count = MAXWEARABLE_LEGACY;
if (sendPV8 && count > MAXWEARABLE_PV7)
{ {
wears = new OSDArray(count - MAXWEARABLE_PV7); AvatarWearable dummyWearable = new AvatarWearable();
for (int i = MAXWEARABLE_PV7; i < count; ++i)
if (i < m_wearables.Length)
wears.Add(m_wearables[i].Pack()); wears.Add(m_wearables[i].Pack());
else
data["wrbls8"] = wears; wears.Add(dummyWearable.Pack());
count = MAXWEARABLE_PV7;
} }
}
if(count > m_wearables.Length)
count = m_wearables.Length;
wears = new OSDArray(count);
for (int i = 0; i < count; ++i)
wears.Add(m_wearables[i].Pack());
data["wearables"] = wears; data["wearables"] = wears;
// Avatar Textures // Avatar Textures
OSDArray textures; OSDArray textures = new OSDArray(AvatarAppearance.TEXTURE_COUNT);
if (sendPV8) for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++)
{ {
byte[] te = m_texture.GetBakesBytes(); if (m_texture.FaceTextures[i] != null)
data["te8"] = OSD.FromBinary(te); textures.Add(OSD.FromUUID(m_texture.FaceTextures[i].TextureID));
}
else else
{ textures.Add(OSD.FromUUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE));
textures = new OSDArray(TEXTURE_COUNT_PV7);
for (uint i = 0; i < TEXTURE_COUNT_PV7; ++i)
textures.Add(OSD.FromUUID(m_texture.GetFace(i).TextureID));
data["textures"] = textures;
} }
data["textures"] = textures;
if (m_cacheitems != null) if (m_cacheitems != null)
{ {
OSDArray baked = WearableCacheItem.BakedToOSD(m_cacheitems, 0, BAKES_COUNT_PV7); OSDArray baked = WearableCacheItem.BakedToOSD(m_cacheitems);
if (baked != null && baked.Count > 0) if (baked != null)
data["bakedcache"] = baked; data["bakedcache"] = baked;
baked = WearableCacheItem.BakedToOSD(m_cacheitems, BAKES_COUNT_PV7, -1);
if (baked != null && baked.Count > 0)
data["bc8"] = baked;
} }
// Visual Parameters // Visual Parameters
@ -817,178 +790,68 @@ namespace OpenSim.Framework
return data; return data;
} }
public OSDMap PackForNotecard(bool NoHuds = true)
{
OSDMap data = new OSDMap();
data["serial"] = OSD.FromInteger(m_serial);
data["height"] = OSD.FromReal(m_avatarHeight);
data["aphz"] = OSD.FromReal(AvatarPreferencesHoverZ);
// old regions may not like missing/empty wears
OSDArray wears = new OSDArray(MAXWEARABLE_LEGACY);
for (int i = 0; i< MAXWEARABLE_LEGACY; ++i)
wears.Add(new OSDArray());
data["wearables"] = wears;
// Avatar Textures
OSDArray textures;
// allow old regions to still see something
textures = new OSDArray(TEXTURE_COUNT_PV7);
textures.Add(OSD.FromUUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE));
for (uint i = 1; i < TEXTURE_COUNT_PV7; ++i)
textures.Add(OSD.FromUUID(m_texture.GetFace(i).TextureID));
data["textures"] = textures;
bool needExtra = false;
for (int i = BAKES_COUNT_PV7; i < BAKE_INDICES.Length; ++i)
{
int idx = BAKE_INDICES[i];
if (m_texture.FaceTextures[idx] == null)
continue;
if (m_texture.FaceTextures[idx].TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE ||
m_texture.FaceTextures[idx].TextureID == UUID.Zero)
continue;
needExtra = true;
}
if (needExtra)
{
byte[] te = m_texture.GetBakesBytes();
data["te8"] = OSD.FromBinary(te);
}
// Visual Parameters
OSDBinary visualparams = new OSDBinary(m_visualparams);
data["visualparams"] = visualparams;
lock (m_attachments)
{
// Attachments
OSDArray attachs = new OSDArray(m_attachments.Count);
foreach (AvatarAttachment attach in GetAttachments())
{
if (NoHuds &&
attach.AttachPoint >= (uint)AttachmentPoint.HUDCenter2 &&
attach.AttachPoint <= (uint)AttachmentPoint.HUDBottomRight)
continue;
attachs.Add(attach.Pack());
}
data["attachments"] = attachs;
}
return data;
}
/// <summary> /// <summary>
/// Unpack and OSDMap and initialize the appearance /// Unpack and OSDMap and initialize the appearance
/// from it /// from it
/// </summary> /// </summary>
public void Unpack(OSDMap data) public void Unpack(OSDMap data)
{ {
SetDefaultWearables(); if ((data != null) && (data["serial"] != null))
SetDefaultTexture(); m_serial = data["serial"].AsInteger();
SetDefaultParams(); if ((data != null) && (data["height"] != null))
m_attachments = new Dictionary<int, List<AvatarAttachment>>(); // m_avatarHeight = (float)data["height"].AsReal();
SetSize(new Vector3(0.45f,0.6f, (float)data["height"].AsReal()));
if(data == null)
{
m_log.Warn("[AVATAR APPEARANCE]: data to unpack is null");
return;
}
OSD tmpOSD;
if (data.TryGetValue("serial", out tmpOSD))
m_serial = tmpOSD.AsInteger();
if(data.TryGetValue("aphz", out tmpOSD))
AvatarPreferencesHoverZ = (float)tmpOSD.AsReal();
if (data.TryGetValue("height", out tmpOSD))
SetSize(new Vector3(0.45f, 0.6f, (float)tmpOSD.AsReal()));
try try
{ {
// Wearables // Wearables
OSD tmpOSD8; SetDefaultWearables();
OSDArray wears8 = null; if ((data != null) && (data["wearables"] != null) && (data["wearables"]).Type == OSDType.Array)
int wears8Count = 0;
if (data.TryGetValue("wrbls8", out tmpOSD8) && (tmpOSD8 is OSDArray))
{ {
wears8 = (OSDArray)tmpOSD8; OSDArray wears = (OSDArray)(data["wearables"]);
wears8Count = wears8.Count;
}
if (data.TryGetValue("wearables", out tmpOSD) && (tmpOSD is OSDArray)) int count = wears.Count;
{
OSDArray wears = (OSDArray)tmpOSD;
if(wears.Count + wears8Count > 0)
{
m_wearables = new AvatarWearable[wears.Count + wears8Count];
for (int i = 0; i < wears.Count; ++i) m_wearables = new AvatarWearable[count];
for (int i = 0; i < count; i++)
m_wearables[i] = new AvatarWearable((OSDArray)wears[i]); m_wearables[i] = new AvatarWearable((OSDArray)wears[i]);
if (wears8Count > 0) }
else
{ {
for (int i = 0; i < wears8Count; ++i) m_log.Warn("[AVATAR APPEARANCE]: failed to unpack wearables");
m_wearables[i + wears.Count] = new AvatarWearable((OSDArray)wears8[i]);
}
}
} }
if (data.TryGetValue("te8", out tmpOSD)) // Avatar Textures
SetDefaultTexture();
if ((data != null) && (data["textures"] != null) && (data["textures"]).Type == OSDType.Array)
{ {
byte[] teb = tmpOSD.AsBinary(); OSDArray textures = (OSDArray)(data["textures"]);
Primitive.TextureEntry te = new Primitive.TextureEntry(teb, 0, teb.Length); for (int i = 0; i < AvatarAppearance.TEXTURE_COUNT && i < textures.Count; i++)
m_texture = te; {
UUID textureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE;
if (textures[i] != null)
textureID = textures[i].AsUUID();
m_texture.CreateFace((uint)i).TextureID = new UUID(textureID);
} }
else if (data.TryGetValue("textures", out tmpOSD) && (tmpOSD is OSDArray))
{
OSDArray textures = (OSDArray)tmpOSD;
for (int i = 0; i < textures.Count && i < TEXTURE_COUNT_PV7; ++i)
{
tmpOSD = textures[i];
if (tmpOSD != null)
m_texture.CreateFace((uint)i).TextureID = tmpOSD.AsUUID();
} }
else
{
m_log.Warn("[AVATAR APPEARANCE]: failed to unpack textures");
} }
if (data.TryGetValue("bakedcache", out tmpOSD) && (tmpOSD is OSDArray)) if ((data != null) && (data["bakedcache"] != null) && (data["bakedcache"]).Type == OSDType.Array)
{ {
OSDArray bakedOSDArray = (OSDArray)tmpOSD; OSDArray bakedOSDArray = (OSDArray)(data["bakedcache"]);
m_cacheitems = WearableCacheItem.GetDefaultCacheItem(); m_cacheitems = WearableCacheItem.BakedFromOSD(bakedOSDArray);
bakedOSDArray = (OSDArray)tmpOSD;
foreach (OSDMap item in bakedOSDArray)
{
int idx = item["textureindex"].AsInteger();
if (idx < 0 || idx >= m_cacheitems.Length)
continue;
m_cacheitems[idx].CacheId = item["cacheid"].AsUUID();
m_cacheitems[idx].TextureID = item["textureid"].AsUUID();
m_cacheitems[idx].TextureAsset = null;
}
if (data.TryGetValue("bc8", out tmpOSD) && (tmpOSD is OSDArray))
{
bakedOSDArray = (OSDArray)tmpOSD;
foreach (OSDMap item in bakedOSDArray)
{
int idx = item["textureindex"].AsInteger();
if (idx < 0 || idx >= m_cacheitems.Length)
continue;
m_cacheitems[idx].CacheId = item["cacheid"].AsUUID();
m_cacheitems[idx].TextureID = item["textureid"].AsUUID();
m_cacheitems[idx].TextureAsset = null;
}
}
} }
// Visual Parameters // Visual Parameters
if (data.TryGetValue("visualparams", out tmpOSD)) SetDefaultParams();
if ((data != null) && (data["visualparams"] != null))
{ {
if (tmpOSD is OSDBinary || tmpOSD is OSDArray) if ((data["visualparams"].Type == OSDType.Binary) || (data["visualparams"].Type == OSDType.Array))
m_visualparams = tmpOSD.AsBinary(); m_visualparams = data["visualparams"].AsBinary();
} }
else else
{ {
@ -996,9 +859,10 @@ namespace OpenSim.Framework
} }
// Attachments // Attachments
if (data.TryGetValue("attachments", out tmpOSD) && tmpOSD is OSDArray) m_attachments = new Dictionary<int, List<AvatarAttachment>>();
if ((data != null) && (data["attachments"] != null) && (data["attachments"]).Type == OSDType.Array)
{ {
OSDArray attachs = (OSDArray)tmpOSD; OSDArray attachs = (OSDArray)(data["attachments"]);
for (int i = 0; i < attachs.Count; i++) for (int i = 0; i < attachs.Count; i++)
{ {
AvatarAttachment att = new AvatarAttachment((OSDMap)attachs[i]); AvatarAttachment att = new AvatarAttachment((OSDMap)attachs[i]);
@ -1018,32 +882,6 @@ namespace OpenSim.Framework
#endregion #endregion
public bool CanTeleport(float version)
{
if (version >= 0.8)
return true;
if (m_wearables.Length <= MAXWEARABLE_PV7)
return true;
for(int i = MAXWEARABLE_PV7; i < m_wearables.Length; ++i)
{
if(m_wearables[i].Count > 0)
return false;
}
// also check baked
for (int i = BAKES_COUNT_PV7; i < BAKE_INDICES.Length; i++)
{
int idx = BAKE_INDICES[i];
if (m_texture.FaceTextures[idx] == null)
continue;
if (m_texture.FaceTextures[idx].TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE ||
m_texture.FaceTextures[idx].TextureID == UUID.Zero)
continue;
return false;
}
return true;
}
#region VPElement #region VPElement
/// <summary> /// <summary>

View File

@ -68,18 +68,11 @@ namespace OpenSim.Framework
public void Unpack(OSDMap args) public void Unpack(OSDMap args)
{ {
OSD tmpOSD; if (args["point"] != null)
if (args.TryGetValue("point", out tmpOSD)) AttachPoint = args["point"].AsInteger();
AttachPoint = tmpOSD.AsInteger();
if (args.TryGetValue("item", out tmpOSD))
ItemID = tmpOSD.AsUUID();
else
ItemID = UUID.Zero;
if (args.TryGetValue("asset", out tmpOSD)) ItemID = (args["item"] != null) ? args["item"].AsUUID() : UUID.Zero;
AssetID = tmpOSD.AsUUID(); AssetID = (args["asset"] != null) ? args["asset"].AsUUID() : UUID.Zero;
else
AssetID = UUID.Zero;
} }
} }
} }

View File

@ -67,14 +67,10 @@ namespace OpenSim.Framework
public static readonly int ALPHA = 13; public static readonly int ALPHA = 13;
public static readonly int TATTOO = 14; public static readonly int TATTOO = 14;
public static readonly int LEGACY_VERSION_MAX_WEARABLES = 15; public static readonly int LEGACY_VERSION_MAX_WEARABLES = 15;
// public static readonly int PHYSICS = 15;
public static readonly int PHYSICS = 15; // public static int MAX_WEARABLES = 16;
public static int MAX_WEARABLES_PV7 = 16;
public static readonly int UNIVERSAL = 16;
public static int MAX_WEARABLES = 17;
public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9"); public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9");
@ -95,11 +91,11 @@ namespace OpenSim.Framework
public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111"); public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111");
public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120"); public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120");
public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8"); // public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8");
public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594"); // public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594");
public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1"); // public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1");
public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007"); // public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007");
protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>(); protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>();
protected List<UUID> m_ids = new List<UUID>(); protected List<UUID> m_ids = new List<UUID>();
@ -136,12 +132,10 @@ namespace OpenSim.Framework
public void Unpack(OSDArray args) public void Unpack(OSDArray args)
{ {
Clear(); Clear();
OSD tmpOSDA, tmpOSDB;
foreach (OSDMap weardata in args) foreach (OSDMap weardata in args)
{ {
tmpOSDA = weardata["item"]; Add(weardata["item"].AsUUID(), weardata["asset"].AsUUID());
tmpOSDB = weardata["asset"];
Add(tmpOSDA.AsUUID(), tmpOSDB.AsUUID());
} }
} }

View File

@ -0,0 +1,148 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Threading;
namespace OpenSim.Framework
{
public class BlockingQueue<T>
{
private readonly Queue<T> m_pqueue = new Queue<T>();
private readonly Queue<T> m_queue = new Queue<T>();
private readonly object m_queueSync = new object();
public void PriorityEnqueue(T value)
{
lock (m_queueSync)
{
m_pqueue.Enqueue(value);
Monitor.Pulse(m_queueSync);
}
}
public void Enqueue(T value)
{
lock (m_queueSync)
{
m_queue.Enqueue(value);
Monitor.Pulse(m_queueSync);
}
}
public T Dequeue()
{
lock (m_queueSync)
{
while (m_queue.Count < 1 && m_pqueue.Count < 1)
{
Monitor.Wait(m_queueSync);
}
if (m_pqueue.Count > 0)
return m_pqueue.Dequeue();
if (m_queue.Count > 0)
return m_queue.Dequeue();
return default(T);
}
}
public T Dequeue(int msTimeout)
{
lock (m_queueSync)
{
if (m_queue.Count < 1 && m_pqueue.Count < 1)
{
if(!Monitor.Wait(m_queueSync, msTimeout))
return default(T);
}
if (m_pqueue.Count > 0)
return m_pqueue.Dequeue();
if (m_queue.Count > 0)
return m_queue.Dequeue();
return default(T);
}
}
/// <summary>
/// Indicate whether this queue contains the given item.
/// </summary>
/// <remarks>
/// This method is not thread-safe. Do not rely on the result without consistent external locking.
/// </remarks>
public bool Contains(T item)
{
lock (m_queueSync)
{
if (m_queue.Count < 1 && m_pqueue.Count < 1)
return false;
if (m_pqueue.Contains(item))
return true;
return m_queue.Contains(item);
}
}
/// <summary>
/// Return a count of the number of requests on this queue.
/// </summary>
public int Count()
{
lock (m_queueSync)
return m_queue.Count + m_pqueue.Count;
}
/// <summary>
/// Return the array of items on this queue.
/// </summary>
/// <remarks>
/// This method is not thread-safe. Do not rely on the result without consistent external locking.
/// </remarks>
public T[] GetQueueArray()
{
lock (m_queueSync)
{
if (m_queue.Count < 1 && m_pqueue.Count < 1)
return new T[0];
return m_queue.ToArray();
}
}
public void Clear()
{
lock (m_queueSync)
{
m_pqueue.Clear();
m_queue.Clear();
Monitor.Pulse(m_queueSync);
}
}
}
}

View File

@ -38,7 +38,6 @@ namespace OpenSim.Framework
DebugChannel = 6, DebugChannel = 6,
Region = 7, Region = 7,
Owner = 8, Owner = 8,
Direct = 9, //llRegionSayTo
Broadcast = 0xFF Broadcast = 0xFF
} }
} }

View File

@ -398,8 +398,7 @@ namespace OpenSim.Framework
// Scripted // Scripted
public ControllerData[] Controllers; public ControllerData[] Controllers;
public string CallbackURI; // to remove public string CallbackURI;
public string NewCallbackURI;
// These two must have the same Count // These two must have the same Count
public List<ISceneObject> AttachmentObjects; public List<ISceneObject> AttachmentObjects;
@ -529,9 +528,6 @@ namespace OpenSim.Framework
if ((CallbackURI != null) && (!CallbackURI.Equals(""))) if ((CallbackURI != null) && (!CallbackURI.Equals("")))
args["callback_uri"] = OSD.FromString(CallbackURI); args["callback_uri"] = OSD.FromString(CallbackURI);
if ((NewCallbackURI != null) && (!NewCallbackURI.Equals("")))
args["cb_uri"] = OSD.FromString(NewCallbackURI);
// Attachment objects for fatpack messages // Attachment objects for fatpack messages
if (AttachmentObjects != null) if (AttachmentObjects != null)
{ {
@ -571,141 +567,145 @@ namespace OpenSim.Framework
public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx) public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
{ {
//m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Unpack data"); //m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Unpack data");
OSD tmp;
if (args.TryGetValue("region_id", out tmp) && tmp != null)
UUID.TryParse(tmp.AsString(), out RegionID);
if (args.TryGetValue("circuit_code", out tmp) && tmp != null) if (args.ContainsKey("region_id"))
UInt32.TryParse(tmp.AsString(), out CircuitCode); UUID.TryParse(args["region_id"].AsString(), out RegionID);
if (args.TryGetValue("agent_uuid", out tmp) && tmp != null) if (args["circuit_code"] != null)
AgentID = tmp.AsUUID(); UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
if (args.TryGetValue("session_uuid", out tmp) && tmp != null) if (args["agent_uuid"] != null)
SessionID = tmp.AsUUID(); AgentID = args["agent_uuid"].AsUUID();
if (args.TryGetValue("position", out tmp) && tmp != null) if (args["session_uuid"] != null)
Vector3.TryParse(tmp.AsString(), out Position); SessionID = args["session_uuid"].AsUUID();
if (args.TryGetValue("velocity", out tmp) && tmp != null) if (args["position"] != null)
Vector3.TryParse(tmp.AsString(), out Velocity); Vector3.TryParse(args["position"].AsString(), out Position);
if (args.TryGetValue("center", out tmp) && tmp != null) if (args["velocity"] != null)
Vector3.TryParse(tmp.AsString(), out Center); Vector3.TryParse(args["velocity"].AsString(), out Velocity);
if (args.TryGetValue("size", out tmp) && tmp != null) if (args["center"] != null)
Vector3.TryParse(tmp.AsString(), out Size); Vector3.TryParse(args["center"].AsString(), out Center);
if (args.TryGetValue("at_axis", out tmp) && tmp != null) if (args["size"] != null)
Vector3.TryParse(tmp.AsString(), out AtAxis); Vector3.TryParse(args["size"].AsString(), out Size);
if (args.TryGetValue("left_axis", out tmp) && tmp != null) if (args["at_axis"] != null)
Vector3.TryParse(tmp.AsString(), out AtAxis); Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
if (args.TryGetValue("up_axis", out tmp) && tmp != null) if (args["left_axis"] != null)
Vector3.TryParse(tmp.AsString(), out AtAxis); Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);
if (args.TryGetValue("wait_for_root", out tmp) && tmp != null) if (args["up_axis"] != null)
SenderWantsToWaitForRoot = tmp.AsBoolean(); Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);
if (args.TryGetValue("far", out tmp) && tmp != null) if (args.ContainsKey("wait_for_root") && args["wait_for_root"] != null)
Far = (float)(tmp.AsReal()); SenderWantsToWaitForRoot = args["wait_for_root"].AsBoolean();
if (args.TryGetValue("aspect", out tmp) && tmp != null) if (args["far"] != null)
Aspect = (float)tmp.AsReal(); Far = (float)(args["far"].AsReal());
if (args.TryGetValue("throttles", out tmp) && tmp != null) if (args["aspect"] != null)
Throttles = tmp.AsBinary(); Aspect = (float)args["aspect"].AsReal();
if (args.TryGetValue("locomotion_state", out tmp) && tmp != null) if (args["throttles"] != null)
UInt32.TryParse(tmp.AsString(), out LocomotionState); Throttles = args["throttles"].AsBinary();
if (args.TryGetValue("head_rotation", out tmp) && tmp != null) if (args["locomotion_state"] != null)
Quaternion.TryParse(tmp.AsString(), out HeadRotation); UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState);
if (args.TryGetValue("body_rotation", out tmp) && tmp != null) if (args["head_rotation"] != null)
Quaternion.TryParse(tmp.AsString(), out BodyRotation); Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation);
if (args.TryGetValue("control_flags", out tmp) && tmp != null) if (args["body_rotation"] != null)
UInt32.TryParse(tmp.AsString(), out ControlFlags); Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation);
if (args.TryGetValue("energy_level", out tmp) && tmp != null) if (args["control_flags"] != null)
EnergyLevel = (float)(tmp.AsReal()); UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags);
if (args.TryGetValue("god_data", out tmp) && tmp != null) if (args["energy_level"] != null)
GodData = tmp; EnergyLevel = (float)(args["energy_level"].AsReal());
if (args.TryGetValue("always_run", out tmp) && tmp != null) //if (args["god_level"] != null)
AlwaysRun = tmp.AsBoolean(); // Byte.TryParse(args["god_level"].AsString(), out GodLevel);
if (args.TryGetValue("prey_agent", out tmp) && tmp != null) if (args.ContainsKey("god_data") && args["god_data"] != null)
PreyAgent = tmp.AsUUID(); GodData = args["god_data"];
if (args.TryGetValue("agent_access", out tmp) && tmp != null) if (args["always_run"] != null)
Byte.TryParse(tmp.AsString(), out AgentAccess); AlwaysRun = args["always_run"].AsBoolean();
if (args.TryGetValue("agent_cof", out tmp) && tmp != null) if (args["prey_agent"] != null)
agentCOF = tmp.AsUUID(); PreyAgent = args["prey_agent"].AsUUID();
if (args.TryGetValue("crossingflags", out tmp) && tmp != null) if (args["agent_access"] != null)
CrossingFlags = (byte)tmp.AsInteger(); Byte.TryParse(args["agent_access"].AsString(), out AgentAccess);
if (args.ContainsKey("agent_cof") && args["agent_cof"] != null)
agentCOF = args["agent_cof"].AsUUID();
if (args.ContainsKey("crossingflags") && args["crossingflags"] != null)
CrossingFlags = (byte)args["crossingflags"].AsInteger();
if(CrossingFlags != 0) if(CrossingFlags != 0)
{ {
if (args.TryGetValue("crossExtraFlags", out tmp) && tmp != null) if (args.ContainsKey("crossExtraFlags") && args["crossExtraFlags"] != null)
CrossExtraFlags = (byte)tmp.AsInteger(); CrossExtraFlags = (byte)args["crossExtraFlags"].AsInteger();
} }
if (args.TryGetValue("active_group_id", out tmp) && tmp != null) if (args.ContainsKey("active_group_id") && args["active_group_id"] != null)
ActiveGroupID = tmp.AsUUID(); ActiveGroupID = args["active_group_id"].AsUUID();
if (args.TryGetValue("active_group_name", out tmp) && tmp != null) if (args.ContainsKey("active_group_name") && args["active_group_name"] != null)
ActiveGroupName = tmp.AsString(); ActiveGroupName = args["active_group_name"].AsString();
if(args.TryGetValue("active_group_title", out tmp) && tmp != null) if(args.ContainsKey("active_group_title") && args["active_group_title"] != null)
ActiveGroupTitle = tmp.AsString(); ActiveGroupTitle = args["active_group_title"].AsString();
if (args.TryGetValue("children_seeds", out tmp) && tmp is OSDArray) if (args.ContainsKey("children_seeds") && (args["children_seeds"] != null) &&
(args["children_seeds"].Type == OSDType.Array))
{ {
OSDArray childrenSeeds = (OSDArray)tmp; OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
ChildrenCapSeeds = new Dictionary<ulong, string>(); ChildrenCapSeeds = new Dictionary<ulong, string>();
foreach (OSD o in childrenSeeds) foreach (OSD o in childrenSeeds)
{ {
if (o is OSDMap) if (o.Type == OSDType.Map)
{ {
ulong handle = 0; ulong handle = 0;
string seed = ""; string seed = "";
OSDMap pair = (OSDMap)o; OSDMap pair = (OSDMap)o;
if (pair.TryGetValue("handle", out tmp)) if (pair["handle"] != null)
if (!UInt64.TryParse(tmp.AsString(), out handle)) if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
continue; continue;
if (pair.TryGetValue("seed", out tmp)) if (pair["seed"] != null)
seed = tmp.AsString(); seed = pair["seed"].AsString();
if (!ChildrenCapSeeds.ContainsKey(handle)) if (!ChildrenCapSeeds.ContainsKey(handle))
ChildrenCapSeeds.Add(handle, seed); ChildrenCapSeeds.Add(handle, seed);
} }
} }
} }
if (args.TryGetValue("animations", out tmp) && tmp is OSDArray) if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array)
{ {
OSDArray anims = (OSDArray)tmp; OSDArray anims = (OSDArray)(args["animations"]);
Anims = new Animation[anims.Count]; Anims = new Animation[anims.Count];
int i = 0; int i = 0;
foreach (OSD o in anims) foreach (OSD o in anims)
{ {
if (o is OSDMap) if (o.Type == OSDType.Map)
{ {
Anims[i++] = new Animation((OSDMap)o); Anims[i++] = new Animation((OSDMap)o);
} }
} }
} }
if (args.TryGetValue("default_animation", out tmp) && tmp is OSDMap) if (args["default_animation"] != null)
{ {
try try
{ {
DefaultAnim = new Animation((OSDMap)tmp); DefaultAnim = new Animation((OSDMap)args["default_animation"]);
} }
catch catch
{ {
@ -713,11 +713,11 @@ namespace OpenSim.Framework
} }
} }
if (args.TryGetValue("animation_state", out tmp) && tmp is OSDMap) if (args["animation_state"] != null)
{ {
try try
{ {
AnimState = new Animation((OSDMap)tmp); AnimState = new Animation((OSDMap)args["animation_state"]);
} }
catch catch
{ {
@ -727,9 +727,9 @@ namespace OpenSim.Framework
MovementAnimationOverRides.Clear(); MovementAnimationOverRides.Clear();
if (args.TryGetValue("movementAO", out tmp) && tmp is OSDArray) if (args["movementAO"] != null && args["movementAO"].Type == OSDType.Array)
{ {
OSDArray AOs = (OSDArray)tmp; OSDArray AOs = (OSDArray)(args["movementAO"]);
int count = AOs.Count; int count = AOs.Count;
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
@ -744,8 +744,8 @@ namespace OpenSim.Framework
} }
} }
if (args.TryGetValue("motion_state", out tmp) && tmp != null) if (args.ContainsKey("motion_state"))
MotionState = (byte)tmp.AsInteger(); MotionState = (byte)args["motion_state"].AsInteger();
//if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array) //if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array)
//{ //{
@ -758,10 +758,10 @@ namespace OpenSim.Framework
// packed_appearence should contain all appearance information // packed_appearence should contain all appearance information
if (args.TryGetValue("packed_appearance", out tmp) && tmp is OSDMap) if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map)
{ {
m_log.WarnFormat("[CHILDAGENTDATAUPDATE] got packed appearance"); m_log.WarnFormat("[CHILDAGENTDATAUPDATE] got packed appearance");
Appearance = new AvatarAppearance((OSDMap)tmp); Appearance = new AvatarAppearance((OSDMap)args["packed_appearance"]);
} }
else else
{ {
@ -773,19 +773,19 @@ namespace OpenSim.Framework
// The code to unpack textures, visuals, wearables and attachments // The code to unpack textures, visuals, wearables and attachments
// should be removed; packed appearance contains the full appearance // should be removed; packed appearance contains the full appearance
// This is retained for backward compatibility only // This is retained for backward compatibility only
if (args.TryGetValue("texture_entry", out tmp) && tmp != null) if (args["texture_entry"] != null)
{ {
byte[] rawtextures = tmp.AsBinary(); byte[] rawtextures = args["texture_entry"].AsBinary();
Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures, 0, rawtextures.Length); Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures, 0, rawtextures.Length);
Appearance.SetTextureEntries(textures); Appearance.SetTextureEntries(textures);
} }
if (args.TryGetValue("visual_params", out tmp) && tmp != null) if (args["visual_params"] != null)
Appearance.SetVisualParams(tmp.AsBinary()); Appearance.SetVisualParams(args["visual_params"].AsBinary());
if (args.TryGetValue("wearables", out tmp) && tmp is OSDArray) if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array)
{ {
OSDArray wears = (OSDArray)tmp; OSDArray wears = (OSDArray)(args["wearables"]);
for (int i = 0; i < wears.Count / 2; i++) for (int i = 0; i < wears.Count / 2; i++)
{ {
@ -794,12 +794,12 @@ namespace OpenSim.Framework
} }
} }
if (args.TryGetValue("attachments", out tmp) && tmp is OSDArray) if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array)
{ {
OSDArray attachs = (OSDArray)tmp; OSDArray attachs = (OSDArray)(args["attachments"]);
foreach (OSD o in attachs) foreach (OSD o in attachs)
{ {
if (o is OSDMap) if (o.Type == OSDType.Map)
{ {
// We know all of these must end up as attachments so we // We know all of these must end up as attachments so we
// append rather than replace to ensure multiple attachments // append rather than replace to ensure multiple attachments
@ -811,36 +811,38 @@ namespace OpenSim.Framework
} }
// end of code to remove // end of code to remove
} }
/* moved above
if (args.TryGetValue("controllers", out tmp) && tmp is OSDArray) if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map)
Appearance = new AvatarAppearance((OSDMap)args["packed_appearance"]);
else
m_log.WarnFormat("[CHILDAGENTDATAUPDATE] No packed appearance");
*/
if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array)
{ {
OSDArray controls = (OSDArray)tmp; OSDArray controls = (OSDArray)(args["controllers"]);
Controllers = new ControllerData[controls.Count]; Controllers = new ControllerData[controls.Count];
int i = 0; int i = 0;
foreach (OSD o in controls) foreach (OSD o in controls)
{ {
if (o is OSDMap) if (o.Type == OSDType.Map)
{ {
Controllers[i++] = new ControllerData((OSDMap)o); Controllers[i++] = new ControllerData((OSDMap)o);
} }
} }
} }
if (args.TryGetValue("callback_uri", out tmp) && tmp != null) if (args["callback_uri"] != null)
CallbackURI = tmp.AsString(); CallbackURI = args["callback_uri"].AsString();
if (args.TryGetValue("cb_uri", out tmp) && tmp != null)
NewCallbackURI = tmp.AsString();
// Attachment objects // Attachment objects
if (args.TryGetValue("attach_objects", out tmp) && tmp is OSDArray) if (args["attach_objects"] != null && args["attach_objects"].Type == OSDType.Array)
{ {
OSDArray attObjs = (OSDArray)tmp; OSDArray attObjs = (OSDArray)(args["attach_objects"]);
AttachmentObjects = new List<ISceneObject>(); AttachmentObjects = new List<ISceneObject>();
AttachmentObjectStates = new List<string>(); AttachmentObjectStates = new List<string>();
foreach (OSD o in attObjs) foreach (OSD o in attObjs)
{ {
if (o is OSDMap) if (o.Type == OSDType.Map)
{ {
OSDMap info = (OSDMap)o; OSDMap info = (OSDMap)o;
ISceneObject so = scene.DeserializeObject(info["sog"].AsString()); ISceneObject so = scene.DeserializeObject(info["sog"].AsString());
@ -852,10 +854,10 @@ namespace OpenSim.Framework
} }
} }
if (args.TryGetValue("parent_part", out tmp) && tmp != null) if (args["parent_part"] != null)
ParentPart = tmp.AsUUID(); ParentPart = args["parent_part"].AsUUID();
if (args.TryGetValue("sit_offset", out tmp) && tmp != null) if (args["sit_offset"] != null)
Vector3.TryParse(tmp.AsString(), out SitOffset); Vector3.TryParse(args["sit_offset"].AsString(), out SitOffset);
} }
public AgentData() public AgentData()

View File

@ -51,14 +51,7 @@ namespace OpenSim.Framework
private object m_syncRoot = new object(); private object m_syncRoot = new object();
/// <summary>Number of clients in the collection</summary> /// <summary>Number of clients in the collection</summary>
public int Count public int Count { get { return m_dict1.Count; } }
{
get
{
lock (m_syncRoot)
return m_dict1.Count;
}
}
/// <summary> /// <summary>
/// Default constructor /// Default constructor
@ -67,7 +60,7 @@ namespace OpenSim.Framework
{ {
m_dict1 = new Dictionary<UUID, IClientAPI>(); m_dict1 = new Dictionary<UUID, IClientAPI>();
m_dict2 = new Dictionary<IPEndPoint, IClientAPI>(); m_dict2 = new Dictionary<IPEndPoint, IClientAPI>();
m_array = null; m_array = new IClientAPI[0];
} }
/// <summary> /// <summary>
@ -81,9 +74,17 @@ namespace OpenSim.Framework
{ {
lock (m_syncRoot) lock (m_syncRoot)
{ {
// allow self healing
// if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint))
// return false;
m_dict1[value.AgentId] = value; m_dict1[value.AgentId] = value;
m_dict2[value.RemoteEndPoint] = value; m_dict2[value.RemoteEndPoint] = value;
m_array = null;
// dict1 is the master
IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
m_dict1.Values.CopyTo(newArray, 0);
m_array = newArray;
} }
return true; return true;
@ -104,7 +105,10 @@ namespace OpenSim.Framework
{ {
m_dict1.Remove(key); m_dict1.Remove(key);
m_dict2.Remove(value.RemoteEndPoint); m_dict2.Remove(value.RemoteEndPoint);
m_array = null;
IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
m_dict1.Values.CopyTo(newArray, 0);
m_array = newArray;
return true; return true;
} }
} }
@ -120,7 +124,7 @@ namespace OpenSim.Framework
{ {
m_dict1.Clear(); m_dict1.Clear();
m_dict2.Clear(); m_dict2.Clear();
m_array = null; m_array = new IClientAPI[0];
} }
} }
@ -131,7 +135,6 @@ namespace OpenSim.Framework
/// <returns>True if the UUID was found in the collection, otherwise false</returns> /// <returns>True if the UUID was found in the collection, otherwise false</returns>
public bool ContainsKey(UUID key) public bool ContainsKey(UUID key)
{ {
lock (m_syncRoot)
return m_dict1.ContainsKey(key); return m_dict1.ContainsKey(key);
} }
@ -142,7 +145,6 @@ namespace OpenSim.Framework
/// <returns>True if the endpoint was found in the collection, otherwise false</returns> /// <returns>True if the endpoint was found in the collection, otherwise false</returns>
public bool ContainsKey(IPEndPoint key) public bool ContainsKey(IPEndPoint key)
{ {
lock (m_syncRoot)
return m_dict2.ContainsKey(key); return m_dict2.ContainsKey(key);
} }
@ -154,12 +156,8 @@ namespace OpenSim.Framework
/// <returns>True if the lookup succeeded, otherwise false</returns> /// <returns>True if the lookup succeeded, otherwise false</returns>
public bool TryGetValue(UUID key, out IClientAPI value) public bool TryGetValue(UUID key, out IClientAPI value)
{ {
try try { return m_dict1.TryGetValue(key, out value); }
{ catch (Exception)
lock (m_syncRoot)
return m_dict1.TryGetValue(key, out value);
}
catch
{ {
value = null; value = null;
return false; return false;
@ -174,12 +172,8 @@ namespace OpenSim.Framework
/// <returns>True if the lookup succeeded, otherwise false</returns> /// <returns>True if the lookup succeeded, otherwise false</returns>
public bool TryGetValue(IPEndPoint key, out IClientAPI value) public bool TryGetValue(IPEndPoint key, out IClientAPI value)
{ {
try try { return m_dict2.TryGetValue(key, out value); }
{ catch (Exception)
lock (m_syncRoot)
return m_dict2.TryGetValue(key, out value);
}
catch
{ {
value = null; value = null;
return false; return false;
@ -193,20 +187,7 @@ namespace OpenSim.Framework
/// <param name="action">Action to perform on each element</param> /// <param name="action">Action to perform on each element</param>
public void ForEach(Action<IClientAPI> action) public void ForEach(Action<IClientAPI> action)
{ {
IClientAPI[] localArray; IClientAPI[] localArray = m_array;
lock (m_syncRoot)
{
if (m_array == null)
{
if (m_dict1.Count == 0)
return;
m_array = new IClientAPI[m_dict1.Count];
m_dict1.Values.CopyTo(m_array, 0);
}
localArray = m_array;
}
for (int i = 0; i < localArray.Length; i++) for (int i = 0; i < localArray.Length; i++)
action(localArray[i]); action(localArray[i]);
} }

4
OpenSim/Framework/ConfigurationMember.cs Executable file → Normal file
View File

@ -262,14 +262,14 @@ namespace OpenSim.Framework
if (configurationDescription.Trim() != String.Empty) if (configurationDescription.Trim() != String.Empty)
{ {
console_result = console_result =
MainConsole.Instance.Prompt( MainConsole.Instance.CmdPrompt(
configurationDescription + ": " + configOption.configurationQuestion, configurationDescription + ": " + configOption.configurationQuestion,
configOption.configurationDefault); configOption.configurationDefault);
} }
else else
{ {
console_result = console_result =
MainConsole.Instance.Prompt(configOption.configurationQuestion, MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
configOption.configurationDefault); configOption.configurationDefault);
} }
} }

5
OpenSim/Framework/Console/CommandConsole.cs Executable file → Normal file
View File

@ -36,7 +36,6 @@ using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using log4net; using log4net;
using OpenSim.Framework; using OpenSim.Framework;
using Nini.Config;
namespace OpenSim.Framework.Console namespace OpenSim.Framework.Console
{ {
@ -790,9 +789,5 @@ namespace OpenSim.Framework.Console
} }
return cmdinput; return cmdinput;
} }
public virtual void ReadConfig(IConfigSource configSource)
{
}
} }
} }

View File

@ -35,39 +35,13 @@ using log4net;
namespace OpenSim.Framework.Console namespace OpenSim.Framework.Console
{ {
public class ConsoleLevel public class ConsoleBase
{
public string m_string;
ConsoleLevel(string v)
{
m_string = v;
}
static public implicit operator ConsoleLevel(string s)
{
return new ConsoleLevel(s);
}
public static string ToString(ConsoleLevel s)
{
return s.m_string;
}
public override string ToString()
{
return m_string;
}
}
public class ConsoleBase : IConsole
{ {
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string prompt = "# "; protected string prompt = "# ";
public IScene ConsoleScene { get; set; } public object ConsoleScene { get; set; }
public string DefaultPrompt { get; set; } public string DefaultPrompt { get; set; }
@ -84,47 +58,27 @@ namespace OpenSim.Framework.Console
{ {
} }
public virtual void Output(string format) public virtual void Output(string text, string level)
{ {
System.Console.WriteLine(format); Output(text);
} }
public virtual void Output(string format, params object[] components) public virtual void Output(string text)
{ {
string level = null;
if (components != null && components.Length > 0)
{
if (components[0] == null || components[0] is ConsoleLevel)
{
if (components[0] is ConsoleLevel)
level = ((ConsoleLevel)components[0]).ToString();
if (components.Length > 1)
{
object[] tmp = new object[components.Length - 1];
Array.Copy(components, 1, tmp, 0, components.Length - 1);
components = tmp;
}
else
components = null;
}
}
string text;
if (components == null || components.Length == 0)
text = format;
else
text = String.Format(format, components);
System.Console.WriteLine(text); System.Console.WriteLine(text);
} }
public string Prompt(string p) public virtual void OutputFormat(string format, params object[] components)
{
Output(string.Format(format, components));
}
public string CmdPrompt(string p)
{ {
return ReadLine(String.Format("{0}: ", p), false, true); return ReadLine(String.Format("{0}: ", p), false, true);
} }
public string Prompt(string p, string def) public string CmdPrompt(string p, string def)
{ {
string ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, true); string ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, true);
if (ret == String.Empty) if (ret == String.Empty)
@ -133,14 +87,14 @@ namespace OpenSim.Framework.Console
return ret; return ret;
} }
public string Prompt(string p, List<char> excludedCharacters) public string CmdPrompt(string p, List<char> excludedCharacters)
{ {
bool itisdone = false; bool itisdone = false;
string ret = String.Empty; string ret = String.Empty;
while (!itisdone) while (!itisdone)
{ {
itisdone = true; itisdone = true;
ret = Prompt(p); ret = CmdPrompt(p);
foreach (char c in excludedCharacters) foreach (char c in excludedCharacters)
{ {
@ -155,26 +109,20 @@ namespace OpenSim.Framework.Console
return ret; return ret;
} }
public virtual string Prompt(string p, string def, List<char> excludedCharacters, bool echo = true) public string CmdPrompt(string p, string def, List<char> excludedCharacters)
{ {
bool itisdone = false; bool itisdone = false;
string ret = String.Empty; string ret = String.Empty;
while (!itisdone) while (!itisdone)
{ {
itisdone = true; itisdone = true;
ret = CmdPrompt(p, def);
if (def == null) if (ret == String.Empty)
ret = ReadLine(String.Format("{0}: ", p), false, echo);
else
ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, echo);
if (ret == String.Empty && def != null)
{ {
ret = def; ret = def;
} }
else else
{
if (excludedCharacters != null)
{ {
foreach (char c in excludedCharacters) foreach (char c in excludedCharacters)
{ {
@ -186,20 +134,19 @@ namespace OpenSim.Framework.Console
} }
} }
} }
}
return ret; return ret;
} }
// Displays a command prompt and returns a default value, user may only enter 1 of 2 options // Displays a command prompt and returns a default value, user may only enter 1 of 2 options
public virtual string Prompt(string prompt, string defaultresponse, List<string> options) public string CmdPrompt(string prompt, string defaultresponse, List<string> options)
{ {
bool itisdone = false; bool itisdone = false;
string optstr = String.Empty; string optstr = String.Empty;
foreach (string s in options) foreach (string s in options)
optstr += " " + s; optstr += " " + s;
string temp = Prompt(prompt, defaultresponse); string temp = CmdPrompt(prompt, defaultresponse);
while (itisdone == false) while (itisdone == false)
{ {
if (options.Contains(temp)) if (options.Contains(temp))
@ -209,12 +156,19 @@ namespace OpenSim.Framework.Console
else else
{ {
System.Console.WriteLine("Valid options are" + optstr); System.Console.WriteLine("Valid options are" + optstr);
temp = Prompt(prompt, defaultresponse); temp = CmdPrompt(prompt, defaultresponse);
} }
} }
return temp; return temp;
} }
// Displays a prompt and waits for the user to enter a string, then returns that string
// (Done with no echo and suitable for passwords)
public string PasswdPrompt(string p)
{
return ReadLine(String.Format("{0}: ", p), false, false);
}
public virtual string ReadLine(string p, bool isCommand, bool e) public virtual string ReadLine(string p, bool isCommand, bool e)
{ {
System.Console.Write("{0}", p); System.Console.Write("{0}", p);

20
OpenSim/Framework/Console/ConsoleUtil.cs Executable file → Normal file
View File

@ -75,7 +75,7 @@ namespace OpenSim.Framework.Console
{ {
if (File.Exists(path)) if (File.Exists(path))
{ {
console.Output("File {0} already exists. Please move or remove it.", path); console.OutputFormat("File {0} already exists. Please move or remove it.", path);
return false; return false;
} }
@ -97,7 +97,7 @@ namespace OpenSim.Framework.Console
if (!UUID.TryParse(rawUuid, out uuid)) if (!UUID.TryParse(rawUuid, out uuid))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid uuid", rawUuid); console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid);
return false; return false;
} }
@ -110,7 +110,7 @@ namespace OpenSim.Framework.Console
if (!uint.TryParse(rawLocalId, out localId)) if (!uint.TryParse(rawLocalId, out localId))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid local id", localId); console.OutputFormat("ERROR: {0} is not a valid local id", localId);
return false; return false;
} }
@ -118,7 +118,7 @@ namespace OpenSim.Framework.Console
if (localId == 0) if (localId == 0)
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid local id - it must be greater than 0", localId); console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
return false; return false;
} }
@ -150,7 +150,7 @@ namespace OpenSim.Framework.Console
} }
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid UUID or local id", rawId); console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId);
return false; return false;
} }
@ -167,7 +167,7 @@ namespace OpenSim.Framework.Console
if (!bool.TryParse(rawConsoleString, out b)) if (!bool.TryParse(rawConsoleString, out b))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a true or false value", rawConsoleString); console.OutputFormat("ERROR: {0} is not a true or false value", rawConsoleString);
return false; return false;
} }
@ -187,7 +187,7 @@ namespace OpenSim.Framework.Console
if (!int.TryParse(rawConsoleInt, out i)) if (!int.TryParse(rawConsoleInt, out i))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid integer", rawConsoleInt); console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt);
return false; return false;
} }
@ -207,7 +207,7 @@ namespace OpenSim.Framework.Console
if (!float.TryParse(rawConsoleInput, out i)) if (!float.TryParse(rawConsoleInput, out i))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid float", rawConsoleInput); console.OutputFormat("ERROR: {0} is not a valid float", rawConsoleInput);
return false; return false;
} }
@ -227,7 +227,7 @@ namespace OpenSim.Framework.Console
if (!double.TryParse(rawConsoleInput, out i)) if (!double.TryParse(rawConsoleInput, out i))
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a valid double", rawConsoleInput); console.OutputFormat("ERROR: {0} is not a valid double", rawConsoleInput);
return false; return false;
} }
@ -249,7 +249,7 @@ namespace OpenSim.Framework.Console
if (i < 0) if (i < 0)
{ {
if (console != null) if (console != null)
console.Output("ERROR: {0} is not a positive integer", rawConsoleInt); console.OutputFormat("ERROR: {0} is not a positive integer", rawConsoleInt);
return false; return false;
} }

59
OpenSim/Framework/Console/LocalConsole.cs Executable file → Normal file
View File

@ -46,7 +46,6 @@ namespace OpenSim.Framework.Console
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_historyPath; private string m_historyPath;
private bool m_historyEnable; private bool m_historyEnable;
private bool m_historytimestamps;
// private readonly object m_syncRoot = new object(); // private readonly object m_syncRoot = new object();
private const string LOGLEVEL_NONE = "(none)"; private const string LOGLEVEL_NONE = "(none)";
@ -99,30 +98,15 @@ namespace OpenSim.Framework.Console
string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt"); string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100); int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile)); m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
m_historytimestamps = startupConfig.GetBoolean("ConsoleHistoryTimeStamp", false); m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1}", m_historySize, m_historyPath);
m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1} {2} timestamps",
m_historySize, m_historyPath, m_historytimestamps?"with":"without");
if (File.Exists(m_historyPath)) if (File.Exists(m_historyPath))
{ {
List<string> originallines = new List<string>();
using (StreamReader history_file = new StreamReader(m_historyPath)) using (StreamReader history_file = new StreamReader(m_historyPath))
{ {
string line; string line;
while ((line = history_file.ReadLine()) != null) while ((line = history_file.ReadLine()) != null)
{ {
originallines.Add(line);
if(line.StartsWith("["))
{
int indx = line.IndexOf("]:> ");
if(indx > 0)
{
if(indx + 4 >= line.Length)
line = String.Empty;
else
line = line.Substring(indx + 4);
}
}
m_history.Add(line); m_history.Add(line);
} }
} }
@ -130,14 +114,11 @@ namespace OpenSim.Framework.Console
if (m_history.Count > m_historySize) if (m_history.Count > m_historySize)
{ {
while (m_history.Count > m_historySize) while (m_history.Count > m_historySize)
{
m_history.RemoveAt(0); m_history.RemoveAt(0);
originallines.RemoveAt(0);
}
using (StreamWriter history_file = new StreamWriter(m_historyPath)) using (StreamWriter history_file = new StreamWriter(m_historyPath))
{ {
foreach (string line in originallines) foreach (string line in m_history)
{ {
history_file.WriteLine(line); history_file.WriteLine(line);
} }
@ -160,8 +141,6 @@ namespace OpenSim.Framework.Console
m_history.Add(text); m_history.Add(text);
if (m_historyEnable) if (m_historyEnable)
{ {
if (m_historytimestamps)
text = String.Format("[{0} {1}]:> {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), text);
File.AppendAllText(m_historyPath, text + Environment.NewLine); File.AppendAllText(m_historyPath, text + Environment.NewLine);
} }
} }
@ -359,7 +338,7 @@ namespace OpenSim.Framework.Console
{ {
string outText = text; string outText = text;
if (level != null) if (level != LOGLEVEL_NONE)
{ {
MatchCollection matches = m_categoryRegex.Matches(text); MatchCollection matches = m_categoryRegex.Matches(text);
@ -389,38 +368,13 @@ namespace OpenSim.Framework.Console
System.Console.WriteLine(); System.Console.WriteLine();
} }
public override void Output(string format) public override void Output(string text)
{ {
Output(format, null); Output(text, LOGLEVEL_NONE);
} }
public override void Output(string format, params object[] components) public override void Output(string text, string level)
{ {
string level = null;
if(components != null && components.Length > 0)
{
if(components[0] == null || components[0] is ConsoleLevel)
{
if(components[0] is ConsoleLevel)
level = ((ConsoleLevel)components[0]).ToString();
if (components.Length > 1)
{
object[] tmp = new object[components.Length - 1];
Array.Copy(components, 1, tmp, 0, components.Length - 1);
components = tmp;
}
else
components = null;
}
}
string text;
if (components == null || components.Length == 0)
text = format;
else
text = String.Format(format, components);
FireOnOutput(text); FireOnOutput(text);
lock (m_commandLine) lock (m_commandLine)
@ -428,6 +382,7 @@ namespace OpenSim.Framework.Console
if (m_cursorYPosition == -1) if (m_cursorYPosition == -1)
{ {
WriteLocalText(text, level); WriteLocalText(text, level);
return; return;
} }

20
OpenSim/Framework/Console/MockConsole.cs Executable file → Normal file
View File

@ -30,7 +30,6 @@ using System.Threading;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Xml; using System.Xml;
using Nini.Config;
namespace OpenSim.Framework.Console namespace OpenSim.Framework.Console
{ {
@ -57,24 +56,23 @@ namespace OpenSim.Framework.Console
public string ReadLine(string p, bool isCommand, bool e) { return ""; } public string ReadLine(string p, bool isCommand, bool e) { return ""; }
public IScene ConsoleScene { public object ConsoleScene {
get { return null; } get { return null; }
set {} set {}
} }
public void Output(string format) { } public void Output(string text, string level) {}
public void Output(string format, params object[] components) { } public void Output(string text) {}
public void OutputFormat(string format, params object[] components) {}
public string Prompt(string p) { return ""; } public string CmdPrompt(string p) { return ""; }
public string Prompt(string p, string def) { return ""; } public string CmdPrompt(string p, string def) { return ""; }
public string Prompt(string p, List<char> excludedCharacters) { return ""; } public string CmdPrompt(string p, List<char> excludedCharacters) { return ""; }
public string Prompt(string p, string def, List<char> excludedCharacters, bool echo) { return ""; } public string CmdPrompt(string p, string def, List<char> excludedCharacters) { return ""; }
public string Prompt(string prompt, string defaultresponse, List<string> options) { return ""; } public string CmdPrompt(string prompt, string defaultresponse, List<string> options) { return ""; }
public string PasswdPrompt(string p) { return ""; } public string PasswdPrompt(string p) { return ""; }
public void ReadConfig(IConfigSource configSource) { }
} }
public class MockCommands : ICommands public class MockCommands : ICommands

View File

@ -55,14 +55,12 @@ namespace OpenSim.Framework.Console
{ {
if (m_console != null) if (m_console != null)
{ {
ConsoleLevel level; string level = "normal";
if (le.Level == Level.Error) if (le.Level == Level.Error)
level = "error"; level = "error";
else if (le.Level == Level.Warn) else if (le.Level == Level.Warn)
level = "warn"; level = "warn";
else
level = "normal";
m_console.Output(loggingMessage, level); m_console.Output(loggingMessage, level);
} }

52
OpenSim/Framework/Console/RemoteConsole.cs Executable file → Normal file
View File

@ -46,8 +46,6 @@ namespace OpenSim.Framework.Console
// //
public class RemoteConsole : CommandConsole public class RemoteConsole : CommandConsole
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Connection specific data, indexed by a session ID // Connection specific data, indexed by a session ID
// we create when a client connects. // we create when a client connects.
protected class ConsoleConnection protected class ConsoleConnection
@ -155,7 +153,7 @@ namespace OpenSim.Framework.Console
m_expireTimer.Start(); m_expireTimer.Start();
} }
public override void ReadConfig(IConfigSource config) public void ReadConfig(IConfigSource config)
{ {
m_Config = config; m_Config = config;
@ -190,46 +188,13 @@ namespace OpenSim.Framework.Console
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand); m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
} }
public override void Output(string format) public override void Output(string text, string level)
{ {
Output(format, null);
}
public override void Output(string format, params object[] components)
{
string level = null;
if (components != null && components.Length > 0)
{
if (components[0] == null || components[0] is ConsoleLevel)
{
if (components[0] is ConsoleLevel)
level = ((ConsoleLevel)components[0]).ToString();
if (components.Length > 1)
{
object[] tmp = new object[components.Length - 1];
Array.Copy(components, 1, tmp, 0, components.Length - 1);
components = tmp;
}
else
components = null;
}
}
string text;
if (components == null || components.Length == 0)
text = format;
else
text = String.Format(format, components);
Output(text, level, false, false, false); Output(text, level, false, false, false);
} }
protected void Output(string text, string level, bool isPrompt, bool isCommand, bool isInput) protected void Output(string text, string level, bool isPrompt, bool isCommand, bool isInput)
{ {
if (level == null)
level = String.Empty;
// Increment the line number. It was 0 and they start at 1 // Increment the line number. It was 0 and they start at 1
// so we need to pre-increment. // so we need to pre-increment.
m_lineNumber++; m_lineNumber++;
@ -263,6 +228,12 @@ namespace OpenSim.Framework.Console
System.Console.WriteLine(text.Trim()); System.Console.WriteLine(text.Trim());
} }
public override void Output(string text)
{
// Output plain (non-logging style) text.
Output(text, String.Empty, false, false, false);
}
public override string ReadLine(string p, bool isCommand, bool e) public override string ReadLine(string p, bool isCommand, bool e)
{ {
// Output the prompt an prepare to wait. This // Output the prompt an prepare to wait. This
@ -429,9 +400,10 @@ namespace OpenSim.Framework.Console
} }
// This call is a CAP. The URL is the authentication. // This call is a CAP. The URL is the authentication.
string uri = "/ReadResponses/" + sessionID.ToString(); string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, null, sessionID,25000)); // 25 secs timeout m_Server.AddPollServiceHTTPHandler(
uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, sessionID,25000)); // 25 secs timeout
// Our reply is an XML document. // Our reply is an XML document.
// TODO: Change this to Linq.Xml // TODO: Change this to Linq.Xml
@ -715,6 +687,7 @@ namespace OpenSim.Framework.Console
result["int_response_code"] = 200; result["int_response_code"] = 200;
result["content_type"] = "application/xml"; result["content_type"] = "application/xml";
result["keepalive"] = false; result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result); result = CheckOrigin(result);
return result; return result;
@ -740,6 +713,7 @@ namespace OpenSim.Framework.Console
result["int_response_code"] = 200; result["int_response_code"] = 200;
result["content_type"] = "text/xml"; result["content_type"] = "text/xml";
result["keepalive"] = false; result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result); result = CheckOrigin(result);
return result; return result;

View File

@ -25,22 +25,18 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System; using System;
using OpenMetaverse;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
public class Constants public class Constants
{ {
public const int MaxAgentAttachments = 38;
public const int MaxAgentGroups = 60;
// 'RegionSize' is the legacy region size. // 'RegionSize' is the legacy region size.
// DO NOT USE THIS FOR ANY NEW CODE. Use Scene.RegionInfo.RegionSize[XYZ] as a region might not // DO NOT USE THIS FOR ANY NEW CODE. Use Scene.RegionInfo.RegionSize[XYZ] as a region might not
// be the legacy region size. // be the legacy region size.
public const uint RegionSize = 256; public const uint RegionSize = 256;
public const uint RegionHeight = 4096; public const uint RegionHeight = 4096;
// This could be a parameters but, really, a region of greater than this is pretty unmanageable
public const uint MaximumRegionSize = 4096; public const uint MaximumRegionSize = 8192;
// Since terrain is stored in 16x16 heights, regions must be a multiple of this number and that is the minimum // Since terrain is stored in 16x16 heights, regions must be a multiple of this number and that is the minimum
public const int MinRegionSize = 16; public const int MinRegionSize = 16;
@ -48,9 +44,6 @@ namespace OpenSim.Framework
public const string DefaultTexture = "89556747-24cb-43ed-920b-47caed15465f"; public const string DefaultTexture = "89556747-24cb-43ed-920b-47caed15465f";
public static readonly UUID m_MrOpenSimID = new UUID("11111111-1111-0000-0000-000100bba000");
public static readonly DateTime m_MrOpenSimBorn = new DateTime(2007, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public enum EstateAccessCodex : uint public enum EstateAccessCodex : uint
{ {
AllowedAccess = 1, AllowedAccess = 1,
@ -110,8 +103,8 @@ namespace OpenSim.Framework
/// <summary>Finished, Same Sim</summary> /// <summary>Finished, Same Sim</summary>
FinishedViaSameSim = 1 << 29, FinishedViaSameSim = 1 << 29,
/// <summary>Agent coming into the grid from another grid</summary> /// <summary>Agent coming into the grid from another grid</summary>
ViaHGLogin = 1 << 30, ViaHGLogin = 1 << 30
notViaHGLogin = 0xbffffff
} }
} }
} }

View File

@ -1,139 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Security.Cryptography;
namespace OpenSim.Framework
{
// this is more generic than openmetaverse CRC32
public class Crc32 : HashAlgorithm
{
public const UInt32 DefaultPolynomial = 0xedb88320;
public const UInt32 DefaultSeed = 0xffffffff;
private UInt32 hash;
private UInt32 seed;
private UInt32[] table;
private static UInt32[] defaultTable;
public Crc32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}
public Crc32(UInt32 polynomial, UInt32 seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}
public override void Initialize()
{
hash = seed;
}
protected override void HashCore(byte[] buffer, int start, int length)
{
hash = CalculateHash(table, hash, buffer, start, length);
}
protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}
public override int HashSize
{
get { return 32; }
}
public static UInt32 Compute(byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
}
private static UInt32[] InitializeTable(UInt32 polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
return defaultTable;
UInt32[] createTable = new UInt32[256];
for (int i = 0; i < 256; i++)
{
UInt32 entry = (UInt32)i;
for (int j = 0; j < 8; j++)
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
createTable[i] = entry;
}
if (polynomial == DefaultPolynomial)
defaultTable = createTable;
return createTable;
}
private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
{
UInt32 crc = seed;
for (int i = start; i < size; i++)
unchecked
{
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
}
return crc;
}
private byte[] UInt32ToBigEndianBytes(UInt32 x)
{
return new byte[] {
(byte)((x >> 24) & 0xff),
(byte)((x >> 16) & 0xff),
(byte)((x >> 8) & 0xff),
(byte)(x & 0xff) };
}
}
}

View File

@ -1 +1,56 @@
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Globalization; using System.Threading; namespace OpenSim.Framework { public class Culture { private static readonly CultureInfo m_cultureInfo = new CultureInfo("en-US", false); public static NumberFormatInfo NumberFormatInfo { get { return m_cultureInfo.NumberFormat; } } public static IFormatProvider FormatProvider { get { return m_cultureInfo; } } /// <summary> /// Set Culture to en-US to make string processing of numbers simpler. /// </summary> public static void SetCurrentCulture() { Thread.CurrentThread.CurrentCulture = m_cultureInfo; } public static void SetDefaultCurrentCulture() { CultureInfo.DefaultThreadCurrentCulture = m_cultureInfo; } public static CultureInfo GetDefaultCurrentCulture() { return CultureInfo.DefaultThreadCurrentCulture; } } } /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Globalization;
using System.Threading;
namespace OpenSim.Framework
{
public class Culture
{
private static readonly CultureInfo m_cultureInfo = new CultureInfo("en-US", false);
public static NumberFormatInfo NumberFormatInfo
{
get { return m_cultureInfo.NumberFormat; }
}
public static IFormatProvider FormatProvider
{
get { return m_cultureInfo; }
}
/// <summary>
/// Set Culture to en-US to make string processing of numbers simpler.
/// </summary>
public static void SetCurrentCulture()
{
Thread.CurrentThread.CurrentCulture = m_cultureInfo;
}
}
}

Some files were not shown because too many files have changed in this diff Show More