ArchiveReadRequest.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.IO.Compression;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Monitoring;
  39. using OpenSim.Framework.Serialization;
  40. using OpenSim.Framework.Serialization.External;
  41. using OpenSim.Region.CoreModules.World.Terrain;
  42. using OpenSim.Region.CoreModules.World.Land;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Scenes.Serialization;
  46. using OpenSim.Services.Interfaces;
  47. using System.Threading;
  48. namespace OpenSim.Region.CoreModules.World.Archiver
  49. {
  50. /// <summary>
  51. /// Handles an individual archive read request
  52. /// </summary>
  53. public class ArchiveReadRequest
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. /// <summary>
  57. /// Contains data used while dearchiving a single scene.
  58. /// </summary>
  59. private class DearchiveContext
  60. {
  61. public Scene Scene { get; set; }
  62. public List<string> SerialisedSceneObjects { get; set; }
  63. public List<string> SerialisedParcels { get; set; }
  64. public List<SceneObjectGroup> SceneObjects { get; set; }
  65. public DearchiveContext(Scene scene)
  66. {
  67. Scene = scene;
  68. SerialisedSceneObjects = new List<string>();
  69. SerialisedParcels = new List<string>();
  70. SceneObjects = new List<SceneObjectGroup>();
  71. }
  72. }
  73. /// <summary>
  74. /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
  75. /// bumps here should be compatible.
  76. /// </summary>
  77. public static int MAX_MAJOR_VERSION = 1;
  78. /// <summary>
  79. /// Has the control file been loaded for this archive?
  80. /// </summary>
  81. public bool ControlFileLoaded { get; private set; }
  82. protected string m_loadPath;
  83. protected Scene m_rootScene;
  84. protected Stream m_loadStream;
  85. protected Guid m_requestId;
  86. protected string m_errorMessage;
  87. /// <value>
  88. /// Should the archive being loaded be merged with what is already on the region?
  89. /// Merging usually suppresses terrain and parcel loading
  90. /// </value>
  91. protected bool m_merge;
  92. /// <value>
  93. /// If true, force the loading of terrain from the oar file
  94. /// </value>
  95. protected bool m_forceTerrain;
  96. /// <value>
  97. /// If true, force the loading of parcels from the oar file
  98. /// </value>
  99. protected bool m_forceParcels;
  100. /// <value>
  101. /// Should we ignore any assets when reloading the archive?
  102. /// </value>
  103. protected bool m_skipAssets;
  104. /// <value>
  105. /// Displacement added to each object as it is added to the world
  106. /// </value>
  107. protected Vector3 m_displacement = Vector3.Zero;
  108. /// <value>
  109. /// Rotation (in radians) to apply to the objects as they are loaded.
  110. /// </value>
  111. protected float m_rotation = 0f;
  112. /// <value>
  113. /// original oar region size. not using Constants.RegionSize
  114. /// </value>
  115. protected Vector3 m_incomingRegionSize = new Vector3(256f, 256f, float.MaxValue);
  116. /// <value>
  117. /// Center around which to apply the rotation relative to the original oar position
  118. /// </value>
  119. protected Vector3 m_rotationCenter = new Vector3(128f, 128f, 0f);
  120. /// <value>
  121. /// Corner 1 of a bounding cuboid which specifies which objects we load from the oar
  122. /// </value>
  123. protected Vector3 m_boundingOrigin = Vector3.Zero;
  124. /// <value>
  125. /// Size of a bounding cuboid which specifies which objects we load from the oar
  126. /// </value>
  127. protected Vector3 m_boundingSize = new Vector3(Constants.MaximumRegionSize, Constants.MaximumRegionSize, float.MaxValue);
  128. protected bool m_noObjects = false;
  129. protected bool m_boundingBox = false;
  130. protected bool m_debug = false;
  131. /// <summary>
  132. /// Used to cache lookups for valid uuids.
  133. /// </summary>
  134. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  135. private IUserManagement m_UserMan;
  136. private IUserManagement UserManager
  137. {
  138. get
  139. {
  140. if (m_UserMan == null)
  141. {
  142. m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>();
  143. }
  144. return m_UserMan;
  145. }
  146. }
  147. /// <summary>
  148. /// Used to cache lookups for valid groups.
  149. /// </summary>
  150. private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>();
  151. private IGroupsModule m_groupsModule;
  152. private IAssetService m_assetService = null;
  153. private UUID m_defaultUser;
  154. public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string, object> options)
  155. {
  156. m_rootScene = scene;
  157. if (options.ContainsKey("default-user"))
  158. {
  159. m_defaultUser = (UUID)options["default-user"];
  160. m_log.InfoFormat("Using User {0} as default user", m_defaultUser.ToString());
  161. }
  162. else
  163. {
  164. m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
  165. }
  166. m_loadPath = loadPath;
  167. try
  168. {
  169. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
  170. }
  171. catch (EntryPointNotFoundException e)
  172. {
  173. m_log.ErrorFormat(
  174. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  175. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  176. m_log.Error(e);
  177. }
  178. m_errorMessage = String.Empty;
  179. m_merge = options.ContainsKey("merge");
  180. m_forceTerrain = options.ContainsKey("force-terrain");
  181. m_forceParcels = options.ContainsKey("force-parcels");
  182. m_noObjects = options.ContainsKey("no-objects");
  183. m_skipAssets = options.ContainsKey("skipAssets");
  184. m_requestId = requestId;
  185. m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero;
  186. m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f;
  187. m_boundingOrigin = Vector3.Zero;
  188. m_boundingSize = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, float.MaxValue);
  189. if (options.ContainsKey("bounding-origin"))
  190. {
  191. Vector3 boOption = (Vector3)options["bounding-origin"];
  192. if (boOption != m_boundingOrigin)
  193. {
  194. m_boundingOrigin = boOption;
  195. }
  196. m_boundingBox = true;
  197. }
  198. if (options.ContainsKey("bounding-size"))
  199. {
  200. Vector3 bsOption = (Vector3)options["bounding-size"];
  201. bool clip = false;
  202. if (bsOption.X <= 0 || bsOption.X > m_boundingSize.X)
  203. {
  204. bsOption.X = m_boundingSize.X;
  205. clip = true;
  206. }
  207. if (bsOption.Y <= 0 || bsOption.Y > m_boundingSize.Y)
  208. {
  209. bsOption.Y = m_boundingSize.Y;
  210. clip = true;
  211. }
  212. if (bsOption != m_boundingSize)
  213. {
  214. m_boundingSize = bsOption;
  215. m_boundingBox = true;
  216. }
  217. if (clip) m_log.InfoFormat("[ARCHIVER]: The bounding cube specified is larger than the destination region! Clipping to {0}.", m_boundingSize.ToString());
  218. }
  219. m_debug = options.ContainsKey("debug");
  220. // Zero can never be a valid user id (or group)
  221. m_validUserUuids[UUID.Zero] = false;
  222. m_validGroupUuids[UUID.Zero] = false;
  223. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  224. m_assetService = m_rootScene.AssetService;
  225. }
  226. public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object> options)
  227. {
  228. m_rootScene = scene;
  229. m_loadPath = null;
  230. m_loadStream = loadStream;
  231. m_skipAssets = options.ContainsKey("skipAssets");
  232. m_merge = options.ContainsKey("merge");
  233. m_requestId = requestId;
  234. m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
  235. // Zero can never be a valid user id
  236. m_validUserUuids[UUID.Zero] = false;
  237. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  238. m_assetService = m_rootScene.AssetService;
  239. }
  240. /// <summary>
  241. /// Dearchive the region embodied in this request.
  242. /// </summary>
  243. public void DearchiveRegion()
  244. {
  245. DearchiveRegion(true);
  246. }
  247. public void DearchiveRegion(bool shouldStartScripts)
  248. {
  249. int successfulAssetRestores = 0;
  250. int failedAssetRestores = 0;
  251. DearchiveScenesInfo dearchivedScenes;
  252. // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
  253. // Therefore, we have to keep track of the dearchive context of all the scenes.
  254. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
  255. string fullPath = "NONE";
  256. TarArchiveReader archive = null;
  257. byte[] data;
  258. TarArchiveReader.TarEntryType entryType;
  259. try
  260. {
  261. FindAndLoadControlFile(out archive, out dearchivedScenes);
  262. while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
  263. {
  264. //m_log.DebugFormat(
  265. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  266. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  267. continue;
  268. // Find the scene that this file belongs to
  269. Scene scene;
  270. string filePath;
  271. if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
  272. continue; // this file belongs to a region that we're not loading
  273. DearchiveContext sceneContext = null;
  274. if (scene != null)
  275. {
  276. if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
  277. {
  278. sceneContext = new DearchiveContext(scene);
  279. sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
  280. }
  281. }
  282. // Process the file
  283. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects)
  284. {
  285. sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  286. }
  287. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  288. {
  289. if (LoadAsset(filePath, data))
  290. successfulAssetRestores++;
  291. else
  292. failedAssetRestores++;
  293. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  294. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  295. }
  296. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_forceTerrain))
  297. {
  298. LoadTerrain(scene, filePath, data);
  299. }
  300. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  301. {
  302. LoadRegionSettings(scene, filePath, data, dearchivedScenes);
  303. }
  304. else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_forceParcels))
  305. {
  306. sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
  307. }
  308. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  309. {
  310. // Ignore, because we already read the control file
  311. }
  312. }
  313. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  314. }
  315. catch (Exception e)
  316. {
  317. m_log.Error(
  318. String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
  319. m_errorMessage += e.ToString();
  320. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  321. return;
  322. }
  323. finally
  324. {
  325. if (archive != null)
  326. archive.Close();
  327. }
  328. if (!m_skipAssets)
  329. {
  330. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  331. if (failedAssetRestores > 0)
  332. {
  333. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  334. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  335. }
  336. }
  337. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  338. {
  339. m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
  340. if (!m_merge)
  341. {
  342. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  343. sceneContext.Scene.DeleteAllSceneObjects();
  344. }
  345. try
  346. {
  347. LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
  348. LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
  349. // Inform any interested parties that the region has changed. We waited until now so that all
  350. // of the region's objects will be loaded when we send this notification.
  351. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
  352. if (estateModule != null)
  353. estateModule.TriggerRegionInfoChange();
  354. }
  355. catch (Exception e)
  356. {
  357. m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
  358. m_errorMessage += e.ToString();
  359. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  360. return;
  361. }
  362. }
  363. // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
  364. // that users can enter the scene. If we allow the scripts to start in the loop above
  365. // then they significantly increase the time until the OAR finishes loading.
  366. if (shouldStartScripts)
  367. {
  368. WorkManager.RunInThread(o =>
  369. {
  370. Thread.Sleep(15000);
  371. m_log.Info("[ARCHIVER]: Starting scripts in scene objects...");
  372. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  373. {
  374. foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
  375. {
  376. sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
  377. sceneObject.ResumeScripts();
  378. }
  379. sceneContext.SceneObjects.Clear();
  380. }
  381. m_log.Info("[ARCHIVER]: Start scripts done");
  382. }, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId));
  383. }
  384. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  385. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
  386. }
  387. /// <summary>
  388. /// Searches through the files in the archive for the control file, and reads it.
  389. /// We must read the control file first, in order to know which regions are available.
  390. /// </summary>
  391. /// <remarks>
  392. /// In most cases the control file *is* first, since that's how we create archives. However,
  393. /// it's possible that someone rewrote the archive externally so we can't rely on this fact.
  394. /// </remarks>
  395. /// <param name="archive"></param>
  396. /// <param name="dearchivedScenes"></param>
  397. private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes)
  398. {
  399. archive = new TarArchiveReader(m_loadStream);
  400. dearchivedScenes = new DearchiveScenesInfo();
  401. string filePath;
  402. byte[] data;
  403. TarArchiveReader.TarEntryType entryType;
  404. bool firstFile = true;
  405. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  406. {
  407. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  408. continue;
  409. if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  410. {
  411. LoadControlFile(filePath, data, dearchivedScenes);
  412. // Find which scenes are available in the simulator
  413. ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup();
  414. SceneManager.Instance.ForEachScene(delegate(Scene scene2)
  415. {
  416. simulatorScenes.AddScene(scene2);
  417. });
  418. simulatorScenes.CalcSceneLocations();
  419. dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes);
  420. // If the control file wasn't the first file then reset the read pointer
  421. if (!firstFile)
  422. {
  423. m_log.Warn("[ARCHIVER]: Control file wasn't the first file in the archive");
  424. if (m_loadStream.CanSeek)
  425. {
  426. m_loadStream.Seek(0, SeekOrigin.Begin);
  427. }
  428. else if (m_loadPath != null)
  429. {
  430. archive.Close();
  431. archive = null;
  432. m_loadStream.Close();
  433. m_loadStream = null;
  434. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress);
  435. archive = new TarArchiveReader(m_loadStream);
  436. }
  437. else
  438. {
  439. // There isn't currently a scenario where this happens, but it's best to add a check just in case
  440. throw new Exception("[ARCHIVER]: Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking");
  441. }
  442. }
  443. return;
  444. }
  445. firstFile = false;
  446. }
  447. throw new Exception("[ARCHIVER]: Control file not found");
  448. }
  449. /// <summary>
  450. /// Load serialized scene objects.
  451. /// </summary>
  452. protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects)
  453. {
  454. // Reload serialized prims
  455. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  456. // Convert rotation to radians
  457. double rotation = Math.PI * m_rotation / 180f;
  458. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, (float)rotation);
  459. UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
  460. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  461. int sceneObjectsLoadedCount = 0;
  462. Vector3 boundingExtent = new Vector3(m_boundingOrigin.X + m_boundingSize.X, m_boundingOrigin.Y + m_boundingSize.Y, m_boundingOrigin.Z + m_boundingSize.Z);
  463. foreach (string serialisedSceneObject in serialisedSceneObjects)
  464. {
  465. /*
  466. m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
  467. // Really large xml files (multi megabyte) appear to cause
  468. // memory problems
  469. // when loading the xml. But don't enable this check yet
  470. if (serialisedSceneObject.Length > 5000000)
  471. {
  472. m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
  473. continue;
  474. }
  475. */
  476. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  477. Vector3 pos = sceneObject.AbsolutePosition;
  478. if (m_debug)
  479. m_log.DebugFormat("[ARCHIVER]: Loading object from OAR with original scene position {0}.", pos.ToString());
  480. // Happily this does not do much to the object since it hasn't been added to the scene yet
  481. if (!sceneObject.IsAttachment)
  482. {
  483. if (m_rotation != 0f)
  484. {
  485. //fix the rotation center to the middle of the incoming region now as it's otherwise hopelessly confusing on varRegions
  486. //as it only works with objects and terrain (using old Merge method) and not parcels
  487. m_rotationCenter.X = m_incomingRegionSize.X / 2;
  488. m_rotationCenter.Y = m_incomingRegionSize.Y / 2;
  489. // Rotate the object
  490. sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
  491. // Get object position relative to rotation axis
  492. Vector3 offset = pos - m_rotationCenter;
  493. // Rotate the object position
  494. offset *= rot;
  495. // Restore the object position back to relative to the region
  496. pos = m_rotationCenter + offset;
  497. if (m_debug) m_log.DebugFormat("[ARCHIVER]: After rotation, object from OAR is at scene position {0}.", pos.ToString());
  498. }
  499. if (m_boundingBox)
  500. {
  501. if (pos.X < m_boundingOrigin.X || pos.X >= boundingExtent.X
  502. || pos.Y < m_boundingOrigin.Y || pos.Y >= boundingExtent.Y
  503. || pos.Z < m_boundingOrigin.Z || pos.Z >= boundingExtent.Z)
  504. {
  505. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Skipping object from OAR in scene because it's position {0} is outside of bounding cube.", pos.ToString());
  506. continue;
  507. }
  508. //adjust object position to be relative to <0,0> so we can apply the displacement
  509. pos.X -= m_boundingOrigin.X;
  510. pos.Y -= m_boundingOrigin.Y;
  511. }
  512. if (m_displacement != Vector3.Zero)
  513. {
  514. pos += m_displacement;
  515. if (m_debug) m_log.DebugFormat("[ARCHIVER]: After displacement, object from OAR is at scene position {0}.", pos.ToString());
  516. }
  517. sceneObject.AbsolutePosition = pos;
  518. }
  519. if (m_debug)
  520. m_log.DebugFormat("[ARCHIVER]: Placing object from OAR in scene at position {0}. ", pos.ToString());
  521. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  522. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  523. // on the same region server and multiple examples a single object archive to be imported
  524. // to the same scene (when this is possible).
  525. sceneObject.ResetIDs();
  526. if (isTelehub)
  527. {
  528. // Change the Telehub Object to the new UUID
  529. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  530. scene.RegionInfo.RegionSettings.Save();
  531. oldTelehubUUID = UUID.Zero;
  532. }
  533. ModifySceneObject(scene, sceneObject);
  534. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  535. {
  536. sceneObjectsLoadedCount++;
  537. sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  538. sceneObject.ResumeScripts();
  539. }
  540. }
  541. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  542. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  543. if (ignoredObjects > 0)
  544. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene or were out of bounds", ignoredObjects);
  545. if (oldTelehubUUID != UUID.Zero)
  546. {
  547. m_log.WarnFormat("[ARCHIVER]: Telehub object not found: {0}", oldTelehubUUID);
  548. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  549. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  550. }
  551. }
  552. /// <summary>
  553. /// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the
  554. /// User IDs and Group IDs are valid, but other manipulations could be done as well.
  555. /// </summary>
  556. private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject)
  557. {
  558. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  559. // or creator data is present. Otherwise, use the estate owner instead.
  560. foreach (SceneObjectPart part in sceneObject.Parts)
  561. {
  562. if (string.IsNullOrEmpty(part.CreatorData))
  563. {
  564. if (!ResolveUserUuid(scene, part.CreatorID))
  565. part.CreatorID = m_defaultUser;
  566. }
  567. if (UserManager != null)
  568. UserManager.AddUser(part.CreatorID, part.CreatorData);
  569. if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID)))
  570. part.OwnerID = m_defaultUser;
  571. if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID)))
  572. part.LastOwnerID = m_defaultUser;
  573. if (!ResolveGroupUuid(part.GroupID))
  574. part.GroupID = UUID.Zero;
  575. // And zap any troublesome sit target information
  576. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  577. // part.SitTargetPosition = new Vector3(0, 0, 0);
  578. // Fix ownership/creator of inventory items
  579. // Not doing so results in inventory items
  580. // being no copy/no mod for everyone
  581. lock (part.TaskInventory)
  582. {
  583. /* avination code disabled for opensim
  584. // And zap any troublesome sit target information
  585. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  586. part.SitTargetPosition = new Vector3(0, 0, 0);
  587. */
  588. // Fix ownership/creator of inventory items
  589. // Not doing so results in inventory items
  590. // being no copy/no mod for everyone
  591. part.TaskInventory.LockItemsForRead(true);
  592. TaskInventoryDictionary inv = part.TaskInventory;
  593. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  594. {
  595. if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID)))
  596. {
  597. kvp.Value.OwnerID = m_defaultUser;
  598. }
  599. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  600. {
  601. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  602. kvp.Value.CreatorID = m_defaultUser;
  603. }
  604. if (UserManager != null)
  605. UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  606. if (!ResolveGroupUuid(kvp.Value.GroupID))
  607. kvp.Value.GroupID = UUID.Zero;
  608. }
  609. part.TaskInventory.LockItemsForRead(false);
  610. }
  611. }
  612. }
  613. /// <summary>
  614. /// Load serialized parcels.
  615. /// </summary>
  616. /// <param name="scene"></param>
  617. /// <param name="serialisedParcels"></param>
  618. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  619. {
  620. // Reload serialized parcels
  621. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  622. List<LandData> landData = new List<LandData>();
  623. ILandObject landObject = scene.RequestModuleInterface<ILandObject>();
  624. List<ILandObject> parcels;
  625. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  626. Vector2 displacement = new Vector2(m_displacement.X, m_displacement.Y);
  627. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  628. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  629. Vector2 regionSize = new Vector2(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY);
  630. // Gather any existing parcels before we add any more. Later as we add parcels we can check if the new parcel
  631. // data overlays any of the old data, and we can modify and remove (if empty) the old parcel so that there's no conflict
  632. parcels = scene.LandChannel.AllParcels();
  633. foreach (string serialisedParcel in serialisedParcels)
  634. {
  635. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  636. bool overrideRegionSize = true; //use the src land parcel data size not the dst region size
  637. bool isEmptyNow;
  638. Vector3 AABBMin;
  639. Vector3 AABBMax;
  640. // create a new LandObject that we can use to manipulate the incoming source parcel data
  641. // this is ok, but just beware that some of the LandObject functions (that we haven't used here) still
  642. // assume we're always using the destination region size
  643. LandData ld = new LandData();
  644. landObject = new LandObject(ld, scene);
  645. landObject.LandData = parcel;
  646. bool[,] srcLandBitmap = landObject.ConvertBytesToLandBitmap(overrideRegionSize);
  647. if (landObject.IsLandBitmapEmpty(srcLandBitmap))
  648. {
  649. m_log.InfoFormat("[ARCHIVER]: Skipping source parcel {0} with GlobalID: {1} LocalID: {2} that has no claimed land.",
  650. parcel.Name, parcel.GlobalID, parcel.LocalID);
  651. continue;
  652. }
  653. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for source parcel: {0} with GlobalID: {1} LocalID: {2}.",
  654. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  655. //landObject.DebugLandBitmap(srcLandBitmap);
  656. bool[,] dstLandBitmap = landObject.RemapLandBitmap(srcLandBitmap, displacement, m_rotation, boundingOrigin, boundingSize, regionSize, out isEmptyNow, out AABBMin, out AABBMax);
  657. if (isEmptyNow)
  658. {
  659. m_log.WarnFormat("[ARCHIVER]: Not adding destination parcel {0} with GlobalID: {1} LocalID: {2} because, after applying rotation, bounding and displacement, it has no claimed land.",
  660. parcel.Name, parcel.GlobalID, parcel.LocalID);
  661. continue;
  662. }
  663. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for destination parcel: {0} with GlobalID: {1} LocalID: {2} after applying rotation, bounding and displacement.",
  664. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  665. //landObject.DebugLandBitmap(dstLandBitmap);
  666. landObject.LandBitmap = dstLandBitmap;
  667. parcel.Bitmap = landObject.ConvertLandBitmapToBytes();
  668. parcel.AABBMin = AABBMin;
  669. parcel.AABBMax = AABBMax;
  670. if (m_merge)
  671. {
  672. // give the remapped parcel a new GlobalID, in case we're using the same OAR twice and a bounding cube, displacement and --merge
  673. parcel.GlobalID = UUID.Random();
  674. //now check if the area of this new incoming parcel overlays an area in any existing parcels
  675. //and if so modify or lose the existing parcels
  676. for (int i = 0; i < parcels.Count; i++)
  677. {
  678. if (parcels[i] != null)
  679. {
  680. bool[,] modLandBitmap = parcels[i].ConvertBytesToLandBitmap(overrideRegionSize);
  681. modLandBitmap = parcels[i].RemoveFromLandBitmap(modLandBitmap, dstLandBitmap, out isEmptyNow, out AABBMin, out AABBMax);
  682. if (isEmptyNow)
  683. {
  684. parcels[i] = null;
  685. }
  686. else
  687. {
  688. parcels[i].LandBitmap = modLandBitmap;
  689. parcels[i].LandData.Bitmap = parcels[i].ConvertLandBitmapToBytes();
  690. parcels[i].LandData.AABBMin = AABBMin;
  691. parcels[i].LandData.AABBMax = AABBMax;
  692. }
  693. }
  694. }
  695. }
  696. // Validate User and Group UUID's
  697. if (!ResolveGroupUuid(parcel.GroupID))
  698. parcel.GroupID = UUID.Zero;
  699. if (parcel.IsGroupOwned)
  700. {
  701. if (parcel.GroupID != UUID.Zero)
  702. {
  703. // In group-owned parcels, OwnerID=GroupID. This should already be the case, but let's make sure.
  704. parcel.OwnerID = parcel.GroupID;
  705. }
  706. else
  707. {
  708. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  709. parcel.IsGroupOwned = false;
  710. }
  711. }
  712. else
  713. {
  714. if (!ResolveUserUuid(scene, parcel.OwnerID))
  715. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  716. }
  717. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  718. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  719. {
  720. if (ResolveUserUuid(scene, entry.AgentID))
  721. accessList.Add(entry);
  722. // else, drop this access rule
  723. }
  724. parcel.ParcelAccessList = accessList;
  725. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  726. parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  727. landData.Add(parcel);
  728. }
  729. if (m_merge)
  730. {
  731. for (int i = 0; i < parcels.Count; i++) //if merging then we need to also add back in any existing parcels
  732. {
  733. if (parcels[i] != null) landData.Add(parcels[i].LandData);
  734. }
  735. }
  736. m_log.InfoFormat("[ARCHIVER]: Clearing {0} parcels.", parcels.Count);
  737. bool setupDefaultParcel = (landData.Count == 0);
  738. scene.LandChannel.Clear(setupDefaultParcel);
  739. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  740. m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
  741. }
  742. /// <summary>
  743. /// Look up the given user id to check whether it's one that is valid for this grid.
  744. /// </summary>
  745. /// <param name="scene"></param>
  746. /// <param name="uuid"></param>
  747. /// <returns></returns>
  748. private bool ResolveUserUuid(Scene scene, UUID uuid)
  749. {
  750. lock (m_validUserUuids)
  751. {
  752. if (!m_validUserUuids.ContainsKey(uuid))
  753. {
  754. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  755. // to occur many times, and we only want to query the users service once.
  756. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  757. m_validUserUuids.Add(uuid, account != null);
  758. }
  759. return m_validUserUuids[uuid];
  760. }
  761. }
  762. /// <summary>
  763. /// Look up the given group id to check whether it's one that is valid for this grid.
  764. /// </summary>
  765. /// <param name="uuid"></param>
  766. /// <returns></returns>
  767. private bool ResolveGroupUuid(UUID uuid)
  768. {
  769. lock (m_validGroupUuids)
  770. {
  771. if (!m_validGroupUuids.ContainsKey(uuid))
  772. {
  773. bool exists;
  774. if (m_groupsModule == null)
  775. {
  776. exists = false;
  777. }
  778. else
  779. {
  780. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  781. // to occur many times, and we only want to query the groups service once.
  782. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  783. }
  784. m_validGroupUuids.Add(uuid, exists);
  785. }
  786. return m_validGroupUuids[uuid];
  787. }
  788. }
  789. /// Load an asset
  790. /// </summary>
  791. /// <param name="assetFilename"></param>
  792. /// <param name="data"></param>
  793. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  794. private bool LoadAsset(string assetPath, byte[] data)
  795. {
  796. // Right now we're nastily obtaining the UUID from the filename
  797. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  798. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  799. if (i == -1)
  800. {
  801. m_log.ErrorFormat(
  802. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  803. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  804. return false;
  805. }
  806. string extension = filename.Substring(i);
  807. string uuid = filename.Remove(filename.Length - extension.Length);
  808. if (m_assetService.GetMetadata(uuid) != null)
  809. {
  810. sbyte asype = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  811. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  812. return true;
  813. }
  814. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  815. {
  816. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  817. if (assetType == (sbyte)AssetType.Unknown)
  818. {
  819. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  820. }
  821. else if (assetType == (sbyte)AssetType.Object)
  822. {
  823. data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data,
  824. sog =>
  825. {
  826. ModifySceneObject(m_rootScene, sog);
  827. return true;
  828. });
  829. if (data == null)
  830. return false;
  831. }
  832. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  833. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  834. asset.Data = data;
  835. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  836. // exists.
  837. m_assetService.Store(asset);
  838. /**
  839. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  840. * it might be best done when dearchive takes place on a separate thread
  841. if (asset.Type=AssetType.Texture)
  842. {
  843. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  844. if (cacheLayerDecode != null)
  845. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  846. }
  847. */
  848. return true;
  849. }
  850. else
  851. {
  852. m_log.ErrorFormat(
  853. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  854. assetPath, extension);
  855. return false;
  856. }
  857. }
  858. /// <summary>
  859. /// Load region settings data
  860. /// </summary>
  861. /// <param name="scene"></param>
  862. /// <param name="settingsPath"></param>
  863. /// <param name="data"></param>
  864. /// <param name="dearchivedScenes"></param>
  865. /// <returns>
  866. /// true if settings were loaded successfully, false otherwise
  867. /// </returns>
  868. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  869. {
  870. RegionSettings loadedRegionSettings;
  871. try
  872. {
  873. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  874. }
  875. catch (Exception e)
  876. {
  877. m_log.ErrorFormat(
  878. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  879. settingsPath, e);
  880. return false;
  881. }
  882. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  883. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  884. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  885. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  886. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  887. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  888. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  889. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  890. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  891. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  892. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  893. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  894. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  895. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  896. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  897. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  898. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  899. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  900. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  901. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  902. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  903. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  904. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  905. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  906. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  907. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  908. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  909. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  910. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  911. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  912. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  913. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  914. currentRegionSettings.ClearSpawnPoints();
  915. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  916. currentRegionSettings.AddSpawnPoint(sp);
  917. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  918. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  919. currentRegionSettings.Save();
  920. scene.TriggerEstateSunUpdate();
  921. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  922. if (estateModule != null)
  923. estateModule.sendRegionHandshakeToAll();
  924. return true;
  925. }
  926. /// <summary>
  927. /// Load terrain data
  928. /// </summary>
  929. /// <param name="scene"></param>
  930. /// <param name="terrainPath"></param>
  931. /// <param name="data"></param>
  932. /// <returns>
  933. /// true if terrain was resolved successfully, false otherwise.
  934. /// </returns>
  935. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  936. {
  937. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  938. using (MemoryStream ms = new MemoryStream(data))
  939. {
  940. if (m_displacement != Vector3.Zero || m_rotation != 0f || m_boundingBox)
  941. {
  942. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  943. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  944. terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, boundingOrigin, boundingSize, ms); ;
  945. }
  946. else
  947. {
  948. terrainModule.LoadFromStream(terrainPath, ms);
  949. }
  950. }
  951. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  952. return true;
  953. }
  954. /// <summary>
  955. /// Load oar control file
  956. /// </summary>
  957. /// <param name="path"></param>
  958. /// <param name="data"></param>
  959. /// <param name="dearchivedScenes"></param>
  960. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  961. {
  962. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  963. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  964. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  965. // Loaded metadata will be empty if no information exists in the archive
  966. dearchivedScenes.LoadedCreationDateTime = 0;
  967. dearchivedScenes.DefaultOriginalID = "";
  968. bool multiRegion = false;
  969. while (xtr.Read())
  970. {
  971. if (xtr.NodeType == XmlNodeType.Element)
  972. {
  973. if (xtr.Name.ToString() == "archive")
  974. {
  975. int majorVersion = int.Parse(xtr["major_version"]);
  976. int minorVersion = int.Parse(xtr["minor_version"]);
  977. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  978. if (majorVersion > MAX_MAJOR_VERSION)
  979. {
  980. throw new Exception(
  981. string.Format(
  982. "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
  983. majorVersion, MAX_MAJOR_VERSION));
  984. }
  985. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  986. }
  987. else if (xtr.Name.ToString() == "datetime")
  988. {
  989. int value;
  990. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  991. dearchivedScenes.LoadedCreationDateTime = value;
  992. }
  993. else if (xtr.Name.ToString() == "row")
  994. {
  995. multiRegion = true;
  996. dearchivedScenes.StartRow();
  997. }
  998. else if (xtr.Name.ToString() == "region")
  999. {
  1000. dearchivedScenes.StartRegion();
  1001. }
  1002. else if (xtr.Name.ToString() == "id")
  1003. {
  1004. string id = xtr.ReadElementContentAsString();
  1005. dearchivedScenes.DefaultOriginalID = id;
  1006. if(multiRegion)
  1007. dearchivedScenes.SetRegionOriginalID(id);
  1008. }
  1009. else if (xtr.Name.ToString() == "dir")
  1010. {
  1011. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  1012. }
  1013. else if (xtr.Name.ToString() == "size_in_meters")
  1014. {
  1015. Vector3 value;
  1016. string size = "<" + xtr.ReadElementContentAsString() + ",0>";
  1017. if (Vector3.TryParse(size, out value))
  1018. {
  1019. m_incomingRegionSize = value;
  1020. if(multiRegion)
  1021. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1022. m_log.DebugFormat("[ARCHIVER]: Found region_size info {0}",
  1023. m_incomingRegionSize.ToString());
  1024. }
  1025. }
  1026. }
  1027. }
  1028. dearchivedScenes.MultiRegionFormat = multiRegion;
  1029. if (!multiRegion)
  1030. {
  1031. // Add the single scene
  1032. dearchivedScenes.StartRow();
  1033. dearchivedScenes.StartRegion();
  1034. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  1035. dearchivedScenes.SetRegionDirectory("");
  1036. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1037. }
  1038. ControlFileLoaded = true;
  1039. if(xtr != null)
  1040. xtr.Close();
  1041. return dearchivedScenes;
  1042. }
  1043. }
  1044. }