ArchiveReadRequest.cs 56 KB

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