Update svn properties. Minor formatting cleanup.

0.6.0-stable
Jeff Ames 2008-05-01 14:31:30 +00:00
parent bdf1262605
commit d51ce47b2d
83 changed files with 16583 additions and 16599 deletions

View File

@ -1,39 +1,39 @@
CREATE TABLE `land` CREATE TABLE `land`
( (
`UUID` varchar (255) NOT NULL, `UUID` varchar (255) NOT NULL,
`RegionUUID` varchar (255) DEFAULT NULL , `RegionUUID` varchar (255) DEFAULT NULL ,
`LocalLandID` int (11) DEFAULT NULL , `LocalLandID` int (11) DEFAULT NULL ,
`Bitmap` longblob, `Bitmap` longblob,
`Name` varchar (255) DEFAULT NULL , `Name` varchar (255) DEFAULT NULL ,
`Description` varchar (255) DEFAULT NULL , `Description` varchar (255) DEFAULT NULL ,
`OwnerUUID` varchar (255) DEFAULT NULL , `OwnerUUID` varchar (255) DEFAULT NULL ,
`IsGroupOwned` int (11) DEFAULT NULL , `IsGroupOwned` int (11) DEFAULT NULL ,
`Area` int (11) DEFAULT NULL , `Area` int (11) DEFAULT NULL ,
`AuctionID` int (11) DEFAULT NULL , `AuctionID` int (11) DEFAULT NULL ,
`Category` int (11) DEFAULT NULL , `Category` int (11) DEFAULT NULL ,
`ClaimDate` int (11) DEFAULT NULL , `ClaimDate` int (11) DEFAULT NULL ,
`ClaimPrice` int (11) DEFAULT NULL , `ClaimPrice` int (11) DEFAULT NULL ,
`GroupUUID` varchar (255) DEFAULT NULL , `GroupUUID` varchar (255) DEFAULT NULL ,
`SalePrice` int (11) DEFAULT NULL , `SalePrice` int (11) DEFAULT NULL ,
`LandStatus` int (11) DEFAULT NULL , `LandStatus` int (11) DEFAULT NULL ,
`LandFlags` int (11) DEFAULT NULL , `LandFlags` int (11) DEFAULT NULL ,
`LandingType` int (11) DEFAULT NULL , `LandingType` int (11) DEFAULT NULL ,
`MediaAutoScale` int (11) DEFAULT NULL , `MediaAutoScale` int (11) DEFAULT NULL ,
`MediaTextureUUID` varchar (255) DEFAULT NULL , `MediaTextureUUID` varchar (255) DEFAULT NULL ,
`MediaURL` varchar (255) DEFAULT NULL , `MediaURL` varchar (255) DEFAULT NULL ,
`MusicURL` varchar (255) DEFAULT NULL , `MusicURL` varchar (255) DEFAULT NULL ,
`PassHours` float DEFAULT NULL , `PassHours` float DEFAULT NULL ,
`PassPrice` int (11) DEFAULT NULL , `PassPrice` int (11) DEFAULT NULL ,
`SnapshotUUID` varchar (255) DEFAULT NULL , `SnapshotUUID` varchar (255) DEFAULT NULL ,
`UserLocationX` float DEFAULT NULL , `UserLocationX` float DEFAULT NULL ,
`UserLocationY` float DEFAULT NULL , `UserLocationY` float DEFAULT NULL ,
`UserLocationZ` float DEFAULT NULL , `UserLocationZ` float DEFAULT NULL ,
`UserLookAtX` float DEFAULT NULL , `UserLookAtX` float DEFAULT NULL ,
`UserLookAtY` float DEFAULT NULL , `UserLookAtY` float DEFAULT NULL ,
`UserLookAtZ` float DEFAULT NULL , `UserLookAtZ` float DEFAULT NULL ,
`AuthbuyerID` varchar(36) default '00000000-0000-0000-0000-000000000000' not null, `AuthbuyerID` varchar(36) default '00000000-0000-0000-0000-000000000000' not null,
PRIMARY KEY (`UUID`) PRIMARY KEY (`UUID`)
) )
ENGINE=INNODB ENGINE=INNODB
DEFAULT CHARSET=utf8 COMMENT='Rev. 2'; DEFAULT CHARSET=utf8 COMMENT='Rev. 2';

View File

@ -1,3 +1,3 @@
ALTER TABLE `land` ALTER TABLE `land`
ADD COLUMN `AuthbuyerID` varchar(36) default '00000000-0000-0000-0000-000000000000' not null, ADD COLUMN `AuthbuyerID` varchar(36) default '00000000-0000-0000-0000-000000000000' not null,
COMMENT='Rev. 2'; COMMENT='Rev. 2';

View File

@ -1,65 +1,65 @@
using System; using System;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
[Serializable] [Serializable]
public class Location : ICloneable public class Location : ICloneable
{ {
private readonly int m_x; private readonly int m_x;
private readonly int m_y; private readonly int m_y;
public Location(int x, int y) public Location(int x, int y)
{ {
m_x = x; m_x = x;
m_y = y; m_y = y;
} }
public int X public int X
{ {
get { return m_x; } get { return m_x; }
} }
public int Y public int Y
{ {
get { return m_y; } get { return m_y; }
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(obj, this)) if (ReferenceEquals(obj, this))
return true; return true;
if (obj is Location) if (obj is Location)
{ {
return Equals((Location) obj); return Equals((Location) obj);
} }
return base.Equals(obj); return base.Equals(obj);
} }
public bool Equals(Location loc) public bool Equals(Location loc)
{ {
return loc.X == X && loc.Y == Y; return loc.X == X && loc.Y == Y;
} }
public bool Equals(int x, int y) public bool Equals(int x, int y)
{ {
return X == x && y == Y; return X == x && y == Y;
} }
public UInt64 RegionHandle public UInt64 RegionHandle
{ {
get { return UInt64.MinValue; } get { return UInt64.MinValue; }
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return X.GetHashCode() * 29 + Y.GetHashCode(); return X.GetHashCode() * 29 + Y.GetHashCode();
} }
public object Clone() public object Clone()
{ {
return new Location(X, Y); return new Location(X, Y);
} }
} }
} }

View File

@ -588,7 +588,6 @@ namespace OpenSim
m_moduleLoader, m_dumpAssetsToFile, m_physicalPrim, m_see_into_region_from_neighbor); m_moduleLoader, m_dumpAssetsToFile, m_physicalPrim, m_see_into_region_from_neighbor);
} }
public void handleRestartRegion(RegionInfo whichRegion) public void handleRestartRegion(RegionInfo whichRegion)
{ {
m_log.Error("[OPENSIM MAIN]: Got restart signal from SceneManager"); m_log.Error("[OPENSIM MAIN]: Got restart signal from SceneManager");

View File

@ -1,228 +1,228 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using libsecondlife.Packets; using libsecondlife.Packets;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload
{ {
public class AssetDownloadModule : IRegionModule public class AssetDownloadModule : IRegionModule
{ {
/// <summary> /// <summary>
/// Asset requests with data which are ready to be sent back to requesters. This includes textures. /// Asset requests with data which are ready to be sent back to requesters. This includes textures.
/// </summary> /// </summary>
private List<AssetRequest> AssetRequests; private List<AssetRequest> AssetRequests;
private Scene m_scene; private Scene m_scene;
private Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>(); private Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>();
/// ///
/// Assets requests (for each user) which are waiting for asset server data. This includes texture requests /// Assets requests (for each user) which are waiting for asset server data. This includes texture requests
/// </summary> /// </summary>
private Dictionary<LLUUID, Dictionary<LLUUID, AssetRequest>> RequestedAssets; private Dictionary<LLUUID, Dictionary<LLUUID, AssetRequest>> RequestedAssets;
public AssetDownloadModule() public AssetDownloadModule()
{ {
RequestedAssets = new Dictionary<LLUUID, Dictionary<LLUUID, AssetRequest>>(); RequestedAssets = new Dictionary<LLUUID, Dictionary<LLUUID, AssetRequest>>();
AssetRequests = new List<AssetRequest>(); AssetRequests = new List<AssetRequest>();
} }
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{ {
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
// scene.EventManager.OnNewClient += NewClient; // scene.EventManager.OnNewClient += NewClient;
} }
if (m_scene == null) if (m_scene == null)
{ {
m_scene = scene; m_scene = scene;
// m_thread = new Thread(new ThreadStart(RunAssetQueue)); // m_thread = new Thread(new ThreadStart(RunAssetQueue));
// m_thread.Name = "AssetDownloadQueueThread"; // m_thread.Name = "AssetDownloadQueueThread";
// m_thread.IsBackground = true; // m_thread.IsBackground = true;
// m_thread.Start(); // m_thread.Start();
// OpenSim.Framework.ThreadTracker.Add(m_thread); // OpenSim.Framework.ThreadTracker.Add(m_thread);
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "AssetDownloadModule"; } get { return "AssetDownloadModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
// client.OnRequestAsset += AddAssetRequest; // client.OnRequestAsset += AddAssetRequest;
} }
/// <summary> /// <summary>
/// Make an asset request the result of which will be packeted up and sent directly back to the client. /// Make an asset request the result of which will be packeted up and sent directly back to the client.
/// </summary> /// </summary>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="transferRequest"></param> /// <param name="transferRequest"></param>
public void AddAssetRequest(IClientAPI userInfo, TransferRequestPacket transferRequest) public void AddAssetRequest(IClientAPI userInfo, TransferRequestPacket transferRequest)
{ {
LLUUID requestID = null; LLUUID requestID = null;
byte source = 2; byte source = 2;
if (transferRequest.TransferInfo.SourceType == 2) if (transferRequest.TransferInfo.SourceType == 2)
{ {
//direct asset request //direct asset request
requestID = new LLUUID(transferRequest.TransferInfo.Params, 0); requestID = new LLUUID(transferRequest.TransferInfo.Params, 0);
} }
else if (transferRequest.TransferInfo.SourceType == 3) else if (transferRequest.TransferInfo.SourceType == 3)
{ {
//inventory asset request //inventory asset request
requestID = new LLUUID(transferRequest.TransferInfo.Params, 80); requestID = new LLUUID(transferRequest.TransferInfo.Params, 80);
source = 3; source = 3;
//Console.WriteLine("asset request " + requestID); //Console.WriteLine("asset request " + requestID);
} }
//not found asset //not found asset
// so request from asset server // so request from asset server
Dictionary<LLUUID, AssetRequest> userRequests = null; Dictionary<LLUUID, AssetRequest> userRequests = null;
if (RequestedAssets.TryGetValue(userInfo.AgentId, out userRequests)) if (RequestedAssets.TryGetValue(userInfo.AgentId, out userRequests))
{ {
if (!userRequests.ContainsKey(requestID)) if (!userRequests.ContainsKey(requestID))
{ {
AssetRequest request = new AssetRequest(); AssetRequest request = new AssetRequest();
request.RequestUser = userInfo; request.RequestUser = userInfo;
request.RequestAssetID = requestID; request.RequestAssetID = requestID;
request.TransferRequestID = transferRequest.TransferInfo.TransferID; request.TransferRequestID = transferRequest.TransferInfo.TransferID;
request.AssetRequestSource = source; request.AssetRequestSource = source;
request.Params = transferRequest.TransferInfo.Params; request.Params = transferRequest.TransferInfo.Params;
userRequests[requestID] = request; userRequests[requestID] = request;
m_scene.AssetCache.GetAsset(requestID, AssetCallback, false); m_scene.AssetCache.GetAsset(requestID, AssetCallback, false);
} }
} }
else else
{ {
userRequests = new Dictionary<LLUUID, AssetRequest>(); userRequests = new Dictionary<LLUUID, AssetRequest>();
AssetRequest request = new AssetRequest(); AssetRequest request = new AssetRequest();
request.RequestUser = userInfo; request.RequestUser = userInfo;
request.RequestAssetID = requestID; request.RequestAssetID = requestID;
request.TransferRequestID = transferRequest.TransferInfo.TransferID; request.TransferRequestID = transferRequest.TransferInfo.TransferID;
request.AssetRequestSource = source; request.AssetRequestSource = source;
request.Params = transferRequest.TransferInfo.Params; request.Params = transferRequest.TransferInfo.Params;
userRequests.Add(requestID, request); userRequests.Add(requestID, request);
RequestedAssets[userInfo.AgentId] = userRequests; RequestedAssets[userInfo.AgentId] = userRequests;
m_scene.AssetCache.GetAsset(requestID, AssetCallback, false); m_scene.AssetCache.GetAsset(requestID, AssetCallback, false);
} }
} }
public void AssetCallback(LLUUID assetID, AssetBase asset) public void AssetCallback(LLUUID assetID, AssetBase asset)
{ {
if (asset != null) if (asset != null)
{ {
foreach (Dictionary<LLUUID, AssetRequest> userRequests in RequestedAssets.Values) foreach (Dictionary<LLUUID, AssetRequest> userRequests in RequestedAssets.Values)
{ {
if (userRequests.ContainsKey(assetID)) if (userRequests.ContainsKey(assetID))
{ {
AssetRequest req = userRequests[assetID]; AssetRequest req = userRequests[assetID];
if (req != null) if (req != null)
{ {
req.AssetInf = asset; req.AssetInf = asset;
req.NumPackets = CalculateNumPackets(asset.Data); req.NumPackets = CalculateNumPackets(asset.Data);
userRequests.Remove(assetID); userRequests.Remove(assetID);
AssetRequests.Add(req); AssetRequests.Add(req);
} }
} }
} }
} }
} }
/// <summary> /// <summary>
/// Calculate the number of packets required to send the asset to the client. /// Calculate the number of packets required to send the asset to the client.
/// </summary> /// </summary>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns></returns> /// <returns></returns>
private int CalculateNumPackets(byte[] data) private int CalculateNumPackets(byte[] data)
{ {
const uint m_maxPacketSize = 600; const uint m_maxPacketSize = 600;
int numPackets = 1; int numPackets = 1;
if (data.LongLength > m_maxPacketSize) if (data.LongLength > m_maxPacketSize)
{ {
// over max number of bytes so split up file // over max number of bytes so split up file
long restData = data.LongLength - m_maxPacketSize; long restData = data.LongLength - m_maxPacketSize;
int restPackets = (int) ((restData + m_maxPacketSize - 1) / m_maxPacketSize); int restPackets = (int) ((restData + m_maxPacketSize - 1) / m_maxPacketSize);
numPackets += restPackets; numPackets += restPackets;
} }
return numPackets; return numPackets;
} }
#region Nested type: AssetRequest #region Nested type: AssetRequest
public class AssetRequest public class AssetRequest
{ {
public AssetBase AssetInf; public AssetBase AssetInf;
public byte AssetRequestSource = 2; public byte AssetRequestSource = 2;
public long DataPointer = 0; public long DataPointer = 0;
public int DiscardLevel = -1; public int DiscardLevel = -1;
public AssetBase ImageInfo; public AssetBase ImageInfo;
public bool IsTextureRequest; public bool IsTextureRequest;
public int NumPackets = 0; public int NumPackets = 0;
public int PacketCounter = 0; public int PacketCounter = 0;
public byte[] Params = null; public byte[] Params = null;
public LLUUID RequestAssetID; public LLUUID RequestAssetID;
public IClientAPI RequestUser; public IClientAPI RequestUser;
public LLUUID TransferRequestID; public LLUUID TransferRequestID;
//public bool AssetInCache; //public bool AssetInCache;
//public int TimeRequested; //public int TimeRequested;
public AssetRequest() public AssetRequest()
{ {
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,412 +1,412 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using libsecondlife; using libsecondlife;
using libsecondlife.Packets; using libsecondlife.Packets;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction
{ {
/// <summary> /// <summary>
/// Manage asset transactions for a single agent. /// Manage asset transactions for a single agent.
/// </summary> /// </summary>
public class AgentAssetTransactions public class AgentAssetTransactions
{ {
//private static readonly log4net.ILog m_log //private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Fields // Fields
private bool m_dumpAssetsToFile; private bool m_dumpAssetsToFile;
public AgentAssetTransactionsManager Manager; public AgentAssetTransactionsManager Manager;
public LLUUID UserID; public LLUUID UserID;
public Dictionary<LLUUID, AssetXferUploader> XferUploaders = new Dictionary<LLUUID, AssetXferUploader>(); public Dictionary<LLUUID, AssetXferUploader> XferUploaders = new Dictionary<LLUUID, AssetXferUploader>();
// Methods // Methods
public AgentAssetTransactions(LLUUID agentID, AgentAssetTransactionsManager manager, bool dumpAssetsToFile) public AgentAssetTransactions(LLUUID agentID, AgentAssetTransactionsManager manager, bool dumpAssetsToFile)
{ {
UserID = agentID; UserID = agentID;
Manager = manager; Manager = manager;
m_dumpAssetsToFile = dumpAssetsToFile; m_dumpAssetsToFile = dumpAssetsToFile;
} }
public AssetXferUploader RequestXferUploader(LLUUID transactionID) public AssetXferUploader RequestXferUploader(LLUUID transactionID)
{ {
if (!XferUploaders.ContainsKey(transactionID)) if (!XferUploaders.ContainsKey(transactionID))
{ {
AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile); AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile);
lock (XferUploaders) lock (XferUploaders)
{ {
XferUploaders.Add(transactionID, uploader); XferUploaders.Add(transactionID, uploader);
} }
return uploader; return uploader;
} }
return null; return null;
} }
public void HandleXfer(ulong xferID, uint packetID, byte[] data) public void HandleXfer(ulong xferID, uint packetID, byte[] data)
{ {
// AssetXferUploader uploaderFound = null; // AssetXferUploader uploaderFound = null;
lock (XferUploaders) lock (XferUploaders)
{ {
foreach (AssetXferUploader uploader in XferUploaders.Values) foreach (AssetXferUploader uploader in XferUploaders.Values)
{ {
if (uploader.XferID == xferID) if (uploader.XferID == xferID)
{ {
uploader.HandleXferPacket(xferID, packetID, data); uploader.HandleXferPacket(xferID, packetID, data);
break; break;
} }
} }
} }
} }
public void RequestCreateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, public void RequestCreateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType, uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask) sbyte type, byte wearableType, uint nextOwnerMask)
{ {
if (XferUploaders.ContainsKey(transactionID)) if (XferUploaders.ContainsKey(transactionID))
{ {
XferUploaders[transactionID].RequestCreateInventoryItem(remoteClient, transactionID, folderID, XferUploaders[transactionID].RequestCreateInventoryItem(remoteClient, transactionID, folderID,
callbackID, description, name, invType, type, callbackID, description, name, invType, type,
wearableType, nextOwnerMask); wearableType, nextOwnerMask);
} }
} }
public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item) InventoryItemBase item)
{ {
if (XferUploaders.ContainsKey(transactionID)) if (XferUploaders.ContainsKey(transactionID))
{ {
XferUploaders[transactionID].RequestUpdateInventoryItem(remoteClient, transactionID, item); XferUploaders[transactionID].RequestUpdateInventoryItem(remoteClient, transactionID, item);
} }
} }
/// <summary> /// <summary>
/// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed. /// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed.
/// </summary> /// </summary>
/// <param name="transactionID"></param> /// <param name="transactionID"></param>
/// <returns>The asset if the upload has completed, null if it has not.</returns> /// <returns>The asset if the upload has completed, null if it has not.</returns>
public AssetBase GetTransactionAsset(LLUUID transactionID) public AssetBase GetTransactionAsset(LLUUID transactionID)
{ {
if (XferUploaders.ContainsKey(transactionID)) if (XferUploaders.ContainsKey(transactionID))
{ {
AssetXferUploader uploader = XferUploaders[transactionID]; AssetXferUploader uploader = XferUploaders[transactionID];
AssetBase asset = uploader.GetAssetData(); AssetBase asset = uploader.GetAssetData();
lock (XferUploaders) lock (XferUploaders)
{ {
XferUploaders.Remove(transactionID); XferUploaders.Remove(transactionID);
} }
return asset; return asset;
} }
return null; return null;
} }
// Nested Types // Nested Types
#region Nested type: AssetXferUploader #region Nested type: AssetXferUploader
public class AssetXferUploader public class AssetXferUploader
{ {
// Fields // Fields
public bool AddToInventory; public bool AddToInventory;
public AssetBase Asset; public AssetBase Asset;
public LLUUID InventFolder = LLUUID.Zero; public LLUUID InventFolder = LLUUID.Zero;
private sbyte invType = 0; private sbyte invType = 0;
private bool m_createItem = false; private bool m_createItem = false;
private string m_description = String.Empty; private string m_description = String.Empty;
private bool m_dumpAssetToFile; private bool m_dumpAssetToFile;
private bool m_finished = false; private bool m_finished = false;
private string m_name = String.Empty; private string m_name = String.Empty;
private bool m_storeLocal; private bool m_storeLocal;
private AgentAssetTransactions m_userTransactions; private AgentAssetTransactions m_userTransactions;
private uint nextPerm = 0; private uint nextPerm = 0;
private IClientAPI ourClient; private IClientAPI ourClient;
public LLUUID TransactionID = LLUUID.Zero; public LLUUID TransactionID = LLUUID.Zero;
private sbyte type = 0; private sbyte type = 0;
public bool UploadComplete; public bool UploadComplete;
private byte wearableType = 0; private byte wearableType = 0;
public ulong XferID; public ulong XferID;
public AssetXferUploader(AgentAssetTransactions transactions, bool dumpAssetToFile) public AssetXferUploader(AgentAssetTransactions transactions, bool dumpAssetToFile)
{ {
m_userTransactions = transactions; m_userTransactions = transactions;
m_dumpAssetToFile = dumpAssetToFile; m_dumpAssetToFile = dumpAssetToFile;
} }
/// <summary> /// <summary>
/// Process transfer data received from the client. /// Process transfer data received from the client.
/// </summary> /// </summary>
/// <param name="xferID"></param> /// <param name="xferID"></param>
/// <param name="packetID"></param> /// <param name="packetID"></param>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns> /// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data) public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
{ {
if (XferID == xferID) if (XferID == xferID)
{ {
if (Asset.Data.Length > 1) if (Asset.Data.Length > 1)
{ {
byte[] destinationArray = new byte[Asset.Data.Length + data.Length]; byte[] destinationArray = new byte[Asset.Data.Length + data.Length];
Array.Copy(Asset.Data, 0, destinationArray, 0, Asset.Data.Length); Array.Copy(Asset.Data, 0, destinationArray, 0, Asset.Data.Length);
Array.Copy(data, 0, destinationArray, Asset.Data.Length, data.Length); Array.Copy(data, 0, destinationArray, Asset.Data.Length, data.Length);
Asset.Data = destinationArray; Asset.Data = destinationArray;
} }
else else
{ {
byte[] buffer2 = new byte[data.Length - 4]; byte[] buffer2 = new byte[data.Length - 4];
Array.Copy(data, 4, buffer2, 0, data.Length - 4); Array.Copy(data, 4, buffer2, 0, data.Length - 4);
Asset.Data = buffer2; Asset.Data = buffer2;
} }
ConfirmXferPacketPacket newPack = new ConfirmXferPacketPacket(); ConfirmXferPacketPacket newPack = new ConfirmXferPacketPacket();
newPack.XferID.ID = xferID; newPack.XferID.ID = xferID;
newPack.XferID.Packet = packetID; newPack.XferID.Packet = packetID;
ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset); ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset);
if ((packetID & 0x80000000) != 0) if ((packetID & 0x80000000) != 0)
{ {
SendCompleteMessage(); SendCompleteMessage();
return true; return true;
} }
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Initialise asset transfer from the client /// Initialise asset transfer from the client
/// </summary> /// </summary>
/// <param name="xferID"></param> /// <param name="xferID"></param>
/// <param name="packetID"></param> /// <param name="packetID"></param>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise</returns> /// <returns>True if the transfer is complete, false otherwise</returns>
public bool Initialise(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data, public bool Initialise(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data,
bool storeLocal, bool tempFile) bool storeLocal, bool tempFile)
{ {
ourClient = remoteClient; ourClient = remoteClient;
Asset = new AssetBase(); Asset = new AssetBase();
Asset.FullID = assetID; Asset.FullID = assetID;
Asset.InvType = type; Asset.InvType = type;
Asset.Type = type; Asset.Type = type;
Asset.Data = data; Asset.Data = data;
Asset.Name = "blank"; Asset.Name = "blank";
Asset.Description = "empty"; Asset.Description = "empty";
Asset.Local = storeLocal; Asset.Local = storeLocal;
Asset.Temporary = tempFile; Asset.Temporary = tempFile;
TransactionID = transaction; TransactionID = transaction;
m_storeLocal = storeLocal; m_storeLocal = storeLocal;
if (Asset.Data.Length > 2) if (Asset.Data.Length > 2)
{ {
SendCompleteMessage(); SendCompleteMessage();
return true; return true;
} }
else else
{ {
RequestStartXfer(); RequestStartXfer();
} }
return false; return false;
} }
protected void RequestStartXfer() protected void RequestStartXfer()
{ {
UploadComplete = false; UploadComplete = false;
XferID = Util.GetNextXferID(); XferID = Util.GetNextXferID();
RequestXferPacket newPack = new RequestXferPacket(); RequestXferPacket newPack = new RequestXferPacket();
newPack.XferID.ID = XferID; newPack.XferID.ID = XferID;
newPack.XferID.VFileType = Asset.Type; newPack.XferID.VFileType = Asset.Type;
newPack.XferID.VFileID = Asset.FullID; newPack.XferID.VFileID = Asset.FullID;
newPack.XferID.FilePath = 0; newPack.XferID.FilePath = 0;
newPack.XferID.Filename = new byte[0]; newPack.XferID.Filename = new byte[0];
ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset); ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset);
} }
protected void SendCompleteMessage() protected void SendCompleteMessage()
{ {
UploadComplete = true; UploadComplete = true;
AssetUploadCompletePacket newPack = new AssetUploadCompletePacket(); AssetUploadCompletePacket newPack = new AssetUploadCompletePacket();
newPack.AssetBlock.Type = Asset.Type; newPack.AssetBlock.Type = Asset.Type;
newPack.AssetBlock.Success = true; newPack.AssetBlock.Success = true;
newPack.AssetBlock.UUID = Asset.FullID; newPack.AssetBlock.UUID = Asset.FullID;
ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset); ourClient.OutPacket(newPack, ThrottleOutPacketType.Asset);
m_finished = true; m_finished = true;
if (m_createItem) if (m_createItem)
{ {
DoCreateItem(); DoCreateItem();
} }
else if (m_storeLocal) else if (m_storeLocal)
{ {
m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset); m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset);
} }
// Console.WriteLine("upload complete "+ this.TransactionID); // Console.WriteLine("upload complete "+ this.TransactionID);
if (m_dumpAssetToFile) if (m_dumpAssetToFile)
{ {
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
string filename = string filename =
String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", now.Year, now.Month, now.Day, String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second, Asset.Name, Asset.Type); now.Hour, now.Minute, now.Second, Asset.Name, Asset.Type);
SaveAssetToFile(filename, Asset.Data); SaveAssetToFile(filename, Asset.Data);
} }
} }
///Left this in and commented in case there are unforseen issues ///Left this in and commented in case there are unforseen issues
//private void SaveAssetToFile(string filename, byte[] data) //private void SaveAssetToFile(string filename, byte[] data)
//{ //{
// FileStream fs = File.Create(filename); // FileStream fs = File.Create(filename);
// BinaryWriter bw = new BinaryWriter(fs); // BinaryWriter bw = new BinaryWriter(fs);
// bw.Write(data); // bw.Write(data);
// bw.Close(); // bw.Close();
// fs.Close(); // fs.Close();
//} //}
private void SaveAssetToFile(string filename, byte[] data) private void SaveAssetToFile(string filename, byte[] data)
{ {
string assetPath = "UserAssets"; string assetPath = "UserAssets";
if (!Directory.Exists(assetPath)) if (!Directory.Exists(assetPath))
{ {
Directory.CreateDirectory(assetPath); Directory.CreateDirectory(assetPath);
} }
FileStream fs = File.Create(Path.Combine(assetPath, filename)); FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs); BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data); bw.Write(data);
bw.Close(); bw.Close();
fs.Close(); fs.Close();
} }
public void RequestCreateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, public void RequestCreateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType, uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask) sbyte type, byte wearableType, uint nextOwnerMask)
{ {
if (TransactionID == transactionID) if (TransactionID == transactionID)
{ {
InventFolder = folderID; InventFolder = folderID;
m_name = name; m_name = name;
m_description = description; m_description = description;
this.type = type; this.type = type;
this.invType = invType; this.invType = invType;
this.wearableType = wearableType; this.wearableType = wearableType;
nextPerm = nextOwnerMask; nextPerm = nextOwnerMask;
Asset.Name = name; Asset.Name = name;
Asset.Description = description; Asset.Description = description;
Asset.Type = type; Asset.Type = type;
Asset.InvType = invType; Asset.InvType = invType;
m_createItem = true; m_createItem = true;
if (m_finished) if (m_finished)
{ {
DoCreateItem(); DoCreateItem();
} }
} }
} }
public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item) InventoryItemBase item)
{ {
if (TransactionID == transactionID) if (TransactionID == transactionID)
{ {
CachedUserInfo userInfo = CachedUserInfo userInfo =
m_userTransactions.Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails( m_userTransactions.Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails(
remoteClient.AgentId); remoteClient.AgentId);
if (userInfo != null) if (userInfo != null)
{ {
LLUUID assetID = LLUUID.Combine(transactionID, remoteClient.SecureSessionId); LLUUID assetID = LLUUID.Combine(transactionID, remoteClient.SecureSessionId);
AssetBase asset AssetBase asset
= m_userTransactions.Manager.MyScene.CommsManager.AssetCache.GetAsset( = m_userTransactions.Manager.MyScene.CommsManager.AssetCache.GetAsset(
assetID, (item.AssetType == (int) AssetType.Texture ? true : false)); assetID, (item.AssetType == (int) AssetType.Texture ? true : false));
if (asset == null) if (asset == null)
{ {
asset = m_userTransactions.GetTransactionAsset(transactionID); asset = m_userTransactions.GetTransactionAsset(transactionID);
} }
if (asset != null && asset.FullID == assetID) if (asset != null && asset.FullID == assetID)
{ {
asset.Name = item.Name; asset.Name = item.Name;
asset.Description = item.Description; asset.Description = item.Description;
asset.InvType = (sbyte) item.InvType; asset.InvType = (sbyte) item.InvType;
asset.Type = (sbyte) item.AssetType; asset.Type = (sbyte) item.AssetType;
item.AssetID = asset.FullID; item.AssetID = asset.FullID;
m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset); m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset);
} }
userInfo.UpdateItem(remoteClient.AgentId, item); userInfo.UpdateItem(remoteClient.AgentId, item);
} }
} }
} }
private void DoCreateItem() private void DoCreateItem()
{ {
//really need to fix this call, if lbsa71 saw this he would die. //really need to fix this call, if lbsa71 saw this he would die.
m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset); m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset);
CachedUserInfo userInfo = CachedUserInfo userInfo =
m_userTransactions.Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails(ourClient.AgentId); m_userTransactions.Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails(ourClient.AgentId);
if (userInfo != null) if (userInfo != null)
{ {
InventoryItemBase item = new InventoryItemBase(); InventoryItemBase item = new InventoryItemBase();
item.Owner = ourClient.AgentId; item.Owner = ourClient.AgentId;
item.Creator = ourClient.AgentId; item.Creator = ourClient.AgentId;
item.ID = LLUUID.Random(); item.ID = LLUUID.Random();
item.AssetID = Asset.FullID; item.AssetID = Asset.FullID;
item.Description = m_description; item.Description = m_description;
item.Name = m_name; item.Name = m_name;
item.AssetType = type; item.AssetType = type;
item.InvType = invType; item.InvType = invType;
item.Folder = InventFolder; item.Folder = InventFolder;
item.BasePermissions = 2147483647; item.BasePermissions = 2147483647;
item.CurrentPermissions = 2147483647; item.CurrentPermissions = 2147483647;
item.NextPermissions = nextPerm; item.NextPermissions = nextPerm;
item.Flags = (uint) wearableType; item.Flags = (uint) wearableType;
userInfo.AddItem(ourClient.AgentId, item); userInfo.AddItem(ourClient.AgentId, item);
ourClient.SendInventoryItemCreateUpdate(item); ourClient.SendInventoryItemCreateUpdate(item);
} }
} }
public AssetBase GetAssetData() public AssetBase GetAssetData()
{ {
if (m_finished) if (m_finished)
{ {
return Asset; return Asset;
} }
return null; return null;
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,291 +1,291 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction
{ {
public class AssetTransactionModule : IRegionModule, IAgentAssetTransactions public class AssetTransactionModule : IRegionModule, IAgentAssetTransactions
{ {
private readonly Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>(); private readonly Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>();
private bool m_dumpAssetsToFile = false; private bool m_dumpAssetsToFile = false;
private Scene m_scene = null; private Scene m_scene = null;
private AgentAssetTransactionsManager m_transactionManager; private AgentAssetTransactionsManager m_transactionManager;
public AssetTransactionModule() public AssetTransactionModule()
{ {
// System.Console.WriteLine("creating AgentAssetTransactionModule"); // System.Console.WriteLine("creating AgentAssetTransactionModule");
} }
#region IAgentAssetTransactions Members #region IAgentAssetTransactions Members
public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType, uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask) sbyte type, byte wearableType, uint nextOwnerMask)
{ {
m_transactionManager.HandleItemCreationFromTransaction(remoteClient, transactionID, folderID, callbackID, description, name, invType, type, m_transactionManager.HandleItemCreationFromTransaction(remoteClient, transactionID, folderID, callbackID, description, name, invType, type,
wearableType, nextOwnerMask); wearableType, nextOwnerMask);
} }
public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID, public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item) InventoryItemBase item)
{ {
m_transactionManager.HandleItemUpdateFromTransaction(remoteClient, transactionID, item); m_transactionManager.HandleItemUpdateFromTransaction(remoteClient, transactionID, item);
} }
public void RemoveAgentAssetTransactions(LLUUID userID) public void RemoveAgentAssetTransactions(LLUUID userID)
{ {
m_transactionManager.RemoveAgentAssetTransactions(userID); m_transactionManager.RemoveAgentAssetTransactions(userID);
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{ {
// System.Console.WriteLine("initialising AgentAssetTransactionModule"); // System.Console.WriteLine("initialising AgentAssetTransactionModule");
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IAgentAssetTransactions>(this); scene.RegisterModuleInterface<IAgentAssetTransactions>(this);
scene.EventManager.OnNewClient += NewClient; scene.EventManager.OnNewClient += NewClient;
} }
if (m_scene == null) if (m_scene == null)
{ {
m_scene = scene; m_scene = scene;
if (config.Configs["StandAlone"] != null) if (config.Configs["StandAlone"] != null)
{ {
try try
{ {
m_dumpAssetsToFile = config.Configs["StandAlone"].GetBoolean("dump_assets_to_file", false); m_dumpAssetsToFile = config.Configs["StandAlone"].GetBoolean("dump_assets_to_file", false);
m_transactionManager = new AgentAssetTransactionsManager(m_scene, m_dumpAssetsToFile); m_transactionManager = new AgentAssetTransactionsManager(m_scene, m_dumpAssetsToFile);
} }
catch (Exception) catch (Exception)
{ {
m_transactionManager = new AgentAssetTransactionsManager(m_scene, false); m_transactionManager = new AgentAssetTransactionsManager(m_scene, false);
} }
} }
else else
{ {
m_transactionManager = new AgentAssetTransactionsManager(m_scene, false); m_transactionManager = new AgentAssetTransactionsManager(m_scene, false);
} }
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "AgentTransactionModule"; } get { return "AgentTransactionModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
client.OnAssetUploadRequest += m_transactionManager.HandleUDPUploadRequest; client.OnAssetUploadRequest += m_transactionManager.HandleUDPUploadRequest;
client.OnXferReceive += m_transactionManager.HandleXfer; client.OnXferReceive += m_transactionManager.HandleXfer;
} }
} }
public class AgentAssetTransactionsManager public class AgentAssetTransactionsManager
{ {
private static readonly ILog m_log private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Fields // Fields
/// <summary> /// <summary>
/// Each agent has its own singleton collection of transactions /// Each agent has its own singleton collection of transactions
/// </summary> /// </summary>
private Dictionary<LLUUID, AgentAssetTransactions> AgentTransactions = private Dictionary<LLUUID, AgentAssetTransactions> AgentTransactions =
new Dictionary<LLUUID, AgentAssetTransactions>(); new Dictionary<LLUUID, AgentAssetTransactions>();
/// <summary> /// <summary>
/// Should we dump uploaded assets to the filesystem? /// Should we dump uploaded assets to the filesystem?
/// </summary> /// </summary>
private bool m_dumpAssetsToFile; private bool m_dumpAssetsToFile;
public Scene MyScene; public Scene MyScene;
public AgentAssetTransactionsManager(Scene scene, bool dumpAssetsToFile) public AgentAssetTransactionsManager(Scene scene, bool dumpAssetsToFile)
{ {
MyScene = scene; MyScene = scene;
m_dumpAssetsToFile = dumpAssetsToFile; m_dumpAssetsToFile = dumpAssetsToFile;
} }
/// <summary> /// <summary>
/// Get the collection of asset transactions for the given user. If one does not already exist, it /// Get the collection of asset transactions for the given user. If one does not already exist, it
/// is created. /// is created.
/// </summary> /// </summary>
/// <param name="userID"></param> /// <param name="userID"></param>
/// <returns></returns> /// <returns></returns>
private AgentAssetTransactions GetUserTransactions(LLUUID userID) private AgentAssetTransactions GetUserTransactions(LLUUID userID)
{ {
lock (AgentTransactions) lock (AgentTransactions)
{ {
if (!AgentTransactions.ContainsKey(userID)) if (!AgentTransactions.ContainsKey(userID))
{ {
AgentAssetTransactions transactions AgentAssetTransactions transactions
= new AgentAssetTransactions(userID, this, m_dumpAssetsToFile); = new AgentAssetTransactions(userID, this, m_dumpAssetsToFile);
AgentTransactions.Add(userID, transactions); AgentTransactions.Add(userID, transactions);
} }
return AgentTransactions[userID]; return AgentTransactions[userID];
} }
} }
/// <summary> /// <summary>
/// Remove the given agent asset transactions. This should be called when a client is departing /// Remove the given agent asset transactions. This should be called when a client is departing
/// from a scene (and hence won't be making any more transactions here). /// from a scene (and hence won't be making any more transactions here).
/// </summary> /// </summary>
/// <param name="userID"></param> /// <param name="userID"></param>
public void RemoveAgentAssetTransactions(LLUUID userID) public void RemoveAgentAssetTransactions(LLUUID userID)
{ {
// m_log.DebugFormat("Removing agent asset transactions structure for agent {0}", userID); // m_log.DebugFormat("Removing agent asset transactions structure for agent {0}", userID);
lock (AgentTransactions) lock (AgentTransactions)
{ {
AgentTransactions.Remove(userID); AgentTransactions.Remove(userID);
} }
} }
/// <summary> /// <summary>
/// Create an inventory item from data that has been received through a transaction. /// Create an inventory item from data that has been received through a transaction.
/// ///
/// This is called when new clothing or body parts are created. It may also be called in other /// This is called when new clothing or body parts are created. It may also be called in other
/// situations. /// situations.
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="transactionID"></param> /// <param name="transactionID"></param>
/// <param name="folderID"></param> /// <param name="folderID"></param>
/// <param name="callbackID"></param> /// <param name="callbackID"></param>
/// <param name="description"></param> /// <param name="description"></param>
/// <param name="name"></param> /// <param name="name"></param>
/// <param name="invType"></param> /// <param name="invType"></param>
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="wearableType"></param> /// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param> /// <param name="nextOwnerMask"></param>
public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType, uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask) sbyte type, byte wearableType, uint nextOwnerMask)
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[TRANSACTIONS MANAGER] Called HandleItemCreationFromTransaction with item {0}", name); "[TRANSACTIONS MANAGER] Called HandleItemCreationFromTransaction with item {0}", name);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.RequestCreateInventoryItem( transactions.RequestCreateInventoryItem(
remoteClient, transactionID, folderID, callbackID, description, remoteClient, transactionID, folderID, callbackID, description,
name, invType, type, wearableType, nextOwnerMask); name, invType, type, wearableType, nextOwnerMask);
} }
/// <summary> /// <summary>
/// Update an inventory item with data that has been received through a transaction. /// Update an inventory item with data that has been received through a transaction.
/// ///
/// This is called when clothing or body parts are updated (for instance, with new textures or /// This is called when clothing or body parts are updated (for instance, with new textures or
/// colours). It may also be called in other situations. /// colours). It may also be called in other situations.
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="transactionID"></param> /// <param name="transactionID"></param>
/// <param name="item"></param> /// <param name="item"></param>
public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID, public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item) InventoryItemBase item)
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[TRANSACTIONS MANAGER] Called HandleItemUpdateFromTransaction with item {0}", "[TRANSACTIONS MANAGER] Called HandleItemUpdateFromTransaction with item {0}",
item.Name); item.Name);
AgentAssetTransactions transactions AgentAssetTransactions transactions
= GetUserTransactions(remoteClient.AgentId); = GetUserTransactions(remoteClient.AgentId);
transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item); transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item);
} }
/// <summary> /// <summary>
/// Request that a client (agent) begin an asset transfer. /// Request that a client (agent) begin an asset transfer.
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="assetID"></param> /// <param name="assetID"></param>
/// <param name="transaction"></param> /// <param name="transaction"></param>
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="data"></param></param> /// <param name="data"></param></param>
/// <param name="tempFile"></param> /// <param name="tempFile"></param>
public void HandleUDPUploadRequest(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, public void HandleUDPUploadRequest(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type,
byte[] data, bool storeLocal, bool tempFile) byte[] data, bool storeLocal, bool tempFile)
{ {
// Console.WriteLine("asset upload of " + assetID); // Console.WriteLine("asset upload of " + assetID);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
AgentAssetTransactions.AssetXferUploader uploader = transactions.RequestXferUploader(transaction); AgentAssetTransactions.AssetXferUploader uploader = transactions.RequestXferUploader(transaction);
if (uploader != null) if (uploader != null)
{ {
if (uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile)) if (uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile))
{ {
} }
} }
} }
/// <summary> /// <summary>
/// Handle asset transfer data packets received in response to the asset upload request in /// Handle asset transfer data packets received in response to the asset upload request in
/// HandleUDPUploadRequest() /// HandleUDPUploadRequest()
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="xferID"></param> /// <param name="xferID"></param>
/// <param name="packetID"></param> /// <param name="packetID"></param>
/// <param name="data"></param> /// <param name="data"></param>
public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data) public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data)
{ {
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.HandleXfer(xferID, packetID, data); transactions.HandleXfer(xferID, packetID, data);
} }
} }
} }

View File

@ -1,219 +1,219 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload
{ {
public class TextureDownloadModule : IRegionModule public class TextureDownloadModule : IRegionModule
{ {
//private static readonly log4net.ILog m_log //private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// There is one queue for all textures waiting to be sent, regardless of the requesting user. /// There is one queue for all textures waiting to be sent, regardless of the requesting user.
/// </summary> /// </summary>
private readonly BlockingQueue<ITextureSender> m_queueSenders private readonly BlockingQueue<ITextureSender> m_queueSenders
= new BlockingQueue<ITextureSender>(); = new BlockingQueue<ITextureSender>();
/// <summary> /// <summary>
/// Each user has their own texture download service. /// Each user has their own texture download service.
/// </summary> /// </summary>
private readonly Dictionary<LLUUID, UserTextureDownloadService> m_userTextureServices = private readonly Dictionary<LLUUID, UserTextureDownloadService> m_userTextureServices =
new Dictionary<LLUUID, UserTextureDownloadService>(); new Dictionary<LLUUID, UserTextureDownloadService>();
private Scene m_scene; private Scene m_scene;
private List<Scene> m_scenes = new List<Scene>(); private List<Scene> m_scenes = new List<Scene>();
private Thread m_thread; private Thread m_thread;
public TextureDownloadModule() public TextureDownloadModule()
{ {
} }
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (m_scene == null) if (m_scene == null)
{ {
//Console.WriteLine("Creating Texture download module"); //Console.WriteLine("Creating Texture download module");
m_thread = new Thread(new ThreadStart(ProcessTextureSenders)); m_thread = new Thread(new ThreadStart(ProcessTextureSenders));
m_thread.Name = "ProcessTextureSenderThread"; m_thread.Name = "ProcessTextureSenderThread";
m_thread.IsBackground = true; m_thread.IsBackground = true;
m_thread.Start(); m_thread.Start();
ThreadTracker.Add(m_thread); ThreadTracker.Add(m_thread);
} }
if (!m_scenes.Contains(scene)) if (!m_scenes.Contains(scene))
{ {
m_scenes.Add(scene); m_scenes.Add(scene);
m_scene = scene; m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient; m_scene.EventManager.OnNewClient += NewClient;
m_scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence; m_scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence;
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "TextureDownloadModule"; } get { return "TextureDownloadModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
/// <summary> /// <summary>
/// Cleanup the texture service related objects for the removed presence. /// Cleanup the texture service related objects for the removed presence.
/// </summary> /// </summary>
/// <param name="agentId"> </param> /// <param name="agentId"> </param>
private void EventManager_OnRemovePresence(LLUUID agentId) private void EventManager_OnRemovePresence(LLUUID agentId)
{ {
UserTextureDownloadService textureService; UserTextureDownloadService textureService;
lock (m_userTextureServices) lock (m_userTextureServices)
{ {
if (m_userTextureServices.TryGetValue(agentId, out textureService)) if (m_userTextureServices.TryGetValue(agentId, out textureService))
{ {
textureService.Close(); textureService.Close();
m_userTextureServices.Remove(agentId); m_userTextureServices.Remove(agentId);
} }
} }
} }
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
client.OnRequestTexture += TextureRequest; client.OnRequestTexture += TextureRequest;
} }
/// <summary> /// <summary>
/// Does this user have a registered texture download service? /// Does this user have a registered texture download service?
/// </summary> /// </summary>
/// <param name="userID"></param> /// <param name="userID"></param>
/// <param name="textureService"></param> /// <param name="textureService"></param>
/// <returns>Always returns true, since a service is created if one does not already exist</returns> /// <returns>Always returns true, since a service is created if one does not already exist</returns>
private bool TryGetUserTextureService( private bool TryGetUserTextureService(
IClientAPI client, out UserTextureDownloadService textureService) IClientAPI client, out UserTextureDownloadService textureService)
{ {
lock (m_userTextureServices) lock (m_userTextureServices)
{ {
if (m_userTextureServices.TryGetValue(client.AgentId, out textureService)) if (m_userTextureServices.TryGetValue(client.AgentId, out textureService))
{ {
return true; return true;
} }
textureService = new UserTextureDownloadService(client, m_scene, m_queueSenders); textureService = new UserTextureDownloadService(client, m_scene, m_queueSenders);
m_userTextureServices.Add(client.AgentId, textureService); m_userTextureServices.Add(client.AgentId, textureService);
return true; return true;
} }
} }
/// <summary> /// <summary>
/// Start the process of requesting a given texture. /// Start the process of requesting a given texture.
/// </summary> /// </summary>
/// <param name="sender"> </param> /// <param name="sender"> </param>
/// <param name="e"></param> /// <param name="e"></param>
public void TextureRequest(Object sender, TextureRequestArgs e) public void TextureRequest(Object sender, TextureRequestArgs e)
{ {
IClientAPI client = (IClientAPI) sender; IClientAPI client = (IClientAPI) sender;
UserTextureDownloadService textureService; UserTextureDownloadService textureService;
if (TryGetUserTextureService(client, out textureService)) if (TryGetUserTextureService(client, out textureService))
{ {
textureService.HandleTextureRequest(e); textureService.HandleTextureRequest(e);
} }
} }
/// <summary> /// <summary>
/// Entry point for the thread dedicated to processing the texture queue. /// Entry point for the thread dedicated to processing the texture queue.
/// </summary> /// </summary>
public void ProcessTextureSenders() public void ProcessTextureSenders()
{ {
ITextureSender sender = null; ITextureSender sender = null;
while (true) while (true)
{ {
sender = m_queueSenders.Dequeue(); sender = m_queueSenders.Dequeue();
if (sender.Cancel) if (sender.Cancel)
{ {
TextureSent(sender); TextureSent(sender);
sender.Cancel = false; sender.Cancel = false;
} }
else else
{ {
bool finished = sender.SendTexturePacket(); bool finished = sender.SendTexturePacket();
if (finished) if (finished)
{ {
TextureSent(sender); TextureSent(sender);
} }
else else
{ {
m_queueSenders.Enqueue(sender); m_queueSenders.Enqueue(sender);
} }
} }
// Make sure that any sender we currently have can get garbage collected // Make sure that any sender we currently have can get garbage collected
sender = null; sender = null;
//m_log.InfoFormat("[TEXTURE DOWNLOAD] Texture sender queue size: {0}", m_queueSenders.Count()); //m_log.InfoFormat("[TEXTURE DOWNLOAD] Texture sender queue size: {0}", m_queueSenders.Count());
} }
} }
/// <summary> /// <summary>
/// Called when the texture has finished sending. /// Called when the texture has finished sending.
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
private void TextureSent(ITextureSender sender) private void TextureSent(ITextureSender sender)
{ {
sender.Sending = false; sender.Sending = false;
//m_log.DebugFormat("[TEXTURE DOWNLOAD]: Removing download stat for {0}", sender.assetID); //m_log.DebugFormat("[TEXTURE DOWNLOAD]: Removing download stat for {0}", sender.assetID);
m_scene.AddPendingDownloads(-1); m_scene.AddPendingDownloads(-1);
} }
} }
} }

View File

@ -1,98 +1,98 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using libsecondlife; using libsecondlife;
using libsecondlife.Packets; using libsecondlife.Packets;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload
{ {
/// <summary> /// <summary>
/// Sends a 'texture not found' packet back to the client /// Sends a 'texture not found' packet back to the client
/// </summary> /// </summary>
public class TextureNotFoundSender : ITextureSender public class TextureNotFoundSender : ITextureSender
{ {
//private static readonly log4net.ILog m_log //private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private bool m_cancel = false; private bool m_cancel = false;
private IClientAPI m_client; private IClientAPI m_client;
// See ITextureSender // See ITextureSender
private bool m_sending = false; private bool m_sending = false;
private LLUUID m_textureId; private LLUUID m_textureId;
// See ITextureSender // See ITextureSender
public TextureNotFoundSender(IClientAPI client, LLUUID textureID) public TextureNotFoundSender(IClientAPI client, LLUUID textureID)
{ {
m_client = client; m_client = client;
m_textureId = textureID; m_textureId = textureID;
} }
#region ITextureSender Members #region ITextureSender Members
public bool Sending public bool Sending
{ {
get { return false; } get { return false; }
set { m_sending = value; } set { m_sending = value; }
} }
public bool Cancel public bool Cancel
{ {
get { return false; } get { return false; }
set { m_cancel = value; } set { m_cancel = value; }
} }
// See ITextureSender // See ITextureSender
public void UpdateRequest(int discardLevel, uint packetNumber) public void UpdateRequest(int discardLevel, uint packetNumber)
{ {
// Not need to implement since priority changes don't affect this operation // Not need to implement since priority changes don't affect this operation
} }
// See ITextureSender // See ITextureSender
public bool SendTexturePacket() public bool SendTexturePacket()
{ {
//m_log.InfoFormat( //m_log.InfoFormat(
// "[TEXTURE NOT FOUND SENDER]: Informing the client that texture {0} cannot be found", // "[TEXTURE NOT FOUND SENDER]: Informing the client that texture {0} cannot be found",
// m_textureId); // m_textureId);
ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket(); ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket();
notFound.ImageID.ID = m_textureId; notFound.ImageID.ID = m_textureId;
// XXX Temporarily disabling as this appears to be causing client crashes on at least // XXX Temporarily disabling as this appears to be causing client crashes on at least
// 1.19.0(5) of the Linden Second Life client. // 1.19.0(5) of the Linden Second Life client.
// m_client.OutPacket(notFound, ThrottleOutPacketType.Texture); // m_client.OutPacket(notFound, ThrottleOutPacketType.Texture);
return true; return true;
} }
#endregion #endregion
} }
} }

View File

@ -1,249 +1,249 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Limit; using OpenSim.Framework.Communications.Limit;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload
{ {
/// <summary> /// <summary>
/// This module sets up texture senders in response to client texture requests, and places them on a /// This module sets up texture senders in response to client texture requests, and places them on a
/// processing queue once those senders have the appropriate data (i.e. a texture retrieved from the /// processing queue once those senders have the appropriate data (i.e. a texture retrieved from the
/// asset cache). /// asset cache).
/// </summary> /// </summary>
public class UserTextureDownloadService public class UserTextureDownloadService
{ {
private static readonly ILog m_log private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// We will allow the client to request the same texture n times before dropping further requests /// We will allow the client to request the same texture n times before dropping further requests
/// ///
/// This number includes repeated requests for the same texture at different resolutions (which we don't /// This number includes repeated requests for the same texture at different resolutions (which we don't
/// currently handle properly as far as I know). However, this situation should be handled in a more /// currently handle properly as far as I know). However, this situation should be handled in a more
/// sophisticated way. /// sophisticated way.
/// </summary> /// </summary>
private static readonly int MAX_ALLOWED_TEXTURE_REQUESTS = 5; private static readonly int MAX_ALLOWED_TEXTURE_REQUESTS = 5;
/// <summary> /// <summary>
/// XXX Also going to limit requests for found textures. /// XXX Also going to limit requests for found textures.
/// </summary> /// </summary>
private readonly IRequestLimitStrategy<LLUUID> foundTextureLimitStrategy private readonly IRequestLimitStrategy<LLUUID> foundTextureLimitStrategy
= new RepeatLimitStrategy<LLUUID>(MAX_ALLOWED_TEXTURE_REQUESTS); = new RepeatLimitStrategy<LLUUID>(MAX_ALLOWED_TEXTURE_REQUESTS);
private readonly IClientAPI m_client; private readonly IClientAPI m_client;
private readonly Scene m_scene; private readonly Scene m_scene;
/// <summary> /// <summary>
/// Texture Senders are placed in this queue once they have received their texture from the asset /// Texture Senders are placed in this queue once they have received their texture from the asset
/// cache. Another module actually invokes the send. /// cache. Another module actually invokes the send.
/// </summary> /// </summary>
private readonly BlockingQueue<ITextureSender> m_sharedSendersQueue; private readonly BlockingQueue<ITextureSender> m_sharedSendersQueue;
/// <summary> /// <summary>
/// Holds texture senders before they have received the appropriate texture from the asset cache. /// Holds texture senders before they have received the appropriate texture from the asset cache.
/// </summary> /// </summary>
private readonly Dictionary<LLUUID, TextureSender.TextureSender> m_textureSenders = new Dictionary<LLUUID, TextureSender.TextureSender>(); private readonly Dictionary<LLUUID, TextureSender.TextureSender> m_textureSenders = new Dictionary<LLUUID, TextureSender.TextureSender>();
/// <summary> /// <summary>
/// We're going to limit requests for the same missing texture. /// We're going to limit requests for the same missing texture.
/// XXX This is really a temporary solution to deal with the situation where a client continually requests /// XXX This is really a temporary solution to deal with the situation where a client continually requests
/// the same missing textures /// the same missing textures
/// </summary> /// </summary>
private readonly IRequestLimitStrategy<LLUUID> missingTextureLimitStrategy private readonly IRequestLimitStrategy<LLUUID> missingTextureLimitStrategy
= new RepeatLimitStrategy<LLUUID>(MAX_ALLOWED_TEXTURE_REQUESTS); = new RepeatLimitStrategy<LLUUID>(MAX_ALLOWED_TEXTURE_REQUESTS);
public UserTextureDownloadService( public UserTextureDownloadService(
IClientAPI client, Scene scene, BlockingQueue<ITextureSender> sharedQueue) IClientAPI client, Scene scene, BlockingQueue<ITextureSender> sharedQueue)
{ {
m_client = client; m_client = client;
m_scene = scene; m_scene = scene;
m_sharedSendersQueue = sharedQueue; m_sharedSendersQueue = sharedQueue;
} }
/// <summary> /// <summary>
/// Handle a texture request. This involves creating a texture sender and placing it on the /// Handle a texture request. This involves creating a texture sender and placing it on the
/// previously passed in shared queue. /// previously passed in shared queue.
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
public void HandleTextureRequest(TextureRequestArgs e) public void HandleTextureRequest(TextureRequestArgs e)
{ {
TextureSender.TextureSender textureSender; TextureSender.TextureSender textureSender;
//TODO: should be working out the data size/ number of packets to be sent for each discard level //TODO: should be working out the data size/ number of packets to be sent for each discard level
if ((e.DiscardLevel >= 0) || (e.Priority != 0)) if ((e.DiscardLevel >= 0) || (e.Priority != 0))
{ {
lock (m_textureSenders) lock (m_textureSenders)
{ {
if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender)) if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender))
{ {
// If we've received new non UUID information for this request and it hasn't dispatched // If we've received new non UUID information for this request and it hasn't dispatched
// yet, then update the request accordingly. // yet, then update the request accordingly.
textureSender.UpdateRequest(e.DiscardLevel, e.PacketNumber); textureSender.UpdateRequest(e.DiscardLevel, e.PacketNumber);
} }
else else
{ {
if (!foundTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) if (!foundTextureLimitStrategy.AllowRequest(e.RequestedAssetID))
{ {
// m_log.DebugFormat( // m_log.DebugFormat(
// "[USER TEXTURE DOWNLOAD SERVICE]: Refusing request for {0} from client {1}", // "[USER TEXTURE DOWNLOAD SERVICE]: Refusing request for {0} from client {1}",
// e.RequestedAssetID, m_client.AgentId); // e.RequestedAssetID, m_client.AgentId);
return; return;
} }
else if (!missingTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) else if (!missingTextureLimitStrategy.AllowRequest(e.RequestedAssetID))
{ {
if (missingTextureLimitStrategy.IsFirstRefusal(e.RequestedAssetID)) if (missingTextureLimitStrategy.IsFirstRefusal(e.RequestedAssetID))
{ {
// Commenting out this message for now as it causes too much noise with other // Commenting out this message for now as it causes too much noise with other
// debug messages. // debug messages.
// TODO: possibly record this as a statistic in the future // TODO: possibly record this as a statistic in the future
// //
// m_log.DebugFormat( // m_log.DebugFormat(
// "[USER TEXTURE DOWNLOAD SERVICE]: Dropping requests for notified missing texture {0} for client {1} since we have received more than {2} requests", // "[USER TEXTURE DOWNLOAD SERVICE]: Dropping requests for notified missing texture {0} for client {1} since we have received more than {2} requests",
// e.RequestedAssetID, m_client.AgentId, MAX_ALLOWED_TEXTURE_REQUESTS); // e.RequestedAssetID, m_client.AgentId, MAX_ALLOWED_TEXTURE_REQUESTS);
} }
return; return;
} }
m_scene.AddPendingDownloads(1); m_scene.AddPendingDownloads(1);
TextureSender.TextureSender requestHandler = new TextureSender.TextureSender(m_client, e.DiscardLevel, e.PacketNumber); TextureSender.TextureSender requestHandler = new TextureSender.TextureSender(m_client, e.DiscardLevel, e.PacketNumber);
m_textureSenders.Add(e.RequestedAssetID, requestHandler); m_textureSenders.Add(e.RequestedAssetID, requestHandler);
m_scene.AssetCache.GetAsset(e.RequestedAssetID, TextureCallback, true); m_scene.AssetCache.GetAsset(e.RequestedAssetID, TextureCallback, true);
} }
} }
} }
else else
{ {
lock (m_textureSenders) lock (m_textureSenders)
{ {
if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender)) if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender))
{ {
textureSender.Cancel = true; textureSender.Cancel = true;
} }
} }
} }
} }
/// <summary> /// <summary>
/// The callback for the asset cache when a texture has been retrieved. This method queues the /// The callback for the asset cache when a texture has been retrieved. This method queues the
/// texture sender for processing. /// texture sender for processing.
/// </summary> /// </summary>
/// <param name="textureID"></param> /// <param name="textureID"></param>
/// <param name="texture"></param> /// <param name="texture"></param>
public void TextureCallback(LLUUID textureID, AssetBase texture) public void TextureCallback(LLUUID textureID, AssetBase texture)
{ {
//m_log.DebugFormat("[USER TEXTURE DOWNLOAD SERVICE]: Calling TextureCallback with {0}, texture == null is {1}", textureID, (texture == null ? true : false)); //m_log.DebugFormat("[USER TEXTURE DOWNLOAD SERVICE]: Calling TextureCallback with {0}, texture == null is {1}", textureID, (texture == null ? true : false));
lock (m_textureSenders) lock (m_textureSenders)
{ {
TextureSender.TextureSender textureSender; TextureSender.TextureSender textureSender;
if (m_textureSenders.TryGetValue(textureID, out textureSender)) if (m_textureSenders.TryGetValue(textureID, out textureSender))
{ {
// XXX It may be perfectly valid for a texture to have no data... but if we pass // XXX It may be perfectly valid for a texture to have no data... but if we pass
// this on to the TextureSender it will blow up, so just discard for now. // this on to the TextureSender it will blow up, so just discard for now.
// Needs investigation. // Needs investigation.
if (texture == null || texture.Data == null) if (texture == null || texture.Data == null)
{ {
if (!missingTextureLimitStrategy.IsMonitoringRequests(textureID)) if (!missingTextureLimitStrategy.IsMonitoringRequests(textureID))
{ {
missingTextureLimitStrategy.MonitorRequests(textureID); missingTextureLimitStrategy.MonitorRequests(textureID);
m_log.DebugFormat( m_log.DebugFormat(
"[USER TEXTURE DOWNLOAD SERVICE]: Queueing first TextureNotFoundSender for {0}, client {1}", "[USER TEXTURE DOWNLOAD SERVICE]: Queueing first TextureNotFoundSender for {0}, client {1}",
textureID, m_client.AgentId); textureID, m_client.AgentId);
} }
ITextureSender textureNotFoundSender = new TextureNotFoundSender(m_client, textureID); ITextureSender textureNotFoundSender = new TextureNotFoundSender(m_client, textureID);
EnqueueTextureSender(textureNotFoundSender); EnqueueTextureSender(textureNotFoundSender);
} }
else else
{ {
if (!textureSender.ImageLoaded) if (!textureSender.ImageLoaded)
{ {
textureSender.TextureReceived(texture); textureSender.TextureReceived(texture);
EnqueueTextureSender(textureSender); EnqueueTextureSender(textureSender);
foundTextureLimitStrategy.MonitorRequests(textureID); foundTextureLimitStrategy.MonitorRequests(textureID);
} }
} }
//m_log.InfoFormat("[TEXTURE SENDER] Removing texture sender with uuid {0}", textureID); //m_log.InfoFormat("[TEXTURE SENDER] Removing texture sender with uuid {0}", textureID);
m_textureSenders.Remove(textureID); m_textureSenders.Remove(textureID);
//m_log.InfoFormat("[TEXTURE SENDER] Current texture senders in dictionary: {0}", m_textureSenders.Count); //m_log.InfoFormat("[TEXTURE SENDER] Current texture senders in dictionary: {0}", m_textureSenders.Count);
} }
else else
{ {
m_log.WarnFormat( m_log.WarnFormat(
"Got a texture uuid {0} with no sender object to handle it, this shouldn't happen", "Got a texture uuid {0} with no sender object to handle it, this shouldn't happen",
textureID); textureID);
} }
} }
} }
/// <summary> /// <summary>
/// Place a ready texture sender on the processing queue. /// Place a ready texture sender on the processing queue.
/// </summary> /// </summary>
/// <param name="textureSender"></param> /// <param name="textureSender"></param>
private void EnqueueTextureSender(ITextureSender textureSender) private void EnqueueTextureSender(ITextureSender textureSender)
{ {
textureSender.Cancel = false; textureSender.Cancel = false;
textureSender.Sending = true; textureSender.Sending = true;
if (!m_sharedSendersQueue.Contains(textureSender)) if (!m_sharedSendersQueue.Contains(textureSender))
{ {
m_sharedSendersQueue.Enqueue(textureSender); m_sharedSendersQueue.Enqueue(textureSender);
} }
} }
/// <summary> /// <summary>
/// Close this module. /// Close this module.
/// </summary> /// </summary>
internal void Close() internal void Close()
{ {
lock (m_textureSenders) lock (m_textureSenders)
{ {
foreach (TextureSender.TextureSender textureSender in m_textureSenders.Values) foreach (TextureSender.TextureSender textureSender in m_textureSenders.Values)
{ {
textureSender.Cancel = true; textureSender.Cancel = true;
} }
m_textureSenders.Clear(); m_textureSenders.Clear();
} }
} }
} }
} }

View File

@ -1,223 +1,223 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Reflection; using System.Reflection;
using libsecondlife.Packets; using libsecondlife.Packets;
using log4net; using log4net;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.Agent.TextureSender namespace OpenSim.Region.Environment.Modules.Agent.TextureSender
{ {
/// <summary> /// <summary>
/// A TextureSender handles the process of receiving a texture requested by the client from the /// A TextureSender handles the process of receiving a texture requested by the client from the
/// AssetCache, and then sending that texture back to the client. /// AssetCache, and then sending that texture back to the client.
/// </summary> /// </summary>
public class TextureSender : ITextureSender public class TextureSender : ITextureSender
{ {
private static readonly ILog m_log private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// Records the number of times texture send has been called. /// Records the number of times texture send has been called.
/// </summary> /// </summary>
public int counter = 0; public int counter = 0;
public bool ImageLoaded = false; public bool ImageLoaded = false;
/// <summary> /// <summary>
/// Holds the texture asset to send. /// Holds the texture asset to send.
/// </summary> /// </summary>
private AssetBase m_asset; private AssetBase m_asset;
//public LLUUID assetID { get { return m_asset.FullID; } } //public LLUUID assetID { get { return m_asset.FullID; } }
private bool m_cancel = false; private bool m_cancel = false;
// See ITextureSender // See ITextureSender
private bool m_sending = false; private bool m_sending = false;
/// <summary> /// <summary>
/// This is actually the number of extra packets required to send the texture data! We always assume /// This is actually the number of extra packets required to send the texture data! We always assume
/// at least one is required. /// at least one is required.
/// </summary> /// </summary>
private int NumPackets = 0; private int NumPackets = 0;
/// <summary> /// <summary>
/// Holds the packet number to send next. In this case, each packet is 1000 bytes long and starts /// Holds the packet number to send next. In this case, each packet is 1000 bytes long and starts
/// at the 600th byte (0th indexed). /// at the 600th byte (0th indexed).
/// </summary> /// </summary>
private int PacketCounter = 0; private int PacketCounter = 0;
private int RequestedDiscardLevel = -1; private int RequestedDiscardLevel = -1;
private IClientAPI RequestUser; private IClientAPI RequestUser;
private uint StartPacketNumber = 0; private uint StartPacketNumber = 0;
public TextureSender(IClientAPI client, int discardLevel, uint packetNumber) public TextureSender(IClientAPI client, int discardLevel, uint packetNumber)
{ {
RequestUser = client; RequestUser = client;
RequestedDiscardLevel = discardLevel; RequestedDiscardLevel = discardLevel;
StartPacketNumber = packetNumber; StartPacketNumber = packetNumber;
} }
#region ITextureSender Members #region ITextureSender Members
public bool Cancel public bool Cancel
{ {
get { return false; } get { return false; }
set { m_cancel = value; } set { m_cancel = value; }
} }
public bool Sending public bool Sending
{ {
get { return false; } get { return false; }
set { m_sending = value; } set { m_sending = value; }
} }
// See ITextureSender // See ITextureSender
public void UpdateRequest(int discardLevel, uint packetNumber) public void UpdateRequest(int discardLevel, uint packetNumber)
{ {
RequestedDiscardLevel = discardLevel; RequestedDiscardLevel = discardLevel;
StartPacketNumber = packetNumber; StartPacketNumber = packetNumber;
PacketCounter = (int) StartPacketNumber; PacketCounter = (int) StartPacketNumber;
} }
// See ITextureSender // See ITextureSender
public bool SendTexturePacket() public bool SendTexturePacket()
{ {
//m_log.DebugFormat("[TEXTURE SENDER]: Sending packet for {0}", m_asset.FullID); //m_log.DebugFormat("[TEXTURE SENDER]: Sending packet for {0}", m_asset.FullID);
SendPacket(); SendPacket();
counter++; counter++;
if ((NumPackets == 0) || (RequestedDiscardLevel == -1) || (PacketCounter > NumPackets) || if ((NumPackets == 0) || (RequestedDiscardLevel == -1) || (PacketCounter > NumPackets) ||
((RequestedDiscardLevel > 0) && (counter > 50 + (NumPackets / (RequestedDiscardLevel + 1))))) ((RequestedDiscardLevel > 0) && (counter > 50 + (NumPackets / (RequestedDiscardLevel + 1)))))
{ {
return true; return true;
} }
return false; return false;
} }
#endregion #endregion
/// <summary> /// <summary>
/// Load up the texture data to send. /// Load up the texture data to send.
/// </summary> /// </summary>
/// <param name="asset"> /// <param name="asset">
/// A <see cref="AssetBase"/> /// A <see cref="AssetBase"/>
/// </param> /// </param>
public void TextureReceived(AssetBase asset) public void TextureReceived(AssetBase asset)
{ {
m_asset = asset; m_asset = asset;
NumPackets = CalculateNumPackets(asset.Data.Length); NumPackets = CalculateNumPackets(asset.Data.Length);
PacketCounter = (int) StartPacketNumber; PacketCounter = (int) StartPacketNumber;
ImageLoaded = true; ImageLoaded = true;
} }
/// <summary> /// <summary>
/// Sends a texture packet to the client. /// Sends a texture packet to the client.
/// </summary> /// </summary>
private void SendPacket() private void SendPacket()
{ {
if (PacketCounter <= NumPackets) if (PacketCounter <= NumPackets)
{ {
if (PacketCounter == 0) if (PacketCounter == 0)
{ {
if (NumPackets == 0) if (NumPackets == 0)
{ {
ImageDataPacket im = new ImageDataPacket(); ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false; im.Header.Reliable = false;
im.ImageID.Packets = 1; im.ImageID.Packets = 1;
im.ImageID.ID = m_asset.FullID; im.ImageID.ID = m_asset.FullID;
im.ImageID.Size = (uint) m_asset.Data.Length; im.ImageID.Size = (uint) m_asset.Data.Length;
im.ImageData.Data = m_asset.Data; im.ImageData.Data = m_asset.Data;
im.ImageID.Codec = 2; im.ImageID.Codec = 2;
RequestUser.OutPacket(im, ThrottleOutPacketType.Texture); RequestUser.OutPacket(im, ThrottleOutPacketType.Texture);
PacketCounter++; PacketCounter++;
} }
else else
{ {
ImageDataPacket im = new ImageDataPacket(); ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false; im.Header.Reliable = false;
im.ImageID.Packets = (ushort) (NumPackets); im.ImageID.Packets = (ushort) (NumPackets);
im.ImageID.ID = m_asset.FullID; im.ImageID.ID = m_asset.FullID;
im.ImageID.Size = (uint) m_asset.Data.Length; im.ImageID.Size = (uint) m_asset.Data.Length;
im.ImageData.Data = new byte[600]; im.ImageData.Data = new byte[600];
Array.Copy(m_asset.Data, 0, im.ImageData.Data, 0, 600); Array.Copy(m_asset.Data, 0, im.ImageData.Data, 0, 600);
im.ImageID.Codec = 2; im.ImageID.Codec = 2;
RequestUser.OutPacket(im, ThrottleOutPacketType.Texture); RequestUser.OutPacket(im, ThrottleOutPacketType.Texture);
PacketCounter++; PacketCounter++;
} }
} }
else else
{ {
ImagePacketPacket im = new ImagePacketPacket(); ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false; im.Header.Reliable = false;
im.ImageID.Packet = (ushort) (PacketCounter); im.ImageID.Packet = (ushort) (PacketCounter);
im.ImageID.ID = m_asset.FullID; im.ImageID.ID = m_asset.FullID;
int size = m_asset.Data.Length - 600 - (1000 * (PacketCounter - 1)); int size = m_asset.Data.Length - 600 - (1000 * (PacketCounter - 1));
if (size > 1000) size = 1000; if (size > 1000) size = 1000;
im.ImageData.Data = new byte[size]; im.ImageData.Data = new byte[size];
try try
{ {
Array.Copy(m_asset.Data, 600 + (1000 * (PacketCounter - 1)), im.ImageData.Data, 0, size); Array.Copy(m_asset.Data, 600 + (1000 * (PacketCounter - 1)), im.ImageData.Data, 0, size);
} }
catch (ArgumentOutOfRangeException) catch (ArgumentOutOfRangeException)
{ {
m_log.Error("[TEXTURE SENDER]: Unable to separate texture into multiple packets: Array bounds failure on asset:" + m_log.Error("[TEXTURE SENDER]: Unable to separate texture into multiple packets: Array bounds failure on asset:" +
m_asset.FullID.ToString()); m_asset.FullID.ToString());
return; return;
} }
RequestUser.OutPacket(im, ThrottleOutPacketType.Texture); RequestUser.OutPacket(im, ThrottleOutPacketType.Texture);
PacketCounter++; PacketCounter++;
} }
} }
} }
/// <summary> /// <summary>
/// Calculate the number of packets that will be required to send the texture loaded into this sender /// Calculate the number of packets that will be required to send the texture loaded into this sender
/// This is actually the number of 1000 byte packets not including an initial 600 byte packet... /// This is actually the number of 1000 byte packets not including an initial 600 byte packet...
/// </summary> /// </summary>
/// <param name="length"></param> /// <param name="length"></param>
/// <returns></returns> /// <returns></returns>
private int CalculateNumPackets(int length) private int CalculateNumPackets(int length)
{ {
int numPackets = 0; int numPackets = 0;
if (length > 600) if (length > 600)
{ {
//over 600 bytes so split up file //over 600 bytes so split up file
int restData = (length - 600); int restData = (length - 600);
int restPackets = ((restData + 999) / 1000); int restPackets = ((restData + 999) / 1000);
numPackets = restPackets; numPackets = restPackets;
} }
return numPackets; return numPackets;
} }
} }
} }

View File

@ -1,235 +1,235 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Agent.Xfer namespace OpenSim.Region.Environment.Modules.Agent.Xfer
{ {
public class XferModule : IRegionModule, IXfer public class XferModule : IRegionModule, IXfer
{ {
private Scene m_scene; private Scene m_scene;
public Dictionary<string, byte[]> NewFiles = new Dictionary<string, byte[]>(); public Dictionary<string, byte[]> NewFiles = new Dictionary<string, byte[]>();
public Dictionary<ulong, XferDownLoad> Transfers = new Dictionary<ulong, XferDownLoad>(); public Dictionary<ulong, XferDownLoad> Transfers = new Dictionary<ulong, XferDownLoad>();
public XferModule() public XferModule()
{ {
} }
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient; m_scene.EventManager.OnNewClient += NewClient;
m_scene.RegisterModuleInterface<IXfer>(this); m_scene.RegisterModuleInterface<IXfer>(this);
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "XferModule"; } get { return "XferModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
#region IXfer Members #region IXfer Members
public bool AddNewFile(string fileName, byte[] data) public bool AddNewFile(string fileName, byte[] data)
{ {
lock (NewFiles) lock (NewFiles)
{ {
if (NewFiles.ContainsKey(fileName)) if (NewFiles.ContainsKey(fileName))
{ {
NewFiles[fileName] = data; NewFiles[fileName] = data;
} }
else else
{ {
NewFiles.Add(fileName, data); NewFiles.Add(fileName, data);
} }
} }
return true; return true;
} }
#endregion #endregion
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
client.OnRequestXfer += RequestXfer; client.OnRequestXfer += RequestXfer;
client.OnConfirmXfer += AckPacket; client.OnConfirmXfer += AckPacket;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="xferID"></param> /// <param name="xferID"></param>
/// <param name="fileName"></param> /// <param name="fileName"></param>
public void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName) public void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName)
{ {
lock (NewFiles) lock (NewFiles)
{ {
if (NewFiles.ContainsKey(fileName)) if (NewFiles.ContainsKey(fileName))
{ {
if (!Transfers.ContainsKey(xferID)) if (!Transfers.ContainsKey(xferID))
{ {
byte[] fileData = NewFiles[fileName]; byte[] fileData = NewFiles[fileName];
XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient); XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient);
Transfers.Add(xferID, transaction); Transfers.Add(xferID, transaction);
NewFiles.Remove(fileName); NewFiles.Remove(fileName);
if (transaction.StartSend()) if (transaction.StartSend())
{ {
Transfers.Remove(xferID); Transfers.Remove(xferID);
} }
} }
} }
} }
} }
public void AckPacket(IClientAPI remoteClient, ulong xferID, uint packet) public void AckPacket(IClientAPI remoteClient, ulong xferID, uint packet)
{ {
if (Transfers.ContainsKey(xferID)) if (Transfers.ContainsKey(xferID))
{ {
if (Transfers[xferID].AckPacket(packet)) if (Transfers[xferID].AckPacket(packet))
{ {
{ {
Transfers.Remove(xferID); Transfers.Remove(xferID);
} }
} }
} }
} }
#region Nested type: XferDownLoad #region Nested type: XferDownLoad
public class XferDownLoad public class XferDownLoad
{ {
public IClientAPI Client; public IClientAPI Client;
private bool complete; private bool complete;
public byte[] Data = new byte[0]; public byte[] Data = new byte[0];
public int DataPointer = 0; public int DataPointer = 0;
public string FileName = String.Empty; public string FileName = String.Empty;
public uint Packet = 0; public uint Packet = 0;
public uint Serial = 1; public uint Serial = 1;
public ulong XferID = 0; public ulong XferID = 0;
public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client) public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client)
{ {
FileName = fileName; FileName = fileName;
Data = data; Data = data;
XferID = xferID; XferID = xferID;
Client = client; Client = client;
} }
public XferDownLoad() public XferDownLoad()
{ {
} }
/// <summary> /// <summary>
/// Start a transfer /// Start a transfer
/// </summary> /// </summary>
/// <returns>True if the transfer is complete, false if not</returns> /// <returns>True if the transfer is complete, false if not</returns>
public bool StartSend() public bool StartSend()
{ {
if (Data.Length < 1000) if (Data.Length < 1000)
{ {
// for now (testing ) we only support files under 1000 bytes // for now (testing ) we only support files under 1000 bytes
byte[] transferData = new byte[Data.Length + 4]; byte[] transferData = new byte[Data.Length + 4];
Array.Copy(Helpers.IntToBytes(Data.Length), 0, transferData, 0, 4); Array.Copy(Helpers.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, Data.Length); Array.Copy(Data, 0, transferData, 4, Data.Length);
Client.SendXferPacket(XferID, 0 + 0x80000000, transferData); Client.SendXferPacket(XferID, 0 + 0x80000000, transferData);
complete = true; complete = true;
} }
else else
{ {
byte[] transferData = new byte[1000 + 4]; byte[] transferData = new byte[1000 + 4];
Array.Copy(Helpers.IntToBytes(Data.Length), 0, transferData, 0, 4); Array.Copy(Helpers.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, 0, transferData, 4, 1000); Array.Copy(Data, 0, transferData, 4, 1000);
Client.SendXferPacket(XferID, 0, transferData); Client.SendXferPacket(XferID, 0, transferData);
Packet++; Packet++;
DataPointer = 1000; DataPointer = 1000;
} }
return complete; return complete;
} }
/// <summary> /// <summary>
/// Respond to an ack packet from the client /// Respond to an ack packet from the client
/// </summary> /// </summary>
/// <param name="packet"></param> /// <param name="packet"></param>
/// <returns>True if the transfer is complete, false otherwise</returns> /// <returns>True if the transfer is complete, false otherwise</returns>
public bool AckPacket(uint packet) public bool AckPacket(uint packet)
{ {
if (!complete) if (!complete)
{ {
if ((Data.Length - DataPointer) > 1000) if ((Data.Length - DataPointer) > 1000)
{ {
byte[] transferData = new byte[1000]; byte[] transferData = new byte[1000];
Array.Copy(Data, DataPointer, transferData, 0, 1000); Array.Copy(Data, DataPointer, transferData, 0, 1000);
Client.SendXferPacket(XferID, Packet, transferData); Client.SendXferPacket(XferID, Packet, transferData);
Packet++; Packet++;
DataPointer += 1000; DataPointer += 1000;
} }
else else
{ {
byte[] transferData = new byte[Data.Length - DataPointer]; byte[] transferData = new byte[Data.Length - DataPointer];
Array.Copy(Data, DataPointer, transferData, 0, Data.Length - DataPointer); Array.Copy(Data, DataPointer, transferData, 0, Data.Length - DataPointer);
uint endPacket = Packet |= (uint) 0x80000000; uint endPacket = Packet |= (uint) 0x80000000;
Client.SendXferPacket(XferID, endPacket, transferData); Client.SendXferPacket(XferID, endPacket, transferData);
Packet++; Packet++;
DataPointer += (Data.Length - DataPointer); DataPointer += (Data.Length - DataPointer);
complete = true; complete = true;
} }
} }
return complete; return complete;
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,338 +1,338 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
using OpenSim.Data.MySQLMapper; using OpenSim.Data.MySQLMapper;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
using OpenSim.Data.Base; using OpenSim.Data.Base;
namespace OpenSim.Region.Environment.Modules namespace OpenSim.Region.Environment.Modules
{ {
public class AvatarFactoryModule : IAvatarFactory public class AvatarFactoryModule : IAvatarFactory
{ {
private Scene m_scene = null; private Scene m_scene = null;
private readonly Dictionary<LLUUID, AvatarAppearance> m_avatarsAppearance = new Dictionary<LLUUID, AvatarAppearance>(); private readonly Dictionary<LLUUID, AvatarAppearance> m_avatarsAppearance = new Dictionary<LLUUID, AvatarAppearance>();
private bool m_enablePersist = false; private bool m_enablePersist = false;
private string m_connectionString; private string m_connectionString;
private bool m_configured = false; private bool m_configured = false;
private BaseDatabaseConnector m_databaseMapper; private BaseDatabaseConnector m_databaseMapper;
private AppearanceTableMapper m_appearanceMapper; private AppearanceTableMapper m_appearanceMapper;
private Dictionary<LLUUID, EventWaitHandle> m_fetchesInProgress = new Dictionary<LLUUID, EventWaitHandle>(); private Dictionary<LLUUID, EventWaitHandle> m_fetchesInProgress = new Dictionary<LLUUID, EventWaitHandle>();
private object m_syncLock = new object(); private object m_syncLock = new object();
public bool TryGetAvatarAppearance(LLUUID avatarId, out AvatarAppearance appearance) public bool TryGetAvatarAppearance(LLUUID avatarId, out AvatarAppearance appearance)
{ {
//should only let one thread at a time do this part //should only let one thread at a time do this part
EventWaitHandle waitHandle = null; EventWaitHandle waitHandle = null;
bool fetchInProgress = false; bool fetchInProgress = false;
lock (m_syncLock) lock (m_syncLock)
{ {
appearance = CheckCache(avatarId); appearance = CheckCache(avatarId);
if (appearance != null) if (appearance != null)
{ {
return true; return true;
} }
//not in cache so check to see if another thread is already fetching it //not in cache so check to see if another thread is already fetching it
if (m_fetchesInProgress.TryGetValue(avatarId, out waitHandle)) if (m_fetchesInProgress.TryGetValue(avatarId, out waitHandle))
{ {
fetchInProgress = true; fetchInProgress = true;
} }
else else
{ {
fetchInProgress = false; fetchInProgress = false;
//no thread already fetching this appearance, so add a wait handle to list //no thread already fetching this appearance, so add a wait handle to list
//for any following threads that want the same appearance //for any following threads that want the same appearance
waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
m_fetchesInProgress.Add(avatarId, waitHandle); m_fetchesInProgress.Add(avatarId, waitHandle);
} }
} }
if (fetchInProgress) if (fetchInProgress)
{ {
waitHandle.WaitOne(); waitHandle.WaitOne();
appearance = CheckCache(avatarId); appearance = CheckCache(avatarId);
if (appearance != null) if (appearance != null)
{ {
waitHandle = null; waitHandle = null;
return true; return true;
} }
else else
{ {
waitHandle = null; waitHandle = null;
return false; return false;
} }
} }
else else
{ {
Thread.Sleep(5000); Thread.Sleep(5000);
//this is the first thread to request this appearance //this is the first thread to request this appearance
//so let it check the db and if not found then create a default appearance //so let it check the db and if not found then create a default appearance
//and add that to the cache //and add that to the cache
appearance = CheckDatabase(avatarId); appearance = CheckDatabase(avatarId);
if (appearance != null) if (appearance != null)
{ {
//appearance has now been added to cache so lets pulse any waiting threads //appearance has now been added to cache so lets pulse any waiting threads
lock (m_syncLock) lock (m_syncLock)
{ {
m_fetchesInProgress.Remove(avatarId); m_fetchesInProgress.Remove(avatarId);
waitHandle.Set(); waitHandle.Set();
} }
// waitHandle.Close(); // waitHandle.Close();
waitHandle = null; waitHandle = null;
return true; return true;
} }
//not found a appearance for the user, so create a new default one //not found a appearance for the user, so create a new default one
appearance = CreateDefault(avatarId); appearance = CreateDefault(avatarId);
if (appearance != null) if (appearance != null)
{ {
//update database //update database
if (m_enablePersist) if (m_enablePersist)
{ {
m_appearanceMapper.Add(avatarId.UUID, appearance); m_appearanceMapper.Add(avatarId.UUID, appearance);
} }
//add appearance to dictionary cache //add appearance to dictionary cache
lock (m_avatarsAppearance) lock (m_avatarsAppearance)
{ {
m_avatarsAppearance[avatarId] = appearance; m_avatarsAppearance[avatarId] = appearance;
} }
//appearance has now been added to cache so lets pulse any waiting threads //appearance has now been added to cache so lets pulse any waiting threads
lock (m_syncLock) lock (m_syncLock)
{ {
m_fetchesInProgress.Remove(avatarId); m_fetchesInProgress.Remove(avatarId);
waitHandle.Set(); waitHandle.Set();
} }
// waitHandle.Close(); // waitHandle.Close();
waitHandle = null; waitHandle = null;
return true; return true;
} }
else else
{ {
//something went wrong, so release the wait handle and remove it //something went wrong, so release the wait handle and remove it
//all waiting threads will fail to find cached appearance //all waiting threads will fail to find cached appearance
//but its better for them to fail than wait for ever //but its better for them to fail than wait for ever
lock (m_syncLock) lock (m_syncLock)
{ {
m_fetchesInProgress.Remove(avatarId); m_fetchesInProgress.Remove(avatarId);
waitHandle.Set(); waitHandle.Set();
} }
//waitHandle.Close(); //waitHandle.Close();
waitHandle = null; waitHandle = null;
return false; return false;
} }
} }
} }
private AvatarAppearance CreateDefault(LLUUID avatarId) private AvatarAppearance CreateDefault(LLUUID avatarId)
{ {
AvatarAppearance appearance = null; AvatarAppearance appearance = null;
AvatarWearable[] wearables; AvatarWearable[] wearables;
byte[] visualParams; byte[] visualParams;
GetDefaultAvatarAppearance(out wearables, out visualParams); GetDefaultAvatarAppearance(out wearables, out visualParams);
appearance = new AvatarAppearance(avatarId, wearables, visualParams); appearance = new AvatarAppearance(avatarId, wearables, visualParams);
return appearance; return appearance;
} }
private AvatarAppearance CheckDatabase(LLUUID avatarId) private AvatarAppearance CheckDatabase(LLUUID avatarId)
{ {
AvatarAppearance appearance = null; AvatarAppearance appearance = null;
if (m_enablePersist) if (m_enablePersist)
{ {
if (m_appearanceMapper.TryGetValue(avatarId.UUID, out appearance)) if (m_appearanceMapper.TryGetValue(avatarId.UUID, out appearance))
{ {
appearance.VisualParams = GetDefaultVisualParams(); appearance.VisualParams = GetDefaultVisualParams();
appearance.TextureEntry = AvatarAppearance.GetDefaultTextureEntry(); appearance.TextureEntry = AvatarAppearance.GetDefaultTextureEntry();
lock (m_avatarsAppearance) lock (m_avatarsAppearance)
{ {
m_avatarsAppearance[avatarId] = appearance; m_avatarsAppearance[avatarId] = appearance;
} }
} }
} }
return appearance; return appearance;
} }
private AvatarAppearance CheckCache(LLUUID avatarId) private AvatarAppearance CheckCache(LLUUID avatarId)
{ {
AvatarAppearance appearance = null; AvatarAppearance appearance = null;
lock (m_avatarsAppearance) lock (m_avatarsAppearance)
{ {
if (m_avatarsAppearance.ContainsKey(avatarId)) if (m_avatarsAppearance.ContainsKey(avatarId))
{ {
appearance = m_avatarsAppearance[avatarId]; appearance = m_avatarsAppearance[avatarId];
} }
} }
return appearance; return appearance;
} }
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
scene.RegisterModuleInterface<IAvatarFactory>(this); scene.RegisterModuleInterface<IAvatarFactory>(this);
scene.EventManager.OnNewClient += NewClient; scene.EventManager.OnNewClient += NewClient;
if (m_scene == null) if (m_scene == null)
{ {
m_scene = scene; m_scene = scene;
} }
if (!m_configured) if (!m_configured)
{ {
m_configured = true; m_configured = true;
try try
{ {
m_enablePersist = source.Configs["Startup"].GetBoolean("appearance_persist", false); m_enablePersist = source.Configs["Startup"].GetBoolean("appearance_persist", false);
m_connectionString = source.Configs["Startup"].GetString("appearance_connection_string", ""); m_connectionString = source.Configs["Startup"].GetString("appearance_connection_string", "");
} }
catch (Exception) catch (Exception)
{ {
} }
if (m_enablePersist) if (m_enablePersist)
{ {
m_databaseMapper = new MySQLDatabaseMapper(m_connectionString); m_databaseMapper = new MySQLDatabaseMapper(m_connectionString);
m_appearanceMapper = new AppearanceTableMapper(m_databaseMapper, "AvatarAppearance"); m_appearanceMapper = new AppearanceTableMapper(m_databaseMapper, "AvatarAppearance");
} }
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "Default Avatar Factory"; } get { return "Default Avatar Factory"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
client.OnAvatarNowWearing += AvatarIsWearing; client.OnAvatarNowWearing += AvatarIsWearing;
} }
public void RemoveClient(IClientAPI client) public void RemoveClient(IClientAPI client)
{ {
// client.OnAvatarNowWearing -= AvatarIsWearing; // client.OnAvatarNowWearing -= AvatarIsWearing;
} }
public void AvatarIsWearing(Object sender, AvatarWearingArgs e) public void AvatarIsWearing(Object sender, AvatarWearingArgs e)
{ {
IClientAPI clientView = (IClientAPI)sender; IClientAPI clientView = (IClientAPI)sender;
CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(clientView.AgentId); CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(clientView.AgentId);
if (profile != null) if (profile != null)
{ {
if (profile.RootFolder != null) if (profile.RootFolder != null)
{ {
if (m_avatarsAppearance.ContainsKey(clientView.AgentId)) if (m_avatarsAppearance.ContainsKey(clientView.AgentId))
{ {
AvatarAppearance avatAppearance = null; AvatarAppearance avatAppearance = null;
lock (m_avatarsAppearance) lock (m_avatarsAppearance)
{ {
avatAppearance = m_avatarsAppearance[clientView.AgentId]; avatAppearance = m_avatarsAppearance[clientView.AgentId];
} }
foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
{ {
if (wear.Type < 13) if (wear.Type < 13)
{ {
if (wear.ItemID == LLUUID.Zero) if (wear.ItemID == LLUUID.Zero)
{ {
avatAppearance.Wearables[wear.Type].ItemID = LLUUID.Zero; avatAppearance.Wearables[wear.Type].ItemID = LLUUID.Zero;
avatAppearance.Wearables[wear.Type].AssetID = LLUUID.Zero; avatAppearance.Wearables[wear.Type].AssetID = LLUUID.Zero;
UpdateDatabase(clientView.AgentId, avatAppearance); UpdateDatabase(clientView.AgentId, avatAppearance);
} }
else else
{ {
LLUUID assetId; LLUUID assetId;
InventoryItemBase baseItem = profile.RootFolder.HasItem(wear.ItemID); InventoryItemBase baseItem = profile.RootFolder.HasItem(wear.ItemID);
if (baseItem != null) if (baseItem != null)
{ {
assetId = baseItem.assetID; assetId = baseItem.assetID;
avatAppearance.Wearables[wear.Type].AssetID = assetId; avatAppearance.Wearables[wear.Type].AssetID = assetId;
avatAppearance.Wearables[wear.Type].ItemID = wear.ItemID; avatAppearance.Wearables[wear.Type].ItemID = wear.ItemID;
UpdateDatabase(clientView.AgentId, avatAppearance); UpdateDatabase(clientView.AgentId, avatAppearance);
} }
} }
} }
} }
} }
} }
} }
} }
public void UpdateDatabase(LLUUID userID, AvatarAppearance avatAppearance) public void UpdateDatabase(LLUUID userID, AvatarAppearance avatAppearance)
{ {
if (m_enablePersist) if (m_enablePersist)
{ {
m_appearanceMapper.Update(userID.UUID, avatAppearance); m_appearanceMapper.Update(userID.UUID, avatAppearance);
} }
} }
public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams) public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
{ {
visualParams = GetDefaultVisualParams(); visualParams = GetDefaultVisualParams();
wearables = AvatarWearable.DefaultWearables; wearables = AvatarWearable.DefaultWearables;
} }
private static byte[] GetDefaultVisualParams() private static byte[] GetDefaultVisualParams()
{ {
byte[] visualParams; byte[] visualParams;
visualParams = new byte[218]; visualParams = new byte[218];
for (int i = 0; i < 218; i++) for (int i = 0; i < 218; i++)
{ {
visualParams[i] = 100; visualParams[i] = 100;
} }
return visualParams; return visualParams;
} }
} }
}*/ }*/

File diff suppressed because it is too large Load Diff

View File

@ -1,273 +1,273 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Avatar.Groups namespace OpenSim.Region.Environment.Modules.Avatar.Groups
{ {
public class GroupsModule : IRegionModule public class GroupsModule : IRegionModule
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<LLUUID, GroupList> m_grouplistmap = new Dictionary<LLUUID, GroupList>(); private Dictionary<LLUUID, GroupList> m_grouplistmap = new Dictionary<LLUUID, GroupList>();
private Dictionary<LLUUID, GroupData> m_groupmap = new Dictionary<LLUUID, GroupData>(); private Dictionary<LLUUID, GroupData> m_groupmap = new Dictionary<LLUUID, GroupData>();
private Dictionary<LLUUID, IClientAPI> m_iclientmap = new Dictionary<LLUUID, IClientAPI>(); private Dictionary<LLUUID, IClientAPI> m_iclientmap = new Dictionary<LLUUID, IClientAPI>();
private List<Scene> m_scene = new List<Scene>(); private List<Scene> m_scene = new List<Scene>();
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
lock (m_scene) lock (m_scene)
{ {
m_scene.Add(scene); m_scene.Add(scene);
} }
scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnGridInstantMessageToGroupsModule += OnGridInstantMessage; scene.EventManager.OnGridInstantMessageToGroupsModule += OnGridInstantMessage;
//scene.EventManager. //scene.EventManager.
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
m_log.Info("[GROUP]: Shutting down group module."); m_log.Info("[GROUP]: Shutting down group module.");
lock (m_iclientmap) lock (m_iclientmap)
{ {
m_iclientmap.Clear(); m_iclientmap.Clear();
} }
lock (m_groupmap) lock (m_groupmap)
{ {
m_groupmap.Clear(); m_groupmap.Clear();
} }
lock (m_grouplistmap) lock (m_grouplistmap)
{ {
m_grouplistmap.Clear(); m_grouplistmap.Clear();
} }
GC.Collect(); GC.Collect();
} }
public string Name public string Name
{ {
get { return "GroupsModule"; } get { return "GroupsModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
private void OnNewClient(IClientAPI client) private void OnNewClient(IClientAPI client)
{ {
// All friends establishment protocol goes over instant message // All friends establishment protocol goes over instant message
// There's no way to send a message from the sim // There's no way to send a message from the sim
// to a user to 'add a friend' without causing dialog box spam // to a user to 'add a friend' without causing dialog box spam
// //
// The base set of friends are added when the user signs on in their XMLRPC response // The base set of friends are added when the user signs on in their XMLRPC response
// Generated by LoginService. The friends are retreived from the database by the UserManager // Generated by LoginService. The friends are retreived from the database by the UserManager
// Subscribe to instant messages // Subscribe to instant messages
client.OnInstantMessage += OnInstantMessage; client.OnInstantMessage += OnInstantMessage;
client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
lock (m_iclientmap) lock (m_iclientmap)
{ {
if (!m_iclientmap.ContainsKey(client.AgentId)) if (!m_iclientmap.ContainsKey(client.AgentId))
{ {
m_iclientmap.Add(client.AgentId, client); m_iclientmap.Add(client.AgentId, client);
} }
} }
GroupData OpenSimulatorGroup = new GroupData(); GroupData OpenSimulatorGroup = new GroupData();
OpenSimulatorGroup.ActiveGroupTitle = "OpenSimulator Tester"; OpenSimulatorGroup.ActiveGroupTitle = "OpenSimulator Tester";
OpenSimulatorGroup.GroupID = new LLUUID("00000000-68f9-1111-024e-222222111120"); OpenSimulatorGroup.GroupID = new LLUUID("00000000-68f9-1111-024e-222222111120");
OpenSimulatorGroup.GroupMembers.Add(client.AgentId); OpenSimulatorGroup.GroupMembers.Add(client.AgentId);
OpenSimulatorGroup.groupName = "OpenSimulator Testing"; OpenSimulatorGroup.groupName = "OpenSimulator Testing";
OpenSimulatorGroup.ActiveGroupPowers = GroupPowers.LandAllowSetHome; OpenSimulatorGroup.ActiveGroupPowers = GroupPowers.LandAllowSetHome;
OpenSimulatorGroup.GroupTitles.Add("OpenSimulator Tester"); OpenSimulatorGroup.GroupTitles.Add("OpenSimulator Tester");
lock (m_groupmap) lock (m_groupmap)
{ {
if (!m_groupmap.ContainsKey(client.AgentId)) if (!m_groupmap.ContainsKey(client.AgentId))
{ {
m_groupmap.Add(client.AgentId, OpenSimulatorGroup); m_groupmap.Add(client.AgentId, OpenSimulatorGroup);
} }
} }
GroupList testGroupList = new GroupList(); GroupList testGroupList = new GroupList();
testGroupList.m_GroupList.Add(new LLUUID("00000000-68f9-1111-024e-222222111120")); testGroupList.m_GroupList.Add(new LLUUID("00000000-68f9-1111-024e-222222111120"));
lock (m_grouplistmap) lock (m_grouplistmap)
{ {
if (!m_grouplistmap.ContainsKey(client.AgentId)) if (!m_grouplistmap.ContainsKey(client.AgentId))
{ {
m_grouplistmap.Add(client.AgentId, testGroupList); m_grouplistmap.Add(client.AgentId, testGroupList);
} }
} }
m_log.Info("[GROUP]: Adding " + client.FirstName + " " + client.LastName + " to OpenSimulator Tester group"); m_log.Info("[GROUP]: Adding " + client.FirstName + " " + client.LastName + " to OpenSimulator Tester group");
} }
private void OnAgentDataUpdateRequest(IClientAPI remoteClient, LLUUID AgentID, LLUUID SessionID) private void OnAgentDataUpdateRequest(IClientAPI remoteClient, LLUUID AgentID, LLUUID SessionID)
{ {
string firstname = remoteClient.FirstName; string firstname = remoteClient.FirstName;
string lastname = remoteClient.LastName; string lastname = remoteClient.LastName;
LLUUID ActiveGroupID = LLUUID.Zero; LLUUID ActiveGroupID = LLUUID.Zero;
uint ActiveGroupPowers = 0; uint ActiveGroupPowers = 0;
string ActiveGroupName = ""; string ActiveGroupName = "";
string ActiveGroupTitle = ""; string ActiveGroupTitle = "";
bool foundUser = false; bool foundUser = false;
lock (m_iclientmap) lock (m_iclientmap)
{ {
if (m_iclientmap.ContainsKey(remoteClient.AgentId)) if (m_iclientmap.ContainsKey(remoteClient.AgentId))
{ {
foundUser = true; foundUser = true;
} }
} }
if (foundUser) if (foundUser)
{ {
lock (m_groupmap) lock (m_groupmap)
{ {
if (m_groupmap.ContainsKey(remoteClient.AgentId)) if (m_groupmap.ContainsKey(remoteClient.AgentId))
{ {
GroupData grp = m_groupmap[remoteClient.AgentId]; GroupData grp = m_groupmap[remoteClient.AgentId];
if (grp != null) if (grp != null)
{ {
ActiveGroupID = grp.GroupID; ActiveGroupID = grp.GroupID;
ActiveGroupName = grp.groupName; ActiveGroupName = grp.groupName;
ActiveGroupPowers = grp.groupPowers; ActiveGroupPowers = grp.groupPowers;
ActiveGroupTitle = grp.ActiveGroupTitle; ActiveGroupTitle = grp.ActiveGroupTitle;
} }
//remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); //remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle);
} }
} }
} }
} }
private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID,
LLUUID fromAgentSession, LLUUID toAgentID, LLUUID fromAgentSession, LLUUID toAgentID,
LLUUID imSessionID, uint timestamp, string fromAgentName, LLUUID imSessionID, uint timestamp, string fromAgentName,
string message, byte dialog, bool fromGroup, byte offline, string message, byte dialog, bool fromGroup, byte offline,
uint ParentEstateID, LLVector3 Position, LLUUID RegionID, uint ParentEstateID, LLVector3 Position, LLUUID RegionID,
byte[] binaryBucket) byte[] binaryBucket)
{ {
} }
private void OnGridInstantMessage(GridInstantMessage msg) private void OnGridInstantMessage(GridInstantMessage msg)
{ {
// Trigger the above event handler // Trigger the above event handler
OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession),
new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName,
msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID,
new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID),
msg.binaryBucket); msg.binaryBucket);
} }
private void OnClientClosed(LLUUID agentID) private void OnClientClosed(LLUUID agentID)
{ {
lock (m_iclientmap) lock (m_iclientmap)
{ {
if (m_iclientmap.ContainsKey(agentID)) if (m_iclientmap.ContainsKey(agentID))
{ {
IClientAPI cli = m_iclientmap[agentID]; IClientAPI cli = m_iclientmap[agentID];
if (cli != null) if (cli != null)
{ {
m_log.Info("[GROUP]: Removing all reference to groups for " + cli.FirstName + " " + cli.LastName); m_log.Info("[GROUP]: Removing all reference to groups for " + cli.FirstName + " " + cli.LastName);
} }
else else
{ {
m_log.Info("[GROUP]: Removing all reference to groups for " + agentID.ToString()); m_log.Info("[GROUP]: Removing all reference to groups for " + agentID.ToString());
} }
m_iclientmap.Remove(agentID); m_iclientmap.Remove(agentID);
} }
} }
lock (m_groupmap) lock (m_groupmap)
{ {
if (m_groupmap.ContainsKey(agentID)) if (m_groupmap.ContainsKey(agentID))
{ {
m_groupmap.Remove(agentID); m_groupmap.Remove(agentID);
} }
} }
lock (m_grouplistmap) lock (m_grouplistmap)
{ {
if (m_grouplistmap.ContainsKey(agentID)) if (m_grouplistmap.ContainsKey(agentID))
{ {
m_grouplistmap.Remove(agentID); m_grouplistmap.Remove(agentID);
} }
} }
GC.Collect(); GC.Collect();
} }
} }
public class GroupData public class GroupData
{ {
public string ActiveGroupTitle; public string ActiveGroupTitle;
public LLUUID GroupID; public LLUUID GroupID;
public List<LLUUID> GroupMembers; public List<LLUUID> GroupMembers;
public string groupName; public string groupName;
public uint groupPowers = (uint) (GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome); public uint groupPowers = (uint) (GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome);
public List<string> GroupTitles; public List<string> GroupTitles;
public GroupData() public GroupData()
{ {
GroupTitles = new List<string>(); GroupTitles = new List<string>();
GroupMembers = new List<LLUUID>(); GroupMembers = new List<LLUUID>();
} }
public GroupPowers ActiveGroupPowers public GroupPowers ActiveGroupPowers
{ {
set { groupPowers = (uint) value; } set { groupPowers = (uint) value; }
get { return (GroupPowers) groupPowers; } get { return (GroupPowers) groupPowers; }
} }
} }
public class GroupList public class GroupList
{ {
public List<LLUUID> m_GroupList; public List<LLUUID> m_GroupList;
public GroupList() public GroupList()
{ {
m_GroupList = new List<LLUUID>(); m_GroupList = new List<LLUUID>();
} }
} }
} }

View File

@ -1,158 +1,158 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage
{ {
public class InstantMessageModule : IRegionModule public class InstantMessageModule : IRegionModule
{ {
private readonly List<Scene> m_scenes = new List<Scene>(); private readonly List<Scene> m_scenes = new List<Scene>();
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
lock (m_scenes) lock (m_scenes)
{ {
if (m_scenes.Count == 0) if (m_scenes.Count == 0)
{ {
//scene.AddXmlRPCHandler("avatar_location_update", processPresenceUpdate); //scene.AddXmlRPCHandler("avatar_location_update", processPresenceUpdate);
} }
if (!m_scenes.Contains(scene)) if (!m_scenes.Contains(scene))
{ {
m_scenes.Add(scene); m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnGridInstantMessageToIMModule += OnGridInstantMessage; scene.EventManager.OnGridInstantMessageToIMModule += OnGridInstantMessage;
} }
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "InstantMessageModule"; } get { return "InstantMessageModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
private void OnNewClient(IClientAPI client) private void OnNewClient(IClientAPI client)
{ {
client.OnInstantMessage += OnInstantMessage; client.OnInstantMessage += OnInstantMessage;
} }
private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID,
LLUUID fromAgentSession, LLUUID toAgentID, LLUUID fromAgentSession, LLUUID toAgentID,
LLUUID imSessionID, uint timestamp, string fromAgentName, LLUUID imSessionID, uint timestamp, string fromAgentName,
string message, byte dialog, bool fromGroup, byte offline, string message, byte dialog, bool fromGroup, byte offline,
uint ParentEstateID, LLVector3 Position, LLUUID RegionID, uint ParentEstateID, LLVector3 Position, LLUUID RegionID,
byte[] binaryBucket) byte[] binaryBucket)
{ {
bool dialogHandledElsewhere bool dialogHandledElsewhere
= ((dialog == 38) || (dialog == 39) || (dialog == 40) = ((dialog == 38) || (dialog == 39) || (dialog == 40)
|| dialog == (byte) InstantMessageDialog.InventoryOffered || dialog == (byte) InstantMessageDialog.InventoryOffered
|| dialog == (byte) InstantMessageDialog.InventoryAccepted || dialog == (byte) InstantMessageDialog.InventoryAccepted
|| dialog == (byte) InstantMessageDialog.InventoryDeclined); || dialog == (byte) InstantMessageDialog.InventoryDeclined);
// IM dialogs need to be pre-processed and have their sessionID filled by the server // IM dialogs need to be pre-processed and have their sessionID filled by the server
// so the sim can match the transaction on the return packet. // so the sim can match the transaction on the return packet.
// Don't send a Friend Dialog IM with a LLUUID.Zero session. // Don't send a Friend Dialog IM with a LLUUID.Zero session.
if (!(dialogHandledElsewhere && imSessionID == LLUUID.Zero)) if (!(dialogHandledElsewhere && imSessionID == LLUUID.Zero))
{ {
// Try root avatar only first // Try root avatar only first
foreach (Scene scene in m_scenes) foreach (Scene scene in m_scenes)
{ {
if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence)
{ {
// Local message // Local message
ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
if (!user.IsChildAgent) if (!user.IsChildAgent)
{ {
user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message,
toAgentID, imSessionID, fromAgentName, dialog, toAgentID, imSessionID, fromAgentName, dialog,
timestamp); timestamp);
// Message sent // Message sent
return; return;
} }
} }
} }
// try child avatar second // try child avatar second
foreach (Scene scene in m_scenes) foreach (Scene scene in m_scenes)
{ {
if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence)
{ {
// Local message // Local message
ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message,
toAgentID, imSessionID, fromAgentName, dialog, toAgentID, imSessionID, fromAgentName, dialog,
timestamp); timestamp);
// Message sent // Message sent
return; return;
} }
} }
} }
// Still here, try send via Grid // Still here, try send via Grid
// TODO // TODO
} }
// Trusty OSG1 called method. This method also gets called from the FriendsModule // Trusty OSG1 called method. This method also gets called from the FriendsModule
// Turns out the sim has to send an instant message to the user to get it to show an accepted friend. // Turns out the sim has to send an instant message to the user to get it to show an accepted friend.
private void OnGridInstantMessage(GridInstantMessage msg) private void OnGridInstantMessage(GridInstantMessage msg)
{ {
// Trigger the above event handler // Trigger the above event handler
OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession),
new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName,
msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID,
new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID),
msg.binaryBucket); msg.binaryBucket);
} }
} }
} }

View File

@ -1,220 +1,220 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Avatar.Inventory namespace OpenSim.Region.Environment.Modules.Avatar.Inventory
{ {
public class InventoryModule : IRegionModule public class InventoryModule : IRegionModule
{ {
private static readonly ILog m_log private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// We need to keep track of the pending item offers between clients since the itemId offered only /// We need to keep track of the pending item offers between clients since the itemId offered only
/// occurs in the initial offer message, not the accept message. So this dictionary links /// occurs in the initial offer message, not the accept message. So this dictionary links
/// IM Session Ids to ItemIds /// IM Session Ids to ItemIds
/// </summary> /// </summary>
private IDictionary<LLUUID, LLUUID> m_pendingOffers = new Dictionary<LLUUID, LLUUID>(); private IDictionary<LLUUID, LLUUID> m_pendingOffers = new Dictionary<LLUUID, LLUUID>();
private Scene m_scene; private Scene m_scene;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnNewClient += OnNewClient;
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "InventoryModule"; } get { return "InventoryModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
private void OnNewClient(IClientAPI client) private void OnNewClient(IClientAPI client)
{ {
// Inventory giving is conducted via instant message // Inventory giving is conducted via instant message
client.OnInstantMessage += OnInstantMessage; client.OnInstantMessage += OnInstantMessage;
} }
private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID,
LLUUID fromAgentSession, LLUUID toAgentID, LLUUID fromAgentSession, LLUUID toAgentID,
LLUUID imSessionID, uint timestamp, string fromAgentName, LLUUID imSessionID, uint timestamp, string fromAgentName,
string message, byte dialog, bool fromGroup, byte offline, string message, byte dialog, bool fromGroup, byte offline,
uint ParentEstateID, LLVector3 Position, LLUUID RegionID, uint ParentEstateID, LLVector3 Position, LLUUID RegionID,
byte[] binaryBucket) byte[] binaryBucket)
{ {
if (dialog == (byte) InstantMessageDialog.InventoryOffered) if (dialog == (byte) InstantMessageDialog.InventoryOffered)
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}", "[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}",
client.AgentId, client.Name, toAgentID); client.AgentId, client.Name, toAgentID);
if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence)
{ {
ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID];
if (!user.IsChildAgent) if (!user.IsChildAgent)
{ {
//byte[] rawId = new byte[16]; //byte[] rawId = new byte[16];
// First byte of the array is probably the item type // First byte of the array is probably the item type
// Next 16 bytes are the UUID // Next 16 bytes are the UUID
//Array.Copy(binaryBucket, 1, rawId, 0, 16); //Array.Copy(binaryBucket, 1, rawId, 0, 16);
//LLUUID itemId = new LLUUID(new Guid(rawId)); //LLUUID itemId = new LLUUID(new Guid(rawId));
LLUUID itemId = new LLUUID(binaryBucket, 1); LLUUID itemId = new LLUUID(binaryBucket, 1);
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: ItemId for giving is {0}", itemId); "[AGENT INVENTORY]: ItemId for giving is {0}", itemId);
m_pendingOffers[imSessionID] = itemId; m_pendingOffers[imSessionID] = itemId;
user.ControllingClient.SendInstantMessage( user.ControllingClient.SendInstantMessage(
fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName,
dialog, timestamp, binaryBucket); dialog, timestamp, binaryBucket);
return; return;
} }
else else
{ {
m_log.WarnFormat( m_log.WarnFormat(
"[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!",
toAgentID, client.AgentId, client.Name, message); toAgentID, client.AgentId, client.Name, message);
} }
} }
else else
{ {
m_log.WarnFormat( m_log.WarnFormat(
"[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}", "[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}",
toAgentID, client.AgentId, client.Name, message); toAgentID, client.AgentId, client.Name, message);
} }
} }
else if (dialog == (byte) InstantMessageDialog.InventoryAccepted) else if (dialog == (byte) InstantMessageDialog.InventoryAccepted)
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}", "[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}",
client.AgentId, client.Name, toAgentID); client.AgentId, client.Name, toAgentID);
if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence)
{ {
ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID];
if (!user.IsChildAgent) if (!user.IsChildAgent)
{ {
user.ControllingClient.SendInstantMessage( user.ControllingClient.SendInstantMessage(
fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName,
dialog, timestamp, binaryBucket); dialog, timestamp, binaryBucket);
if (m_pendingOffers.ContainsKey(imSessionID)) if (m_pendingOffers.ContainsKey(imSessionID))
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: Accepted item id {0}", m_pendingOffers[imSessionID]); "[AGENT INVENTORY]: Accepted item id {0}", m_pendingOffers[imSessionID]);
// Since the message originates from the accepting client, the toAgentID is // Since the message originates from the accepting client, the toAgentID is
// the agent giving the item. // the agent giving the item.
m_scene.GiveInventoryItem(client, toAgentID, m_pendingOffers[imSessionID]); m_scene.GiveInventoryItem(client, toAgentID, m_pendingOffers[imSessionID]);
m_pendingOffers.Remove(imSessionID); m_pendingOffers.Remove(imSessionID);
} }
else else
{ {
m_log.ErrorFormat( m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept", "[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept",
imSessionID); imSessionID);
} }
return; return;
} }
else else
{ {
m_log.WarnFormat( m_log.WarnFormat(
"[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!",
toAgentID, client.AgentId, client.Name, message); toAgentID, client.AgentId, client.Name, message);
} }
} }
else else
{ {
m_log.WarnFormat( m_log.WarnFormat(
"[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}", "[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}",
toAgentID, client.AgentId, client.Name, message); toAgentID, client.AgentId, client.Name, message);
} }
} }
else if (dialog == (byte) InstantMessageDialog.InventoryDeclined) else if (dialog == (byte) InstantMessageDialog.InventoryDeclined)
{ {
if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence)
{ {
ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID];
if (!user.IsChildAgent) if (!user.IsChildAgent)
{ {
user.ControllingClient.SendInstantMessage( user.ControllingClient.SendInstantMessage(
fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName,
dialog, timestamp, binaryBucket); dialog, timestamp, binaryBucket);
if (m_pendingOffers.ContainsKey(imSessionID)) if (m_pendingOffers.ContainsKey(imSessionID))
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: Declined item id {0}", m_pendingOffers[imSessionID]); "[AGENT INVENTORY]: Declined item id {0}", m_pendingOffers[imSessionID]);
m_pendingOffers.Remove(imSessionID); m_pendingOffers.Remove(imSessionID);
} }
else else
{ {
m_log.ErrorFormat( m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline", "[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline",
imSessionID); imSessionID);
} }
} }
} }
} }
} }
} }
} }

View File

@ -1,133 +1,133 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Avatar.Profiles namespace OpenSim.Region.Environment.Modules.Avatar.Profiles
{ {
public class AvatarProfilesModule : IRegionModule public class AvatarProfilesModule : IRegionModule
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene; private Scene m_scene;
public AvatarProfilesModule() public AvatarProfilesModule()
{ {
} }
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient; m_scene.EventManager.OnNewClient += NewClient;
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "AvatarProfilesModule"; } get { return "AvatarProfilesModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
public void NewClient(IClientAPI client) public void NewClient(IClientAPI client)
{ {
client.OnRequestAvatarProperties += RequestAvatarProperty; client.OnRequestAvatarProperties += RequestAvatarProperty;
client.OnUpdateAvatarProperties += UpdateAvatarProperties; client.OnUpdateAvatarProperties += UpdateAvatarProperties;
} }
public void RemoveClient(IClientAPI client) public void RemoveClient(IClientAPI client)
{ {
client.OnRequestAvatarProperties -= RequestAvatarProperty; client.OnRequestAvatarProperties -= RequestAvatarProperty;
client.OnUpdateAvatarProperties -= UpdateAvatarProperties; client.OnUpdateAvatarProperties -= UpdateAvatarProperties;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="avatarID"></param> /// <param name="avatarID"></param>
public void RequestAvatarProperty(IClientAPI remoteClient, LLUUID avatarID) public void RequestAvatarProperty(IClientAPI remoteClient, LLUUID avatarID)
{ {
// FIXME: finish adding fields such as url, masking, etc. // FIXME: finish adding fields such as url, masking, etc.
LLUUID partner = new LLUUID("11111111-1111-0000-0000-000100bba000"); LLUUID partner = new LLUUID("11111111-1111-0000-0000-000100bba000");
UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(avatarID); UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(avatarID);
if (null != profile) if (null != profile)
{ {
remoteClient.SendAvatarProperties(profile.ID, profile.AboutText, remoteClient.SendAvatarProperties(profile.ID, profile.AboutText,
Util.ToDateTime(profile.Created).ToString(), Util.ToDateTime(profile.Created).ToString(),
String.Empty, profile.FirstLifeAboutText, profile.CanDoMask, String.Empty, profile.FirstLifeAboutText, profile.CanDoMask,
profile.FirstLifeImage, profile.Image, String.Empty, partner); profile.FirstLifeImage, profile.Image, String.Empty, partner);
} }
else else
{ {
m_log.Debug("[AvatarProfilesModule]: Got null for profile for " + avatarID.ToString()); m_log.Debug("[AvatarProfilesModule]: Got null for profile for " + avatarID.ToString());
} }
} }
public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile) public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile)
{ {
UserProfileData Profile = m_scene.CommsManager.UserService.GetUserProfile(newProfile.ID); UserProfileData Profile = m_scene.CommsManager.UserService.GetUserProfile(newProfile.ID);
// if it's the profile of the user requesting the update, then we change only a few things. // if it's the profile of the user requesting the update, then we change only a few things.
if (remoteClient.AgentId.CompareTo(Profile.ID) == 0) if (remoteClient.AgentId.CompareTo(Profile.ID) == 0)
{ {
Profile.Image = newProfile.Image; Profile.Image = newProfile.Image;
Profile.FirstLifeImage = newProfile.FirstLifeImage; Profile.FirstLifeImage = newProfile.FirstLifeImage;
Profile.AboutText = newProfile.AboutText; Profile.AboutText = newProfile.AboutText;
Profile.FirstLifeAboutText = newProfile.FirstLifeAboutText; Profile.FirstLifeAboutText = newProfile.FirstLifeAboutText;
} }
else else
{ {
return; return;
} }
if (m_scene.CommsManager.UserService.UpdateUserProfileProperties(Profile)) if (m_scene.CommsManager.UserService.UpdateUserProfileProperties(Profile))
{ {
RequestAvatarProperty(remoteClient, newProfile.ID); RequestAvatarProperty(remoteClient, newProfile.ID);
} }
} }
} }
} }

View File

@ -1,290 +1,290 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using Nwc.XmlRpc; using Nwc.XmlRpc;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers; using OpenSim.Framework.Servers;
using OpenSim.Region.Capabilities; using OpenSim.Region.Capabilities;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
using Caps=OpenSim.Region.Capabilities.Caps; using Caps=OpenSim.Region.Capabilities.Caps;
namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice
{ {
public class AsteriskVoiceModule : IRegionModule public class AsteriskVoiceModule : IRegionModule
{ {
private static readonly ILog m_log = private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; private static readonly string m_parcelVoiceInfoRequestPath = "0007/";
private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; private static readonly string m_provisionVoiceAccountRequestPath = "0008/";
private string m_asterisk; private string m_asterisk;
private string m_asterisk_password; private string m_asterisk_password;
private string m_asterisk_salt; private string m_asterisk_salt;
private int m_asterisk_timeout; private int m_asterisk_timeout;
private string m_confDomain; private string m_confDomain;
private IConfig m_config; private IConfig m_config;
private Scene m_scene; private Scene m_scene;
private string m_sipDomain; private string m_sipDomain;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
m_config = config.Configs["AsteriskVoice"]; m_config = config.Configs["AsteriskVoice"];
if (null == m_config) if (null == m_config)
{ {
m_log.Info("[ASTERISKVOICE] no config found, plugin disabled"); m_log.Info("[ASTERISKVOICE] no config found, plugin disabled");
return; return;
} }
if (!m_config.GetBoolean("enabled", false)) if (!m_config.GetBoolean("enabled", false))
{ {
m_log.Info("[ASTERISKVOICE] plugin disabled by configuration"); m_log.Info("[ASTERISKVOICE] plugin disabled by configuration");
return; return;
} }
m_log.Info("[ASTERISKVOICE] plugin enabled"); m_log.Info("[ASTERISKVOICE] plugin enabled");
try try
{ {
m_sipDomain = m_config.GetString("sip_domain", String.Empty); m_sipDomain = m_config.GetString("sip_domain", String.Empty);
m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain); m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain);
m_confDomain = m_config.GetString("conf_domain", String.Empty); m_confDomain = m_config.GetString("conf_domain", String.Empty);
m_log.InfoFormat("[ASTERISKVOICE] using conf domain {0}", m_confDomain); m_log.InfoFormat("[ASTERISKVOICE] using conf domain {0}", m_confDomain);
m_asterisk = m_config.GetString("asterisk_frontend", String.Empty); m_asterisk = m_config.GetString("asterisk_frontend", String.Empty);
m_asterisk_password = m_config.GetString("asterisk_password", String.Empty); m_asterisk_password = m_config.GetString("asterisk_password", String.Empty);
m_asterisk_timeout = m_config.GetInt("asterisk_timeout", 3000); m_asterisk_timeout = m_config.GetInt("asterisk_timeout", 3000);
m_asterisk_salt = m_config.GetString("asterisk_salt", "Wuffwuff"); m_asterisk_salt = m_config.GetString("asterisk_salt", "Wuffwuff");
if (String.IsNullOrEmpty(m_asterisk)) throw new Exception("missing asterisk_frontend config parameter"); if (String.IsNullOrEmpty(m_asterisk)) throw new Exception("missing asterisk_frontend config parameter");
if (String.IsNullOrEmpty(m_asterisk_password)) throw new Exception("missing asterisk_password config parameter"); if (String.IsNullOrEmpty(m_asterisk_password)) throw new Exception("missing asterisk_password config parameter");
m_log.InfoFormat("[ASTERISKVOICE] using asterisk front end {0}", m_asterisk); m_log.InfoFormat("[ASTERISKVOICE] using asterisk front end {0}", m_asterisk);
scene.EventManager.OnRegisterCaps += OnRegisterCaps; scene.EventManager.OnRegisterCaps += OnRegisterCaps;
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message); m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message);
m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString()); m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString());
return; return;
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "AsteriskVoiceModule"; } get { return "AsteriskVoiceModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
public void OnRegisterCaps(LLUUID agentID, Caps caps) public void OnRegisterCaps(LLUUID agentID, Caps caps)
{ {
m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath; string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("ParcelVoiceInfoRequest", caps.RegisterHandler("ParcelVoiceInfoRequest",
new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath,
delegate(string request, string path, string param) delegate(string request, string path, string param)
{ {
return ParcelVoiceInfoRequest(request, path, param, return ParcelVoiceInfoRequest(request, path, param,
agentID, caps); agentID, caps);
})); }));
caps.RegisterHandler("ProvisionVoiceAccountRequest", caps.RegisterHandler("ProvisionVoiceAccountRequest",
new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath,
delegate(string request, string path, string param) delegate(string request, string path, string param)
{ {
return ProvisionVoiceAccountRequest(request, path, param, return ProvisionVoiceAccountRequest(request, path, param,
agentID, caps); agentID, caps);
})); }));
} }
/// <summary> /// <summary>
/// Callback for a client request for ParcelVoiceInfo /// Callback for a client request for ParcelVoiceInfo
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="param"></param> /// <param name="param"></param>
/// <param name="agentID"></param> /// <param name="agentID"></param>
/// <param name="caps"></param> /// <param name="caps"></param>
/// <returns></returns> /// <returns></returns>
public string ParcelVoiceInfoRequest(string request, string path, string param, public string ParcelVoiceInfoRequest(string request, string path, string param,
LLUUID agentID, Caps caps) LLUUID agentID, Caps caps)
{ {
// we need to do: // we need to do:
// - send channel_uri: as "sip:regionID@m_sipDomain" // - send channel_uri: as "sip:regionID@m_sipDomain"
try try
{ {
m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param); request, path, param);
// setup response to client // setup response to client
Hashtable creds = new Hashtable(); Hashtable creds = new Hashtable();
creds["channel_uri"] = String.Format("sip:{0}@{1}", creds["channel_uri"] = String.Format("sip:{0}@{1}",
m_scene.RegionInfo.RegionID, m_sipDomain); m_scene.RegionInfo.RegionID, m_sipDomain);
string regionName = m_scene.RegionInfo.RegionName; string regionName = m_scene.RegionInfo.RegionName;
ScenePresence avatar = m_scene.GetScenePresence(agentID); ScenePresence avatar = m_scene.GetScenePresence(agentID);
if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); if (null == m_scene.LandChannel) throw new Exception("land data not yet available");
LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
LLSDParcelVoiceInfoResponse parcelVoiceInfo = LLSDParcelVoiceInfoResponse parcelVoiceInfo =
new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds);
string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
// update region on asterisk-opensim frontend // update region on asterisk-opensim frontend
Hashtable requestData = new Hashtable(); Hashtable requestData = new Hashtable();
requestData["admin_password"] = m_asterisk_password; requestData["admin_password"] = m_asterisk_password;
requestData["region"] = m_scene.RegionInfo.RegionID.ToString(); requestData["region"] = m_scene.RegionInfo.RegionID.ToString();
if (!String.IsNullOrEmpty(m_confDomain)) if (!String.IsNullOrEmpty(m_confDomain))
{ {
requestData["region"] += String.Format("@{0}", m_confDomain); requestData["region"] += String.Format("@{0}", m_confDomain);
} }
ArrayList SendParams = new ArrayList(); ArrayList SendParams = new ArrayList();
SendParams.Add(requestData); SendParams.Add(requestData);
XmlRpcRequest updateAccountRequest = new XmlRpcRequest("region_update", SendParams); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("region_update", SendParams);
XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout);
Hashtable responseData = (Hashtable) updateAccountResponse.Value; Hashtable responseData = (Hashtable) updateAccountResponse.Value;
if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed"); if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed");
bool success = Convert.ToBoolean((string) responseData["success"]); bool success = Convert.ToBoolean((string) responseData["success"]);
if (!success) throw new Exception("region_update failed"); if (!success) throw new Exception("region_update failed");
m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: {0}", r); m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: {0}", r);
return r; return r;
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0}, retry later", e.Message); m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0}, retry later", e.Message);
m_log.DebugFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0} failed", e.ToString()); m_log.DebugFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0} failed", e.ToString());
return "<llsd>undef</llsd>"; return "<llsd>undef</llsd>";
} }
} }
/// <summary> /// <summary>
/// Callback for a client request for Voice Account Details /// Callback for a client request for Voice Account Details
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="param"></param> /// <param name="param"></param>
/// <param name="agentID"></param> /// <param name="agentID"></param>
/// <param name="caps"></param> /// <param name="caps"></param>
/// <returns></returns> /// <returns></returns>
public string ProvisionVoiceAccountRequest(string request, string path, string param, public string ProvisionVoiceAccountRequest(string request, string path, string param,
LLUUID agentID, Caps caps) LLUUID agentID, Caps caps)
{ {
// we need to // we need to
// - get user data from UserProfileCacheService // - get user data from UserProfileCacheService
// - generate nonce for user voice account password // - generate nonce for user voice account password
// - issue XmlRpc request to asterisk opensim front end: // - issue XmlRpc request to asterisk opensim front end:
// + user: base 64 encoded user name (otherwise SL // + user: base 64 encoded user name (otherwise SL
// client is unhappy) // client is unhappy)
// + password: nonce // + password: nonce
// - the XmlRpc call to asteris-opensim was successful: // - the XmlRpc call to asteris-opensim was successful:
// send account details back to client // send account details back to client
try try
{ {
m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param); request, path, param);
// get user data & prepare voice account response // get user data & prepare voice account response
string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes());
voiceUser = voiceUser.Replace('+', '-').Replace('/', '_'); voiceUser = voiceUser.Replace('+', '-').Replace('/', '_');
CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID);
if (null == userInfo) throw new Exception("cannot get user details"); if (null == userInfo) throw new Exception("cannot get user details");
// we generate a nonce everytime // we generate a nonce everytime
string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt); string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt);
LLSDVoiceAccountResponse voiceAccountResponse = LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(voiceUser, voicePassword); new LLSDVoiceAccountResponse(voiceUser, voicePassword);
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r);
// update user account on asterisk frontend // update user account on asterisk frontend
Hashtable requestData = new Hashtable(); Hashtable requestData = new Hashtable();
requestData["admin_password"] = m_asterisk_password; requestData["admin_password"] = m_asterisk_password;
requestData["username"] = voiceUser; requestData["username"] = voiceUser;
if (!String.IsNullOrEmpty(m_sipDomain)) if (!String.IsNullOrEmpty(m_sipDomain))
{ {
requestData["username"] += String.Format("@{0}", m_sipDomain); requestData["username"] += String.Format("@{0}", m_sipDomain);
} }
requestData["password"] = voicePassword; requestData["password"] = voicePassword;
ArrayList SendParams = new ArrayList(); ArrayList SendParams = new ArrayList();
SendParams.Add(requestData); SendParams.Add(requestData);
XmlRpcRequest updateAccountRequest = new XmlRpcRequest("account_update", SendParams); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("account_update", SendParams);
XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout);
Hashtable responseData = (Hashtable) updateAccountResponse.Value; Hashtable responseData = (Hashtable) updateAccountResponse.Value;
if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed"); if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed");
bool success = Convert.ToBoolean((string) responseData["success"]); bool success = Convert.ToBoolean((string) responseData["success"]);
if (!success) throw new Exception("account_update failed"); if (!success) throw new Exception("account_update failed");
return r; return r;
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0}, retry later", e.Message); m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0}, retry later", e.Message);
m_log.DebugFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0} failed", e.ToString()); m_log.DebugFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0} failed", e.ToString());
return "<llsd>undef</llsd>"; return "<llsd>undef</llsd>";
} }
} }
} }
} }

View File

@ -1,200 +1,200 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers; using OpenSim.Framework.Servers;
using OpenSim.Region.Capabilities; using OpenSim.Region.Capabilities;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
using Caps=OpenSim.Region.Capabilities.Caps; using Caps=OpenSim.Region.Capabilities.Caps;
namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice
{ {
public class SIPVoiceModule : IRegionModule public class SIPVoiceModule : IRegionModule
{ {
private static readonly ILog m_log = private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; private static readonly string m_parcelVoiceInfoRequestPath = "0007/";
private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; private static readonly string m_provisionVoiceAccountRequestPath = "0008/";
private IConfig m_config; private IConfig m_config;
private Scene m_scene; private Scene m_scene;
private string m_sipDomain; private string m_sipDomain;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
m_config = config.Configs["Voice"]; m_config = config.Configs["Voice"];
if (null == m_config || !m_config.GetBoolean("enabled", false)) if (null == m_config || !m_config.GetBoolean("enabled", false))
{ {
m_log.Info("[VOICE] plugin disabled"); m_log.Info("[VOICE] plugin disabled");
return; return;
} }
m_log.Info("[VOICE] plugin enabled"); m_log.Info("[VOICE] plugin enabled");
m_sipDomain = m_config.GetString("sip_domain", String.Empty); m_sipDomain = m_config.GetString("sip_domain", String.Empty);
if (String.IsNullOrEmpty(m_sipDomain)) if (String.IsNullOrEmpty(m_sipDomain))
{ {
m_log.Error("[VOICE] plugin mis-configured: missing sip_domain configuration"); m_log.Error("[VOICE] plugin mis-configured: missing sip_domain configuration");
m_log.Info("[VOICE] plugin disabled"); m_log.Info("[VOICE] plugin disabled");
return; return;
} }
m_log.InfoFormat("[VOICE] using SIP domain {0}", m_sipDomain); m_log.InfoFormat("[VOICE] using SIP domain {0}", m_sipDomain);
scene.EventManager.OnRegisterCaps += OnRegisterCaps; scene.EventManager.OnRegisterCaps += OnRegisterCaps;
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "VoiceModule"; } get { return "VoiceModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
public void OnRegisterCaps(LLUUID agentID, Caps caps) public void OnRegisterCaps(LLUUID agentID, Caps caps)
{ {
m_log.DebugFormat("[VOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); m_log.DebugFormat("[VOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath; string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("ParcelVoiceInfoRequest", caps.RegisterHandler("ParcelVoiceInfoRequest",
new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath,
delegate(string request, string path, string param) delegate(string request, string path, string param)
{ {
return ParcelVoiceInfoRequest(request, path, param, return ParcelVoiceInfoRequest(request, path, param,
agentID, caps); agentID, caps);
})); }));
caps.RegisterHandler("ProvisionVoiceAccountRequest", caps.RegisterHandler("ProvisionVoiceAccountRequest",
new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath,
delegate(string request, string path, string param) delegate(string request, string path, string param)
{ {
return ProvisionVoiceAccountRequest(request, path, param, return ProvisionVoiceAccountRequest(request, path, param,
agentID, caps); agentID, caps);
})); }));
} }
/// <summary> /// <summary>
/// Callback for a client request for ParcelVoiceInfo /// Callback for a client request for ParcelVoiceInfo
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="param"></param> /// <param name="param"></param>
/// <param name="agentID"></param> /// <param name="agentID"></param>
/// <param name="caps"></param> /// <param name="caps"></param>
/// <returns></returns> /// <returns></returns>
public string ParcelVoiceInfoRequest(string request, string path, string param, public string ParcelVoiceInfoRequest(string request, string path, string param,
LLUUID agentID, Caps caps) LLUUID agentID, Caps caps)
{ {
try try
{ {
m_log.DebugFormat("[VOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); m_log.DebugFormat("[VOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", request, path, param);
// FIXME: get the creds from region file or from config // FIXME: get the creds from region file or from config
Hashtable creds = new Hashtable(); Hashtable creds = new Hashtable();
creds["channel_uri"] = String.Format("sip:{0}@{1}", agentID, m_sipDomain); creds["channel_uri"] = String.Format("sip:{0}@{1}", agentID, m_sipDomain);
string regionName = m_scene.RegionInfo.RegionName; string regionName = m_scene.RegionInfo.RegionName;
ScenePresence avatar = m_scene.GetScenePresence(agentID); ScenePresence avatar = m_scene.GetScenePresence(agentID);
if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); if (null == m_scene.LandChannel) throw new Exception("land data not yet available");
LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
LLSDParcelVoiceInfoResponse parcelVoiceInfo = LLSDParcelVoiceInfoResponse parcelVoiceInfo =
new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds);
string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
m_log.DebugFormat("[VOICE][PARCELVOICE]: {0}", r); m_log.DebugFormat("[VOICE][PARCELVOICE]: {0}", r);
return r; return r;
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[CAPS]: {0}, try again later", e.ToString()); m_log.ErrorFormat("[CAPS]: {0}, try again later", e.ToString());
} }
return null; return null;
} }
/// <summary> /// <summary>
/// Callback for a client request for Voice Account Details /// Callback for a client request for Voice Account Details
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="param"></param> /// <param name="param"></param>
/// <param name="agentID"></param> /// <param name="agentID"></param>
/// <param name="caps"></param> /// <param name="caps"></param>
/// <returns></returns> /// <returns></returns>
public string ProvisionVoiceAccountRequest(string request, string path, string param, public string ProvisionVoiceAccountRequest(string request, string path, string param,
LLUUID agentID, Caps caps) LLUUID agentID, Caps caps)
{ {
try try
{ {
m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param); request, path, param);
string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes());
voiceUser = voiceUser.Replace('+', '-').Replace('/', '_'); voiceUser = voiceUser.Replace('+', '-').Replace('/', '_');
CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID);
if (null == userInfo) throw new Exception("cannot get user details"); if (null == userInfo) throw new Exception("cannot get user details");
LLSDVoiceAccountResponse voiceAccountResponse = LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(voiceUser, "$1$" + userInfo.UserProfile.PasswordHash); new LLSDVoiceAccountResponse(voiceUser, "$1$" + userInfo.UserProfile.PasswordHash);
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r);
return r; return r;
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[CAPS][PROVISIONVOICE]: {0}, retry later", e.Message); m_log.ErrorFormat("[CAPS][PROVISIONVOICE]: {0}, retry later", e.Message);
} }
return null; return null;
} }
} }
} }

View File

@ -1,308 +1,308 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using log4net; using log4net;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.Framework namespace OpenSim.Region.Environment.Modules.Framework
{ {
/// <summary> /// <summary>
/// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s. /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s.
/// Used for console commands and script API generation /// Used for console commands and script API generation
/// </summary> /// </summary>
public class Command : ICommand public class Command : ICommand
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<CommandArgument> m_args = new List<CommandArgument>(); private List<CommandArgument> m_args = new List<CommandArgument>();
private Action<object[]> m_command; private Action<object[]> m_command;
private string m_help; private string m_help;
private string m_name; private string m_name;
public Command(string name, Action<Object[]> command, string help) public Command(string name, Action<Object[]> command, string help)
{ {
m_name = name; m_name = name;
m_command = command; m_command = command;
m_help = help; m_help = help;
} }
#region ICommand Members #region ICommand Members
public void AddArgument(string name, string helptext, string type) public void AddArgument(string name, string helptext, string type)
{ {
m_args.Add(new CommandArgument(name, helptext, type)); m_args.Add(new CommandArgument(name, helptext, type));
} }
public string Name public string Name
{ {
get { return m_name; } get { return m_name; }
} }
public string Help public string Help
{ {
get { return m_help; } get { return m_help; }
} }
public Dictionary<string, string> Arguments public Dictionary<string, string> Arguments
{ {
get get
{ {
Dictionary<string, string> tmp = new Dictionary<string, string>(); Dictionary<string, string> tmp = new Dictionary<string, string>();
foreach (CommandArgument arg in m_args) foreach (CommandArgument arg in m_args)
{ {
tmp.Add(arg.Name, arg.ArgumentType); tmp.Add(arg.Name, arg.ArgumentType);
} }
return tmp; return tmp;
} }
} }
public void ShowConsoleHelp() public void ShowConsoleHelp()
{ {
m_log.Info("== " + Name + " =="); m_log.Info("== " + Name + " ==");
m_log.Info(m_help); m_log.Info(m_help);
m_log.Info("= Parameters ="); m_log.Info("= Parameters =");
foreach (CommandArgument arg in m_args) foreach (CommandArgument arg in m_args)
{ {
m_log.Info("* " + arg.Name + " (" + arg.ArgumentType + ")"); m_log.Info("* " + arg.Name + " (" + arg.ArgumentType + ")");
m_log.Info("\t" + arg.HelpText); m_log.Info("\t" + arg.HelpText);
} }
} }
public void Run(Object[] args) public void Run(Object[] args)
{ {
Object[] cleanArgs = new Object[m_args.Count]; Object[] cleanArgs = new Object[m_args.Count];
if (args.Length < cleanArgs.Length) if (args.Length < cleanArgs.Length)
{ {
m_log.Error("Missing " + (cleanArgs.Length - args.Length) + " argument(s)"); m_log.Error("Missing " + (cleanArgs.Length - args.Length) + " argument(s)");
ShowConsoleHelp(); ShowConsoleHelp();
return; return;
} }
if (args.Length > cleanArgs.Length) if (args.Length > cleanArgs.Length)
{ {
m_log.Error("Too many arguments for this command. Type '<module> <command> help' for help."); m_log.Error("Too many arguments for this command. Type '<module> <command> help' for help.");
return; return;
} }
int i = 0; int i = 0;
foreach (Object arg in args) foreach (Object arg in args)
{ {
if (string.IsNullOrEmpty(arg.ToString())) if (string.IsNullOrEmpty(arg.ToString()))
{ {
m_log.Error("Empty arguments are not allowed"); m_log.Error("Empty arguments are not allowed");
return; return;
} }
try try
{ {
switch (m_args[i].ArgumentType) switch (m_args[i].ArgumentType)
{ {
case "String": case "String":
m_args[i].ArgumentValue = arg.ToString(); m_args[i].ArgumentValue = arg.ToString();
break; break;
case "Integer": case "Integer":
m_args[i].ArgumentValue = Int32.Parse(arg.ToString()); m_args[i].ArgumentValue = Int32.Parse(arg.ToString());
break; break;
case "Double": case "Double":
m_args[i].ArgumentValue = Double.Parse(arg.ToString()); m_args[i].ArgumentValue = Double.Parse(arg.ToString());
break; break;
case "Boolean": case "Boolean":
m_args[i].ArgumentValue = Boolean.Parse(arg.ToString()); m_args[i].ArgumentValue = Boolean.Parse(arg.ToString());
break; break;
default: default:
m_log.Error("Unknown desired type for argument " + m_args[i].Name + " on command " + m_name); m_log.Error("Unknown desired type for argument " + m_args[i].Name + " on command " + m_name);
break; break;
} }
} }
catch (FormatException) catch (FormatException)
{ {
m_log.Error("Argument number " + (i + 1) + m_log.Error("Argument number " + (i + 1) +
" (" + m_args[i].Name + ") must be a valid " + " (" + m_args[i].Name + ") must be a valid " +
m_args[i].ArgumentType.ToLower() + "."); m_args[i].ArgumentType.ToLower() + ".");
} }
cleanArgs[i] = m_args[i].ArgumentValue; cleanArgs[i] = m_args[i].ArgumentValue;
i++; i++;
} }
m_command.Invoke(cleanArgs); m_command.Invoke(cleanArgs);
} }
#endregion #endregion
} }
/// <summary> /// <summary>
/// A single command argument, contains name, type and at runtime, value. /// A single command argument, contains name, type and at runtime, value.
/// </summary> /// </summary>
public class CommandArgument public class CommandArgument
{ {
private string m_help; private string m_help;
private string m_name; private string m_name;
private string m_type; private string m_type;
private Object m_val; private Object m_val;
public CommandArgument(string name, string help, string type) public CommandArgument(string name, string help, string type)
{ {
m_name = name; m_name = name;
m_help = help; m_help = help;
m_type = type; m_type = type;
} }
public string Name public string Name
{ {
get { return m_name; } get { return m_name; }
} }
public string HelpText public string HelpText
{ {
get { return m_help; } get { return m_help; }
} }
public string ArgumentType public string ArgumentType
{ {
get { return m_type; } get { return m_type; }
} }
public Object ArgumentValue public Object ArgumentValue
{ {
get { return m_val; } get { return m_val; }
set { m_val = value; } set { m_val = value; }
} }
} }
/// <summary> /// <summary>
/// A class to enable modules to register console and script commands, which enforces typing and valid input. /// A class to enable modules to register console and script commands, which enforces typing and valid input.
/// </summary> /// </summary>
public class Commander : ICommander public class Commander : ICommander
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, ICommand> m_commands = new Dictionary<string, ICommand>(); private Dictionary<string, ICommand> m_commands = new Dictionary<string, ICommand>();
private string m_name; private string m_name;
public Commander(string name) public Commander(string name)
{ {
m_name = name; m_name = name;
} }
#region ICommander Members #region ICommander Members
public void RegisterCommand(string commandName, ICommand command) public void RegisterCommand(string commandName, ICommand command)
{ {
m_commands[commandName] = command; m_commands[commandName] = command;
} }
/// <summary> /// <summary>
/// Generates a runtime C# class which can be compiled and inserted via reflection to enable modules to register new script commands /// Generates a runtime C# class which can be compiled and inserted via reflection to enable modules to register new script commands
/// </summary> /// </summary>
/// <returns>Returns C# source code to create a binding</returns> /// <returns>Returns C# source code to create a binding</returns>
public string GenerateRuntimeAPI() public string GenerateRuntimeAPI()
{ {
string classSrc = "\n\tpublic class " + m_name + " {\n"; string classSrc = "\n\tpublic class " + m_name + " {\n";
foreach (ICommand com in m_commands.Values) foreach (ICommand com in m_commands.Values)
{ {
classSrc += "\tpublic void " + EscapeRuntimeAPICommand(com.Name) + "( "; classSrc += "\tpublic void " + EscapeRuntimeAPICommand(com.Name) + "( ";
foreach (KeyValuePair<string, string> arg in com.Arguments) foreach (KeyValuePair<string, string> arg in com.Arguments)
{ {
classSrc += arg.Value + " " + Util.Md5Hash(arg.Key) + ","; classSrc += arg.Value + " " + Util.Md5Hash(arg.Key) + ",";
} }
classSrc = classSrc.Remove(classSrc.Length - 1); // Delete the last comma classSrc = classSrc.Remove(classSrc.Length - 1); // Delete the last comma
classSrc += " )\n\t{\n"; classSrc += " )\n\t{\n";
classSrc += "\t\tObject[] args = new Object[" + com.Arguments.Count.ToString() + "];\n"; classSrc += "\t\tObject[] args = new Object[" + com.Arguments.Count.ToString() + "];\n";
int i = 0; int i = 0;
foreach (KeyValuePair<string, string> arg in com.Arguments) foreach (KeyValuePair<string, string> arg in com.Arguments)
{ {
classSrc += "\t\targs[" + i.ToString() + "] = " + Util.Md5Hash(arg.Key) + " " + ";\n"; classSrc += "\t\targs[" + i.ToString() + "] = " + Util.Md5Hash(arg.Key) + " " + ";\n";
i++; i++;
} }
classSrc += "\t\tGetCommander(\"" + m_name + "\").Run(\"" + com.Name + "\", args);\n"; classSrc += "\t\tGetCommander(\"" + m_name + "\").Run(\"" + com.Name + "\", args);\n";
classSrc += "\t}\n"; classSrc += "\t}\n";
} }
classSrc += "}\n"; classSrc += "}\n";
return classSrc; return classSrc;
} }
/// <summary> /// <summary>
/// Runs a specified function with attached arguments /// Runs a specified function with attached arguments
/// *** <b>DO NOT CALL DIRECTLY.</b> *** /// *** <b>DO NOT CALL DIRECTLY.</b> ***
/// Call ProcessConsoleCommand instead if handling human input. /// Call ProcessConsoleCommand instead if handling human input.
/// </summary> /// </summary>
/// <param name="function">The function name to call</param> /// <param name="function">The function name to call</param>
/// <param name="args">The function parameters</param> /// <param name="args">The function parameters</param>
public void Run(string function, object[] args) public void Run(string function, object[] args)
{ {
m_commands[function].Run(args); m_commands[function].Run(args);
} }
public void ProcessConsoleCommand(string function, string[] args) public void ProcessConsoleCommand(string function, string[] args)
{ {
if (m_commands.ContainsKey(function)) if (m_commands.ContainsKey(function))
{ {
if (args.Length > 0 && args[0] == "help") if (args.Length > 0 && args[0] == "help")
{ {
m_commands[function].ShowConsoleHelp(); m_commands[function].ShowConsoleHelp();
} }
else else
{ {
m_commands[function].Run(args); m_commands[function].Run(args);
} }
} }
else else
{ {
if (function != "help") if (function != "help")
m_log.Error("Invalid command - No such command exists"); m_log.Error("Invalid command - No such command exists");
if (function == "api") if (function == "api")
m_log.Info(GenerateRuntimeAPI()); m_log.Info(GenerateRuntimeAPI());
ShowConsoleHelp(); ShowConsoleHelp();
} }
} }
#endregion #endregion
private void ShowConsoleHelp() private void ShowConsoleHelp()
{ {
m_log.Info("===" + m_name + "==="); m_log.Info("===" + m_name + "===");
foreach (ICommand com in m_commands.Values) foreach (ICommand com in m_commands.Values)
{ {
m_log.Info("* " + com.Name + " - " + com.Help); m_log.Info("* " + com.Name + " - " + com.Help);
} }
} }
private string EscapeRuntimeAPICommand(string command) private string EscapeRuntimeAPICommand(string command)
{ {
command = command.Replace('-', '_'); command = command.Replace('-', '_');
StringBuilder tmp = new StringBuilder(command); StringBuilder tmp = new StringBuilder(command);
tmp[0] = tmp[0].ToString().ToUpper().ToCharArray()[0]; tmp[0] = tmp[0].ToString().ToUpper().ToCharArray()[0];
return tmp.ToString(); return tmp.ToString();
} }
} }
} }

View File

@ -1,88 +1,88 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 Nini.Config; using Nini.Config;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Framework namespace OpenSim.Region.Environment.Modules.Framework
{ {
public class CommanderTestModule : IRegionModule, ICommandableModule public class CommanderTestModule : IRegionModule, ICommandableModule
{ {
private Commander m_commander = new Commander("CommanderTest"); private Commander m_commander = new Commander("CommanderTest");
private Scene m_scene; private Scene m_scene;
#region ICommandableModule Members #region ICommandableModule Members
public ICommander CommandInterface public ICommander CommandInterface
{ {
get { throw new NotImplementedException(); } get { throw new NotImplementedException(); }
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
m_scene = scene; m_scene = scene;
} }
public void PostInitialise() public void PostInitialise()
{ {
Command testCommand = new Command("hello", InterfaceHelloWorld, "Says a simple debugging test string"); Command testCommand = new Command("hello", InterfaceHelloWorld, "Says a simple debugging test string");
testCommand.AddArgument("world", "Write world here", "string"); testCommand.AddArgument("world", "Write world here", "string");
m_commander.RegisterCommand("hello", testCommand); m_commander.RegisterCommand("hello", testCommand);
// Register me // Register me
m_scene.RegisterModuleCommander("commandertest", m_commander); m_scene.RegisterModuleCommander("commandertest", m_commander);
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "CommanderTestModule"; } get { return "CommanderTestModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
private void InterfaceHelloWorld(Object[] args) private void InterfaceHelloWorld(Object[] args)
{ {
Console.WriteLine("Hello World"); Console.WriteLine("Hello World");
} }
} }
} }

View File

@ -1,16 +1,16 @@
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Modules.Communications.Interregion; using OpenSim.Region.Environment.Modules.Communications.Interregion;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Grid.Interregion namespace OpenSim.Region.Environment.Modules.Grid.Interregion
{ {
public interface IInterregionModule public interface IInterregionModule
{ {
void RegisterMethod<T>(T e); void RegisterMethod<T>(T e);
bool HasInterface<T>(Location loc); bool HasInterface<T>(Location loc);
T RequestInterface<T>(Location loc); T RequestInterface<T>(Location loc);
T[] RequestInterface<T>(); T[] RequestInterface<T>();
Location GetLocationByDirection(Scene scene, InterregionModule.Direction dir); Location GetLocationByDirection(Scene scene, InterregionModule.Direction dir);
void internal_CreateRemotingObjects(); void internal_CreateRemotingObjects();
} }
} }

View File

@ -1,180 +1,180 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Remoting; using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Remoting.Channels.Tcp;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Modules.Grid.Interregion; using OpenSim.Region.Environment.Modules.Grid.Interregion;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Communications.Interregion namespace OpenSim.Region.Environment.Modules.Communications.Interregion
{ {
public class InterregionModule : IInterregionModule, IRegionModule public class InterregionModule : IInterregionModule, IRegionModule
{ {
#region Direction enum #region Direction enum
public enum Direction public enum Direction
{ {
North, North,
NorthEast, NorthEast,
East, East,
SouthEast, SouthEast,
South, South,
SouthWest, SouthWest,
West, West,
NorthWest NorthWest
} }
#endregion #endregion
private readonly Dictionary<Type, Object> m_interfaces = new Dictionary<Type, object>(); private readonly Dictionary<Type, Object> m_interfaces = new Dictionary<Type, object>();
private readonly List<Location> m_myLocations = new List<Location>(); private readonly List<Location> m_myLocations = new List<Location>();
private readonly Dictionary<Location, string[]> m_neighbourInterfaces = new Dictionary<Location, string[]>(); private readonly Dictionary<Location, string[]> m_neighbourInterfaces = new Dictionary<Location, string[]>();
private readonly Dictionary<Location, RemotingObject> m_neighbourRemote = new Dictionary<Location, RemotingObject>(); private readonly Dictionary<Location, RemotingObject> m_neighbourRemote = new Dictionary<Location, RemotingObject>();
private IConfigSource m_config; private IConfigSource m_config;
private bool m_enabled = false; private bool m_enabled = false;
private Object m_lockObject = new object(); private Object m_lockObject = new object();
private RemotingObject m_myRemote; private RemotingObject m_myRemote;
private TcpChannel m_tcpChannel; private TcpChannel m_tcpChannel;
private int m_tcpPort = 10101; private int m_tcpPort = 10101;
#region IInterregionModule Members #region IInterregionModule Members
public void internal_CreateRemotingObjects() public void internal_CreateRemotingObjects()
{ {
lock (m_lockObject) lock (m_lockObject)
{ {
if (m_tcpChannel == null) if (m_tcpChannel == null)
{ {
m_myRemote = new RemotingObject(m_interfaces, m_myLocations.ToArray()); m_myRemote = new RemotingObject(m_interfaces, m_myLocations.ToArray());
m_tcpChannel = new TcpChannel(m_tcpPort); m_tcpChannel = new TcpChannel(m_tcpPort);
ChannelServices.RegisterChannel(m_tcpChannel, false); ChannelServices.RegisterChannel(m_tcpChannel, false);
RemotingServices.Marshal(m_myRemote, "OpenSimRemote2", typeof (RemotingObject)); RemotingServices.Marshal(m_myRemote, "OpenSimRemote2", typeof (RemotingObject));
} }
} }
} }
public void RegisterMethod<T>(T e) public void RegisterMethod<T>(T e)
{ {
m_interfaces[typeof (T)] = e; m_interfaces[typeof (T)] = e;
} }
public bool HasInterface<T>(Location loc) public bool HasInterface<T>(Location loc)
{ {
foreach (string val in m_neighbourInterfaces[loc]) foreach (string val in m_neighbourInterfaces[loc])
{ {
if (val == typeof (T).FullName) if (val == typeof (T).FullName)
{ {
return true; return true;
} }
} }
return false; return false;
} }
public T RequestInterface<T>(Location loc) public T RequestInterface<T>(Location loc)
{ {
if (m_neighbourRemote.ContainsKey(loc)) if (m_neighbourRemote.ContainsKey(loc))
{ {
return m_neighbourRemote[loc].RequestInterface<T>(); return m_neighbourRemote[loc].RequestInterface<T>();
} }
else else
{ {
throw new IndexOutOfRangeException("No neighbour availible at that location"); throw new IndexOutOfRangeException("No neighbour availible at that location");
} }
} }
public T[] RequestInterface<T>() public T[] RequestInterface<T>()
{ {
List<T> m_t = new List<T>(); List<T> m_t = new List<T>();
foreach (RemotingObject remote in m_neighbourRemote.Values) foreach (RemotingObject remote in m_neighbourRemote.Values)
{ {
try try
{ {
m_t.Add(remote.RequestInterface<T>()); m_t.Add(remote.RequestInterface<T>());
} }
catch (NotSupportedException) catch (NotSupportedException)
{ {
} }
} }
return m_t.ToArray(); return m_t.ToArray();
} }
public Location GetLocationByDirection(Scene scene, Direction dir) public Location GetLocationByDirection(Scene scene, Direction dir)
{ {
return new Location(0, 0); return new Location(0, 0);
} }
#endregion #endregion
//TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated.
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
if (m_enabled) if (m_enabled)
{ {
m_myLocations.Add(new Location((int) scene.RegionInfo.RegionLocX, m_myLocations.Add(new Location((int) scene.RegionInfo.RegionLocX,
(int) scene.RegionInfo.RegionLocY)); (int) scene.RegionInfo.RegionLocY));
m_config = source; m_config = source;
scene.RegisterModuleInterface<IInterregionModule>(this); scene.RegisterModuleInterface<IInterregionModule>(this);
} }
} }
//TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated.
public void PostInitialise() public void PostInitialise()
{ {
if (m_enabled) if (m_enabled)
{ {
try try
{ {
m_tcpPort = m_config.Configs["Comms"].GetInt("remoting_port", m_tcpPort); m_tcpPort = m_config.Configs["Comms"].GetInt("remoting_port", m_tcpPort);
} }
catch catch
{ {
} }
internal_CreateRemotingObjects(); internal_CreateRemotingObjects();
} }
} }
public void Close() public void Close()
{ {
ChannelServices.UnregisterChannel(m_tcpChannel); ChannelServices.UnregisterChannel(m_tcpChannel);
} }
public string Name public string Name
{ {
get { return "InterregionModule"; } get { return "InterregionModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
public void RegisterRemoteRegion(string uri) public void RegisterRemoteRegion(string uri)
{ {
RegisterRemotingInterface((RemotingObject) Activator.GetObject(typeof (RemotingObject), uri)); RegisterRemotingInterface((RemotingObject) Activator.GetObject(typeof (RemotingObject), uri));
} }
private void RegisterRemotingInterface(RemotingObject remote) private void RegisterRemotingInterface(RemotingObject remote)
{ {
Location[] locs = remote.GetLocations(); Location[] locs = remote.GetLocations();
string[] interfaces = remote.GetInterfaces(); string[] interfaces = remote.GetInterfaces();
foreach (Location loc in locs) foreach (Location loc in locs)
{ {
m_neighbourInterfaces[loc] = interfaces; m_neighbourInterfaces[loc] = interfaces;
m_neighbourRemote[loc] = remote; m_neighbourRemote[loc] = remote;
} }
} }
} }
} }

View File

@ -1,50 +1,50 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using OpenSim.Framework; using OpenSim.Framework;
namespace OpenSim.Region.Environment.Modules.Grid.Interregion namespace OpenSim.Region.Environment.Modules.Grid.Interregion
{ {
public class RemotingObject : MarshalByRefObject public class RemotingObject : MarshalByRefObject
{ {
private readonly Location[] m_coords; private readonly Location[] m_coords;
private readonly Dictionary<Type, Object> m_interfaces = new Dictionary<Type, object>(); private readonly Dictionary<Type, Object> m_interfaces = new Dictionary<Type, object>();
public RemotingObject(Dictionary<Type, Object> myInterfaces, Location[] coords) public RemotingObject(Dictionary<Type, Object> myInterfaces, Location[] coords)
{ {
m_interfaces = myInterfaces; m_interfaces = myInterfaces;
m_coords = coords; m_coords = coords;
} }
public Location[] GetLocations() public Location[] GetLocations()
{ {
return (Location[]) m_coords.Clone(); return (Location[]) m_coords.Clone();
} }
public string[] GetInterfaces() public string[] GetInterfaces()
{ {
string[] interfaces = new string[m_interfaces.Count]; string[] interfaces = new string[m_interfaces.Count];
int i = 0; int i = 0;
foreach (KeyValuePair<Type, object> pair in m_interfaces) foreach (KeyValuePair<Type, object> pair in m_interfaces)
{ {
interfaces[i++] = pair.Key.FullName; interfaces[i++] = pair.Key.FullName;
} }
return interfaces; return interfaces;
} }
/// <summary> /// <summary>
/// Returns a registered interface availible to neighbouring regions. /// Returns a registered interface availible to neighbouring regions.
/// </summary> /// </summary>
/// <typeparam name="T">The type of interface you wish to request</typeparam> /// <typeparam name="T">The type of interface you wish to request</typeparam>
/// <returns>A MarshalByRefObject inherited from this region inheriting the interface requested.</returns> /// <returns>A MarshalByRefObject inherited from this region inheriting the interface requested.</returns>
/// <remarks>All registered interfaces <b>MUST</b> inherit from MarshalByRefObject and use only serialisable types.</remarks> /// <remarks>All registered interfaces <b>MUST</b> inherit from MarshalByRefObject and use only serialisable types.</remarks>
public T RequestInterface<T>() public T RequestInterface<T>()
{ {
if (m_interfaces.ContainsKey(typeof (T))) if (m_interfaces.ContainsKey(typeof (T)))
return (T) m_interfaces[typeof (T)]; return (T) m_interfaces[typeof (T)];
throw new NotSupportedException("No such interface registered."); throw new NotSupportedException("No such interface registered.");
} }
} }
} }

View File

@ -1,283 +1,283 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenJPEGNet; using OpenJPEGNet;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture
{ {
public class DynamicTextureModule : IRegionModule, IDynamicTextureManager public class DynamicTextureModule : IRegionModule, IDynamicTextureManager
{ {
private Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>(); private Dictionary<LLUUID, Scene> RegisteredScenes = new Dictionary<LLUUID, Scene>();
private Dictionary<string, IDynamicTextureRender> RenderPlugins = private Dictionary<string, IDynamicTextureRender> RenderPlugins =
new Dictionary<string, IDynamicTextureRender>(); new Dictionary<string, IDynamicTextureRender>();
private Dictionary<LLUUID, DynamicTextureUpdater> Updaters = new Dictionary<LLUUID, DynamicTextureUpdater>(); private Dictionary<LLUUID, DynamicTextureUpdater> Updaters = new Dictionary<LLUUID, DynamicTextureUpdater>();
#region IDynamicTextureManager Members #region IDynamicTextureManager Members
public void RegisterRender(string handleType, IDynamicTextureRender render) public void RegisterRender(string handleType, IDynamicTextureRender render)
{ {
if (!RenderPlugins.ContainsKey(handleType)) if (!RenderPlugins.ContainsKey(handleType))
{ {
RenderPlugins.Add(handleType, render); RenderPlugins.Add(handleType, render);
} }
} }
public void ReturnData(LLUUID id, byte[] data) public void ReturnData(LLUUID id, byte[] data)
{ {
if (Updaters.ContainsKey(id)) if (Updaters.ContainsKey(id))
{ {
DynamicTextureUpdater updater = Updaters[id]; DynamicTextureUpdater updater = Updaters[id];
if (RegisteredScenes.ContainsKey(updater.SimUUID)) if (RegisteredScenes.ContainsKey(updater.SimUUID))
{ {
Scene scene = RegisteredScenes[updater.SimUUID]; Scene scene = RegisteredScenes[updater.SimUUID];
updater.DataReceived(data, scene); updater.DataReceived(data, scene);
} }
} }
} }
public LLUUID AddDynamicTextureURL(LLUUID simID, LLUUID primID, string contentType, string url, public LLUUID AddDynamicTextureURL(LLUUID simID, LLUUID primID, string contentType, string url,
string extraParams, int updateTimer) string extraParams, int updateTimer)
{ {
return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255);
} }
public LLUUID AddDynamicTextureURL(LLUUID simID, LLUUID primID, string contentType, string url, public LLUUID AddDynamicTextureURL(LLUUID simID, LLUUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{ {
if (RenderPlugins.ContainsKey(contentType)) if (RenderPlugins.ContainsKey(contentType))
{ {
//Console.WriteLine("dynamic texture being created: " + url + " of type " + contentType); //Console.WriteLine("dynamic texture being created: " + url + " of type " + contentType);
DynamicTextureUpdater updater = new DynamicTextureUpdater(); DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID; updater.SimUUID = simID;
updater.PrimID = primID; updater.PrimID = primID;
updater.ContentType = contentType; updater.ContentType = contentType;
updater.Url = url; updater.Url = url;
updater.UpdateTimer = updateTimer; updater.UpdateTimer = updateTimer;
updater.UpdaterID = LLUUID.Random(); updater.UpdaterID = LLUUID.Random();
updater.Params = extraParams; updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending; updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue; updater.FrontAlpha = AlphaValue;
if (!Updaters.ContainsKey(updater.UpdaterID)) if (!Updaters.ContainsKey(updater.UpdaterID))
{ {
Updaters.Add(updater.UpdaterID, updater); Updaters.Add(updater.UpdaterID, updater);
} }
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
return updater.UpdaterID; return updater.UpdaterID;
} }
return LLUUID.Zero; return LLUUID.Zero;
} }
public LLUUID AddDynamicTextureData(LLUUID simID, LLUUID primID, string contentType, string data, public LLUUID AddDynamicTextureData(LLUUID simID, LLUUID primID, string contentType, string data,
string extraParams, int updateTimer) string extraParams, int updateTimer)
{ {
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255);
} }
public LLUUID AddDynamicTextureData(LLUUID simID, LLUUID primID, string contentType, string data, public LLUUID AddDynamicTextureData(LLUUID simID, LLUUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{ {
if (RenderPlugins.ContainsKey(contentType)) if (RenderPlugins.ContainsKey(contentType))
{ {
DynamicTextureUpdater updater = new DynamicTextureUpdater(); DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID; updater.SimUUID = simID;
updater.PrimID = primID; updater.PrimID = primID;
updater.ContentType = contentType; updater.ContentType = contentType;
updater.BodyData = data; updater.BodyData = data;
updater.UpdateTimer = updateTimer; updater.UpdateTimer = updateTimer;
updater.UpdaterID = LLUUID.Random(); updater.UpdaterID = LLUUID.Random();
updater.Params = extraParams; updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending; updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue; updater.FrontAlpha = AlphaValue;
if (!Updaters.ContainsKey(updater.UpdaterID)) if (!Updaters.ContainsKey(updater.UpdaterID))
{ {
Updaters.Add(updater.UpdaterID, updater); Updaters.Add(updater.UpdaterID, updater);
} }
RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
return updater.UpdaterID; return updater.UpdaterID;
} }
return LLUUID.Zero; return LLUUID.Zero;
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{ {
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IDynamicTextureManager>(this); scene.RegisterModuleInterface<IDynamicTextureManager>(this);
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "DynamicTextureModule"; } get { return "DynamicTextureModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
#region Nested type: DynamicTextureUpdater #region Nested type: DynamicTextureUpdater
public class DynamicTextureUpdater public class DynamicTextureUpdater
{ {
public bool BlendWithOldTexture = false; public bool BlendWithOldTexture = false;
public string BodyData; public string BodyData;
public string ContentType; public string ContentType;
public byte FrontAlpha = 255; public byte FrontAlpha = 255;
public LLUUID LastAssetID; public LLUUID LastAssetID;
public string Params; public string Params;
public LLUUID PrimID; public LLUUID PrimID;
public bool SetNewFrontAlpha = false; public bool SetNewFrontAlpha = false;
public LLUUID SimUUID; public LLUUID SimUUID;
public LLUUID UpdaterID; public LLUUID UpdaterID;
public int UpdateTimer; public int UpdateTimer;
public string Url; public string Url;
public DynamicTextureUpdater() public DynamicTextureUpdater()
{ {
LastAssetID = LLUUID.Zero; LastAssetID = LLUUID.Zero;
UpdateTimer = 0; UpdateTimer = 0;
BodyData = null; BodyData = null;
} }
public void DataReceived(byte[] data, Scene scene) public void DataReceived(byte[] data, Scene scene)
{ {
SceneObjectPart part = scene.GetSceneObjectPart(PrimID); SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
byte[] assetData; byte[] assetData;
AssetBase oldAsset = null; AssetBase oldAsset = null;
if (BlendWithOldTexture) if (BlendWithOldTexture)
{ {
LLUUID lastTextureID = part.Shape.Textures.DefaultTexture.TextureID; LLUUID lastTextureID = part.Shape.Textures.DefaultTexture.TextureID;
oldAsset = scene.AssetCache.GetAsset(lastTextureID, true); oldAsset = scene.AssetCache.GetAsset(lastTextureID, true);
if (oldAsset != null) if (oldAsset != null)
{ {
assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha); assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
} }
else else
{ {
assetData = new byte[data.Length]; assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length); Array.Copy(data, assetData, data.Length);
} }
} }
else else
{ {
assetData = new byte[data.Length]; assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length); Array.Copy(data, assetData, data.Length);
} }
//TODO delete the last asset(data), if it was a dynamic texture //TODO delete the last asset(data), if it was a dynamic texture
AssetBase asset = new AssetBase(); AssetBase asset = new AssetBase();
asset.FullID = LLUUID.Random(); asset.FullID = LLUUID.Random();
asset.Data = assetData; asset.Data = assetData;
asset.Name = "DynamicImage" + Util.RandomClass.Next(1, 10000); asset.Name = "DynamicImage" + Util.RandomClass.Next(1, 10000);
asset.Type = 0; asset.Type = 0;
asset.Description = "dynamic image"; asset.Description = "dynamic image";
asset.Local = false; asset.Local = false;
asset.Temporary = true; asset.Temporary = true;
scene.AssetCache.AddAsset(asset); scene.AssetCache.AddAsset(asset);
LastAssetID = asset.FullID; LastAssetID = asset.FullID;
part.Shape.Textures = new LLObject.TextureEntry(asset.FullID); part.Shape.Textures = new LLObject.TextureEntry(asset.FullID);
part.ScheduleFullUpdate(); part.ScheduleFullUpdate();
} }
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
{ {
Bitmap image1 = new Bitmap(OpenJPEG.DecodeToImage(frontImage)); Bitmap image1 = new Bitmap(OpenJPEG.DecodeToImage(frontImage));
Bitmap image2 = new Bitmap(OpenJPEG.DecodeToImage(backImage)); Bitmap image2 = new Bitmap(OpenJPEG.DecodeToImage(backImage));
if (setNewAlpha) if (setNewAlpha)
{ {
SetAlpha(ref image1, newAlpha); SetAlpha(ref image1, newAlpha);
} }
Bitmap joint = MergeBitMaps(image1, image2); Bitmap joint = MergeBitMaps(image1, image2);
return OpenJPEG.EncodeFromImage(joint, true); return OpenJPEG.EncodeFromImage(joint, true);
} }
public Bitmap MergeBitMaps(Bitmap front, Bitmap back) public Bitmap MergeBitMaps(Bitmap front, Bitmap back)
{ {
Bitmap joint; Bitmap joint;
Graphics jG; Graphics jG;
joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb); joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb);
jG = Graphics.FromImage(joint); jG = Graphics.FromImage(joint);
jG.DrawImage(back, 0, 0, back.Width, back.Height); jG.DrawImage(back, 0, 0, back.Width, back.Height);
jG.DrawImage(front, 0, 0, back.Width, back.Height); jG.DrawImage(front, 0, 0, back.Width, back.Height);
return joint; return joint;
} }
private void SetAlpha(ref Bitmap b, byte alpha) private void SetAlpha(ref Bitmap b, byte alpha)
{ {
for (int w = 0; w < b.Width; w++) for (int w = 0; w < b.Width; w++)
{ {
for (int h = 0; h < b.Height; h++) for (int h = 0; h < b.Height; h++)
{ {
b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h))); b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h)));
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,364 +1,364 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
/***************************************************** /*****************************************************
* *
* ScriptsHttpRequests * ScriptsHttpRequests
* *
* Implements the llHttpRequest and http_response * Implements the llHttpRequest and http_response
* callback. * callback.
* *
* Some stuff was already in LSLLongCmdHandler, and then * Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So, * there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of * I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the * LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and * start and stop methods, and setting up pending and
* completed queues. These are processed in the * completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the * LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work. * XMLRPCModule, since that seems to work.
* *
* //TODO * //TODO
* *
* This probably needs some throttling mechanism but * This probably needs some throttling mechanism but
* its wide open right now. This applies to both * its wide open right now. This applies to both
* number of requests and data volume. * number of requests and data volume.
* *
* Linden puts all kinds of header fields in the requests. * Linden puts all kinds of header fields in the requests.
* Not doing any of that: * Not doing any of that:
* User-Agent * User-Agent
* X-SecondLife-Shard * X-SecondLife-Shard
* X-SecondLife-Object-Name * X-SecondLife-Object-Name
* X-SecondLife-Object-Key * X-SecondLife-Object-Key
* X-SecondLife-Region * X-SecondLife-Region
* X-SecondLife-Local-Position * X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity * X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation * X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name * X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key * X-SecondLife-Owner-Key
* *
* HTTPS support * HTTPS support
* *
* Configurable timeout? * Configurable timeout?
* Configurable max repsonse size? * Configurable max repsonse size?
* Configurable * Configurable
* *
* **************************************************/ * **************************************************/
namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest
{ {
public class HttpRequestModule : IRegionModule, IHttpRequests public class HttpRequestModule : IRegionModule, IHttpRequests
{ {
private object HttpListLock = new object(); private object HttpListLock = new object();
private int httpTimeout = 30000; private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests"; private string m_name = "HttpScriptRequests";
// <request id, HttpRequestClass> // <request id, HttpRequestClass>
private Dictionary<LLUUID, HttpRequestClass> m_pendingRequests; private Dictionary<LLUUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene; private Scene m_scene;
private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>(); private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public HttpRequestModule() public HttpRequestModule()
{ {
} }
#region IHttpRequests Members #region IHttpRequests Members
public LLUUID MakeHttpRequest(string url, string parameters, string body) public LLUUID MakeHttpRequest(string url, string parameters, string body)
{ {
return LLUUID.Zero; return LLUUID.Zero;
} }
public LLUUID StartHttpRequest(uint localID, LLUUID itemID, string url, List<string> parameters, string body) public LLUUID StartHttpRequest(uint localID, LLUUID itemID, string url, List<string> parameters, string body)
{ {
LLUUID reqID = LLUUID.Random(); LLUUID reqID = LLUUID.Random();
HttpRequestClass htc = new HttpRequestClass(); HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed // Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest // see http://wiki.secondlife.com/wiki/LlHTTPRequest
// //
// Parameters are expected in {key, value, ... , key, value} // Parameters are expected in {key, value, ... , key, value}
if (parameters != null) if (parameters != null)
{ {
string[] parms = parameters.ToArray(); string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length / 2; i += 2) for (int i = 0; i < parms.Length / 2; i += 2)
{ {
switch (Int32.Parse(parms[i])) switch (Int32.Parse(parms[i]))
{ {
case HttpRequestClass.HTTP_METHOD: case HttpRequestClass.HTTP_METHOD:
htc.httpMethod = parms[i + 1]; htc.httpMethod = parms[i + 1];
break; break;
case HttpRequestClass.HTTP_MIMETYPE: case HttpRequestClass.HTTP_MIMETYPE:
htc.httpMIMEType = parms[i + 1]; htc.httpMIMEType = parms[i + 1];
break; break;
case HttpRequestClass.HTTP_BODY_MAXLENGTH: case HttpRequestClass.HTTP_BODY_MAXLENGTH:
// TODO implement me // TODO implement me
break; break;
case HttpRequestClass.HTTP_VERIFY_CERT: case HttpRequestClass.HTTP_VERIFY_CERT:
// TODO implement me // TODO implement me
break; break;
} }
} }
} }
htc.localID = localID; htc.localID = localID;
htc.itemID = itemID; htc.itemID = itemID;
htc.url = url; htc.url = url;
htc.reqID = reqID; htc.reqID = reqID;
htc.httpTimeout = httpTimeout; htc.httpTimeout = httpTimeout;
htc.outbound_body = body; htc.outbound_body = body;
lock (HttpListLock) lock (HttpListLock)
{ {
m_pendingRequests.Add(reqID, htc); m_pendingRequests.Add(reqID, htc);
} }
htc.process(); htc.process();
return reqID; return reqID;
} }
public void StopHttpRequest(uint m_localID, LLUUID m_itemID) public void StopHttpRequest(uint m_localID, LLUUID m_itemID)
{ {
if (m_pendingRequests != null) if (m_pendingRequests != null)
{ {
lock (HttpListLock) lock (HttpListLock)
{ {
HttpRequestClass tmpReq; HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq)) if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{ {
tmpReq.Stop(); tmpReq.Stop();
m_pendingRequests.Remove(m_itemID); m_pendingRequests.Remove(m_itemID);
} }
} }
} }
} }
/* /*
* TODO * TODO
* Not sure how important ordering is is here - the next first * Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list * one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or * position, not the order in which the request was started or
* finsihed. I thought about setting up a queue for this, but * finsihed. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now * it will need some refactoring and this works 'enough' right now
*/ */
public HttpRequestClass GetNextCompletedRequest() public HttpRequestClass GetNextCompletedRequest()
{ {
lock (HttpListLock) lock (HttpListLock)
{ {
foreach (LLUUID luid in m_pendingRequests.Keys) foreach (LLUUID luid in m_pendingRequests.Keys)
{ {
HttpRequestClass tmpReq; HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq)) if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{ {
if (tmpReq.finished) if (tmpReq.finished)
{ {
return tmpReq; return tmpReq;
} }
} }
} }
} }
return null; return null;
} }
public void RemoveCompletedRequest(LLUUID id) public void RemoveCompletedRequest(LLUUID id)
{ {
lock (HttpListLock) lock (HttpListLock)
{ {
HttpRequestClass tmpReq; HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq)) if (m_pendingRequests.TryGetValue(id, out tmpReq))
{ {
tmpReq.Stop(); tmpReq.Stop();
tmpReq = null; tmpReq = null;
m_pendingRequests.Remove(id); m_pendingRequests.Remove(id);
} }
} }
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_scene = scene; m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequests>(this); m_scene.RegisterModuleInterface<IHttpRequests>(this);
m_pendingRequests = new Dictionary<LLUUID, HttpRequestClass>(); m_pendingRequests = new Dictionary<LLUUID, HttpRequestClass>();
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return m_name; } get { return m_name; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
} }
public class HttpRequestClass public class HttpRequestClass
{ {
// Constants for parameters // Constants for parameters
public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_BODY_MAXLENGTH = 2;
public const int HTTP_METHOD = 0; public const int HTTP_METHOD = 0;
public const int HTTP_MIMETYPE = 1; public const int HTTP_MIMETYPE = 1;
public const int HTTP_VERIFY_CERT = 3; public const int HTTP_VERIFY_CERT = 3;
public bool finished; public bool finished;
public int httpBodyMaxLen = 2048; // not implemented public int httpBodyMaxLen = 2048; // not implemented
// Parameter members and default values // Parameter members and default values
public string httpMethod = "GET"; public string httpMethod = "GET";
public string httpMIMEType = "text/plain;charset=utf-8"; public string httpMIMEType = "text/plain;charset=utf-8";
private Thread httpThread; private Thread httpThread;
public int httpTimeout; public int httpTimeout;
public bool httpVerifyCert = true; // not implemented public bool httpVerifyCert = true; // not implemented
// Request info // Request info
public LLUUID itemID; public LLUUID itemID;
public uint localID; public uint localID;
public DateTime next; public DateTime next;
public string outbound_body; public string outbound_body;
public LLUUID reqID; public LLUUID reqID;
public HttpWebRequest request; public HttpWebRequest request;
public string response_body; public string response_body;
public List<string> response_metadata; public List<string> response_metadata;
public int status; public int status;
public string url; public string url;
public void process() public void process()
{ {
httpThread = new Thread(SendRequest); httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread"; httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal; httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true; httpThread.IsBackground = true;
finished = false; finished = false;
httpThread.Start(); httpThread.Start();
ThreadTracker.Add(httpThread); ThreadTracker.Add(httpThread);
} }
/* /*
* TODO: More work on the response codes. Right now * TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception * returning 200 for success or 499 for exception
*/ */
public void SendRequest() public void SendRequest()
{ {
HttpWebResponse response = null; HttpWebResponse response = null;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192]; byte[] buf = new byte[8192];
string tempString = null; string tempString = null;
int count = 0; int count = 0;
try try
{ {
request = (HttpWebRequest) request = (HttpWebRequest)
WebRequest.Create(url); WebRequest.Create(url);
request.Method = httpMethod; request.Method = httpMethod;
request.ContentType = httpMIMEType; request.ContentType = httpMIMEType;
request.Timeout = httpTimeout; request.Timeout = httpTimeout;
// execute the request // execute the request
response = (HttpWebResponse) response = (HttpWebResponse)
request.GetResponse(); request.GetResponse();
Stream resStream = response.GetResponseStream(); Stream resStream = response.GetResponseStream();
do do
{ {
// fill the buffer with data // fill the buffer with data
count = resStream.Read(buf, 0, buf.Length); count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data // make sure we read some data
if (count != 0) if (count != 0)
{ {
// translate from bytes to ASCII text // translate from bytes to ASCII text
tempString = Encoding.UTF8.GetString(buf, 0, count); tempString = Encoding.UTF8.GetString(buf, 0, count);
// continue building the string // continue building the string
sb.Append(tempString); sb.Append(tempString);
} }
} while (count > 0); // any more data to read? } while (count > 0); // any more data to read?
response_body = sb.ToString(); response_body = sb.ToString();
} }
catch (Exception e) catch (Exception e)
{ {
status = 499; status = 499;
response_body = e.Message; response_body = e.Message;
finished = true; finished = true;
return; return;
} }
status = 200; status = 200;
finished = true; finished = true;
} }
public void Stop() public void Stop()
{ {
try try
{ {
httpThread.Abort(); httpThread.Abort();
} }
catch (Exception) catch (Exception)
{ {
} }
} }
} }
} }

View File

@ -1,191 +1,191 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Net; using System.Net;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenJPEGNet; using OpenJPEGNet;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL
{ {
public class LoadImageURLModule : IRegionModule, IDynamicTextureRender public class LoadImageURLModule : IRegionModule, IDynamicTextureRender
{ {
private string m_name = "LoadImageURL"; private string m_name = "LoadImageURL";
private Scene m_scene; private Scene m_scene;
private IDynamicTextureManager m_textureManager; private IDynamicTextureManager m_textureManager;
#region IDynamicTextureRender Members #region IDynamicTextureRender Members
public string GetName() public string GetName()
{ {
return m_name; return m_name;
} }
public string GetContentType() public string GetContentType()
{ {
return ("image"); return ("image");
} }
public bool SupportsAsynchronous() public bool SupportsAsynchronous()
{ {
return true; return true;
} }
public byte[] ConvertUrl(string url, string extraParams) public byte[] ConvertUrl(string url, string extraParams)
{ {
return null; return null;
} }
public byte[] ConvertStream(Stream data, string extraParams) public byte[] ConvertStream(Stream data, string extraParams)
{ {
return null; return null;
} }
public bool AsyncConvertUrl(LLUUID id, string url, string extraParams) public bool AsyncConvertUrl(LLUUID id, string url, string extraParams)
{ {
MakeHttpRequest(url, id); MakeHttpRequest(url, id);
return true; return true;
} }
public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams) public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams)
{ {
return false; return false;
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (m_scene == null) if (m_scene == null)
{ {
m_scene = scene; m_scene = scene;
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>(); m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null) if (m_textureManager != null)
{ {
m_textureManager.RegisterRender(GetContentType(), this); m_textureManager.RegisterRender(GetContentType(), this);
} }
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return m_name; } get { return m_name; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
private void MakeHttpRequest(string url, LLUUID requestID) private void MakeHttpRequest(string url, LLUUID requestID)
{ {
WebRequest request = HttpWebRequest.Create(url); WebRequest request = HttpWebRequest.Create(url);
RequestState state = new RequestState((HttpWebRequest) request, requestID); RequestState state = new RequestState((HttpWebRequest) request, requestID);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state); IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds; state.TimeOfRequest = (int) t.TotalSeconds;
} }
private void HttpRequestReturn(IAsyncResult result) private void HttpRequestReturn(IAsyncResult result)
{ {
RequestState state = (RequestState) result.AsyncState; RequestState state = (RequestState) result.AsyncState;
WebRequest request = (WebRequest) state.Request; WebRequest request = (WebRequest) state.Request;
HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(result); HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(result);
if (response.StatusCode == HttpStatusCode.OK) if (response.StatusCode == HttpStatusCode.OK)
{ {
Bitmap image = new Bitmap(response.GetResponseStream()); Bitmap image = new Bitmap(response.GetResponseStream());
Size newsize; Size newsize;
// TODO: make this a bit less hard coded // TODO: make this a bit less hard coded
if ((image.Height < 64) && (image.Width < 64)) if ((image.Height < 64) && (image.Width < 64))
{ {
newsize = new Size(32, 32); newsize = new Size(32, 32);
} }
else if ((image.Height < 128) && (image.Width < 128)) else if ((image.Height < 128) && (image.Width < 128))
{ {
newsize = new Size(64, 64); newsize = new Size(64, 64);
} }
else if ((image.Height < 256) && (image.Width < 256)) else if ((image.Height < 256) && (image.Width < 256))
{ {
newsize = new Size(128, 128); newsize = new Size(128, 128);
} }
else if ((image.Height < 512 && image.Width < 512)) else if ((image.Height < 512 && image.Width < 512))
{ {
newsize = new Size(256, 256); newsize = new Size(256, 256);
} }
else if ((image.Height < 1024 && image.Width < 1024)) else if ((image.Height < 1024 && image.Width < 1024))
{ {
newsize = new Size(512, 512); newsize = new Size(512, 512);
} }
else else
{ {
newsize = new Size(1024, 1024); newsize = new Size(1024, 1024);
} }
Bitmap resize = new Bitmap(image, newsize); Bitmap resize = new Bitmap(image, newsize);
byte[] imageJ2000 = OpenJPEG.EncodeFromImage(resize, true); byte[] imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
m_textureManager.ReturnData(state.RequestID, imageJ2000); m_textureManager.ReturnData(state.RequestID, imageJ2000);
} }
} }
#region Nested type: RequestState #region Nested type: RequestState
public class RequestState public class RequestState
{ {
public HttpWebRequest Request = null; public HttpWebRequest Request = null;
public LLUUID RequestID = LLUUID.Zero; public LLUUID RequestID = LLUUID.Zero;
public int TimeOfRequest = 0; public int TimeOfRequest = 0;
public RequestState(HttpWebRequest request, LLUUID requestID) public RequestState(HttpWebRequest request, LLUUID requestID)
{ {
Request = request; Request = request;
RequestID = requestID; RequestID = requestID;
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,369 +1,369 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Net; using System.Net;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenJPEGNet; using OpenJPEGNet;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
using Image=System.Drawing.Image; using Image=System.Drawing.Image;
//using Cairo; //using Cairo;
namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender
{ {
public class VectorRenderModule : IRegionModule, IDynamicTextureRender public class VectorRenderModule : IRegionModule, IDynamicTextureRender
{ {
private string m_name = "VectorRenderModule"; private string m_name = "VectorRenderModule";
private Scene m_scene; private Scene m_scene;
private IDynamicTextureManager m_textureManager; private IDynamicTextureManager m_textureManager;
public VectorRenderModule() public VectorRenderModule()
{ {
} }
#region IDynamicTextureRender Members #region IDynamicTextureRender Members
public string GetContentType() public string GetContentType()
{ {
return ("vector"); return ("vector");
} }
public string GetName() public string GetName()
{ {
return m_name; return m_name;
} }
public bool SupportsAsynchronous() public bool SupportsAsynchronous()
{ {
return true; return true;
} }
public byte[] ConvertUrl(string url, string extraParams) public byte[] ConvertUrl(string url, string extraParams)
{ {
return null; return null;
} }
public byte[] ConvertStream(Stream data, string extraParams) public byte[] ConvertStream(Stream data, string extraParams)
{ {
return null; return null;
} }
public bool AsyncConvertUrl(LLUUID id, string url, string extraParams) public bool AsyncConvertUrl(LLUUID id, string url, string extraParams)
{ {
return false; return false;
} }
public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams) public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams)
{ {
Draw(bodyData, id, extraParams); Draw(bodyData, id, extraParams);
return true; return true;
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
if (m_scene == null) if (m_scene == null)
{ {
m_scene = scene; m_scene = scene;
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>(); m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null) if (m_textureManager != null)
{ {
m_textureManager.RegisterRender(GetContentType(), this); m_textureManager.RegisterRender(GetContentType(), this);
} }
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return m_name; } get { return m_name; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
private void Draw(string data, LLUUID id, string extraParams) private void Draw(string data, LLUUID id, string extraParams)
{ {
// TODO: this is a brutal hack. extraParams should actually be parsed reasonably. // TODO: this is a brutal hack. extraParams should actually be parsed reasonably.
int size = 256; int size = 256;
try try
{ {
size = Convert.ToInt32(extraParams); size = Convert.ToInt32(extraParams);
} }
catch (Exception e) catch (Exception e)
{ {
//Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used //Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used
Console.WriteLine("Problem with Draw. Please verify parameters." + e.ToString()); Console.WriteLine("Problem with Draw. Please verify parameters." + e.ToString());
} }
if ((size < 128) || (size > 1024)) if ((size < 128) || (size > 1024))
size = 256; size = 256;
Bitmap bitmap = new Bitmap(size, size, PixelFormat.Format32bppArgb); Bitmap bitmap = new Bitmap(size, size, PixelFormat.Format32bppArgb);
Graphics graph = Graphics.FromImage(bitmap); Graphics graph = Graphics.FromImage(bitmap);
extraParams = extraParams.ToLower(); extraParams = extraParams.ToLower();
int alpha = 255; int alpha = 255;
if (extraParams == "setalpha") if (extraParams == "setalpha")
{ {
alpha = 0; alpha = 0;
} }
else else
{ {
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, size, size); graph.FillRectangle(new SolidBrush(Color.White), 0, 0, size, size);
} }
for (int w = 0; w < bitmap.Width; w++) for (int w = 0; w < bitmap.Width; w++)
{ {
for (int h = 0; h < bitmap.Height; h++) for (int h = 0; h < bitmap.Height; h++)
{ {
bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h))); bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h)));
} }
} }
GDIDraw(data, graph); GDIDraw(data, graph);
byte[] imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); byte[] imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true);
m_textureManager.ReturnData(id, imageJ2000); m_textureManager.ReturnData(id, imageJ2000);
} }
/* /*
private void CairoDraw(string data, System.Drawing.Graphics graph) private void CairoDraw(string data, System.Drawing.Graphics graph)
{ {
using (Win32Surface draw = new Win32Surface(graph.GetHdc())) using (Win32Surface draw = new Win32Surface(graph.GetHdc()))
{ {
Context contex = new Context(draw); Context contex = new Context(draw);
contex.Antialias = Antialias.None; //fastest method but low quality contex.Antialias = Antialias.None; //fastest method but low quality
contex.LineWidth = 7; contex.LineWidth = 7;
char[] lineDelimiter = { ';' }; char[] lineDelimiter = { ';' };
char[] partsDelimiter = { ',' }; char[] partsDelimiter = { ',' };
string[] lines = data.Split(lineDelimiter); string[] lines = data.Split(lineDelimiter);
foreach (string line in lines) foreach (string line in lines)
{ {
string nextLine = line.Trim(); string nextLine = line.Trim();
if (nextLine.StartsWith("MoveTO")) if (nextLine.StartsWith("MoveTO"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y); GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.MoveTo(x, y); contex.MoveTo(x, y);
} }
else if (nextLine.StartsWith("LineTo")) else if (nextLine.StartsWith("LineTo"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y); GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.LineTo(x, y); contex.LineTo(x, y);
contex.Stroke(); contex.Stroke();
} }
} }
} }
graph.ReleaseHdc(); graph.ReleaseHdc();
} }
*/ */
private void GDIDraw(string data, Graphics graph) private void GDIDraw(string data, Graphics graph)
{ {
Point startPoint = new Point(0, 0); Point startPoint = new Point(0, 0);
Point endPoint = new Point(0, 0); Point endPoint = new Point(0, 0);
Pen drawPen = new Pen(Color.Black, 7); Pen drawPen = new Pen(Color.Black, 7);
Font myFont = new Font("Times New Roman", 14); Font myFont = new Font("Times New Roman", 14);
SolidBrush myBrush = new SolidBrush(Color.Black); SolidBrush myBrush = new SolidBrush(Color.Black);
char[] lineDelimiter = {';'}; char[] lineDelimiter = {';'};
char[] partsDelimiter = {','}; char[] partsDelimiter = {','};
string[] lines = data.Split(lineDelimiter); string[] lines = data.Split(lineDelimiter);
foreach (string line in lines) foreach (string line in lines)
{ {
string nextLine = line.Trim(); string nextLine = line.Trim();
//replace with switch, or even better, do some proper parsing //replace with switch, or even better, do some proper parsing
if (nextLine.StartsWith("MoveTo")) if (nextLine.StartsWith("MoveTo"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
startPoint.X = (int) x; startPoint.X = (int) x;
startPoint.Y = (int) y; startPoint.Y = (int) y;
} }
else if (nextLine.StartsWith("LineTo")) else if (nextLine.StartsWith("LineTo"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
graph.DrawLine(drawPen, startPoint, endPoint); graph.DrawLine(drawPen, startPoint, endPoint);
startPoint.X = endPoint.X; startPoint.X = endPoint.X;
startPoint.Y = endPoint.Y; startPoint.Y = endPoint.Y;
} }
else if (nextLine.StartsWith("Text")) else if (nextLine.StartsWith("Text"))
{ {
nextLine = nextLine.Remove(0, 4); nextLine = nextLine.Remove(0, 4);
nextLine = nextLine.Trim(); nextLine = nextLine.Trim();
graph.DrawString(nextLine, myFont, myBrush, startPoint); graph.DrawString(nextLine, myFont, myBrush, startPoint);
} }
else if (nextLine.StartsWith("Image")) else if (nextLine.StartsWith("Image"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
Image image = ImageHttpRequest(nextLine); Image image = ImageHttpRequest(nextLine);
graph.DrawImage(image, (float) startPoint.X, (float) startPoint.Y, x, y); graph.DrawImage(image, (float) startPoint.X, (float) startPoint.Y, x, y);
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
else if (nextLine.StartsWith("Rectangle")) else if (nextLine.StartsWith("Rectangle"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
else if (nextLine.StartsWith("FillRectangle")) else if (nextLine.StartsWith("FillRectangle"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
else if (nextLine.StartsWith("Ellipse")) else if (nextLine.StartsWith("Ellipse"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
else if (nextLine.StartsWith("FontSize")) else if (nextLine.StartsWith("FontSize"))
{ {
nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim(); nextLine = nextLine.Trim();
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
myFont = new Font("Times New Roman", size); myFont = new Font("Times New Roman", size);
} }
else if (nextLine.StartsWith("PenSize")) else if (nextLine.StartsWith("PenSize"))
{ {
nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim(); nextLine = nextLine.Trim();
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
drawPen.Width = size; drawPen.Width = size;
} }
else if (nextLine.StartsWith("PenColour")) else if (nextLine.StartsWith("PenColour"))
{ {
nextLine = nextLine.Remove(0, 9); nextLine = nextLine.Remove(0, 9);
nextLine = nextLine.Trim(); nextLine = nextLine.Trim();
Color newColour = Color.FromName(nextLine); Color newColour = Color.FromName(nextLine);
myBrush.Color = newColour; myBrush.Color = newColour;
drawPen.Color = newColour; drawPen.Color = newColour;
} }
} }
} }
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y) private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y)
{ {
line = line.Remove(0, startLength); line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter); string[] parts = line.Split(partsDelimiter);
if (parts.Length == 2) if (parts.Length == 2)
{ {
string xVal = parts[0].Trim(); string xVal = parts[0].Trim();
string yVal = parts[1].Trim(); string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
} }
else if (parts.Length > 2) else if (parts.Length > 2)
{ {
string xVal = parts[0].Trim(); string xVal = parts[0].Trim();
string yVal = parts[1].Trim(); string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
line = ""; line = "";
for (int i = 2; i < parts.Length; i++) for (int i = 2; i < parts.Length; i++)
{ {
line = line + parts[i].Trim(); line = line + parts[i].Trim();
line = line + " "; line = line + " ";
} }
} }
} }
private Bitmap ImageHttpRequest(string url) private Bitmap ImageHttpRequest(string url)
{ {
WebRequest request = HttpWebRequest.Create(url); WebRequest request = HttpWebRequest.Create(url);
//Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used. //Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used.
//Ckrinke Stream str = null; //Ckrinke Stream str = null;
HttpWebResponse response = (HttpWebResponse) (request).GetResponse(); HttpWebResponse response = (HttpWebResponse) (request).GetResponse();
if (response.StatusCode == HttpStatusCode.OK) if (response.StatusCode == HttpStatusCode.OK)
{ {
Bitmap image = new Bitmap(response.GetResponseStream()); Bitmap image = new Bitmap(response.GetResponseStream());
return image; return image;
} }
return null; return null;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,79 +1,79 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using Nini.Config; using Nini.Config;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.World.Land namespace OpenSim.Region.Environment.Modules.World.Land
{ {
public class LandManagementModule : IRegionModule public class LandManagementModule : IRegionModule
{ {
private LandChannel landChannel; private LandChannel landChannel;
private Scene m_scene; private Scene m_scene;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
m_scene = scene; m_scene = scene;
landChannel = new LandChannel(scene); landChannel = new LandChannel(scene);
m_scene.EventManager.OnParcelPrimCountAdd += landChannel.addPrimToLandPrimCounts; m_scene.EventManager.OnParcelPrimCountAdd += landChannel.addPrimToLandPrimCounts;
m_scene.EventManager.OnParcelPrimCountUpdate += landChannel.updateLandPrimCounts; m_scene.EventManager.OnParcelPrimCountUpdate += landChannel.updateLandPrimCounts;
m_scene.EventManager.OnAvatarEnteringNewParcel += new EventManager.AvatarEnteringNewParcel(landChannel.handleAvatarChangingParcel); m_scene.EventManager.OnAvatarEnteringNewParcel += new EventManager.AvatarEnteringNewParcel(landChannel.handleAvatarChangingParcel);
m_scene.EventManager.OnClientMovement += new EventManager.ClientMovement(landChannel.handleAnyClientMovement); m_scene.EventManager.OnClientMovement += new EventManager.ClientMovement(landChannel.handleAnyClientMovement);
m_scene.EventManager.OnValidateLandBuy += landChannel.handleLandValidationRequest; m_scene.EventManager.OnValidateLandBuy += landChannel.handleLandValidationRequest;
m_scene.EventManager.OnLandBuy += landChannel.handleLandBuyRequest; m_scene.EventManager.OnLandBuy += landChannel.handleLandBuyRequest;
lock (m_scene) lock (m_scene)
{ {
m_scene.LandChannel = (ILandChannel) landChannel; m_scene.LandChannel = (ILandChannel) landChannel;
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "LandManagementModule"; } get { return "LandManagementModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
} }
} }

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -1,125 +1,125 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Text; using System.Text;
using System.Xml; using System.Xml;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.ExportSerialiser namespace OpenSim.Region.Environment.Modules.ExportSerialiser
{ {
internal class SerialiseObjects : IFileSerialiser internal class SerialiseObjects : IFileSerialiser
{ {
#region IFileSerialiser Members #region IFileSerialiser Members
public string WriteToFile(Scene scene, string dir) public string WriteToFile(Scene scene, string dir)
{ {
string targetFileName = dir + "objects.xml"; string targetFileName = dir + "objects.xml";
SaveSerialisedToFile(targetFileName, scene); SaveSerialisedToFile(targetFileName, scene);
return "objects.xml"; return "objects.xml";
} }
#endregion #endregion
public void SaveSerialisedToFile(string fileName, Scene scene) public void SaveSerialisedToFile(string fileName, Scene scene)
{ {
string xmlstream = GetObjectXml(scene); string xmlstream = GetObjectXml(scene);
MemoryStream stream = ReformatXmlString(xmlstream); MemoryStream stream = ReformatXmlString(xmlstream);
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
CreateXmlFile(stream, fileName); CreateXmlFile(stream, fileName);
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
CreateCompressedXmlFile(stream, fileName); CreateCompressedXmlFile(stream, fileName);
} }
private static MemoryStream ReformatXmlString(string xmlstream) private static MemoryStream ReformatXmlString(string xmlstream)
{ {
MemoryStream stream = new MemoryStream(); MemoryStream stream = new MemoryStream();
XmlTextWriter formatter = new XmlTextWriter(stream, Encoding.UTF8); XmlTextWriter formatter = new XmlTextWriter(stream, Encoding.UTF8);
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstream); doc.LoadXml(xmlstream);
formatter.Formatting = Formatting.Indented; formatter.Formatting = Formatting.Indented;
doc.WriteContentTo(formatter); doc.WriteContentTo(formatter);
formatter.Flush(); formatter.Flush();
return stream; return stream;
} }
private static string GetObjectXml(Scene scene) private static string GetObjectXml(Scene scene)
{ {
string xmlstream = "<scene>"; string xmlstream = "<scene>";
List<EntityBase> EntityList = scene.GetEntities(); List<EntityBase> EntityList = scene.GetEntities();
List<string> EntityXml = new List<string>(); List<string> EntityXml = new List<string>();
foreach (EntityBase ent in EntityList) foreach (EntityBase ent in EntityList)
{ {
if (ent is SceneObjectGroup) if (ent is SceneObjectGroup)
{ {
EntityXml.Add(((SceneObjectGroup) ent).ToXmlString2()); EntityXml.Add(((SceneObjectGroup) ent).ToXmlString2());
} }
} }
EntityXml.Sort(); EntityXml.Sort();
foreach (string xml in EntityXml) foreach (string xml in EntityXml)
xmlstream += xml; xmlstream += xml;
xmlstream += "</scene>"; xmlstream += "</scene>";
return xmlstream; return xmlstream;
} }
private static void CreateXmlFile(MemoryStream xmlStream, string fileName) private static void CreateXmlFile(MemoryStream xmlStream, string fileName)
{ {
FileStream objectsFile = new FileStream(fileName, FileMode.Create); FileStream objectsFile = new FileStream(fileName, FileMode.Create);
xmlStream.WriteTo(objectsFile); xmlStream.WriteTo(objectsFile);
objectsFile.Flush(); objectsFile.Flush();
objectsFile.Close(); objectsFile.Close();
} }
private static void CreateCompressedXmlFile(MemoryStream xmlStream, string fileName) private static void CreateCompressedXmlFile(MemoryStream xmlStream, string fileName)
{ {
#region GZip Compressed Version #region GZip Compressed Version
FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create); FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create);
MemoryStream gzipMSStream = new MemoryStream(); MemoryStream gzipMSStream = new MemoryStream();
GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress); GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress);
xmlStream.WriteTo(gzipStream); xmlStream.WriteTo(gzipStream);
gzipMSStream.WriteTo(objectsFileCompressed); gzipMSStream.WriteTo(objectsFileCompressed);
objectsFileCompressed.Flush(); objectsFileCompressed.Flush();
objectsFileCompressed.Close(); objectsFileCompressed.Close();
#endregion #endregion
} }
} }
} }

View File

@ -1,53 +1,53 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Modules.World.Terrain; using OpenSim.Region.Environment.Modules.World.Terrain;
using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders; using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.ExportSerialiser namespace OpenSim.Region.Environment.Modules.ExportSerialiser
{ {
internal class SerialiseTerrain : IFileSerialiser internal class SerialiseTerrain : IFileSerialiser
{ {
#region IFileSerialiser Members #region IFileSerialiser Members
public string WriteToFile(Scene scene, string dir) public string WriteToFile(Scene scene, string dir)
{ {
ITerrainLoader fileSystemExporter = new RAW32(); ITerrainLoader fileSystemExporter = new RAW32();
string targetFileName = dir + "heightmap.r32"; string targetFileName = dir + "heightmap.r32";
lock (scene.Heightmap) lock (scene.Heightmap)
{ {
fileSystemExporter.SaveFile(targetFileName, scene.Heightmap); fileSystemExporter.SaveFile(targetFileName, scene.Heightmap);
} }
return "heightmap.r32"; return "heightmap.r32";
} }
#endregion #endregion
} }
} }

View File

@ -1,169 +1,169 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using Nini.Config; using Nini.Config;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Modules.ExportSerialiser; using OpenSim.Region.Environment.Modules.ExportSerialiser;
using OpenSim.Region.Environment.Modules.Framework; using OpenSim.Region.Environment.Modules.Framework;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.World.Serialiser namespace OpenSim.Region.Environment.Modules.World.Serialiser
{ {
public class SerialiserModule : IRegionModule, IRegionSerialiser public class SerialiserModule : IRegionModule, IRegionSerialiser
{ {
private Commander m_commander = new Commander("Export"); private Commander m_commander = new Commander("Export");
private List<Scene> m_regions = new List<Scene>(); private List<Scene> m_regions = new List<Scene>();
private string m_savedir = "exports" + "/"; private string m_savedir = "exports" + "/";
private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>(); private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>();
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
scene.RegisterModuleCommander("Export", m_commander); scene.RegisterModuleCommander("Export", m_commander);
scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
scene.RegisterModuleInterface<IRegionSerialiser>(this); scene.RegisterModuleInterface<IRegionSerialiser>(this);
lock (m_regions) lock (m_regions)
{ {
m_regions.Add(scene); m_regions.Add(scene);
} }
} }
public void PostInitialise() public void PostInitialise()
{ {
lock (m_serialisers) lock (m_serialisers)
{ {
m_serialisers.Add(new SerialiseTerrain()); m_serialisers.Add(new SerialiseTerrain());
m_serialisers.Add(new SerialiseObjects()); m_serialisers.Add(new SerialiseObjects());
} }
LoadCommanderCommands(); LoadCommanderCommands();
} }
public void Close() public void Close()
{ {
m_regions.Clear(); m_regions.Clear();
} }
public string Name public string Name
{ {
get { return "ExportSerialisationModule"; } get { return "ExportSerialisationModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return true; } get { return true; }
} }
#endregion #endregion
#region IRegionSerialiser Members #region IRegionSerialiser Members
public List<string> SerialiseRegion(Scene scene, string saveDir) public List<string> SerialiseRegion(Scene scene, string saveDir)
{ {
List<string> results = new List<string>(); List<string> results = new List<string>();
if (!Directory.Exists(saveDir)) if (!Directory.Exists(saveDir))
{ {
Directory.CreateDirectory(saveDir); Directory.CreateDirectory(saveDir);
} }
lock (m_serialisers) lock (m_serialisers)
{ {
foreach (IFileSerialiser serialiser in m_serialisers) foreach (IFileSerialiser serialiser in m_serialisers)
{ {
results.Add(serialiser.WriteToFile(scene, saveDir)); results.Add(serialiser.WriteToFile(scene, saveDir));
} }
} }
TextWriter regionInfoWriter = new StreamWriter(saveDir + "README.TXT"); TextWriter regionInfoWriter = new StreamWriter(saveDir + "README.TXT");
regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName); regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName);
regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString()); regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString());
regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString()); regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString());
regionInfoWriter.WriteLine("Serialise Version: 0.1"); regionInfoWriter.WriteLine("Serialise Version: 0.1");
regionInfoWriter.Close(); regionInfoWriter.Close();
TextWriter manifestWriter = new StreamWriter(saveDir + "region.manifest"); TextWriter manifestWriter = new StreamWriter(saveDir + "region.manifest");
foreach (string line in results) foreach (string line in results)
{ {
manifestWriter.WriteLine(line); manifestWriter.WriteLine(line);
} }
manifestWriter.Close(); manifestWriter.Close();
return results; return results;
} }
#endregion #endregion
private void EventManager_OnPluginConsole(string[] args) private void EventManager_OnPluginConsole(string[] args)
{ {
if (args[0] == "export") if (args[0] == "export")
{ {
string[] tmpArgs = new string[args.Length - 2]; string[] tmpArgs = new string[args.Length - 2];
int i = 0; int i = 0;
for (i = 2; i < args.Length; i++) for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i]; tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs); m_commander.ProcessConsoleCommand(args[1], tmpArgs);
} }
} }
private void InterfaceSaveRegion(Object[] args) private void InterfaceSaveRegion(Object[] args)
{ {
foreach (Scene region in m_regions) foreach (Scene region in m_regions)
{ {
if (region.RegionInfo.RegionName == (string) args[0]) if (region.RegionInfo.RegionName == (string) args[0])
{ {
List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/"); List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
} }
} }
} }
private void InterfaceSaveAllRegions(Object[] args) private void InterfaceSaveAllRegions(Object[] args)
{ {
foreach (Scene region in m_regions) foreach (Scene region in m_regions)
{ {
List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/"); List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
} }
} }
private void LoadCommanderCommands() private void LoadCommanderCommands()
{ {
Command serialiseSceneCommand = new Command("save", InterfaceSaveRegion, "Saves the named region into the exports directory."); Command serialiseSceneCommand = new Command("save", InterfaceSaveRegion, "Saves the named region into the exports directory.");
serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String"); serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String");
Command serialiseAllScenesCommand = new Command("save-all", InterfaceSaveAllRegions, "Saves all regions into the exports directory."); Command serialiseAllScenesCommand = new Command("save-all", InterfaceSaveAllRegions, "Saves all regions into the exports directory.");
m_commander.RegisterCommand("save", serialiseSceneCommand); m_commander.RegisterCommand("save", serialiseSceneCommand);
m_commander.RegisterCommand("save-all", serialiseAllScenesCommand); m_commander.RegisterCommand("save-all", serialiseAllScenesCommand);
} }
} }
} }

View File

@ -1,199 +1,199 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules namespace OpenSim.Region.Environment.Modules
{ {
public class SunModule : IRegionModule public class SunModule : IRegionModule
{ {
//private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const int m_default_frame = 100; private const int m_default_frame = 100;
private const double m_real_day = 24.0; private const double m_real_day = 24.0;
private double m_day_length; private double m_day_length;
private int m_dilation; private int m_dilation;
private int m_frame; private int m_frame;
private int m_frame_mod; private int m_frame_mod;
private Scene m_scene; private Scene m_scene;
private long m_start; private long m_start;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
m_start = DateTime.Now.Ticks; m_start = DateTime.Now.Ticks;
m_frame = 0; m_frame = 0;
// Just in case they don't have the stanzas // Just in case they don't have the stanzas
try try
{ {
m_day_length = config.Configs["Sun"].GetDouble("day_length", m_real_day); m_day_length = config.Configs["Sun"].GetDouble("day_length", m_real_day);
m_frame_mod = config.Configs["Sun"].GetInt("frame_rate", m_default_frame); m_frame_mod = config.Configs["Sun"].GetInt("frame_rate", m_default_frame);
} }
catch (Exception) catch (Exception)
{ {
m_day_length = m_real_day; m_day_length = m_real_day;
m_frame_mod = m_default_frame; m_frame_mod = m_default_frame;
} }
m_dilation = (int) (m_real_day / m_day_length); m_dilation = (int) (m_real_day / m_day_length);
m_scene = scene; m_scene = scene;
scene.EventManager.OnFrame += SunUpdate; scene.EventManager.OnFrame += SunUpdate;
scene.EventManager.OnNewClient += SunToClient; scene.EventManager.OnNewClient += SunToClient;
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "SunModule"; } get { return "SunModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
public void SunToClient(IClientAPI client) public void SunToClient(IClientAPI client)
{ {
client.SendSunPos(SunPos(HourOfTheDay()), new LLVector3(0, 0.0f, 10.0f)); client.SendSunPos(SunPos(HourOfTheDay()), new LLVector3(0, 0.0f, 10.0f));
} }
public void SunUpdate() public void SunUpdate()
{ {
if (m_frame < m_frame_mod) if (m_frame < m_frame_mod)
{ {
m_frame++; m_frame++;
return; return;
} }
// m_log.InfoFormat("[SUN]: I've got an update {0} => {1}", m_scene.RegionsInfo.RegionName, HourOfTheDay()); // m_log.InfoFormat("[SUN]: I've got an update {0} => {1}", m_scene.RegionsInfo.RegionName, HourOfTheDay());
List<ScenePresence> avatars = m_scene.GetAvatars(); List<ScenePresence> avatars = m_scene.GetAvatars();
foreach (ScenePresence avatar in avatars) foreach (ScenePresence avatar in avatars)
{ {
avatar.ControllingClient.SendSunPos(SunPos(HourOfTheDay()), new LLVector3(0, 0.0f, 10.0f)); avatar.ControllingClient.SendSunPos(SunPos(HourOfTheDay()), new LLVector3(0, 0.0f, 10.0f));
} }
// set estate settings for region access to sun position // set estate settings for region access to sun position
m_scene.RegionInfo.EstateSettings.sunPosition = SunPos(HourOfTheDay()); m_scene.RegionInfo.EstateSettings.sunPosition = SunPos(HourOfTheDay());
m_frame = 0; m_frame = 0;
} }
// Hour of the Day figures out the hour of the day as a float. // Hour of the Day figures out the hour of the day as a float.
// The intent here is that we seed hour of the day with real // The intent here is that we seed hour of the day with real
// time when the simulator starts, then run time forward // time when the simulator starts, then run time forward
// faster based on time dilation factor. This means that // faster based on time dilation factor. This means that
// ticks don't get out of hand // ticks don't get out of hand
private double HourOfTheDay() private double HourOfTheDay()
{ {
long m_addticks = (DateTime.Now.Ticks - m_start) * m_dilation; long m_addticks = (DateTime.Now.Ticks - m_start) * m_dilation;
DateTime dt = new DateTime(m_start + m_addticks); DateTime dt = new DateTime(m_start + m_addticks);
return (double) dt.Hour + ((double) dt.Minute / 60.0); return (double) dt.Hour + ((double) dt.Minute / 60.0);
} }
private LLVector3 SunPos(double hour) private LLVector3 SunPos(double hour)
{ {
// now we have our radian position // now we have our radian position
double rad = (hour / m_real_day) * 2 * Math.PI - (Math.PI / 2.0); double rad = (hour / m_real_day) * 2 * Math.PI - (Math.PI / 2.0);
double z = Math.Sin(rad); double z = Math.Sin(rad);
double x = Math.Cos(rad); double x = Math.Cos(rad);
return new LLVector3((float) x, 0f, (float) z); return new LLVector3((float) x, 0f, (float) z);
} }
// TODO: clear this out. This is here so that I remember to // TODO: clear this out. This is here so that I remember to
// figure out if we need those other packet fields that I've // figure out if we need those other packet fields that I've
// left out so far // left out so far
// //
// public void SendViewerTime(int phase) // public void SendViewerTime(int phase)
// { // {
// Console.WriteLine("SunPhase: {0}", phase); // Console.WriteLine("SunPhase: {0}", phase);
// SimulatorViewerTimeMessagePacket viewertime = new SimulatorViewerTimeMessagePacket(); // SimulatorViewerTimeMessagePacket viewertime = new SimulatorViewerTimeMessagePacket();
// //viewertime.TimeInfo.SecPerDay = 86400; // //viewertime.TimeInfo.SecPerDay = 86400;
// // viewertime.TimeInfo.SecPerYear = 31536000; // // viewertime.TimeInfo.SecPerYear = 31536000;
// viewertime.TimeInfo.SecPerDay = 1000; // viewertime.TimeInfo.SecPerDay = 1000;
// viewertime.TimeInfo.SecPerYear = 365000; // viewertime.TimeInfo.SecPerYear = 365000;
// viewertime.TimeInfo.SunPhase = 1; // viewertime.TimeInfo.SunPhase = 1;
// int sunPhase = (phase + 2)/2; // int sunPhase = (phase + 2)/2;
// if ((sunPhase < 6) || (sunPhase > 36)) // if ((sunPhase < 6) || (sunPhase > 36))
// { // {
// viewertime.TimeInfo.SunDirection = new LLVector3(0f, 0.8f, -0.8f); // viewertime.TimeInfo.SunDirection = new LLVector3(0f, 0.8f, -0.8f);
// Console.WriteLine("sending night"); // Console.WriteLine("sending night");
// } // }
// else // else
// { // {
// if (sunPhase < 12) // if (sunPhase < 12)
// { // {
// sunPhase = 12; // sunPhase = 12;
// } // }
// sunPhase = sunPhase - 12; // sunPhase = sunPhase - 12;
// //
// float yValue = 0.1f*(sunPhase); // float yValue = 0.1f*(sunPhase);
// Console.WriteLine("Computed SunPhase: {0}, yValue: {1}", sunPhase, yValue); // Console.WriteLine("Computed SunPhase: {0}, yValue: {1}", sunPhase, yValue);
// if (yValue > 1.2f) // if (yValue > 1.2f)
// { // {
// yValue = yValue - 1.2f; // yValue = yValue - 1.2f;
// } // }
// if (yValue > 1) // if (yValue > 1)
// { // {
// yValue = 1; // yValue = 1;
// } // }
// if (yValue < 0) // if (yValue < 0)
// { // {
// yValue = 0; // yValue = 0;
// } // }
// if (sunPhase < 14) // if (sunPhase < 14)
// { // {
// yValue = 1 - yValue; // yValue = 1 - yValue;
// } // }
// if (sunPhase < 12) // if (sunPhase < 12)
// { // {
// yValue *= -1; // yValue *= -1;
// } // }
// viewertime.TimeInfo.SunDirection = new LLVector3(0f, yValue, 0.3f); // viewertime.TimeInfo.SunDirection = new LLVector3(0f, yValue, 0.3f);
// Console.WriteLine("sending sun update " + yValue); // Console.WriteLine("sending sun update " + yValue);
// } // }
// viewertime.TimeInfo.SunAngVelocity = new LLVector3(0, 0.0f, 10.0f); // viewertime.TimeInfo.SunAngVelocity = new LLVector3(0, 0.0f, 10.0f);
// viewertime.TimeInfo.UsecSinceStart = (ulong) Util.UnixTimeSinceEpoch(); // viewertime.TimeInfo.UsecSinceStart = (ulong) Util.UnixTimeSinceEpoch();
// // OutPacket(viewertime); // // OutPacket(viewertime);
// } // }
} }
} }

View File

@ -1,124 +1,124 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes; using OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes;
using OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes; using OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes;
namespace OpenSim.Region.Environment.Modules.World.Terrain.Effects namespace OpenSim.Region.Environment.Modules.World.Terrain.Effects
{ {
internal class CookieCutter : ITerrainEffect internal class CookieCutter : ITerrainEffect
{ {
#region ITerrainEffect Members #region ITerrainEffect Members
public void RunEffect(ITerrainChannel map) public void RunEffect(ITerrainChannel map)
{ {
SmoothArea smooth = new SmoothArea(); SmoothArea smooth = new SmoothArea();
ITerrainPaintableEffect eroder = new WeatherSphere(); ITerrainPaintableEffect eroder = new WeatherSphere();
bool[,] cliffMask = new bool[map.Width,map.Height]; bool[,] cliffMask = new bool[map.Width,map.Height];
bool[,] channelMask = new bool[map.Width,map.Height]; bool[,] channelMask = new bool[map.Width,map.Height];
bool[,] smoothMask = new bool[map.Width,map.Height]; bool[,] smoothMask = new bool[map.Width,map.Height];
Console.WriteLine("S1"); Console.WriteLine("S1");
// Step one, generate rough mask // Step one, generate rough mask
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
Console.Write("."); Console.Write(".");
smoothMask[x, y] = true; smoothMask[x, y] = true;
// Start underwater // Start underwater
map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 5; map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 5;
// Add a little height. (terrain should now be above water, mostly.) // Add a little height. (terrain should now be above water, mostly.)
map[x, y] += 20; map[x, y] += 20;
int channelsX = 4; int channelsX = 4;
int channelWidth = (map.Width / channelsX / 4); int channelWidth = (map.Width / channelsX / 4);
int channelsY = 4; int channelsY = 4;
int channelHeight = (map.Height / channelsY / 4); int channelHeight = (map.Height / channelsY / 4);
SetLowerChannel(map, cliffMask, channelMask, x, y, channelsX, channelWidth, map.Width, x); SetLowerChannel(map, cliffMask, channelMask, x, y, channelsX, channelWidth, map.Width, x);
SetLowerChannel(map, cliffMask, channelMask, x, y, channelsY, channelHeight, map.Height, y); SetLowerChannel(map, cliffMask, channelMask, x, y, channelsY, channelHeight, map.Height, y);
} }
} }
Console.WriteLine("S2"); Console.WriteLine("S2");
//smooth.FloodEffect(map, smoothMask, 4.0); //smooth.FloodEffect(map, smoothMask, 4.0);
Console.WriteLine("S3"); Console.WriteLine("S3");
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (cliffMask[x, y] == true) if (cliffMask[x, y] == true)
eroder.PaintEffect(map, x, y, 4, 0.1); eroder.PaintEffect(map, x, y, 4, 0.1);
} }
} }
for (x = 0; x < map.Width; x += 2) for (x = 0; x < map.Width; x += 2)
{ {
for (y = 0; y < map.Height; y += 2) for (y = 0; y < map.Height; y += 2)
{ {
if (map[x, y] < 0.1) if (map[x, y] < 0.1)
map[x, y] = 0.1; map[x, y] = 0.1;
if (map[x, y] > 256) if (map[x, y] > 256)
map[x, y] = 256; map[x, y] = 256;
} }
} }
//smooth.FloodEffect(map, smoothMask, 4.0); //smooth.FloodEffect(map, smoothMask, 4.0);
} }
#endregion #endregion
private static void SetLowerChannel(ITerrainChannel map, bool[,] cliffMask, bool[,] channelMask, int x, int y, int numChannels, int channelWidth, private static void SetLowerChannel(ITerrainChannel map, bool[,] cliffMask, bool[,] channelMask, int x, int y, int numChannels, int channelWidth,
int mapSize, int rp) int mapSize, int rp)
{ {
for (int i = 0; i < numChannels; i++) for (int i = 0; i < numChannels; i++)
{ {
double distanceToLine = Math.Abs(rp - ((mapSize / numChannels) * i)); double distanceToLine = Math.Abs(rp - ((mapSize / numChannels) * i));
if (distanceToLine < channelWidth) if (distanceToLine < channelWidth)
{ {
if (channelMask[x, y]) if (channelMask[x, y])
return; return;
// Remove channels // Remove channels
map[x, y] -= 10; map[x, y] -= 10;
channelMask[x, y] = true; channelMask[x, y] = true;
} }
if (distanceToLine < 1) if (distanceToLine < 1)
{ {
cliffMask[x, y] = true; cliffMask[x, y] = true;
} }
} }
} }
} }
} }

View File

@ -1,55 +1,55 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.Effects namespace OpenSim.Region.Environment.Modules.World.Terrain.Effects
{ {
internal class DefaultTerrainGenerator : ITerrainEffect internal class DefaultTerrainGenerator : ITerrainEffect
{ {
#region ITerrainEffect Members #region ITerrainEffect Members
public void RunEffect(ITerrainChannel map) public void RunEffect(ITerrainChannel map)
{ {
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 10; map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 10;
double spherFac = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2, Constants.RegionSize / 2, 50) * 0.01; double spherFac = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2, Constants.RegionSize / 2, 50) * 0.01;
if (map[x, y] < spherFac) if (map[x, y] < spherFac)
{ {
map[x, y] = spherFac; map[x, y] = spherFac;
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,62 +1,62 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
/// <summary> /// <summary>
/// A generic windows bitmap loader. /// A generic windows bitmap loader.
/// Should be capable of handling 24-bit RGB images. /// Should be capable of handling 24-bit RGB images.
/// ///
/// Uses the System.Drawing filesystem loader. /// Uses the System.Drawing filesystem loader.
/// </summary> /// </summary>
internal class BMP : GenericSystemDrawing internal class BMP : GenericSystemDrawing
{ {
/// <summary> /// <summary>
/// Exports a file to a image on the disk using a System.Drawing exporter. /// Exports a file to a image on the disk using a System.Drawing exporter.
/// </summary> /// </summary>
/// <param name="filename">The target filename</param> /// <param name="filename">The target filename</param>
/// <param name="map">The terrain channel being saved</param> /// <param name="map">The terrain channel being saved</param>
public override void SaveFile(string filename, ITerrainChannel map) public override void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateGrayscaleBitmapFromMap(map); Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Bmp); colours.Save(filename, ImageFormat.Bmp);
} }
/// <summary> /// <summary>
/// The human readable version of the file format(s) this loader handles /// The human readable version of the file format(s) this loader handles
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public override string ToString() public override string ToString()
{ {
return "BMP"; return "BMP";
} }
} }
} }

View File

@ -1,47 +1,47 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
internal class GIF : GenericSystemDrawing internal class GIF : GenericSystemDrawing
{ {
public override void SaveFile(string filename, ITerrainChannel map) public override void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateGrayscaleBitmapFromMap(map); Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Gif); colours.Save(filename, ImageFormat.Gif);
} }
public override string ToString() public override string ToString()
{ {
return "GIF"; return "GIF";
} }
} }
} }

View File

@ -1,172 +1,172 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
/// <summary> /// <summary>
/// A virtual class designed to have methods overloaded, /// A virtual class designed to have methods overloaded,
/// this class provides an interface for a generic image /// this class provides an interface for a generic image
/// saving and loading mechanism, but does not specify the /// saving and loading mechanism, but does not specify the
/// format. It should not be insubstantiated directly. /// format. It should not be insubstantiated directly.
/// </summary> /// </summary>
public class GenericSystemDrawing : ITerrainLoader public class GenericSystemDrawing : ITerrainLoader
{ {
#region ITerrainLoader Members #region ITerrainLoader Members
public string FileExtension public string FileExtension
{ {
get { return ".gsd"; } get { return ".gsd"; }
} }
/// <summary> /// <summary>
/// Loads a file from a specified filename on the disk, /// Loads a file from a specified filename on the disk,
/// parses the image using the System.Drawing parsers /// parses the image using the System.Drawing parsers
/// then returns a terrain channel. Values are /// then returns a terrain channel. Values are
/// returned based on HSL brightness between 0m and 128m /// returned based on HSL brightness between 0m and 128m
/// </summary> /// </summary>
/// <param name="filename">The target image to load</param> /// <param name="filename">The target image to load</param>
/// <returns>A terrain channel generated from the image.</returns> /// <returns>A terrain channel generated from the image.</returns>
public virtual ITerrainChannel LoadFile(string filename) public virtual ITerrainChannel LoadFile(string filename)
{ {
Bitmap file = new Bitmap(filename); Bitmap file = new Bitmap(filename);
ITerrainChannel retval = new TerrainChannel(file.Width, file.Height); ITerrainChannel retval = new TerrainChannel(file.Width, file.Height);
int x, y; int x, y;
for (x = 0; x < file.Width; x++) for (x = 0; x < file.Width; x++)
{ {
for (y = 0; y < file.Height; y++) for (y = 0; y < file.Height; y++)
{ {
retval[x, y] = file.GetPixel(x, y).GetBrightness() * 128; retval[x, y] = file.GetPixel(x, y).GetBrightness() * 128;
} }
} }
return retval; return retval;
} }
public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h) public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
/// <summary> /// <summary>
/// Exports a file to a image on the disk using a System.Drawing exporter. /// Exports a file to a image on the disk using a System.Drawing exporter.
/// </summary> /// </summary>
/// <param name="filename">The target filename</param> /// <param name="filename">The target filename</param>
/// <param name="map">The terrain channel being saved</param> /// <param name="map">The terrain channel being saved</param>
public virtual void SaveFile(string filename, ITerrainChannel map) public virtual void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateGrayscaleBitmapFromMap(map); Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Png); colours.Save(filename, ImageFormat.Png);
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return "SYS.DRAWING"; return "SYS.DRAWING";
} }
/// <summary> /// <summary>
/// Protected method, generates a grayscale bitmap /// Protected method, generates a grayscale bitmap
/// image from a specified terrain channel. /// image from a specified terrain channel.
/// </summary> /// </summary>
/// <param name="map">The terrain channel to export to bitmap</param> /// <param name="map">The terrain channel to export to bitmap</param>
/// <returns>A System.Drawing.Bitmap containing a grayscale image</returns> /// <returns>A System.Drawing.Bitmap containing a grayscale image</returns>
protected Bitmap CreateGrayscaleBitmapFromMap(ITerrainChannel map) protected Bitmap CreateGrayscaleBitmapFromMap(ITerrainChannel map)
{ {
Bitmap bmp = new Bitmap(map.Width, map.Height); Bitmap bmp = new Bitmap(map.Width, map.Height);
int pallete = 256; int pallete = 256;
Color[] grays = new Color[pallete]; Color[] grays = new Color[pallete];
for (int i = 0; i < grays.Length; i++) for (int i = 0; i < grays.Length; i++)
{ {
grays[i] = Color.FromArgb(i, i, i); grays[i] = Color.FromArgb(i, i, i);
} }
for (int y = 0; y < map.Height; y++) for (int y = 0; y < map.Height; y++)
{ {
for (int x = 0; x < map.Width; x++) for (int x = 0; x < map.Width; x++)
{ {
// 512 is the largest possible height before colours clamp // 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 128.0), 0.0) * (pallete - 1)); int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 128.0), 0.0) * (pallete - 1));
// Handle error conditions // Handle error conditions
if (colorindex > pallete - 1 || colorindex < 0) if (colorindex > pallete - 1 || colorindex < 0)
bmp.SetPixel(x, map.Height - y - 1, Color.Red); bmp.SetPixel(x, map.Height - y - 1, Color.Red);
else else
bmp.SetPixel(x, map.Height - y - 1, grays[colorindex]); bmp.SetPixel(x, map.Height - y - 1, grays[colorindex]);
} }
} }
return bmp; return bmp;
} }
/// <summary> /// <summary>
/// Protected method, generates a coloured bitmap /// Protected method, generates a coloured bitmap
/// image from a specified terrain channel. /// image from a specified terrain channel.
/// </summary> /// </summary>
/// <param name="map">The terrain channel to export to bitmap</param> /// <param name="map">The terrain channel to export to bitmap</param>
/// <returns>A System.Drawing.Bitmap containing a coloured image</returns> /// <returns>A System.Drawing.Bitmap containing a coloured image</returns>
protected Bitmap CreateBitmapFromMap(ITerrainChannel map) protected Bitmap CreateBitmapFromMap(ITerrainChannel map)
{ {
Bitmap gradientmapLd = new Bitmap("defaultstripe.png"); Bitmap gradientmapLd = new Bitmap("defaultstripe.png");
int pallete = gradientmapLd.Height; int pallete = gradientmapLd.Height;
Bitmap bmp = new Bitmap(map.Width, map.Height); Bitmap bmp = new Bitmap(map.Width, map.Height);
Color[] colours = new Color[pallete]; Color[] colours = new Color[pallete];
for (int i = 0; i < pallete; i++) for (int i = 0; i < pallete; i++)
{ {
colours[i] = gradientmapLd.GetPixel(0, i); colours[i] = gradientmapLd.GetPixel(0, i);
} }
for (int y = 0; y < map.Height; y++) for (int y = 0; y < map.Height; y++)
{ {
for (int x = 0; x < map.Width; x++) for (int x = 0; x < map.Width; x++)
{ {
// 512 is the largest possible height before colours clamp // 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1)); int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1));
// Handle error conditions // Handle error conditions
if (colorindex > pallete - 1 || colorindex < 0) if (colorindex > pallete - 1 || colorindex < 0)
bmp.SetPixel(x, map.Height - y - 1, Color.Red); bmp.SetPixel(x, map.Height - y - 1, Color.Red);
else else
bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]); bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]);
} }
} }
return bmp; return bmp;
} }
} }
} }

View File

@ -1,94 +1,94 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
public class JPEG : ITerrainLoader public class JPEG : ITerrainLoader
{ {
#region ITerrainLoader Members #region ITerrainLoader Members
public string FileExtension public string FileExtension
{ {
get { return ".jpg"; } get { return ".jpg"; }
} }
public ITerrainChannel LoadFile(string filename) public ITerrainChannel LoadFile(string filename)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h) public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public void SaveFile(string filename, ITerrainChannel map) public void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateBitmapFromMap(map); Bitmap colours = CreateBitmapFromMap(map);
colours.Save(filename, ImageFormat.Jpeg); colours.Save(filename, ImageFormat.Jpeg);
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return "JPEG"; return "JPEG";
} }
private Bitmap CreateBitmapFromMap(ITerrainChannel map) private Bitmap CreateBitmapFromMap(ITerrainChannel map)
{ {
Bitmap gradientmapLd = new Bitmap("defaultstripe.png"); Bitmap gradientmapLd = new Bitmap("defaultstripe.png");
int pallete = gradientmapLd.Height; int pallete = gradientmapLd.Height;
Bitmap bmp = new Bitmap(map.Width, map.Height); Bitmap bmp = new Bitmap(map.Width, map.Height);
Color[] colours = new Color[pallete]; Color[] colours = new Color[pallete];
for (int i = 0; i < pallete; i++) for (int i = 0; i < pallete; i++)
{ {
colours[i] = gradientmapLd.GetPixel(0, i); colours[i] = gradientmapLd.GetPixel(0, i);
} }
for (int y = 0; y < map.Height; y++) for (int y = 0; y < map.Height; y++)
{ {
for (int x = 0; x < map.Width; x++) for (int x = 0; x < map.Width; x++)
{ {
// 512 is the largest possible height before colours clamp // 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1)); int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1));
bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]); bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]);
} }
} }
return bmp; return bmp;
} }
} }
} }

View File

@ -1,148 +1,148 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.IO; using System.IO;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
public class LLRAW : ITerrainLoader public class LLRAW : ITerrainLoader
{ {
#region ITerrainLoader Members #region ITerrainLoader Members
public ITerrainChannel LoadFile(string filename) public ITerrainChannel LoadFile(string filename)
{ {
TerrainChannel retval = new TerrainChannel(); TerrainChannel retval = new TerrainChannel();
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read); FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s); BinaryReader bs = new BinaryReader(s);
int x, y; int x, y;
for (y = 0; y < retval.Height; y++) for (y = 0; y < retval.Height; y++)
{ {
for (x = 0; x < retval.Width; x++) for (x = 0; x < retval.Width; x++)
{ {
retval[x, y] = (double) bs.ReadByte() * ((double) bs.ReadByte() / 127.0); retval[x, y] = (double) bs.ReadByte() * ((double) bs.ReadByte() / 127.0);
bs.ReadBytes(11); // Advance the stream to next bytes. bs.ReadBytes(11); // Advance the stream to next bytes.
} }
} }
bs.Close(); bs.Close();
s.Close(); s.Close();
return retval; return retval;
} }
public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h) public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public void SaveFile(string filename, ITerrainChannel map) public void SaveFile(string filename, ITerrainChannel map)
{ {
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
BinaryWriter binStream = new BinaryWriter(s); BinaryWriter binStream = new BinaryWriter(s);
// Generate a smegging big lookup table to speed the operation up (it needs it) // Generate a smegging big lookup table to speed the operation up (it needs it)
double[] lookupHeightTable = new double[65536]; double[] lookupHeightTable = new double[65536];
int i, j, x, y; int i, j, x, y;
for (i = 0; i < 256; i++) for (i = 0; i < 256; i++)
{ {
for (j = 0; j < 256; j++) for (j = 0; j < 256; j++)
{ {
lookupHeightTable[i + (j * 256)] = ((double) i * ((double) j / 127.0)); lookupHeightTable[i + (j * 256)] = ((double) i * ((double) j / 127.0));
} }
} }
// Output the calculated raw // Output the calculated raw
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
double t = map[x, y]; double t = map[x, y];
double min = double.MaxValue; double min = double.MaxValue;
int index = 0; int index = 0;
for (i = 0; i < 65536; i++) for (i = 0; i < 65536; i++)
{ {
if (Math.Abs(t - lookupHeightTable[i]) < min) if (Math.Abs(t - lookupHeightTable[i]) < min)
{ {
min = Math.Abs(t - lookupHeightTable[i]); min = Math.Abs(t - lookupHeightTable[i]);
index = i; index = i;
} }
} }
byte red = (byte) (index & 0xFF); byte red = (byte) (index & 0xFF);
byte green = (byte) ((index >> 8) & 0xFF); byte green = (byte) ((index >> 8) & 0xFF);
byte blue = 20; byte blue = 20;
byte alpha1 = 0; // Land Parcels byte alpha1 = 0; // Land Parcels
byte alpha2 = 0; // For Sale Land byte alpha2 = 0; // For Sale Land
byte alpha3 = 0; // Public Edit Object byte alpha3 = 0; // Public Edit Object
byte alpha4 = 0; // Public Edit Land byte alpha4 = 0; // Public Edit Land
byte alpha5 = 255; // Safe Land byte alpha5 = 255; // Safe Land
byte alpha6 = 255; // Flying Allowed byte alpha6 = 255; // Flying Allowed
byte alpha7 = 255; // Create Landmark byte alpha7 = 255; // Create Landmark
byte alpha8 = 255; // Outside Scripts byte alpha8 = 255; // Outside Scripts
byte alpha9 = red; byte alpha9 = red;
byte alpha10 = green; byte alpha10 = green;
binStream.Write(red); binStream.Write(red);
binStream.Write(green); binStream.Write(green);
binStream.Write(blue); binStream.Write(blue);
binStream.Write(alpha1); binStream.Write(alpha1);
binStream.Write(alpha2); binStream.Write(alpha2);
binStream.Write(alpha3); binStream.Write(alpha3);
binStream.Write(alpha4); binStream.Write(alpha4);
binStream.Write(alpha5); binStream.Write(alpha5);
binStream.Write(alpha6); binStream.Write(alpha6);
binStream.Write(alpha7); binStream.Write(alpha7);
binStream.Write(alpha8); binStream.Write(alpha8);
binStream.Write(alpha9); binStream.Write(alpha9);
binStream.Write(alpha10); binStream.Write(alpha10);
} }
} }
binStream.Close(); binStream.Close();
s.Close(); s.Close();
} }
public string FileExtension public string FileExtension
{ {
get { return ".raw"; } get { return ".raw"; }
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return "LL/SL RAW"; return "LL/SL RAW";
} }
} }
} }

View File

@ -1,47 +1,47 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
internal class PNG : GenericSystemDrawing internal class PNG : GenericSystemDrawing
{ {
public override void SaveFile(string filename, ITerrainChannel map) public override void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateGrayscaleBitmapFromMap(map); Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Png); colours.Save(filename, ImageFormat.Png);
} }
public override string ToString() public override string ToString()
{ {
return "PNG"; return "PNG";
} }
} }
} }

View File

@ -1,153 +1,153 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.IO; using System.IO;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
public class RAW32 : ITerrainLoader public class RAW32 : ITerrainLoader
{ {
#region ITerrainLoader Members #region ITerrainLoader Members
public string FileExtension public string FileExtension
{ {
get { return ".r32"; } get { return ".r32"; }
} }
public ITerrainChannel LoadFile(string filename) public ITerrainChannel LoadFile(string filename)
{ {
TerrainChannel retval = new TerrainChannel(); TerrainChannel retval = new TerrainChannel();
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read); FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s); BinaryReader bs = new BinaryReader(s);
int x, y; int x, y;
for (y = 0; y < retval.Height; y++) for (y = 0; y < retval.Height; y++)
{ {
for (x = 0; x < retval.Width; x++) for (x = 0; x < retval.Width; x++)
{ {
retval[x, y] = bs.ReadSingle(); retval[x, y] = bs.ReadSingle();
} }
} }
bs.Close(); bs.Close();
s.Close(); s.Close();
return retval; return retval;
} }
public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight) public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight)
{ {
TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight); TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight);
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read); FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s); BinaryReader bs = new BinaryReader(s);
int currFileXOffset = 0; int currFileXOffset = 0;
int currFileYOffset = 0; int currFileYOffset = 0;
// if our region isn't on the first Y section of the areas to be landscaped, then // if our region isn't on the first Y section of the areas to be landscaped, then
// advance to our section of the file // advance to our section of the file
while (currFileYOffset < offsetY) while (currFileYOffset < offsetY)
{ {
// read a whole strip of regions // read a whole strip of regions
int heightsToRead = sectionHeight * (fileWidth * sectionWidth); int heightsToRead = sectionHeight * (fileWidth * sectionWidth);
bs.ReadBytes(heightsToRead * 4); // because the floats are 4 bytes in the file bs.ReadBytes(heightsToRead * 4); // because the floats are 4 bytes in the file
currFileYOffset++; currFileYOffset++;
} }
// got to the Y start offset within the file of our region // got to the Y start offset within the file of our region
// so read the file bits associated with our region // so read the file bits associated with our region
int x, y; int x, y;
// for each Y within our Y offset // for each Y within our Y offset
for (y = 0; y < sectionHeight; y++) for (y = 0; y < sectionHeight; y++)
{ {
currFileXOffset = 0; currFileXOffset = 0;
// if our region isn't the first X section of the areas to be landscaped, then // if our region isn't the first X section of the areas to be landscaped, then
// advance the stream to the X start pos of our section in the file // advance the stream to the X start pos of our section in the file
// i.e. eat X upto where we start // i.e. eat X upto where we start
while (currFileXOffset < offsetX) while (currFileXOffset < offsetX)
{ {
bs.ReadBytes(sectionWidth * 4); // 4 bytes = single bs.ReadBytes(sectionWidth * 4); // 4 bytes = single
currFileXOffset++; currFileXOffset++;
} }
// got to our X offset, so write our regions X line // got to our X offset, so write our regions X line
for (x = 0; x < sectionWidth; x++) for (x = 0; x < sectionWidth; x++)
{ {
// Read a strip and continue // Read a strip and continue
retval[x, y] = bs.ReadSingle(); retval[x, y] = bs.ReadSingle();
} }
// record that we wrote it // record that we wrote it
currFileXOffset++; currFileXOffset++;
// if our region isn't the last X section of the areas to be landscaped, then // if our region isn't the last X section of the areas to be landscaped, then
// advance the stream to the end of this Y column // advance the stream to the end of this Y column
while (currFileXOffset < fileWidth) while (currFileXOffset < fileWidth)
{ {
// eat the next regions x line // eat the next regions x line
bs.ReadBytes(sectionWidth * 4); // 4 bytes = single bs.ReadBytes(sectionWidth * 4); // 4 bytes = single
currFileXOffset++; currFileXOffset++;
} }
} }
bs.Close(); bs.Close();
s.Close(); s.Close();
return retval; return retval;
} }
public void SaveFile(string filename, ITerrainChannel map) public void SaveFile(string filename, ITerrainChannel map)
{ {
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Create, FileAccess.Write); FileStream s = file.Open(FileMode.Create, FileAccess.Write);
BinaryWriter bs = new BinaryWriter(s); BinaryWriter bs = new BinaryWriter(s);
int x, y; int x, y;
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
bs.Write((float) map[x, y]); bs.Write((float) map[x, y]);
} }
} }
bs.Close(); bs.Close();
s.Close(); s.Close();
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return "RAW32"; return "RAW32";
} }
} }
} }

View File

@ -1,47 +1,47 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
internal class TIFF : GenericSystemDrawing internal class TIFF : GenericSystemDrawing
{ {
public override void SaveFile(string filename, ITerrainChannel map) public override void SaveFile(string filename, ITerrainChannel map)
{ {
Bitmap colours = CreateGrayscaleBitmapFromMap(map); Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Tiff); colours.Save(filename, ImageFormat.Tiff);
} }
public override string ToString() public override string ToString()
{ {
return "TIFF"; return "TIFF";
} }
} }
} }

View File

@ -1,127 +1,127 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.IO; using System.IO;
using System.Text; using System.Text;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders
{ {
/// <summary> /// <summary>
/// Terragen File Format Loader /// Terragen File Format Loader
/// Built from specification at /// Built from specification at
/// http://www.planetside.co.uk/terragen/dev/tgterrain.html /// http://www.planetside.co.uk/terragen/dev/tgterrain.html
/// </summary> /// </summary>
internal class Terragen : ITerrainLoader internal class Terragen : ITerrainLoader
{ {
#region ITerrainLoader Members #region ITerrainLoader Members
public ITerrainChannel LoadFile(string filename) public ITerrainChannel LoadFile(string filename)
{ {
TerrainChannel retval = new TerrainChannel(); TerrainChannel retval = new TerrainChannel();
FileInfo file = new FileInfo(filename); FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read); FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s); BinaryReader bs = new BinaryReader(s);
bool eof = false; bool eof = false;
if (ASCIIEncoding.ASCII.GetString(bs.ReadBytes(16)) == "TERRAGENTERRAIN ") if (ASCIIEncoding.ASCII.GetString(bs.ReadBytes(16)) == "TERRAGENTERRAIN ")
{ {
// Terragen file // Terragen file
while (eof == false) while (eof == false)
{ {
int w = 256; int w = 256;
int h = 256; int h = 256;
string tmp = ASCIIEncoding.ASCII.GetString(bs.ReadBytes(4)); string tmp = ASCIIEncoding.ASCII.GetString(bs.ReadBytes(4));
switch (tmp) switch (tmp)
{ {
case "SIZE": case "SIZE":
int sztmp = bs.ReadInt16() + 1; int sztmp = bs.ReadInt16() + 1;
w = sztmp; w = sztmp;
h = sztmp; h = sztmp;
bs.ReadInt16(); bs.ReadInt16();
break; break;
case "XPTS": case "XPTS":
w = bs.ReadInt16(); w = bs.ReadInt16();
bs.ReadInt16(); bs.ReadInt16();
break; break;
case "YPTS": case "YPTS":
h = bs.ReadInt16(); h = bs.ReadInt16();
bs.ReadInt16(); bs.ReadInt16();
break; break;
case "ALTW": case "ALTW":
eof = true; eof = true;
Int16 heightScale = bs.ReadInt16(); Int16 heightScale = bs.ReadInt16();
Int16 baseHeight = bs.ReadInt16(); Int16 baseHeight = bs.ReadInt16();
retval = new TerrainChannel(w, h); retval = new TerrainChannel(w, h);
int x, y; int x, y;
for (x = 0; x < w; x++) for (x = 0; x < w; x++)
{ {
for (y = 0; y < h; y++) for (y = 0; y < h; y++)
{ {
retval[x, y] = (double) baseHeight + (double) bs.ReadInt16() * (double) heightScale / 65536.0; retval[x, y] = (double) baseHeight + (double) bs.ReadInt16() * (double) heightScale / 65536.0;
} }
} }
break; break;
default: default:
bs.ReadInt32(); bs.ReadInt32();
break; break;
} }
} }
} }
bs.Close(); bs.Close();
s.Close(); s.Close();
return retval; return retval;
} }
public void SaveFile(string filename, ITerrainChannel map) public void SaveFile(string filename, ITerrainChannel map)
{ {
char[] header = "TERRAGENTERRAIN".ToCharArray(); char[] header = "TERRAGENTERRAIN".ToCharArray();
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string FileExtension public string FileExtension
{ {
get { return ".ter"; } get { return ".ter"; }
} }
public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h) public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return "Terragen"; return "Terragen";
} }
} }
} }

View File

@ -1,71 +1,71 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes
{ {
public class FlattenArea : ITerrainFloodEffect public class FlattenArea : ITerrainFloodEffect
{ {
#region ITerrainFloodEffect Members #region ITerrainFloodEffect Members
public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength) public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength)
{ {
double sum = 0.0; double sum = 0.0;
double steps = 0.0; double steps = 0.0;
double avg; double avg;
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (fillArea[x, y]) if (fillArea[x, y])
{ {
sum += map[x, y]; sum += map[x, y];
steps += 1.0; steps += 1.0;
} }
} }
} }
avg = sum / steps; avg = sum / steps;
double str = 0.1 * strength; // == 0.2 in the default client double str = 0.1 * strength; // == 0.2 in the default client
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (fillArea[x, y]) if (fillArea[x, y])
map[x, y] = (map[x, y] * (1.0 - str)) + (avg * str); map[x, y] = (map[x, y] * (1.0 - str)) + (avg * str);
} }
} }
} }
#endregion #endregion
} }
} }

View File

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

View File

@ -1,56 +1,56 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes
{ {
public class NoiseArea : ITerrainFloodEffect public class NoiseArea : ITerrainFloodEffect
{ {
#region ITerrainFloodEffect Members #region ITerrainFloodEffect Members
public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength) public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength)
{ {
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (fillArea[x, y]) if (fillArea[x, y])
{ {
double noise = TerrainUtil.PerlinNoise2D((double) x / Constants.RegionSize, (double) y / Constants.RegionSize, 8, 1.0); double noise = TerrainUtil.PerlinNoise2D((double) x / Constants.RegionSize, (double) y / Constants.RegionSize, 8, 1.0);
map[x, y] += noise * strength; map[x, y] += noise * strength;
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

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

View File

@ -1,60 +1,60 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes
{ {
public class RevertArea : ITerrainFloodEffect public class RevertArea : ITerrainFloodEffect
{ {
private readonly ITerrainChannel m_revertmap; private readonly ITerrainChannel m_revertmap;
public RevertArea(ITerrainChannel revertmap) public RevertArea(ITerrainChannel revertmap)
{ {
m_revertmap = revertmap; m_revertmap = revertmap;
} }
#region ITerrainFloodEffect Members #region ITerrainFloodEffect Members
public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength) public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength)
{ {
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (fillArea[x, y]) if (fillArea[x, y])
{ {
map[x, y] = (map[x, y] * (1.0 - strength)) + (m_revertmap[x, y] * strength); map[x, y] = (map[x, y] * (1.0 - strength)) + (m_revertmap[x, y] * strength);
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,114 +1,114 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes
{ {
public class SmoothArea : ITerrainFloodEffect public class SmoothArea : ITerrainFloodEffect
{ {
#region ITerrainFloodEffect Members #region ITerrainFloodEffect Members
public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength) public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength)
{ {
double area = strength; double area = strength;
double step = strength / 4.0; double step = strength / 4.0;
double[,] manipulate = new double[map.Width,map.Height]; double[,] manipulate = new double[map.Width,map.Height];
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (!fillArea[x, y]) if (!fillArea[x, y])
continue; continue;
double average = 0.0; double average = 0.0;
int avgsteps = 0; int avgsteps = 0;
double n; double n;
for (n = 0.0 - area; n < area; n += step) for (n = 0.0 - area; n < area; n += step)
{ {
double l; double l;
for (l = 0.0 - area; l < area; l += step) for (l = 0.0 - area; l < area; l += step)
{ {
avgsteps++; avgsteps++;
average += GetBilinearInterpolate(x + n, y + l, map); average += GetBilinearInterpolate(x + n, y + l, map);
} }
} }
manipulate[x, y] = average / avgsteps; manipulate[x, y] = average / avgsteps;
} }
} }
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
if (!fillArea[x, y]) if (!fillArea[x, y])
continue; continue;
map[x, y] = manipulate[x, y]; map[x, y] = manipulate[x, y];
} }
} }
} }
#endregion #endregion
private static double GetBilinearInterpolate(double x, double y, ITerrainChannel map) private static double GetBilinearInterpolate(double x, double y, ITerrainChannel map)
{ {
int w = map.Width; int w = map.Width;
int h = map.Height; int h = map.Height;
if (x > w - 2.0) if (x > w - 2.0)
x = w - 2.0; x = w - 2.0;
if (y > h - 2.0) if (y > h - 2.0)
y = h - 2.0; y = h - 2.0;
if (x < 0.0) if (x < 0.0)
x = 0.0; x = 0.0;
if (y < 0.0) if (y < 0.0)
y = 0.0; y = 0.0;
int stepSize = 1; int stepSize = 1;
double h00 = map[(int) x, (int) y]; double h00 = map[(int) x, (int) y];
double h10 = map[(int) x + stepSize, (int) y]; double h10 = map[(int) x + stepSize, (int) y];
double h01 = map[(int) x, (int) y + stepSize]; double h01 = map[(int) x, (int) y + stepSize];
double h11 = map[(int) x + stepSize, (int) y + stepSize]; double h11 = map[(int) x + stepSize, (int) y + stepSize];
double h1 = h00; double h1 = h00;
double h2 = h10; double h2 = h10;
double h3 = h01; double h3 = h01;
double h4 = h11; double h4 = h11;
double a00 = h1; double a00 = h1;
double a10 = h2 - h1; double a10 = h2 - h1;
double a01 = h3 - h1; double a01 = h3 - h1;
double a11 = h1 - h2 - h3 + h4; double a11 = h1 - h2 - h3 + h4;
double partialx = x - (int) x; double partialx = x - (int) x;
double partialz = y - (int) y; double partialz = y - (int) y;
double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz); double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz);
return hi; return hi;
} }
} }
} }

View File

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

View File

@ -1,37 +1,37 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain namespace OpenSim.Region.Environment.Modules.World.Terrain
{ {
public interface ITerrainFloodEffect public interface ITerrainFloodEffect
{ {
void FloodEffect(ITerrainChannel map, Boolean[,] fillArea, double strength); void FloodEffect(ITerrainChannel map, Boolean[,] fillArea, double strength);
} }
} }

View File

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

View File

@ -1,8 +1,8 @@
namespace OpenSim.Region.Environment.Modules.World.Terrain namespace OpenSim.Region.Environment.Modules.World.Terrain
{ {
public interface ITerrainModule public interface ITerrainModule
{ {
void LoadFromFile(string filename); void LoadFromFile(string filename);
void SaveToFile(string filename); void SaveToFile(string filename);
} }
} }

View File

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

View File

@ -1,168 +1,168 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Drawing; using System.Drawing;
using Nini.Config; using Nini.Config;
using OpenJPEGNet; using OpenJPEGNet;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules.World.Terrain namespace OpenSim.Region.Environment.Modules.World.Terrain
{ {
internal class MapImageModule : IMapImageGenerator, IRegionModule internal class MapImageModule : IMapImageGenerator, IRegionModule
{ {
private Scene m_scene; private Scene m_scene;
#region IMapImageGenerator Members #region IMapImageGenerator Members
public byte[] WriteJpeg2000Image(string gradientmap) public byte[] WriteJpeg2000Image(string gradientmap)
{ {
byte[] imageData = null; byte[] imageData = null;
Bitmap bmp = TerrainToBitmap(gradientmap); Bitmap bmp = TerrainToBitmap(gradientmap);
try try
{ {
imageData = OpenJPEG.EncodeFromImage(bmp, true); imageData = OpenJPEG.EncodeFromImage(bmp, true);
} }
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{ {
Console.WriteLine("Failed generating terrain map: " + e); Console.WriteLine("Failed generating terrain map: " + e);
} }
return imageData; return imageData;
} }
#endregion #endregion
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
m_scene = scene; m_scene = scene;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this); m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "MapImageModule"; } get { return "MapImageModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
private void ShadeBuildings(ref Bitmap map) private void ShadeBuildings(ref Bitmap map)
{ {
lock (map) lock (map)
{ {
lock (m_scene.Entities) lock (m_scene.Entities)
{ {
foreach (EntityBase entity in m_scene.Entities.Values) foreach (EntityBase entity in m_scene.Entities.Values)
{ {
if (entity is SceneObjectGroup) if (entity is SceneObjectGroup)
{ {
SceneObjectGroup sog = (SceneObjectGroup) entity; SceneObjectGroup sog = (SceneObjectGroup) entity;
foreach (SceneObjectPart primitive in sog.Children.Values) foreach (SceneObjectPart primitive in sog.Children.Values)
{ {
int x, y, w, h; int x, y, w, h;
x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2)); x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2)); y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
w = (int) primitive.Scale.X; w = (int) primitive.Scale.X;
h = (int) primitive.Scale.Y; h = (int) primitive.Scale.Y;
int dx; int dx;
for (dx = x; dx < x + w; dx++) for (dx = x; dx < x + w; dx++)
{ {
int dy; int dy;
for (dy = y; dy < y + h; dy++) for (dy = y; dy < y + h; dy++)
{ {
if (x < 0 || y < 0) if (x < 0 || y < 0)
continue; continue;
if (x >= map.Width || y >= map.Height) if (x >= map.Width || y >= map.Height)
continue; continue;
map.SetPixel(dx, dy, Color.DarkGray); map.SetPixel(dx, dy, Color.DarkGray);
} }
} }
} }
} }
} }
} }
} }
} }
private Bitmap TerrainToBitmap(string gradientmap) private Bitmap TerrainToBitmap(string gradientmap)
{ {
Bitmap gradientmapLd = new Bitmap(gradientmap); Bitmap gradientmapLd = new Bitmap(gradientmap);
int pallete = gradientmapLd.Height; int pallete = gradientmapLd.Height;
Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height); Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height);
Color[] colours = new Color[pallete]; Color[] colours = new Color[pallete];
for (int i = 0; i < pallete; i++) for (int i = 0; i < pallete; i++)
{ {
colours[i] = gradientmapLd.GetPixel(0, i); colours[i] = gradientmapLd.GetPixel(0, i);
} }
lock (m_scene.Heightmap) lock (m_scene.Heightmap)
{ {
ITerrainChannel copy = m_scene.Heightmap; ITerrainChannel copy = m_scene.Heightmap;
for (int y = 0; y < copy.Height; y++) for (int y = 0; y < copy.Height; y++)
{ {
for (int x = 0; x < copy.Width; x++) for (int x = 0; x < copy.Width; x++)
{ {
// 512 is the largest possible height before colours clamp // 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1)); int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1));
// Handle error conditions // Handle error conditions
if (colorindex > pallete - 1 || colorindex < 0) if (colorindex > pallete - 1 || colorindex < 0)
bmp.SetPixel(x, copy.Height - y - 1, Color.Red); bmp.SetPixel(x, copy.Height - y - 1, Color.Red);
else else
bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]); bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]);
} }
} }
ShadeBuildings(ref bmp); ShadeBuildings(ref bmp);
return bmp; return bmp;
} }
} }
} }
} }

View File

@ -1,312 +1,312 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
/// <summary> /// <summary>
/// Hydraulic Erosion Brush /// Hydraulic Erosion Brush
/// </summary> /// </summary>
public class ErodeSphere : ITerrainPaintableEffect public class ErodeSphere : ITerrainPaintableEffect
{ {
private double rainHeight = 0.2; private double rainHeight = 0.2;
private int rounds = 10; private int rounds = 10;
private NeighbourSystem type = NeighbourSystem.Moore; // Parameter private NeighbourSystem type = NeighbourSystem.Moore; // Parameter
private double waterSaturation = 0.30; // Can carry 1% of water in height private double waterSaturation = 0.30; // Can carry 1% of water in height
#region Supporting Functions #region Supporting Functions
private int[] Neighbours(NeighbourSystem type, int index) private int[] Neighbours(NeighbourSystem type, int index)
{ {
int[] coord = new int[2]; int[] coord = new int[2];
index++; index++;
switch (type) switch (type)
{ {
case NeighbourSystem.Moore: case NeighbourSystem.Moore:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = -1; coord[0] = -1;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -0; coord[0] = -0;
coord[1] = -1; coord[1] = -1;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = -1; coord[1] = -1;
break; break;
case 4: case 4:
coord[0] = -1; coord[0] = -1;
coord[1] = -0; coord[1] = -0;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
case 6: case 6:
coord[0] = +1; coord[0] = +1;
coord[1] = -0; coord[1] = -0;
break; break;
case 7: case 7:
coord[0] = -1; coord[0] = -1;
coord[1] = +1; coord[1] = +1;
break; break;
case 8: case 8:
coord[0] = -0; coord[0] = -0;
coord[1] = +1; coord[1] = +1;
break; break;
case 9: case 9:
coord[0] = +1; coord[0] = +1;
coord[1] = +1; coord[1] = +1;
break; break;
default: default:
break; break;
} }
break; break;
case NeighbourSystem.VonNeumann: case NeighbourSystem.VonNeumann:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = 0; coord[0] = 0;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -1; coord[0] = -1;
coord[1] = 0; coord[1] = 0;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = 0; coord[1] = 0;
break; break;
case 4: case 4:
coord[0] = 0; coord[0] = 0;
coord[1] = +1; coord[1] = +1;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
default: default:
break; break;
} }
break; break;
} }
return coord; return coord;
} }
private enum NeighbourSystem private enum NeighbourSystem
{ {
Moore, Moore,
VonNeumann VonNeumann
} ; } ;
#endregion #endregion
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
// Using one 'rain' round for this, so skipping a useless loop // Using one 'rain' round for this, so skipping a useless loop
// Will need to adapt back in for the Flood brush // Will need to adapt back in for the Flood brush
ITerrainChannel water = new TerrainChannel(map.Width, map.Height); ITerrainChannel water = new TerrainChannel(map.Width, map.Height);
ITerrainChannel sediment = new TerrainChannel(map.Width, map.Height); ITerrainChannel sediment = new TerrainChannel(map.Width, map.Height);
// Fill with rain // Fill with rain
for (x = 0; x < water.Width; x++) for (x = 0; x < water.Width; x++)
for (y = 0; y < water.Height; y++) for (y = 0; y < water.Height; y++)
water[x, y] = Math.Max(0.0, TerrainUtil.SphericalFactor(x, y, rx, ry, strength) * rainHeight * duration); water[x, y] = Math.Max(0.0, TerrainUtil.SphericalFactor(x, y, rx, ry, strength) * rainHeight * duration);
for (int i = 0; i < rounds; i++) for (int i = 0; i < rounds; i++)
{ {
// Erode underlying terrain // Erode underlying terrain
for (x = 0; x < water.Width; x++) for (x = 0; x < water.Width; x++)
{ {
for (y = 0; y < water.Height; y++) for (y = 0; y < water.Height; y++)
{ {
double solConst = (1.0 / rounds); double solConst = (1.0 / rounds);
double sedDelta = water[x, y] * solConst; double sedDelta = water[x, y] * solConst;
map[x, y] -= sedDelta; map[x, y] -= sedDelta;
sediment[x, y] += sedDelta; sediment[x, y] += sedDelta;
} }
} }
// Move water // Move water
for (x = 0; x < water.Width; x++) for (x = 0; x < water.Width; x++)
{ {
for (y = 0; y < water.Height; y++) for (y = 0; y < water.Height; y++)
{ {
if (water[x, y] <= 0) if (water[x, y] <= 0)
continue; continue;
// Step 1. Calculate average of neighbours // Step 1. Calculate average of neighbours
int neighbours = 0; int neighbours = 0;
double altitudeTotal = 0.0; double altitudeTotal = 0.0;
double altitudeMe = map[x, y] + water[x, y]; double altitudeMe = map[x, y] + water[x, y];
int NEIGHBOUR_ME = 4; int NEIGHBOUR_ME = 4;
int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5; int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5;
for (int j = 0; j < NEIGHBOUR_MAX; j++) for (int j = 0; j < NEIGHBOUR_MAX; j++)
{ {
if (j != NEIGHBOUR_ME) if (j != NEIGHBOUR_ME)
{ {
int[] coords = Neighbours(type, j); int[] coords = Neighbours(type, j);
coords[0] += x; coords[0] += x;
coords[1] += y; coords[1] += y;
if (coords[0] > map.Width - 1) if (coords[0] > map.Width - 1)
continue; continue;
if (coords[1] > map.Height - 1) if (coords[1] > map.Height - 1)
continue; continue;
if (coords[0] < 0) if (coords[0] < 0)
continue; continue;
if (coords[1] < 0) if (coords[1] < 0)
continue; continue;
// Calculate total height of this neighbour // Calculate total height of this neighbour
double altitudeNeighbour = water[coords[0], coords[1]] + map[coords[0], coords[1]]; double altitudeNeighbour = water[coords[0], coords[1]] + map[coords[0], coords[1]];
// If it's greater than me... // If it's greater than me...
if (altitudeNeighbour - altitudeMe < 0) if (altitudeNeighbour - altitudeMe < 0)
{ {
// Add it to our calculations // Add it to our calculations
neighbours++; neighbours++;
altitudeTotal += altitudeNeighbour; altitudeTotal += altitudeNeighbour;
} }
} }
} }
if (neighbours == 0) if (neighbours == 0)
continue; continue;
double altitudeAvg = altitudeTotal / neighbours; double altitudeAvg = altitudeTotal / neighbours;
// Step 2. Allocate water to neighbours. // Step 2. Allocate water to neighbours.
for (int j = 0; j < NEIGHBOUR_MAX; j++) for (int j = 0; j < NEIGHBOUR_MAX; j++)
{ {
if (j != NEIGHBOUR_ME) if (j != NEIGHBOUR_ME)
{ {
int[] coords = Neighbours(type, j); int[] coords = Neighbours(type, j);
coords[0] += x; coords[0] += x;
coords[1] += y; coords[1] += y;
if (coords[0] > map.Width - 1) if (coords[0] > map.Width - 1)
continue; continue;
if (coords[1] > map.Height - 1) if (coords[1] > map.Height - 1)
continue; continue;
if (coords[0] < 0) if (coords[0] < 0)
continue; continue;
if (coords[1] < 0) if (coords[1] < 0)
continue; continue;
// Skip if we dont have water to begin with. // Skip if we dont have water to begin with.
if (water[x, y] < 0) if (water[x, y] < 0)
continue; continue;
// Calculate our delta average // Calculate our delta average
double altitudeDelta = altitudeMe - altitudeAvg; double altitudeDelta = altitudeMe - altitudeAvg;
if (altitudeDelta < 0) if (altitudeDelta < 0)
continue; continue;
// Calculate how much water we can move // Calculate how much water we can move
double waterMin = Math.Min(water[x, y], altitudeDelta); double waterMin = Math.Min(water[x, y], altitudeDelta);
double waterDelta = waterMin * ((water[coords[0], coords[1]] + map[coords[0], coords[1]]) double waterDelta = waterMin * ((water[coords[0], coords[1]] + map[coords[0], coords[1]])
/ altitudeTotal); / altitudeTotal);
double sedimentDelta = sediment[x, y] * (waterDelta / water[x, y]); double sedimentDelta = sediment[x, y] * (waterDelta / water[x, y]);
if (sedimentDelta > 0) if (sedimentDelta > 0)
{ {
sediment[x, y] -= sedimentDelta; sediment[x, y] -= sedimentDelta;
sediment[coords[0], coords[1]] += sedimentDelta; sediment[coords[0], coords[1]] += sedimentDelta;
} }
} }
} }
} }
} }
// Evaporate // Evaporate
for (x = 0; x < water.Width; x++) for (x = 0; x < water.Width; x++)
{ {
for (y = 0; y < water.Height; y++) for (y = 0; y < water.Height; y++)
{ {
water[x, y] *= 1.0 - (rainHeight / rounds); water[x, y] *= 1.0 - (rainHeight / rounds);
double waterCapacity = waterSaturation * water[x, y]; double waterCapacity = waterSaturation * water[x, y];
double sedimentDeposit = sediment[x, y] - waterCapacity; double sedimentDeposit = sediment[x, y] - waterCapacity;
if (sedimentDeposit > 0) if (sedimentDeposit > 0)
{ {
sediment[x, y] -= sedimentDeposit; sediment[x, y] -= sedimentDeposit;
map[x, y] += sedimentDeposit; map[x, y] += sedimentDeposit;
} }
} }
} }
} }
// Deposit any remainder (should be minimal) // Deposit any remainder (should be minimal)
for (x = 0; x < water.Width; x++) for (x = 0; x < water.Width; x++)
for (y = 0; y < water.Height; y++) for (y = 0; y < water.Height; y++)
if (sediment[x, y] > 0) if (sediment[x, y] > 0)
map[x, y] += sediment[x, y]; map[x, y] += sediment[x, y];
} }
#endregion #endregion
} }
} }

View File

@ -1,94 +1,94 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class FlattenSphere : ITerrainPaintableEffect public class FlattenSphere : ITerrainPaintableEffect
{ {
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
double[,] tweak = new double[map.Width,map.Height]; double[,] tweak = new double[map.Width,map.Height];
double area = strength; double area = strength;
double step = strength / 4.0; double step = strength / 4.0;
double sum = 0.0; double sum = 0.0;
double step2 = 0.0; double step2 = 0.0;
double avg = 0.0; double avg = 0.0;
// compute delta map // compute delta map
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = SphericalFactor(x, y, rx, ry, strength); double z = SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
sum += map[x, y] * z; sum += map[x, y] * z;
step2 += z; step2 += z;
} }
} }
} }
avg = sum / step2; avg = sum / step2;
// blend in map // blend in map
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = SphericalFactor(x, y, rx, ry, strength) * duration; double z = SphericalFactor(x, y, rx, ry, strength) * duration;
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
if (z > 1.0) if (z > 1.0)
z = 1.0; z = 1.0;
map[x, y] = (map[x, y] * (1.0 - z)) + (avg * z); map[x, y] = (map[x, y] * (1.0 - z)) + (avg * z);
} }
} }
} }
} }
#endregion #endregion
private double SphericalFactor(double x, double y, double rx, double ry, double size) private double SphericalFactor(double x, double y, double rx, double ry, double size)
{ {
double z = size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry)); double z = size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry));
return z; return z;
} }
} }
} }

View File

@ -1,67 +1,67 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class LowerSphere : ITerrainPaintableEffect public class LowerSphere : ITerrainPaintableEffect
{ {
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(x - rx) > strength * 1.1) if (Math.Abs(x - rx) > strength * 1.1)
continue; continue;
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(y - ry) > strength * 1.1) if (Math.Abs(y - ry) > strength * 1.1)
continue; continue;
// Calculate a sphere and add it to the heighmap // Calculate a sphere and add it to the heighmap
double z = strength; double z = strength;
z *= z; z *= z;
z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry)); z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry));
if (z > 0.0) if (z > 0.0)
map[x, y] -= z * duration; map[x, y] -= z * duration;
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,70 +1,70 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class NoiseSphere : ITerrainPaintableEffect public class NoiseSphere : ITerrainPaintableEffect
{ {
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(x - rx) > strength * 1.1) if (Math.Abs(x - rx) > strength * 1.1)
continue; continue;
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(y - ry) > strength * 1.1) if (Math.Abs(y - ry) > strength * 1.1)
continue; continue;
// Calculate a sphere and add it to the heighmap // Calculate a sphere and add it to the heighmap
double z = strength; double z = strength;
z *= z; z *= z;
z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry)); z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry));
double noise = TerrainUtil.PerlinNoise2D((double) x / (double) Constants.RegionSize, (double) y / (double) Constants.RegionSize, 8, 1.0); double noise = TerrainUtil.PerlinNoise2D((double) x / (double) Constants.RegionSize, (double) y / (double) Constants.RegionSize, 8, 1.0);
if (z > 0.0) if (z > 0.0)
map[x, y] += noise * z * duration; map[x, y] += noise * z * duration;
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,225 +1,225 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
/// <summary> /// <summary>
/// Speed-Optimised Hybrid Erosion Brush /// Speed-Optimised Hybrid Erosion Brush
/// ///
/// As per Jacob Olsen's Paper /// As per Jacob Olsen's Paper
/// http://www.oddlabs.com/download/terrain_generation.pdf /// http://www.oddlabs.com/download/terrain_generation.pdf
/// </summary> /// </summary>
public class OlsenSphere : ITerrainPaintableEffect public class OlsenSphere : ITerrainPaintableEffect
{ {
private double nConst = 1024.0; private double nConst = 1024.0;
private NeighbourSystem type = NeighbourSystem.Moore; // Parameter private NeighbourSystem type = NeighbourSystem.Moore; // Parameter
#region Supporting Functions #region Supporting Functions
private int[] Neighbours(NeighbourSystem type, int index) private int[] Neighbours(NeighbourSystem type, int index)
{ {
int[] coord = new int[2]; int[] coord = new int[2];
index++; index++;
switch (type) switch (type)
{ {
case NeighbourSystem.Moore: case NeighbourSystem.Moore:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = -1; coord[0] = -1;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -0; coord[0] = -0;
coord[1] = -1; coord[1] = -1;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = -1; coord[1] = -1;
break; break;
case 4: case 4:
coord[0] = -1; coord[0] = -1;
coord[1] = -0; coord[1] = -0;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
case 6: case 6:
coord[0] = +1; coord[0] = +1;
coord[1] = -0; coord[1] = -0;
break; break;
case 7: case 7:
coord[0] = -1; coord[0] = -1;
coord[1] = +1; coord[1] = +1;
break; break;
case 8: case 8:
coord[0] = -0; coord[0] = -0;
coord[1] = +1; coord[1] = +1;
break; break;
case 9: case 9:
coord[0] = +1; coord[0] = +1;
coord[1] = +1; coord[1] = +1;
break; break;
default: default:
break; break;
} }
break; break;
case NeighbourSystem.VonNeumann: case NeighbourSystem.VonNeumann:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = 0; coord[0] = 0;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -1; coord[0] = -1;
coord[1] = 0; coord[1] = 0;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = 0; coord[1] = 0;
break; break;
case 4: case 4:
coord[0] = 0; coord[0] = 0;
coord[1] = +1; coord[1] = +1;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
default: default:
break; break;
} }
break; break;
} }
return coord; return coord;
} }
private double SphericalFactor(double x, double y, double rx, double ry, double size) private double SphericalFactor(double x, double y, double rx, double ry, double size)
{ {
double z = size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry)); double z = size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry));
return z; return z;
} }
private enum NeighbourSystem private enum NeighbourSystem
{ {
Moore, Moore,
VonNeumann VonNeumann
} ; } ;
#endregion #endregion
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = SphericalFactor(x, y, rx, ry, strength); double z = SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
int NEIGHBOUR_ME = 4; int NEIGHBOUR_ME = 4;
int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5; int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5;
double max = Double.MinValue; double max = Double.MinValue;
int loc = 0; int loc = 0;
double cellmax = 0; double cellmax = 0;
for (int j = 0; j < NEIGHBOUR_MAX; j++) for (int j = 0; j < NEIGHBOUR_MAX; j++)
{ {
if (j != NEIGHBOUR_ME) if (j != NEIGHBOUR_ME)
{ {
int[] coords = Neighbours(type, j); int[] coords = Neighbours(type, j);
coords[0] += x; coords[0] += x;
coords[1] += y; coords[1] += y;
if (coords[0] > map.Width - 1) if (coords[0] > map.Width - 1)
continue; continue;
if (coords[1] > map.Height - 1) if (coords[1] > map.Height - 1)
continue; continue;
if (coords[0] < 0) if (coords[0] < 0)
continue; continue;
if (coords[1] < 0) if (coords[1] < 0)
continue; continue;
cellmax = map[x, y] - map[coords[0], coords[1]]; cellmax = map[x, y] - map[coords[0], coords[1]];
if (cellmax > max) if (cellmax > max)
{ {
max = cellmax; max = cellmax;
loc = j; loc = j;
} }
} }
} }
double T = nConst / ((map.Width + map.Height) / 2); double T = nConst / ((map.Width + map.Height) / 2);
// Apply results // Apply results
if (0 < max && max <= T) if (0 < max && max <= T)
{ {
int[] maxCoords = Neighbours(type, loc); int[] maxCoords = Neighbours(type, loc);
double heightDelta = 0.5 * max * z * duration; double heightDelta = 0.5 * max * z * duration;
map[x, y] -= heightDelta; map[x, y] -= heightDelta;
map[x + maxCoords[0], y + maxCoords[1]] += heightDelta; map[x + maxCoords[0], y + maxCoords[1]] += heightDelta;
} }
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,67 +1,67 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class RaiseSphere : ITerrainPaintableEffect public class RaiseSphere : ITerrainPaintableEffect
{ {
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(x - rx) > strength * 1.1) if (Math.Abs(x - rx) > strength * 1.1)
continue; continue;
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(y - ry) > strength * 1.1) if (Math.Abs(y - ry) > strength * 1.1)
continue; continue;
// Calculate a sphere and add it to the heighmap // Calculate a sphere and add it to the heighmap
double z = strength; double z = strength;
z *= z; z *= z;
z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry)); z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry));
if (z > 0.0) if (z > 0.0)
map[x, y] += z * duration; map[x, y] += z * duration;
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,82 +1,82 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class RevertSphere : ITerrainPaintableEffect public class RevertSphere : ITerrainPaintableEffect
{ {
private ITerrainChannel m_revertmap; private ITerrainChannel m_revertmap;
public RevertSphere(ITerrainChannel revertmap) public RevertSphere(ITerrainChannel revertmap)
{ {
m_revertmap = revertmap; m_revertmap = revertmap;
} }
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
if (duration > 1.0) if (duration > 1.0)
duration = 1.0; duration = 1.0;
if (duration < 0) if (duration < 0)
return; return;
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(x - rx) > strength * 1.1) if (Math.Abs(x - rx) > strength * 1.1)
continue; continue;
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
// Skip everything unlikely to be affected // Skip everything unlikely to be affected
if (Math.Abs(y - ry) > strength * 1.1) if (Math.Abs(y - ry) > strength * 1.1)
continue; continue;
// Calculate a sphere and add it to the heighmap // Calculate a sphere and add it to the heighmap
double z = strength; double z = strength;
z *= z; z *= z;
z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry)); z -= ((x - rx) * (x - rx)) + ((y - ry) * (y - ry));
if (z > 0.0) if (z > 0.0)
{ {
z *= duration; z *= duration;
map[x, y] += (map[x, y] * (1.0 - z)) + (m_revertmap[x, y] * z); map[x, y] += (map[x, y] * (1.0 - z)) + (m_revertmap[x, y] * z);
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,93 +1,93 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
public class SmoothSphere : ITerrainPaintableEffect public class SmoothSphere : ITerrainPaintableEffect
{ {
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
double[,] tweak = new double[map.Width,map.Height]; double[,] tweak = new double[map.Width,map.Height];
double n, l; double n, l;
double area = strength; double area = strength;
double step = strength / 4.0; double step = strength / 4.0;
// compute delta map // compute delta map
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength); double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
double average = 0.0; double average = 0.0;
int avgsteps = 0; int avgsteps = 0;
for (n = 0.0 - area; n < area; n += step) for (n = 0.0 - area; n < area; n += step)
{ {
for (l = 0.0 - area; l < area; l += step) for (l = 0.0 - area; l < area; l += step)
{ {
avgsteps++; avgsteps++;
average += TerrainUtil.GetBilinearInterpolate(x + n, y + l, map); average += TerrainUtil.GetBilinearInterpolate(x + n, y + l, map);
} }
} }
tweak[x, y] = average / avgsteps; tweak[x, y] = average / avgsteps;
} }
} }
} }
// blend in map // blend in map
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength); double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
double da = z; double da = z;
double a = (map[x, y] - tweak[x, y]) * da; double a = (map[x, y] - tweak[x, y]) * da;
double newz = map[x, y] - (a * duration); double newz = map[x, y] - (a * duration);
if (newz > 0.0) if (newz > 0.0)
map[x, y] = newz; map[x, y] = newz;
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,207 +1,207 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes namespace OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes
{ {
/// <summary> /// <summary>
/// Thermal Weathering Paint Brush /// Thermal Weathering Paint Brush
/// </summary> /// </summary>
public class WeatherSphere : ITerrainPaintableEffect public class WeatherSphere : ITerrainPaintableEffect
{ {
private double talus = 0.2; // Number of meters max difference before stop eroding. Tweakage required. private double talus = 0.2; // Number of meters max difference before stop eroding. Tweakage required.
private NeighbourSystem type = NeighbourSystem.Moore; // Parameter private NeighbourSystem type = NeighbourSystem.Moore; // Parameter
#region Supporting Functions #region Supporting Functions
private int[] Neighbours(NeighbourSystem type, int index) private int[] Neighbours(NeighbourSystem type, int index)
{ {
int[] coord = new int[2]; int[] coord = new int[2];
index++; index++;
switch (type) switch (type)
{ {
case NeighbourSystem.Moore: case NeighbourSystem.Moore:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = -1; coord[0] = -1;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -0; coord[0] = -0;
coord[1] = -1; coord[1] = -1;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = -1; coord[1] = -1;
break; break;
case 4: case 4:
coord[0] = -1; coord[0] = -1;
coord[1] = -0; coord[1] = -0;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
case 6: case 6:
coord[0] = +1; coord[0] = +1;
coord[1] = -0; coord[1] = -0;
break; break;
case 7: case 7:
coord[0] = -1; coord[0] = -1;
coord[1] = +1; coord[1] = +1;
break; break;
case 8: case 8:
coord[0] = -0; coord[0] = -0;
coord[1] = +1; coord[1] = +1;
break; break;
case 9: case 9:
coord[0] = +1; coord[0] = +1;
coord[1] = +1; coord[1] = +1;
break; break;
default: default:
break; break;
} }
break; break;
case NeighbourSystem.VonNeumann: case NeighbourSystem.VonNeumann:
switch (index) switch (index)
{ {
case 1: case 1:
coord[0] = 0; coord[0] = 0;
coord[1] = -1; coord[1] = -1;
break; break;
case 2: case 2:
coord[0] = -1; coord[0] = -1;
coord[1] = 0; coord[1] = 0;
break; break;
case 3: case 3:
coord[0] = +1; coord[0] = +1;
coord[1] = 0; coord[1] = 0;
break; break;
case 4: case 4:
coord[0] = 0; coord[0] = 0;
coord[1] = +1; coord[1] = +1;
break; break;
case 5: case 5:
coord[0] = -0; coord[0] = -0;
coord[1] = -0; coord[1] = -0;
break; break;
default: default:
break; break;
} }
break; break;
} }
return coord; return coord;
} }
private enum NeighbourSystem private enum NeighbourSystem
{ {
Moore, Moore,
VonNeumann VonNeumann
} ; } ;
#endregion #endregion
#region ITerrainPaintableEffect Members #region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration) public void PaintEffect(ITerrainChannel map, double rx, double ry, double strength, double duration)
{ {
strength = TerrainUtil.MetersToSphericalStrength(strength); strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y; int x, y;
for (x = 0; x < map.Width; x++) for (x = 0; x < map.Width; x++)
{ {
for (y = 0; y < map.Height; y++) for (y = 0; y < map.Height; y++)
{ {
double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength); double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount if (z > 0) // add in non-zero amount
{ {
int NEIGHBOUR_ME = 4; int NEIGHBOUR_ME = 4;
int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5; int NEIGHBOUR_MAX = type == NeighbourSystem.Moore ? 9 : 5;
for (int j = 0; j < NEIGHBOUR_MAX; j++) for (int j = 0; j < NEIGHBOUR_MAX; j++)
{ {
if (j != NEIGHBOUR_ME) if (j != NEIGHBOUR_ME)
{ {
int[] coords = Neighbours(type, j); int[] coords = Neighbours(type, j);
coords[0] += x; coords[0] += x;
coords[1] += y; coords[1] += y;
if (coords[0] > map.Width - 1) if (coords[0] > map.Width - 1)
continue; continue;
if (coords[1] > map.Height - 1) if (coords[1] > map.Height - 1)
continue; continue;
if (coords[0] < 0) if (coords[0] < 0)
continue; continue;
if (coords[1] < 0) if (coords[1] < 0)
continue; continue;
double heightF = map[x, y]; double heightF = map[x, y];
double target = map[coords[0], coords[1]]; double target = map[coords[0], coords[1]];
if (target > heightF + talus) if (target > heightF + talus)
{ {
double calc = duration * ((target - heightF) - talus) * z; double calc = duration * ((target - heightF) - talus) * z;
heightF += calc; heightF += calc;
target -= calc; target -= calc;
} }
map[x, y] = heightF; map[x, y] = heightF;
map[coords[0], coords[1]] = target; map[coords[0], coords[1]] = target;
} }
} }
} }
} }
} }
} }
#endregion #endregion
} }
} }

View File

@ -1,157 +1,157 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain namespace OpenSim.Region.Environment.Modules.World.Terrain
{ {
/// <summary> /// <summary>
/// A new version of the old Channel class, simplified /// A new version of the old Channel class, simplified
/// </summary> /// </summary>
public class TerrainChannel : ITerrainChannel public class TerrainChannel : ITerrainChannel
{ {
private readonly bool[,] taint; private readonly bool[,] taint;
private double[,] map; private double[,] map;
public TerrainChannel() public TerrainChannel()
{ {
map = new double[Constants.RegionSize,Constants.RegionSize]; map = new double[Constants.RegionSize,Constants.RegionSize];
taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16];
int x; int x;
for (x = 0; x < Constants.RegionSize; x++) for (x = 0; x < Constants.RegionSize; x++)
{ {
int y; int y;
for (y = 0; y < Constants.RegionSize; y++) for (y = 0; y < Constants.RegionSize; y++)
{ {
map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 10; map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 3, 0.25) * 10;
double spherFac = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2, Constants.RegionSize / 2, 50) * 0.01; double spherFac = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2, Constants.RegionSize / 2, 50) * 0.01;
if (map[x, y] < spherFac) if (map[x, y] < spherFac)
{ {
map[x, y] = spherFac; map[x, y] = spherFac;
} }
} }
} }
} }
public TerrainChannel(double[,] import) public TerrainChannel(double[,] import)
{ {
map = import; map = import;
taint = new bool[import.GetLength(0),import.GetLength(1)]; taint = new bool[import.GetLength(0),import.GetLength(1)];
} }
public TerrainChannel(bool createMap) public TerrainChannel(bool createMap)
{ {
if (createMap) if (createMap)
{ {
map = new double[Constants.RegionSize,Constants.RegionSize]; map = new double[Constants.RegionSize,Constants.RegionSize];
taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16];
} }
} }
public TerrainChannel(int w, int h) public TerrainChannel(int w, int h)
{ {
map = new double[w,h]; map = new double[w,h];
taint = new bool[w / 16,h / 16]; taint = new bool[w / 16,h / 16];
} }
#region ITerrainChannel Members #region ITerrainChannel Members
public int Width public int Width
{ {
get { return map.GetLength(0); } get { return map.GetLength(0); }
} }
public int Height public int Height
{ {
get { return map.GetLength(1); } get { return map.GetLength(1); }
} }
public ITerrainChannel MakeCopy() public ITerrainChannel MakeCopy()
{ {
TerrainChannel copy = new TerrainChannel(false); TerrainChannel copy = new TerrainChannel(false);
copy.map = (double[,]) map.Clone(); copy.map = (double[,]) map.Clone();
return copy; return copy;
} }
public float[] GetFloatsSerialised() public float[] GetFloatsSerialised()
{ {
float[] heights = new float[Width * Height]; float[] heights = new float[Width * Height];
int i; int i;
for (i = 0; i < Width * Height; i++) for (i = 0; i < Width * Height; i++)
{ {
heights[i] = (float) map[i % Width, i / Width]; heights[i] = (float) map[i % Width, i / Width];
} }
return heights; return heights;
} }
public double[,] GetDoubles() public double[,] GetDoubles()
{ {
return map; return map;
} }
public double this[int x, int y] public double this[int x, int y]
{ {
get { return map[x, y]; } get { return map[x, y]; }
set set
{ {
if (map[x, y] != value) if (map[x, y] != value)
{ {
taint[x / 16, y / 16] = true; taint[x / 16, y / 16] = true;
map[x, y] = value; map[x, y] = value;
} }
} }
} }
public bool Tainted(int x, int y) public bool Tainted(int x, int y)
{ {
if (taint[x / 16, y / 16]) if (taint[x / 16, y / 16])
{ {
taint[x / 16, y / 16] = false; taint[x / 16, y / 16] = false;
return true; return true;
} }
else else
{ {
return false; return false;
} }
} }
#endregion #endregion
public TerrainChannel Copy() public TerrainChannel Copy()
{ {
TerrainChannel copy = new TerrainChannel(false); TerrainChannel copy = new TerrainChannel(false);
copy.map = (double[,]) map.Clone(); copy.map = (double[,]) map.Clone();
return copy; return copy;
} }
} }
} }

View File

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

View File

@ -1,133 +1,133 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
namespace OpenSim.Region.Environment.Modules.World.Terrain namespace OpenSim.Region.Environment.Modules.World.Terrain
{ {
public static class TerrainUtil public static class TerrainUtil
{ {
public static double MetersToSphericalStrength(double size) public static double MetersToSphericalStrength(double size)
{ {
return Math.Pow(2, size); return Math.Pow(2, size);
} }
public static double SphericalFactor(double x, double y, double rx, double ry, double size) public static double SphericalFactor(double x, double y, double rx, double ry, double size)
{ {
return size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry)); return size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry));
} }
public static double GetBilinearInterpolate(double x, double y, ITerrainChannel map) public static double GetBilinearInterpolate(double x, double y, ITerrainChannel map)
{ {
int w = map.Width; int w = map.Width;
int h = map.Height; int h = map.Height;
if (x > w - 2.0) if (x > w - 2.0)
x = w - 2.0; x = w - 2.0;
if (y > h - 2.0) if (y > h - 2.0)
y = h - 2.0; y = h - 2.0;
if (x < 0.0) if (x < 0.0)
x = 0.0; x = 0.0;
if (y < 0.0) if (y < 0.0)
y = 0.0; y = 0.0;
int stepSize = 1; int stepSize = 1;
double h00 = map[(int) x, (int) y]; double h00 = map[(int) x, (int) y];
double h10 = map[(int) x + stepSize, (int) y]; double h10 = map[(int) x + stepSize, (int) y];
double h01 = map[(int) x, (int) y + stepSize]; double h01 = map[(int) x, (int) y + stepSize];
double h11 = map[(int) x + stepSize, (int) y + stepSize]; double h11 = map[(int) x + stepSize, (int) y + stepSize];
double h1 = h00; double h1 = h00;
double h2 = h10; double h2 = h10;
double h3 = h01; double h3 = h01;
double h4 = h11; double h4 = h11;
double a00 = h1; double a00 = h1;
double a10 = h2 - h1; double a10 = h2 - h1;
double a01 = h3 - h1; double a01 = h3 - h1;
double a11 = h1 - h2 - h3 + h4; double a11 = h1 - h2 - h3 + h4;
double partialx = x - (int) x; double partialx = x - (int) x;
double partialz = y - (int) y; double partialz = y - (int) y;
double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz); double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz);
return hi; return hi;
} }
private static double Noise(double x, double y) private static double Noise(double x, double y)
{ {
int n = (int) x + (int) (y * 749); int n = (int) x + (int) (y * 749);
n = (n << 13) ^ n; n = (n << 13) ^ n;
return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0); return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
} }
private static double SmoothedNoise1(double x, double y) private static double SmoothedNoise1(double x, double y)
{ {
double corners = (Noise(x - 1, y - 1) + Noise(x + 1, y - 1) + Noise(x - 1, y + 1) + Noise(x + 1, y + 1)) / 16; double corners = (Noise(x - 1, y - 1) + Noise(x + 1, y - 1) + Noise(x - 1, y + 1) + Noise(x + 1, y + 1)) / 16;
double sides = (Noise(x - 1, y) + Noise(x + 1, y) + Noise(x, y - 1) + Noise(x, y + 1)) / 8; double sides = (Noise(x - 1, y) + Noise(x + 1, y) + Noise(x, y - 1) + Noise(x, y + 1)) / 8;
double center = Noise(x, y) / 4; double center = Noise(x, y) / 4;
return corners + sides + center; return corners + sides + center;
} }
private static double Interpolate(double x, double y, double z) private static double Interpolate(double x, double y, double z)
{ {
return (x * (1.0 - z)) + (y * z); return (x * (1.0 - z)) + (y * z);
} }
private static double InterpolatedNoise(double x, double y) private static double InterpolatedNoise(double x, double y)
{ {
int integer_X = (int) (x); int integer_X = (int) (x);
double fractional_X = x - integer_X; double fractional_X = x - integer_X;
int integer_Y = (int) y; int integer_Y = (int) y;
double fractional_Y = y - integer_Y; double fractional_Y = y - integer_Y;
double v1 = SmoothedNoise1(integer_X, integer_Y); double v1 = SmoothedNoise1(integer_X, integer_Y);
double v2 = SmoothedNoise1(integer_X + 1, integer_Y); double v2 = SmoothedNoise1(integer_X + 1, integer_Y);
double v3 = SmoothedNoise1(integer_X, integer_Y + 1); double v3 = SmoothedNoise1(integer_X, integer_Y + 1);
double v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1); double v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1);
double i1 = Interpolate(v1, v2, fractional_X); double i1 = Interpolate(v1, v2, fractional_X);
double i2 = Interpolate(v3, v4, fractional_X); double i2 = Interpolate(v3, v4, fractional_X);
return Interpolate(i1, i2, fractional_Y); return Interpolate(i1, i2, fractional_Y);
} }
public static double PerlinNoise2D(double x, double y, int octaves, double persistence) public static double PerlinNoise2D(double x, double y, int octaves, double persistence)
{ {
double frequency = 0.0; double frequency = 0.0;
double amplitude = 0.0; double amplitude = 0.0;
double total = 0.0; double total = 0.0;
for (int i = 0; i < octaves; i++) for (int i = 0; i < octaves; i++)
{ {
frequency = Math.Pow(2, i); frequency = Math.Pow(2, i);
amplitude = Math.Pow(persistence, i); amplitude = Math.Pow(persistence, i);
total += InterpolatedNoise(x * frequency, y * frequency) * amplitude; total += InterpolatedNoise(x * frequency, y * frequency) * amplitude;
} }
return total; return total;
} }
} }
} }

View File

@ -1,59 +1,59 @@
using System; using System;
using NUnit.Framework; using NUnit.Framework;
using OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes; using OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes;
namespace OpenSim.Region.Environment.Modules.World.Terrain.Tests namespace OpenSim.Region.Environment.Modules.World.Terrain.Tests
{ {
[TestFixture] [TestFixture]
public class TerrainTest public class TerrainTest
{ {
[Test] [Test]
public void BrushTest() public void BrushTest()
{ {
TerrainChannel x = new TerrainChannel(256, 256); TerrainChannel x = new TerrainChannel(256, 256);
ITerrainPaintableEffect effect = new RaiseSphere(); ITerrainPaintableEffect effect = new RaiseSphere();
effect.PaintEffect(x, 128.0, 128.0, 50, 0.1); effect.PaintEffect(x, 128.0, 128.0, 50, 0.1);
Assert.That(x[128, 128] > 0.0, "Raise brush not raising values."); Assert.That(x[128, 128] > 0.0, "Raise brush not raising values.");
Assert.That(x[0, 128] > 0.0, "Raise brush lowering edge values."); Assert.That(x[0, 128] > 0.0, "Raise brush lowering edge values.");
x = new TerrainChannel(256, 256); x = new TerrainChannel(256, 256);
effect = new LowerSphere(); effect = new LowerSphere();
effect.PaintEffect(x, 128.0, 128.0, 50, 0.1); effect.PaintEffect(x, 128.0, 128.0, 50, 0.1);
Assert.That(x[128, 128] < 0.0, "Lower not lowering values."); Assert.That(x[128, 128] < 0.0, "Lower not lowering values.");
Assert.That(x[0, 128] < 0.0, "Lower brush affecting edge values."); Assert.That(x[0, 128] < 0.0, "Lower brush affecting edge values.");
} }
[Test] [Test]
public void TerrainChannelTest() public void TerrainChannelTest()
{ {
TerrainChannel x = new TerrainChannel(256, 256); TerrainChannel x = new TerrainChannel(256, 256);
Assert.That(x[0, 0] == 0.0, "Terrain not initialising correctly."); Assert.That(x[0, 0] == 0.0, "Terrain not initialising correctly.");
x[0, 0] = 1.0; x[0, 0] = 1.0;
Assert.That(x[0, 0] == 1.0, "Terrain not setting values correctly."); Assert.That(x[0, 0] == 1.0, "Terrain not setting values correctly.");
x[0, 0] = 0; x[0, 0] = 0;
x[0, 0] += 5.0; x[0, 0] += 5.0;
x[0, 0] -= 1.0; x[0, 0] -= 1.0;
Assert.That(x[0, 0] == 4.0, "Terrain addition/subtraction error."); Assert.That(x[0, 0] == 4.0, "Terrain addition/subtraction error.");
x[0, 0] = Math.PI; x[0, 0] = Math.PI;
double[,] doublesExport = x.GetDoubles(); double[,] doublesExport = x.GetDoubles();
Assert.That(doublesExport[0, 0] == Math.PI, "Export to double[,] array not working correctly."); Assert.That(doublesExport[0, 0] == Math.PI, "Export to double[,] array not working correctly.");
x[0, 0] = 1.0; x[0, 0] = 1.0;
float[] floatsExport = x.GetFloatsSerialised(); float[] floatsExport = x.GetFloatsSerialised();
Assert.That(floatsExport[0] == 1.0f, "Export to float[] not working correctly."); Assert.That(floatsExport[0] == 1.0f, "Export to float[] not working correctly.");
x[0, 0] = 1.0; x[0, 0] = 1.0;
Assert.That(x.Tainted(0, 0), "Terrain channel tainting not working correctly."); Assert.That(x.Tainted(0, 0), "Terrain channel tainting not working correctly.");
Assert.That(!x.Tainted(0, 0), "Terrain channel tainting not working correctly."); Assert.That(!x.Tainted(0, 0), "Terrain channel tainting not working correctly.");
TerrainChannel y = x.Copy(); TerrainChannel y = x.Copy();
Assert.That(!ReferenceEquals(x, y), "Terrain copy not duplicating correctly."); Assert.That(!ReferenceEquals(x, y), "Terrain copy not duplicating correctly.");
Assert.That(!ReferenceEquals(x.GetDoubles(), y.GetDoubles()), "Terrain array not duplicating correctly."); Assert.That(!ReferenceEquals(x.GetDoubles(), y.GetDoubles()), "Terrain array not duplicating correctly.");
} }
} }
} }

View File

@ -1,251 +1,251 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright * * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the * * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* 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 System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Timers; using System.Timers;
using Axiom.Math; using Axiom.Math;
using libsecondlife; using libsecondlife;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Interfaces;
using OpenSim.Region.Environment.Scenes; using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Region.Environment.Modules namespace OpenSim.Region.Environment.Modules
{ {
/// <summary> /// <summary>
/// Version 2.0 - Very hacky compared to the original. Will fix original and release as 0.3 later. /// Version 2.0 - Very hacky compared to the original. Will fix original and release as 0.3 later.
/// </summary> /// </summary>
public class TreePopulatorModule : IRegionModule public class TreePopulatorModule : IRegionModule
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene; private Scene m_scene;
public double m_tree_density = 50.0; // Aim for this many per region public double m_tree_density = 50.0; // Aim for this many per region
public double m_tree_updates = 1000.0; // MS between updates public double m_tree_updates = 1000.0; // MS between updates
private List<LLUUID> m_trees; private List<LLUUID> m_trees;
#region IRegionModule Members #region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config) public void Initialise(Scene scene, IConfigSource config)
{ {
try try
{ {
m_tree_density = config.Configs["Trees"].GetDouble("tree_density", m_tree_density); m_tree_density = config.Configs["Trees"].GetDouble("tree_density", m_tree_density);
} }
catch (Exception) catch (Exception)
{ {
} }
m_trees = new List<LLUUID>(); m_trees = new List<LLUUID>();
m_scene = scene; m_scene = scene;
m_scene.EventManager.OnPluginConsole += new EventManager.OnPluginConsoleDelegate(EventManager_OnPluginConsole); m_scene.EventManager.OnPluginConsole += new EventManager.OnPluginConsoleDelegate(EventManager_OnPluginConsole);
Timer CalculateTrees = new Timer(m_tree_updates); Timer CalculateTrees = new Timer(m_tree_updates);
CalculateTrees.Elapsed += new ElapsedEventHandler(CalculateTrees_Elapsed); CalculateTrees.Elapsed += new ElapsedEventHandler(CalculateTrees_Elapsed);
CalculateTrees.Start(); CalculateTrees.Start();
m_log.Debug("[TREES]: Initialised tree module"); m_log.Debug("[TREES]: Initialised tree module");
} }
public void PostInitialise() public void PostInitialise()
{ {
} }
public void Close() public void Close()
{ {
} }
public string Name public string Name
{ {
get { return "TreePopulatorModule"; } get { return "TreePopulatorModule"; }
} }
public bool IsSharedModule public bool IsSharedModule
{ {
get { return false; } get { return false; }
} }
#endregion #endregion
private void EventManager_OnPluginConsole(string[] args) private void EventManager_OnPluginConsole(string[] args)
{ {
if (args[0] == "tree") if (args[0] == "tree")
{ {
m_log.Debug("[TREES]: New tree planting"); m_log.Debug("[TREES]: New tree planting");
CreateTree(new LLVector3(128.0f, 128.0f, 0.0f)); CreateTree(new LLVector3(128.0f, 128.0f, 0.0f));
} }
} }
private void growTrees() private void growTrees()
{ {
foreach (LLUUID tree in m_trees) foreach (LLUUID tree in m_trees)
{ {
if (m_scene.Entities.ContainsKey(tree)) if (m_scene.Entities.ContainsKey(tree))
{ {
SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
// 100 seconds to grow 1m // 100 seconds to grow 1m
s_tree.Scale += new LLVector3(0.1f, 0.1f, 0.1f); s_tree.Scale += new LLVector3(0.1f, 0.1f, 0.1f);
s_tree.SendFullUpdateToAllClients(); s_tree.SendFullUpdateToAllClients();
//s_tree.ScheduleTerseUpdate(); //s_tree.ScheduleTerseUpdate();
} }
else else
{ {
m_trees.Remove(tree); m_trees.Remove(tree);
} }
} }
} }
private void seedTrees() private void seedTrees()
{ {
foreach (LLUUID tree in m_trees) foreach (LLUUID tree in m_trees)
{ {
if (m_scene.Entities.ContainsKey(tree)) if (m_scene.Entities.ContainsKey(tree))
{ {
SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
if (s_tree.Scale.X > 0.5) if (s_tree.Scale.X > 0.5)
{ {
if (Util.RandomClass.NextDouble() > 0.75) if (Util.RandomClass.NextDouble() > 0.75)
{ {
SpawnChild(s_tree); SpawnChild(s_tree);
} }
} }
} }
else else
{ {
m_trees.Remove(tree); m_trees.Remove(tree);
} }
} }
} }
private void killTrees() private void killTrees()
{ {
foreach (LLUUID tree in m_trees) foreach (LLUUID tree in m_trees)
{ {
double killLikelyhood = 0.0; double killLikelyhood = 0.0;
if (m_scene.Entities.ContainsKey(tree)) if (m_scene.Entities.ContainsKey(tree))
{ {
SceneObjectPart selectedTree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; SceneObjectPart selectedTree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) + double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
Math.Pow(selectedTree.Scale.Y, 2) + Math.Pow(selectedTree.Scale.Y, 2) +
Math.Pow(selectedTree.Scale.Z, 2)); Math.Pow(selectedTree.Scale.Z, 2));
foreach (LLUUID picktree in m_trees) foreach (LLUUID picktree in m_trees)
{ {
if (picktree != tree) if (picktree != tree)
{ {
SceneObjectPart pickedTree = ((SceneObjectGroup) m_scene.Entities[picktree]).RootPart; SceneObjectPart pickedTree = ((SceneObjectGroup) m_scene.Entities[picktree]).RootPart;
double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) + double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
Math.Pow(pickedTree.Scale.Y, 2) + Math.Pow(pickedTree.Scale.Y, 2) +
Math.Pow(pickedTree.Scale.Z, 2)); Math.Pow(pickedTree.Scale.Z, 2));
double pickedTreeDistance = Math.Sqrt(Math.Pow(Math.Abs(pickedTree.AbsolutePosition.X - selectedTree.AbsolutePosition.X), 2) + double pickedTreeDistance = Math.Sqrt(Math.Pow(Math.Abs(pickedTree.AbsolutePosition.X - selectedTree.AbsolutePosition.X), 2) +
Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Y - selectedTree.AbsolutePosition.Y), 2) + Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Y - selectedTree.AbsolutePosition.Y), 2) +
Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Z - selectedTree.AbsolutePosition.Z), 2)); Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Z - selectedTree.AbsolutePosition.Z), 2));
killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1; killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
} }
} }
if (Util.RandomClass.NextDouble() < killLikelyhood) if (Util.RandomClass.NextDouble() < killLikelyhood)
{ {
m_scene.RemoveEntity(selectedTree.ParentGroup); m_scene.RemoveEntity(selectedTree.ParentGroup);
m_trees.Remove(selectedTree.ParentGroup.UUID); m_trees.Remove(selectedTree.ParentGroup.UUID);
m_scene.ForEachClient(delegate(IClientAPI controller) m_scene.ForEachClient(delegate(IClientAPI controller)
{ {
controller.SendKillObject(m_scene.RegionInfo.RegionHandle, controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
selectedTree.LocalId); selectedTree.LocalId);
}); });
break; break;
} }
else else
{ {
selectedTree.SetText(killLikelyhood.ToString(), new Vector3(1.0f, 1.0f, 1.0f), 1.0); selectedTree.SetText(killLikelyhood.ToString(), new Vector3(1.0f, 1.0f, 1.0f), 1.0);
} }
} }
else else
{ {
m_trees.Remove(tree); m_trees.Remove(tree);
} }
} }
} }
private void SpawnChild(SceneObjectPart s_tree) private void SpawnChild(SceneObjectPart s_tree)
{ {
LLVector3 position = new LLVector3(); LLVector3 position = new LLVector3();
position.X = s_tree.AbsolutePosition.X + (1 * (-1 * Util.RandomClass.Next(1))); position.X = s_tree.AbsolutePosition.X + (1 * (-1 * Util.RandomClass.Next(1)));
if (position.X > 255) if (position.X > 255)
position.X = 255; position.X = 255;
if (position.X < 0) if (position.X < 0)
position.X = 0; position.X = 0;
position.Y = s_tree.AbsolutePosition.Y + (1 * (-1 * Util.RandomClass.Next(1))); position.Y = s_tree.AbsolutePosition.Y + (1 * (-1 * Util.RandomClass.Next(1)));
if (position.Y > 255) if (position.Y > 255)
position.Y = 255; position.Y = 255;
if (position.Y < 0) if (position.Y < 0)
position.Y = 0; position.Y = 0;
double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
position.X += (float) randX; position.X += (float) randX;
position.Y += (float) randY; position.Y += (float) randY;
CreateTree(position); CreateTree(position);
} }
private void CreateTree(LLVector3 position) private void CreateTree(LLVector3 position)
{ {
position.Z = (float) m_scene.Heightmap[(int) position.X, (int) position.Y]; position.Z = (float) m_scene.Heightmap[(int) position.X, (int) position.Y];
SceneObjectGroup tree = SceneObjectGroup tree =
m_scene.AddTree(new LLVector3(0.1f, 0.1f, 0.1f), m_scene.AddTree(new LLVector3(0.1f, 0.1f, 0.1f),
LLQuaternion.Identity, LLQuaternion.Identity,
position, position,
Tree.Cypress1, Tree.Cypress1,
false); false);
m_trees.Add(tree.UUID); m_trees.Add(tree.UUID);
tree.SendGroupFullUpdate(); tree.SendGroupFullUpdate();
} }
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e) private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{ {
growTrees(); growTrees();
seedTrees(); seedTrees();
killTrees(); killTrees();
} }
} }
} }

View File

@ -658,7 +658,6 @@ namespace OpenSim.Region.Environment.Scenes
float physicsFPS = 0; float physicsFPS = 0;
int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount(); int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount();
if (agentsInScene > 21) if (agentsInScene > 21)
{ {
if (m_update_entities == 1) if (m_update_entities == 1)
@ -676,7 +675,6 @@ namespace OpenSim.Region.Environment.Scenes
} }
} }
frameMS = System.Environment.TickCount; frameMS = System.Environment.TickCount;
try try
{ {
@ -687,7 +685,6 @@ namespace OpenSim.Region.Environment.Scenes
if (m_frame == Int32.MaxValue) if (m_frame == Int32.MaxValue)
m_frame = 0; m_frame = 0;
physicsMS2 = System.Environment.TickCount; physicsMS2 = System.Environment.TickCount;
if ((m_frame % m_update_physics == 0) && m_physics_enabled) if ((m_frame % m_update_physics == 0) && m_physics_enabled)
m_innerScene.UpdatePreparePhysics(); m_innerScene.UpdatePreparePhysics();

View File

@ -112,7 +112,6 @@ namespace OpenSim.Region.Physics.OdePlugin
private PhysicsActor _parent = null; private PhysicsActor _parent = null;
private PhysicsActor m_taintparent = null; private PhysicsActor m_taintparent = null;
private bool iscolliding = false; private bool iscolliding = false;
private bool m_isphysical = false; private bool m_isphysical = false;
private bool m_isSelected = false; private bool m_isSelected = false;
@ -129,7 +128,6 @@ namespace OpenSim.Region.Physics.OdePlugin
public bool outofBounds = false; public bool outofBounds = false;
private float m_density = 10.000006836f; // Aluminum g/cm3; private float m_density = 10.000006836f; // Aluminum g/cm3;
public bool _zeroFlag = false; public bool _zeroFlag = false;
private bool m_lastUpdateSent = false; private bool m_lastUpdateSent = false;
@ -1761,8 +1759,8 @@ namespace OpenSim.Region.Physics.OdePlugin
public override bool Flying public override bool Flying
{ {
get { return false; //no flying prims for you // no flying prims for you
} get { return false; }
set { } set { }
} }
@ -1832,8 +1830,8 @@ namespace OpenSim.Region.Physics.OdePlugin
public override PrimitiveBaseShape Shape public override PrimitiveBaseShape Shape
{ {
set { set
{
_pbs = value; _pbs = value;
m_taintshape = true; m_taintshape = true;
} }
@ -1851,13 +1849,12 @@ namespace OpenSim.Region.Physics.OdePlugin
returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z)/2; returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z)/2;
return returnVelocity; return returnVelocity;
} }
set { set
{
_velocity = value; _velocity = value;
m_taintVelocity = value; m_taintVelocity = value;
_parent_scene.AddPhysicsActorTaint(this); _parent_scene.AddPhysicsActorTaint(this);
} }
} }
@ -1898,7 +1895,8 @@ namespace OpenSim.Region.Physics.OdePlugin
public override PhysicsVector RotationalVelocity public override PhysicsVector RotationalVelocity
{ {
get { get
{
PhysicsVector pv = new PhysicsVector(0, 0, 0); PhysicsVector pv = new PhysicsVector(0, 0, 0);
if (_zeroFlag) if (_zeroFlag)
return pv; return pv;
@ -1911,6 +1909,7 @@ namespace OpenSim.Region.Physics.OdePlugin
} }
set { m_rotationalVelocity = value; } set { m_rotationalVelocity = value; }
} }
public override void CrossingFailure() public override void CrossingFailure()
{ {
m_crossingfailures++; m_crossingfailures++;
@ -1918,7 +1917,6 @@ namespace OpenSim.Region.Physics.OdePlugin
{ {
base.RaiseOutOfBounds(_position); base.RaiseOutOfBounds(_position);
return; return;
} }
else if (m_crossingfailures == 5) else if (m_crossingfailures == 5)
{ {
@ -1942,7 +1940,6 @@ namespace OpenSim.Region.Physics.OdePlugin
m_taintparent = null; m_taintparent = null;
} }
public override void LockAngularMotion(PhysicsVector axis) public override void LockAngularMotion(PhysicsVector axis)
{ {
// reverse the zero/non zero values for ODE. // reverse the zero/non zero values for ODE.
@ -1958,7 +1955,6 @@ namespace OpenSim.Region.Physics.OdePlugin
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit! // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
if (_parent != null) if (_parent != null)
{ {
} }
else else
{ {
@ -1973,7 +1969,6 @@ namespace OpenSim.Region.Physics.OdePlugin
PhysicsVector l_position = new PhysicsVector(); PhysicsVector l_position = new PhysicsVector();
// kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!) // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
//if (vec.X < 0.0f) { vec.X = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); } //if (vec.X < 0.0f) { vec.X = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
//if (vec.Y < 0.0f) { vec.Y = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); } //if (vec.Y < 0.0f) { vec.Y = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
@ -2014,7 +2009,6 @@ namespace OpenSim.Region.Physics.OdePlugin
// Disables the prim's movement physics.... // Disables the prim's movement physics....
// It's a hack and will generate a console message if it fails. // It's a hack and will generate a console message if it fails.
//IsPhysical = false; //IsPhysical = false;
if (_parent == null) if (_parent == null)
base.RaiseOutOfBounds(_position); base.RaiseOutOfBounds(_position);
@ -2052,10 +2046,8 @@ namespace OpenSim.Region.Physics.OdePlugin
_zeroFlag = false; _zeroFlag = false;
} }
if (_zeroFlag) if (_zeroFlag)
{ {
_velocity.X = 0.0f; _velocity.X = 0.0f;
_velocity.Y = 0.0f; _velocity.Y = 0.0f;
_velocity.Z = 0.0f; _velocity.Z = 0.0f;
@ -2197,8 +2189,6 @@ namespace OpenSim.Region.Physics.OdePlugin
d.JointAttach(Amotor, Body, IntPtr.Zero); d.JointAttach(Amotor, Body, IntPtr.Zero);
d.JointSetAMotorMode(Amotor, dAMotorEuler); d.JointSetAMotorMode(Amotor, dAMotorEuler);
d.JointSetAMotorNumAxes(Amotor,(int)axisnum); d.JointSetAMotorNumAxes(Amotor,(int)axisnum);
int i = 0; int i = 0;
@ -2235,11 +2225,9 @@ namespace OpenSim.Region.Physics.OdePlugin
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f); d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
d.JointSetAMotorParam(Amotor, (int)dParam.FMax, m_tensor); d.JointSetAMotorParam(Amotor, (int)dParam.FMax, m_tensor);
} }
} }
} }

0
share/python/console/shutdown.py Normal file → Executable file
View File