WorldMapModule.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Net;
  34. using System.Reflection;
  35. using System.Threading;
  36. using OpenMetaverse;
  37. using OpenMetaverse.Imaging;
  38. using OpenMetaverse.StructuredData;
  39. using log4net;
  40. using Nini.Config;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Communications.Cache;
  43. using OpenSim.Framework.Communications.Capabilities;
  44. using OpenSim.Framework.Servers;
  45. using OpenSim.Region.Environment.Interfaces;
  46. using OpenSim.Region.Environment.Scenes;
  47. using OpenSim.Region.Environment.Types;
  48. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  49. using OSD = OpenMetaverse.StructuredData.OSD;
  50. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  51. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  52. namespace OpenSim.Region.Environment.Modules.World.WorldMap
  53. {
  54. public class WorldMapModule : IRegionModule
  55. {
  56. private static readonly ILog m_log =
  57. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  58. private static readonly string m_mapLayerPath = "0001/";
  59. private OpenSim.Framework.BlockingQueue<MapRequestState> requests = new OpenSim.Framework.BlockingQueue<MapRequestState>();
  60. //private IConfig m_config;
  61. protected Scene m_scene;
  62. private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>();
  63. private int cachedTime = 0;
  64. private byte[] myMapImageJPEG;
  65. protected bool m_Enabled = false;
  66. private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>();
  67. private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>();
  68. private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>();
  69. private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>();
  70. private List<UUID> m_rootAgents = new List<UUID>();
  71. private Thread mapItemReqThread;
  72. private volatile bool threadrunning = false;
  73. //private int CacheRegionsDistance = 256;
  74. #region IRegionModule Members
  75. public virtual void Initialise(Scene scene, IConfigSource config)
  76. {
  77. IConfig startupConfig = config.Configs["Startup"];
  78. if (startupConfig.GetString("WorldMapModule", "WorldMap") ==
  79. "WorldMap")
  80. m_Enabled = true;
  81. if (!m_Enabled)
  82. return;
  83. m_scene = scene;
  84. }
  85. public virtual void PostInitialise()
  86. {
  87. if (m_Enabled)
  88. AddHandlers();
  89. }
  90. public virtual void Close()
  91. {
  92. }
  93. public virtual string Name
  94. {
  95. get { return "WorldMapModule"; }
  96. }
  97. public bool IsSharedModule
  98. {
  99. get { return false; }
  100. }
  101. #endregion
  102. protected virtual void AddHandlers()
  103. {
  104. myMapImageJPEG = new byte[0];
  105. string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
  106. regionimage = regionimage.Replace("-", "");
  107. m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalEndPoint.Address.ToString() + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage);
  108. m_scene.CommsManager.HttpServer.AddHTTPHandler(regionimage, OnHTTPGetMapImage);
  109. m_scene.CommsManager.HttpServer.AddLLSDHandler(
  110. "/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest);
  111. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  112. m_scene.EventManager.OnNewClient += OnNewClient;
  113. m_scene.EventManager.OnClientClosed += ClientLoggedOut;
  114. m_scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  115. m_scene.EventManager.OnMakeRootAgent += MakeRootAgent;
  116. }
  117. public void OnRegisterCaps(UUID agentID, Caps caps)
  118. {
  119. //m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
  120. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  121. caps.RegisterHandler("MapLayer",
  122. new RestStreamHandler("POST", capsBase + m_mapLayerPath,
  123. delegate(string request, string path, string param,
  124. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  125. {
  126. return MapLayerRequest(request, path, param,
  127. agentID, caps);
  128. }));
  129. }
  130. /// <summary>
  131. /// Callback for a map layer request
  132. /// </summary>
  133. /// <param name="request"></param>
  134. /// <param name="path"></param>
  135. /// <param name="param"></param>
  136. /// <param name="agentID"></param>
  137. /// <param name="caps"></param>
  138. /// <returns></returns>
  139. public string MapLayerRequest(string request, string path, string param,
  140. UUID agentID, Caps caps)
  141. {
  142. //try
  143. //{
  144. //m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}",
  145. //request, path, param,agentID.ToString());
  146. // this is here because CAPS map requests work even beyond the 10,000 limit.
  147. ScenePresence avatarPresence = null;
  148. m_scene.TryGetAvatar(agentID, out avatarPresence);
  149. if (avatarPresence != null)
  150. {
  151. bool lookup = false;
  152. lock (cachedMapBlocks)
  153. {
  154. if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch()))
  155. {
  156. List<MapBlockData> mapBlocks;
  157. mapBlocks = cachedMapBlocks;
  158. avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
  159. }
  160. else
  161. {
  162. lookup = true;
  163. }
  164. }
  165. if (lookup)
  166. {
  167. List<MapBlockData> mapBlocks;
  168. mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks((int)m_scene.RegionInfo.RegionLocX - 8, (int)m_scene.RegionInfo.RegionLocY - 8, (int)m_scene.RegionInfo.RegionLocX + 8, (int)m_scene.RegionInfo.RegionLocY + 8);
  169. avatarPresence.ControllingClient.SendMapBlock(mapBlocks,0);
  170. lock (cachedMapBlocks)
  171. cachedMapBlocks = mapBlocks;
  172. cachedTime = Util.UnixTimeSinceEpoch();
  173. }
  174. }
  175. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  176. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  177. return mapResponse.ToString();
  178. }
  179. /// <summary>
  180. ///
  181. /// </summary>
  182. /// <param name="mapReq"></param>
  183. /// <returns></returns>
  184. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  185. {
  186. m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName);
  187. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  188. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  189. return mapResponse;
  190. }
  191. /// <summary>
  192. ///
  193. /// </summary>
  194. /// <returns></returns>
  195. protected static OSDMapLayer GetOSDMapLayerResponse()
  196. {
  197. OSDMapLayer mapLayer = new OSDMapLayer();
  198. mapLayer.Right = 5000;
  199. mapLayer.Top = 5000;
  200. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  201. return mapLayer;
  202. }
  203. #region EventHandlers
  204. /// <summary>
  205. /// Registered for event
  206. /// </summary>
  207. /// <param name="client"></param>
  208. private void OnNewClient(IClientAPI client)
  209. {
  210. client.OnRequestMapBlocks += RequestMapBlocks;
  211. client.OnMapItemRequest += HandleMapItemRequest;
  212. }
  213. /// <summary>
  214. /// Client logged out, check to see if there are any more root agents in the simulator
  215. /// If not, stop the mapItemRequest Thread
  216. /// Event handler
  217. /// </summary>
  218. /// <param name="AgentId">AgentID that logged out</param>
  219. private void ClientLoggedOut(UUID AgentId)
  220. {
  221. List<ScenePresence> presences = m_scene.GetAvatars();
  222. int rootcount = 0;
  223. for (int i=0;i<presences.Count;i++)
  224. {
  225. if (presences[i] != null)
  226. {
  227. if (!presences[i].IsChildAgent)
  228. rootcount++;
  229. }
  230. }
  231. if (rootcount <= 1)
  232. StopThread();
  233. lock (m_rootAgents)
  234. {
  235. if (m_rootAgents.Contains(AgentId))
  236. {
  237. m_rootAgents.Remove(AgentId);
  238. }
  239. }
  240. }
  241. #endregion
  242. /// <summary>
  243. /// Starts the MapItemRequest Thread
  244. /// Note that this only gets started when there are actually agents in the region
  245. /// Additionally, it gets stopped when there are none.
  246. /// </summary>
  247. /// <param name="o"></param>
  248. private void StartThread(object o)
  249. {
  250. if (threadrunning) return;
  251. threadrunning = true;
  252. m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread");
  253. mapItemReqThread = new Thread(new ThreadStart(process));
  254. mapItemReqThread.IsBackground = true;
  255. mapItemReqThread.Name = "MapItemRequestThread";
  256. mapItemReqThread.Priority = ThreadPriority.BelowNormal;
  257. mapItemReqThread.SetApartmentState(ApartmentState.MTA);
  258. mapItemReqThread.Start();
  259. ThreadTracker.Add(mapItemReqThread);
  260. }
  261. /// <summary>
  262. /// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end
  263. /// </summary>
  264. private void StopThread()
  265. {
  266. MapRequestState st = new MapRequestState();
  267. st.agentID=UUID.Zero;
  268. st.EstateID=0;
  269. st.flags=0;
  270. st.godlike=false;
  271. st.itemtype=0;
  272. st.regionhandle=0;
  273. requests.Enqueue(st);
  274. }
  275. public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags,
  276. uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
  277. {
  278. lock (m_rootAgents)
  279. {
  280. if (!m_rootAgents.Contains(remoteClient.AgentId))
  281. return;
  282. }
  283. uint xstart = 0;
  284. uint ystart = 0;
  285. Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart);
  286. if (itemtype == 6) // we only sevice 6 right now (avatar green dots)
  287. {
  288. if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
  289. {
  290. // Local Map Item Request
  291. List<ScenePresence> avatars = m_scene.GetAvatars();
  292. int tc = System.Environment.TickCount;
  293. List<mapItemReply> mapitems = new List<mapItemReply>();
  294. mapItemReply mapitem = new mapItemReply();
  295. if (avatars.Count == 0 || avatars.Count == 1)
  296. {
  297. mapitem = new mapItemReply();
  298. mapitem.x = (uint)(xstart + 1);
  299. mapitem.y = (uint)(ystart + 1);
  300. mapitem.id = UUID.Zero;
  301. mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
  302. mapitem.Extra = 0;
  303. mapitem.Extra2 = 0;
  304. mapitems.Add(mapitem);
  305. }
  306. else
  307. {
  308. foreach (ScenePresence av in avatars)
  309. {
  310. // Don't send a green dot for yourself
  311. if (av.UUID != remoteClient.AgentId)
  312. {
  313. mapitem = new mapItemReply();
  314. mapitem.x = (uint)(xstart + av.AbsolutePosition.X);
  315. mapitem.y = (uint)(ystart + av.AbsolutePosition.Y);
  316. mapitem.id = UUID.Zero;
  317. mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
  318. mapitem.Extra = 1;
  319. mapitem.Extra2 = 0;
  320. mapitems.Add(mapitem);
  321. }
  322. }
  323. }
  324. remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
  325. }
  326. else
  327. {
  328. // Remote Map Item Request
  329. // ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes.
  330. // Note that we only start up a remote mapItem Request thread if there's users who could
  331. // be making requests
  332. if (!threadrunning)
  333. {
  334. m_log.Warn("[WORLD MAP]: Starting new remote request thread manually. This means that AvatarEnteringParcel never fired! This needs to be fixed! Don't Mantis this, as the developers can see it in this message");
  335. StartThread(new object());
  336. }
  337. RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
  338. }
  339. }
  340. }
  341. /// <summary>
  342. /// Processing thread main() loop for doing remote mapitem requests
  343. /// </summary>
  344. public void process()
  345. {
  346. try
  347. {
  348. while (true)
  349. {
  350. MapRequestState st = requests.Dequeue();
  351. // end gracefully
  352. if (st.agentID == UUID.Zero)
  353. {
  354. ThreadTracker.Remove(mapItemReqThread);
  355. break;
  356. }
  357. bool dorequest = true;
  358. lock (m_rootAgents)
  359. {
  360. if (!m_rootAgents.Contains(st.agentID))
  361. dorequest = false;
  362. }
  363. if (dorequest)
  364. {
  365. OSDMap response = RequestMapItemsAsync("", st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle);
  366. RequestMapItemsCompleted(response);
  367. }
  368. }
  369. }
  370. catch (Exception e)
  371. {
  372. m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e);
  373. }
  374. threadrunning = false;
  375. }
  376. /// <summary>
  377. /// Enqueues the map item request into the processing thread
  378. /// </summary>
  379. /// <param name="state"></param>
  380. public void EnqueueMapItemRequest(MapRequestState state)
  381. {
  382. requests.Enqueue(state);
  383. }
  384. /// <summary>
  385. /// Sends the mapitem response to the IClientAPI
  386. /// </summary>
  387. /// <param name="response">The OSDMap Response for the mapitem</param>
  388. private void RequestMapItemsCompleted(OSDMap response)
  389. {
  390. UUID requestID = response["requestID"].AsUUID();
  391. if (requestID != UUID.Zero)
  392. {
  393. MapRequestState mrs = new MapRequestState();
  394. mrs.agentID = UUID.Zero;
  395. lock (m_openRequests)
  396. {
  397. if (m_openRequests.ContainsKey(requestID))
  398. {
  399. mrs = m_openRequests[requestID];
  400. m_openRequests.Remove(requestID);
  401. }
  402. }
  403. if (mrs.agentID != UUID.Zero)
  404. {
  405. ScenePresence av = null;
  406. m_scene.TryGetAvatar(mrs.agentID, out av);
  407. if (av != null)
  408. {
  409. if (response.ContainsKey(mrs.itemtype.ToString()))
  410. {
  411. List<mapItemReply> returnitems = new List<mapItemReply>();
  412. OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()];
  413. for (int i = 0; i < itemarray.Count; i++)
  414. {
  415. OSDMap mapitem = (OSDMap)itemarray[i];
  416. mapItemReply mi = new mapItemReply();
  417. mi.x = (uint)mapitem["X"].AsInteger();
  418. mi.y = (uint)mapitem["Y"].AsInteger();
  419. mi.id = mapitem["ID"].AsUUID();
  420. mi.Extra = mapitem["Extra"].AsInteger();
  421. mi.Extra2 = mapitem["Extra2"].AsInteger();
  422. mi.name = mapitem["Name"].AsString();
  423. returnitems.Add(mi);
  424. }
  425. av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags);
  426. }
  427. }
  428. }
  429. }
  430. }
  431. /// <summary>
  432. /// Enqueue the MapItem request for remote processing
  433. /// </summary>
  434. /// <param name="httpserver">blank string, we discover this in the process</param>
  435. /// <param name="id">Agent ID that we are making this request on behalf</param>
  436. /// <param name="flags">passed in from packet</param>
  437. /// <param name="EstateID">passed in from packet</param>
  438. /// <param name="godlike">passed in from packet</param>
  439. /// <param name="itemtype">passed in from packet</param>
  440. /// <param name="regionhandle">Region we're looking up</param>
  441. public void RequestMapItems(string httpserver, UUID id, uint flags,
  442. uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
  443. {
  444. MapRequestState st = new MapRequestState();
  445. st.agentID = id;
  446. st.flags = flags;
  447. st.EstateID = EstateID;
  448. st.godlike = godlike;
  449. st.itemtype = itemtype;
  450. st.regionhandle = regionhandle;
  451. EnqueueMapItemRequest(st);
  452. }
  453. /// <summary>
  454. /// Does the actual remote mapitem request
  455. /// This should be called from an asynchronous thread
  456. /// Request failures get blacklisted until region restart so we don't
  457. /// continue to spend resources trying to contact regions that are down.
  458. /// </summary>
  459. /// <param name="httpserver">blank string, we discover this in the process</param>
  460. /// <param name="id">Agent ID that we are making this request on behalf</param>
  461. /// <param name="flags">passed in from packet</param>
  462. /// <param name="EstateID">passed in from packet</param>
  463. /// <param name="godlike">passed in from packet</param>
  464. /// <param name="itemtype">passed in from packet</param>
  465. /// <param name="regionhandle">Region we're looking up</param>
  466. /// <returns></returns>
  467. private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags,
  468. uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
  469. {
  470. bool blacklisted = false;
  471. lock (m_blacklistedregions)
  472. {
  473. if (m_blacklistedregions.ContainsKey(regionhandle))
  474. blacklisted = true;
  475. }
  476. if (blacklisted)
  477. return new OSDMap();
  478. UUID requestID = UUID.Random();
  479. lock (m_cachedRegionMapItemsAddress)
  480. {
  481. if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
  482. httpserver = m_cachedRegionMapItemsAddress[regionhandle];
  483. }
  484. if (httpserver.Length == 0)
  485. {
  486. RegionInfo mreg = m_scene.SceneGridService.RequestNeighbouringRegionInfo(regionhandle);
  487. if (mreg != null)
  488. {
  489. httpserver = "http://" + mreg.ExternalEndPoint.Address.ToString() + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString();
  490. lock (m_cachedRegionMapItemsAddress)
  491. {
  492. if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
  493. m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver);
  494. }
  495. }
  496. else
  497. {
  498. lock (m_blacklistedregions)
  499. {
  500. if (!m_blacklistedregions.ContainsKey(regionhandle))
  501. m_blacklistedregions.Add(regionhandle, System.Environment.TickCount);
  502. }
  503. m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString());
  504. }
  505. }
  506. blacklisted = false;
  507. lock (m_blacklistedurls)
  508. {
  509. if (m_blacklistedurls.ContainsKey(httpserver))
  510. blacklisted = true;
  511. }
  512. // Can't find the http server
  513. if (httpserver.Length == 0 || blacklisted)
  514. return new OSDMap();
  515. MapRequestState mrs = new MapRequestState();
  516. mrs.agentID = id;
  517. mrs.EstateID = EstateID;
  518. mrs.flags = flags;
  519. mrs.godlike = godlike;
  520. mrs.itemtype=itemtype;
  521. mrs.regionhandle = regionhandle;
  522. lock (m_openRequests)
  523. m_openRequests.Add(requestID, mrs);
  524. WebRequest mapitemsrequest = WebRequest.Create(httpserver);
  525. mapitemsrequest.Method = "POST";
  526. mapitemsrequest.ContentType = "application/xml+llsd";
  527. OSDMap RAMap = new OSDMap();
  528. // string RAMapString = RAMap.ToString();
  529. OSD LLSDofRAMap = RAMap; // RENAME if this works
  530. byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
  531. OSDMap responseMap = new OSDMap();
  532. responseMap["requestID"] = OSD.FromUUID(requestID);
  533. Stream os = null;
  534. try
  535. { // send the Post
  536. mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send
  537. os = mapitemsrequest.GetRequestStream();
  538. os.Write(buffer, 0, buffer.Length); //Send it
  539. os.Close();
  540. //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver);
  541. }
  542. catch (WebException ex)
  543. {
  544. m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message);
  545. responseMap["connect"] = OSD.FromBoolean(false);
  546. lock (m_blacklistedurls)
  547. {
  548. if (!m_blacklistedurls.ContainsKey(httpserver))
  549. m_blacklistedurls.Add(httpserver, System.Environment.TickCount);
  550. }
  551. m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
  552. return responseMap;
  553. }
  554. string response_mapItems_reply = null;
  555. { // get the response
  556. try
  557. {
  558. WebResponse webResponse = mapitemsrequest.GetResponse();
  559. if (webResponse != null)
  560. {
  561. StreamReader sr = new StreamReader(webResponse.GetResponseStream());
  562. response_mapItems_reply = sr.ReadToEnd().Trim();
  563. }
  564. else
  565. {
  566. return new OSDMap();
  567. }
  568. }
  569. catch (WebException)
  570. {
  571. responseMap["connect"] = OSD.FromBoolean(false);
  572. lock (m_blacklistedurls)
  573. {
  574. if (!m_blacklistedurls.ContainsKey(httpserver))
  575. m_blacklistedurls.Add(httpserver, System.Environment.TickCount);
  576. }
  577. m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
  578. return responseMap;
  579. }
  580. OSD rezResponse = null;
  581. try
  582. {
  583. rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply);
  584. responseMap = (OSDMap)rezResponse;
  585. responseMap["requestID"] = OSD.FromUUID(requestID);
  586. }
  587. catch (Exception)
  588. {
  589. //m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message);
  590. responseMap["connect"] = OSD.FromBoolean(false);
  591. return responseMap;
  592. }
  593. }
  594. return responseMap;
  595. }
  596. /// <summary>
  597. /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
  598. /// </summary>
  599. /// <param name="minX"></param>
  600. /// <param name="minY"></param>
  601. /// <param name="maxX"></param>
  602. /// <param name="maxY"></param>
  603. public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
  604. {
  605. List<MapBlockData> mapBlocks;
  606. if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible
  607. {
  608. List<MapBlockData> response = new List<MapBlockData>();
  609. // this should return one mapblock at most. But make sure: Look whether the one we requested is in there
  610. mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY);
  611. if (mapBlocks != null)
  612. {
  613. foreach (MapBlockData block in mapBlocks)
  614. {
  615. if (block.X == minX && block.Y == minY)
  616. {
  617. // found it => add it to response
  618. response.Add(block);
  619. break;
  620. }
  621. }
  622. }
  623. if (response.Count == 0)
  624. {
  625. // response still empty => couldn't find the map-tile the user clicked on => tell the client
  626. MapBlockData block = new MapBlockData();
  627. block.X = (ushort)minX;
  628. block.Y = (ushort)minY;
  629. block.Access = 254; // == not there
  630. response.Add(block);
  631. }
  632. remoteClient.SendMapBlock(response, 0);
  633. }
  634. else
  635. {
  636. // normal mapblock request. Use the provided values
  637. mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, maxX + 4, maxY + 4);
  638. remoteClient.SendMapBlock(mapBlocks, flag);
  639. }
  640. }
  641. public Hashtable OnHTTPGetMapImage(Hashtable keysvals)
  642. {
  643. m_log.Debug("[WORLD MAP]: Sending map image jpeg");
  644. Hashtable reply = new Hashtable();
  645. int statuscode = 200;
  646. byte[] jpeg = new byte[0];
  647. if (myMapImageJPEG.Length == 0)
  648. {
  649. MemoryStream imgstream = new MemoryStream();
  650. Bitmap mapTexture = new Bitmap(1,1);
  651. ManagedImage managedImage;
  652. Image image = (Image)mapTexture;
  653. try
  654. {
  655. // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data
  656. imgstream = new MemoryStream();
  657. // non-async because we know we have the asset immediately.
  658. AssetBase mapasset = m_scene.AssetCache.GetAsset(m_scene.RegionInfo.lastMapUUID, true);
  659. // Decode image to System.Drawing.Image
  660. if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
  661. {
  662. // Save to bitmap
  663. mapTexture = new Bitmap(image);
  664. EncoderParameters myEncoderParameters = new EncoderParameters();
  665. myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
  666. // Save bitmap to stream
  667. mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
  668. // Write the stream to a byte array for output
  669. jpeg = imgstream.ToArray();
  670. myMapImageJPEG = jpeg;
  671. }
  672. }
  673. catch (Exception)
  674. {
  675. // Dummy!
  676. m_log.Warn("[WORLD MAP]: Unable to generate Map image");
  677. }
  678. finally
  679. {
  680. // Reclaim memory, these are unmanaged resources
  681. mapTexture.Dispose();
  682. image.Dispose();
  683. imgstream.Close();
  684. imgstream.Dispose();
  685. }
  686. }
  687. else
  688. {
  689. // Use cached version so we don't have to loose our mind
  690. jpeg = myMapImageJPEG;
  691. }
  692. reply["str_response_string"] = Convert.ToBase64String(jpeg);
  693. reply["int_response_code"] = statuscode;
  694. reply["content_type"] = "image/jpeg";
  695. return reply;
  696. }
  697. // From msdn
  698. private static ImageCodecInfo GetEncoderInfo(String mimeType)
  699. {
  700. ImageCodecInfo[] encoders;
  701. encoders = ImageCodecInfo.GetImageEncoders();
  702. for (int j = 0; j < encoders.Length; ++j)
  703. {
  704. if (encoders[j].MimeType == mimeType)
  705. return encoders[j];
  706. }
  707. return null;
  708. }
  709. public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint)
  710. {
  711. uint xstart = 0;
  712. uint ystart = 0;
  713. Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart);
  714. OSDMap responsemap = new OSDMap();
  715. List<ScenePresence> avatars = m_scene.GetAvatars();
  716. OSDArray responsearr = new OSDArray(avatars.Count);
  717. OSDMap responsemapdata = new OSDMap();
  718. int tc = System.Environment.TickCount;
  719. /*
  720. foreach (ScenePresence av in avatars)
  721. {
  722. responsemapdata = new OSDMap();
  723. responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X));
  724. responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y));
  725. responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
  726. responsemapdata["Name"] = OSD.FromString("TH");
  727. responsemapdata["Extra"] = OSD.FromInteger(0);
  728. responsemapdata["Extra2"] = OSD.FromInteger(0);
  729. responsearr.Add(responsemapdata);
  730. }
  731. responsemap["1"] = responsearr;
  732. */
  733. if (avatars.Count == 0)
  734. {
  735. responsemapdata = new OSDMap();
  736. responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
  737. responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
  738. responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
  739. responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
  740. responsemapdata["Extra"] = OSD.FromInteger(0);
  741. responsemapdata["Extra2"] = OSD.FromInteger(0);
  742. responsearr.Add(responsemapdata);
  743. responsemap["6"] = responsearr;
  744. }
  745. else
  746. {
  747. responsearr = new OSDArray(avatars.Count);
  748. foreach (ScenePresence av in avatars)
  749. {
  750. responsemapdata = new OSDMap();
  751. responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X));
  752. responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y));
  753. responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
  754. responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
  755. responsemapdata["Extra"] = OSD.FromInteger(1);
  756. responsemapdata["Extra2"] = OSD.FromInteger(0);
  757. responsearr.Add(responsemapdata);
  758. }
  759. responsemap["6"] = responsearr;
  760. }
  761. return responsemap;
  762. }
  763. private void MakeRootAgent(ScenePresence avatar)
  764. {
  765. // You may ask, why this is in a threadpool to start with..
  766. // The reason is so we don't cause the thread to freeze waiting
  767. // for the 1 second it costs to start a thread manually.
  768. if (!threadrunning)
  769. ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartThread));
  770. lock (m_rootAgents)
  771. {
  772. if (!m_rootAgents.Contains(avatar.UUID))
  773. {
  774. m_rootAgents.Add(avatar.UUID);
  775. }
  776. }
  777. }
  778. private void MakeChildAgent(ScenePresence avatar)
  779. {
  780. List<ScenePresence> presences = m_scene.GetAvatars();
  781. int rootcount = 0;
  782. for (int i = 0; i < presences.Count; i++)
  783. {
  784. if (presences[i] != null)
  785. {
  786. if (!presences[i].IsChildAgent)
  787. rootcount++;
  788. }
  789. }
  790. if (rootcount <= 1)
  791. StopThread();
  792. lock (m_rootAgents)
  793. {
  794. if (m_rootAgents.Contains(avatar.UUID))
  795. {
  796. m_rootAgents.Remove(avatar.UUID);
  797. }
  798. }
  799. }
  800. }
  801. public struct MapRequestState
  802. {
  803. public UUID agentID;
  804. public uint flags;
  805. public uint EstateID;
  806. public bool godlike;
  807. public uint itemtype;
  808. public ulong regionhandle;
  809. }
  810. }