aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs
diff options
context:
space:
mode:
authorJohn Hurliman2010-09-11 20:43:06 -0700
committerJohn Hurliman2010-09-11 20:43:06 -0700
commit109b51758398d24a96a16900e8feb24361aee29d (patch)
treeaa696571c44fcf7afdad1931137a51f3074cd524 /OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs
parentRe-enabled asset last access time logging in MySQL (diff)
downloadopensim-SC_OLD-109b51758398d24a96a16900e8feb24361aee29d.zip
opensim-SC_OLD-109b51758398d24a96a16900e8feb24361aee29d.tar.gz
opensim-SC_OLD-109b51758398d24a96a16900e8feb24361aee29d.tar.bz2
opensim-SC_OLD-109b51758398d24a96a16900e8feb24361aee29d.tar.xz
Fixed the naming mess around data connectors for simulation data
Diffstat (limited to 'OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs')
-rw-r--r--OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs2261
1 files changed, 2261 insertions, 0 deletions
diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs
new file mode 100644
index 0000000..878117e
--- /dev/null
+++ b/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs
@@ -0,0 +1,2261 @@
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
28using System;
29using System.Collections.Generic;
30using System.Data;
31using System.Drawing;
32using System.IO;
33using System.Reflection;
34using log4net;
35using Mono.Data.SqliteClient;
36using OpenMetaverse;
37using OpenSim.Framework;
38using OpenSim.Region.Framework.Interfaces;
39using OpenSim.Region.Framework.Scenes;
40
41namespace OpenSim.Data.SQLiteLegacy
42{
43 /// <summary>
44 /// A RegionData Interface to the SQLite database
45 /// </summary>
46 public class SQLiteSimulationData : ISimulationDataStore
47 {
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49
50 private const string primSelect = "select * from prims";
51 private const string shapeSelect = "select * from primshapes";
52 private const string itemsSelect = "select * from primitems";
53 private const string terrainSelect = "select * from terrain limit 1";
54 private const string landSelect = "select * from land";
55 private const string landAccessListSelect = "select distinct * from landaccesslist";
56 private const string regionbanListSelect = "select * from regionban";
57 private const string regionSettingsSelect = "select * from regionsettings";
58
59 private DataSet ds;
60 private SqliteDataAdapter primDa;
61 private SqliteDataAdapter shapeDa;
62 private SqliteDataAdapter itemsDa;
63 private SqliteDataAdapter terrainDa;
64 private SqliteDataAdapter landDa;
65 private SqliteDataAdapter landAccessListDa;
66 private SqliteDataAdapter regionSettingsDa;
67
68 private SqliteConnection m_conn;
69
70 private String m_connectionString;
71
72 // Temporary attribute while this is experimental
73
74 /***********************************************************************
75 *
76 * Public Interface Functions
77 *
78 **********************************************************************/
79
80 /// <summary>
81 /// See IRegionDataStore
82 /// <list type="bullet">
83 /// <item>Initialises RegionData Interface</item>
84 /// <item>Loads and initialises a new SQLite connection and maintains it.</item>
85 /// </list>
86 /// </summary>
87 /// <param name="connectionString">the connection string</param>
88 public void Initialise(string connectionString)
89 {
90 m_connectionString = connectionString;
91
92 ds = new DataSet();
93
94 m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString);
95 m_conn = new SqliteConnection(m_connectionString);
96 m_conn.Open();
97
98
99
100 SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn);
101 primDa = new SqliteDataAdapter(primSelectCmd);
102 // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);
103
104 SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn);
105 shapeDa = new SqliteDataAdapter(shapeSelectCmd);
106 // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa);
107
108 SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn);
109 itemsDa = new SqliteDataAdapter(itemsSelectCmd);
110
111 SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn);
112 terrainDa = new SqliteDataAdapter(terrainSelectCmd);
113
114 SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn);
115 landDa = new SqliteDataAdapter(landSelectCmd);
116
117 SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn);
118 landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd);
119
120 SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn);
121 regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd);
122 // This actually does the roll forward assembly stuff
123 Assembly assem = GetType().Assembly;
124 Migration m = new Migration(m_conn, assem, "RegionStore");
125 m.Update();
126
127 lock (ds)
128 {
129 ds.Tables.Add(createPrimTable());
130 setupPrimCommands(primDa, m_conn);
131 primDa.Fill(ds.Tables["prims"]);
132
133 ds.Tables.Add(createShapeTable());
134 setupShapeCommands(shapeDa, m_conn);
135
136 ds.Tables.Add(createItemsTable());
137 setupItemsCommands(itemsDa, m_conn);
138 itemsDa.Fill(ds.Tables["primitems"]);
139
140 ds.Tables.Add(createTerrainTable());
141 setupTerrainCommands(terrainDa, m_conn);
142
143 ds.Tables.Add(createLandTable());
144 setupLandCommands(landDa, m_conn);
145
146 ds.Tables.Add(createLandAccessListTable());
147 setupLandAccessCommands(landAccessListDa, m_conn);
148
149 ds.Tables.Add(createRegionSettingsTable());
150
151 setupRegionSettingsCommands(regionSettingsDa, m_conn);
152
153 // WORKAROUND: This is a work around for sqlite on
154 // windows, which gets really unhappy with blob columns
155 // that have no sample data in them. At some point we
156 // need to actually find a proper way to handle this.
157 try
158 {
159 shapeDa.Fill(ds.Tables["primshapes"]);
160 }
161 catch (Exception)
162 {
163 m_log.Info("[REGION DB]: Caught fill error on primshapes table");
164 }
165
166 try
167 {
168 terrainDa.Fill(ds.Tables["terrain"]);
169 }
170 catch (Exception)
171 {
172 m_log.Info("[REGION DB]: Caught fill error on terrain table");
173 }
174
175 try
176 {
177 landDa.Fill(ds.Tables["land"]);
178 }
179 catch (Exception)
180 {
181 m_log.Info("[REGION DB]: Caught fill error on land table");
182 }
183
184 try
185 {
186 landAccessListDa.Fill(ds.Tables["landaccesslist"]);
187 }
188 catch (Exception)
189 {
190 m_log.Info("[REGION DB]: Caught fill error on landaccesslist table");
191 }
192
193 try
194 {
195 regionSettingsDa.Fill(ds.Tables["regionsettings"]);
196 }
197 catch (Exception)
198 {
199 m_log.Info("[REGION DB]: Caught fill error on regionsettings table");
200 }
201 return;
202 }
203 }
204
205 public void Dispose()
206 {
207 if (m_conn != null)
208 {
209 m_conn.Close();
210 m_conn = null;
211 }
212 if (ds != null)
213 {
214 ds.Dispose();
215 ds = null;
216 }
217 if (primDa != null)
218 {
219 primDa.Dispose();
220 primDa = null;
221 }
222 if (shapeDa != null)
223 {
224 shapeDa.Dispose();
225 shapeDa = null;
226 }
227 if (itemsDa != null)
228 {
229 itemsDa.Dispose();
230 itemsDa = null;
231 }
232 if (terrainDa != null)
233 {
234 terrainDa.Dispose();
235 terrainDa = null;
236 }
237 if (landDa != null)
238 {
239 landDa.Dispose();
240 landDa = null;
241 }
242 if (landAccessListDa != null)
243 {
244 landAccessListDa.Dispose();
245 landAccessListDa = null;
246 }
247 if (regionSettingsDa != null)
248 {
249 regionSettingsDa.Dispose();
250 regionSettingsDa = null;
251 }
252 }
253
254 public void StoreRegionSettings(RegionSettings rs)
255 {
256 lock (ds)
257 {
258 DataTable regionsettings = ds.Tables["regionsettings"];
259
260 DataRow settingsRow = regionsettings.Rows.Find(rs.RegionUUID.ToString());
261 if (settingsRow == null)
262 {
263 settingsRow = regionsettings.NewRow();
264 fillRegionSettingsRow(settingsRow, rs);
265 regionsettings.Rows.Add(settingsRow);
266 }
267 else
268 {
269 fillRegionSettingsRow(settingsRow, rs);
270 }
271
272 Commit();
273 }
274 }
275 public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
276 {
277 //This connector doesn't support the windlight module yet
278 //Return default LL windlight settings
279 return new RegionLightShareData();
280 }
281 public void StoreRegionWindlightSettings(RegionLightShareData wl)
282 {
283 //This connector doesn't support the windlight module yet
284 }
285 public RegionSettings LoadRegionSettings(UUID regionUUID)
286 {
287 lock (ds)
288 {
289 DataTable regionsettings = ds.Tables["regionsettings"];
290
291 string searchExp = "regionUUID = '" + regionUUID.ToString() + "'";
292 DataRow[] rawsettings = regionsettings.Select(searchExp);
293 if (rawsettings.Length == 0)
294 {
295 RegionSettings rs = new RegionSettings();
296 rs.RegionUUID = regionUUID;
297 rs.OnSave += StoreRegionSettings;
298
299 StoreRegionSettings(rs);
300
301 return rs;
302 }
303 DataRow row = rawsettings[0];
304
305 RegionSettings newSettings = buildRegionSettings(row);
306 newSettings.OnSave += StoreRegionSettings;
307
308 return newSettings;
309 }
310 }
311
312 /// <summary>
313 /// Adds an object into region storage
314 /// </summary>
315 /// <param name="obj">the object</param>
316 /// <param name="regionUUID">the region UUID</param>
317 public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
318 {
319 uint flags = obj.RootPart.GetEffectiveObjectFlags();
320
321 // Eligibility check
322 //
323 if ((flags & (uint)PrimFlags.Temporary) != 0)
324 return;
325 if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)
326 return;
327
328 lock (ds)
329 {
330 foreach (SceneObjectPart prim in obj.Children.Values)
331 {
332// m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
333 addPrim(prim, obj.UUID, regionUUID);
334 }
335 }
336
337 Commit();
338 // m_log.Info("[Dump of prims]: " + ds.GetXml());
339 }
340
341 /// <summary>
342 /// Removes an object from region storage
343 /// </summary>
344 /// <param name="obj">the object</param>
345 /// <param name="regionUUID">the region UUID</param>
346 public void RemoveObject(UUID obj, UUID regionUUID)
347 {
348 // m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.Guid, regionUUID);
349
350 DataTable prims = ds.Tables["prims"];
351 DataTable shapes = ds.Tables["primshapes"];
352
353 string selectExp = "SceneGroupID = '" + obj + "' and RegionUUID = '" + regionUUID + "'";
354 lock (ds)
355 {
356 DataRow[] primRows = prims.Select(selectExp);
357 foreach (DataRow row in primRows)
358 {
359 // Remove shape rows
360 UUID uuid = new UUID((string) row["UUID"]);
361 DataRow shapeRow = shapes.Rows.Find(uuid.ToString());
362 if (shapeRow != null)
363 {
364 shapeRow.Delete();
365 }
366
367 RemoveItems(uuid);
368
369 // Remove prim row
370 row.Delete();
371 }
372 }
373
374 Commit();
375 }
376
377 /// <summary>
378 /// Remove all persisted items of the given prim.
379 /// The caller must acquire the necessrary synchronization locks and commit or rollback changes.
380 /// </summary>
381 /// <param name="uuid">The item UUID</param>
382 private void RemoveItems(UUID uuid)
383 {
384 DataTable items = ds.Tables["primitems"];
385
386 String sql = String.Format("primID = '{0}'", uuid);
387 DataRow[] itemRows = items.Select(sql);
388
389 foreach (DataRow itemRow in itemRows)
390 {
391 itemRow.Delete();
392 }
393 }
394
395 /// <summary>
396 /// Load persisted objects from region storage.
397 /// </summary>
398 /// <param name="regionUUID">The region UUID</param>
399 /// <returns>List of loaded groups</returns>
400 public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
401 {
402 Dictionary<UUID, SceneObjectGroup> createdObjects = new Dictionary<UUID, SceneObjectGroup>();
403
404 List<SceneObjectGroup> retvals = new List<SceneObjectGroup>();
405
406 DataTable prims = ds.Tables["prims"];
407 DataTable shapes = ds.Tables["primshapes"];
408
409 string byRegion = "RegionUUID = '" + regionUUID + "'";
410
411 lock (ds)
412 {
413 DataRow[] primsForRegion = prims.Select(byRegion);
414 m_log.Info("[REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
415
416 // First, create all groups
417 foreach (DataRow primRow in primsForRegion)
418 {
419 try
420 {
421 SceneObjectPart prim = null;
422
423 string uuid = (string) primRow["UUID"];
424 string objID = (string) primRow["SceneGroupID"];
425
426 if (uuid == objID) //is new SceneObjectGroup ?
427 {
428 prim = buildPrim(primRow);
429 DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
430 if (shapeRow != null)
431 {
432 prim.Shape = buildShape(shapeRow);
433 }
434 else
435 {
436 m_log.Info(
437 "[REGION DB]: No shape found for prim in storage, so setting default box shape");
438 prim.Shape = PrimitiveBaseShape.Default;
439 }
440
441 SceneObjectGroup group = new SceneObjectGroup(prim);
442 createdObjects.Add(group.UUID, group);
443 retvals.Add(group);
444 LoadItems(prim);
445 }
446 }
447 catch (Exception e)
448 {
449 m_log.Error("[REGION DB]: Failed create prim object in new group, exception and data follows");
450 m_log.Info("[REGION DB]: " + e.ToString());
451 foreach (DataColumn col in prims.Columns)
452 {
453 m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
454 }
455 }
456 }
457
458 // Now fill the groups with part data
459 foreach (DataRow primRow in primsForRegion)
460 {
461 try
462 {
463 SceneObjectPart prim = null;
464
465 string uuid = (string) primRow["UUID"];
466 string objID = (string) primRow["SceneGroupID"];
467 if (uuid != objID) //is new SceneObjectGroup ?
468 {
469 prim = buildPrim(primRow);
470 DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
471 if (shapeRow != null)
472 {
473 prim.Shape = buildShape(shapeRow);
474 }
475 else
476 {
477 m_log.Warn(
478 "[REGION DB]: No shape found for prim in storage, so setting default box shape");
479 prim.Shape = PrimitiveBaseShape.Default;
480 }
481
482 createdObjects[new UUID(objID)].AddPart(prim);
483 LoadItems(prim);
484 }
485 }
486 catch (Exception e)
487 {
488 m_log.Error("[REGION DB]: Failed create prim object in group, exception and data follows");
489 m_log.Info("[REGION DB]: " + e.ToString());
490 foreach (DataColumn col in prims.Columns)
491 {
492 m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
493 }
494 }
495 }
496 }
497 return retvals;
498 }
499
500 /// <summary>
501 /// Load in a prim's persisted inventory.
502 /// </summary>
503 /// <param name="prim">the prim</param>
504 private void LoadItems(SceneObjectPart prim)
505 {
506 //m_log.DebugFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID);
507
508 DataTable dbItems = ds.Tables["primitems"];
509 String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
510 DataRow[] dbItemRows = dbItems.Select(sql);
511 IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
512
513 foreach (DataRow row in dbItemRows)
514 {
515 TaskInventoryItem item = buildItem(row);
516 inventory.Add(item);
517
518 //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID);
519 }
520
521 prim.Inventory.RestoreInventoryItems(inventory);
522 }
523
524 /// <summary>
525 /// Store a terrain revision in region storage
526 /// </summary>
527 /// <param name="ter">terrain heightfield</param>
528 /// <param name="regionID">region UUID</param>
529 public void StoreTerrain(double[,] ter, UUID regionID)
530 {
531 lock (ds)
532 {
533 int revision = Util.UnixTimeSinceEpoch();
534
535 // This is added to get rid of the infinitely growing
536 // terrain databases which negatively impact on SQLite
537 // over time. Before reenabling this feature there
538 // needs to be a limitter put on the number of
539 // revisions in the database, as this old
540 // implementation is a DOS attack waiting to happen.
541
542 using (
543 SqliteCommand cmd =
544 new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID and Revision <= :Revision",
545 m_conn))
546 {
547 cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
548 cmd.Parameters.Add(new SqliteParameter(":Revision", revision));
549 cmd.ExecuteNonQuery();
550 }
551
552 // the following is an work around for .NET. The perf
553 // issues associated with it aren't as bad as you think.
554 m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString());
555 String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" +
556 " values(:RegionUUID, :Revision, :Heightfield)";
557
558 using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
559 {
560 cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
561 cmd.Parameters.Add(new SqliteParameter(":Revision", revision));
562 cmd.Parameters.Add(new SqliteParameter(":Heightfield", serializeTerrain(ter)));
563 cmd.ExecuteNonQuery();
564 }
565 }
566 }
567
568 /// <summary>
569 /// Load the latest terrain revision from region storage
570 /// </summary>
571 /// <param name="regionID">the region UUID</param>
572 /// <returns>Heightfield data</returns>
573 public double[,] LoadTerrain(UUID regionID)
574 {
575 lock (ds)
576 {
577 double[,] terret = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];
578 terret.Initialize();
579
580 String sql = "select RegionUUID, Revision, Heightfield from terrain" +
581 " where RegionUUID=:RegionUUID order by Revision desc";
582
583 using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
584 {
585 cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
586
587 using (IDataReader row = cmd.ExecuteReader())
588 {
589 int rev = 0;
590 if (row.Read())
591 {
592 // TODO: put this into a function
593 using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"]))
594 {
595 using (BinaryReader br = new BinaryReader(str))
596 {
597 for (int x = 0; x < (int)Constants.RegionSize; x++)
598 {
599 for (int y = 0; y < (int)Constants.RegionSize; y++)
600 {
601 terret[x, y] = br.ReadDouble();
602 }
603 }
604 }
605 }
606 rev = (int) row["Revision"];
607 }
608 else
609 {
610 m_log.Info("[REGION DB]: No terrain found for region");
611 return null;
612 }
613
614 m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString());
615 }
616 }
617 return terret;
618 }
619 }
620
621 /// <summary>
622 ///
623 /// </summary>
624 /// <param name="globalID"></param>
625 public void RemoveLandObject(UUID globalID)
626 {
627 lock (ds)
628 {
629 // Can't use blanket SQL statements when using SqlAdapters unless you re-read the data into the adapter
630 // after you're done.
631 // replaced below code with the SqliteAdapter version.
632 //using (SqliteCommand cmd = new SqliteCommand("delete from land where UUID=:UUID", m_conn))
633 //{
634 // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
635 // cmd.ExecuteNonQuery();
636 //}
637
638 //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn))
639 //{
640 // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
641 // cmd.ExecuteNonQuery();
642 //}
643
644 DataTable land = ds.Tables["land"];
645 DataTable landaccesslist = ds.Tables["landaccesslist"];
646 DataRow landRow = land.Rows.Find(globalID.ToString());
647 if (landRow != null)
648 {
649 land.Rows.Remove(landRow);
650 }
651 List<DataRow> rowsToDelete = new List<DataRow>();
652 foreach (DataRow rowToCheck in landaccesslist.Rows)
653 {
654 if (rowToCheck["LandUUID"].ToString() == globalID.ToString())
655 rowsToDelete.Add(rowToCheck);
656 }
657 for (int iter = 0; iter < rowsToDelete.Count; iter++)
658 {
659 landaccesslist.Rows.Remove(rowsToDelete[iter]);
660 }
661
662
663 }
664 Commit();
665 }
666
667 /// <summary>
668 ///
669 /// </summary>
670 /// <param name="parcel"></param>
671 public void StoreLandObject(ILandObject parcel)
672 {
673 lock (ds)
674 {
675 DataTable land = ds.Tables["land"];
676 DataTable landaccesslist = ds.Tables["landaccesslist"];
677
678 DataRow landRow = land.Rows.Find(parcel.LandData.GlobalID.ToString());
679 if (landRow == null)
680 {
681 landRow = land.NewRow();
682 fillLandRow(landRow, parcel.LandData, parcel.RegionUUID);
683 land.Rows.Add(landRow);
684 }
685 else
686 {
687 fillLandRow(landRow, parcel.LandData, parcel.RegionUUID);
688 }
689
690 // I know this caused someone issues before, but OpenSim is unusable if we leave this stuff around
691 //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn))
692 //{
693 // cmd.Parameters.Add(new SqliteParameter(":LandUUID", parcel.LandData.GlobalID.ToString()));
694 // cmd.ExecuteNonQuery();
695
696// }
697
698 // This is the slower.. but more appropriate thing to do
699
700 // We can't modify the table with direct queries before calling Commit() and re-filling them.
701 List<DataRow> rowsToDelete = new List<DataRow>();
702 foreach (DataRow rowToCheck in landaccesslist.Rows)
703 {
704 if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString())
705 rowsToDelete.Add(rowToCheck);
706 }
707 for (int iter = 0; iter < rowsToDelete.Count; iter++)
708 {
709 landaccesslist.Rows.Remove(rowsToDelete[iter]);
710 }
711 rowsToDelete.Clear();
712 foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList)
713 {
714 DataRow newAccessRow = landaccesslist.NewRow();
715 fillLandAccessRow(newAccessRow, entry, parcel.LandData.GlobalID);
716 landaccesslist.Rows.Add(newAccessRow);
717 }
718 }
719
720 Commit();
721 }
722
723 /// <summary>
724 ///
725 /// </summary>
726 /// <param name="regionUUID"></param>
727 /// <returns></returns>
728 public List<LandData> LoadLandObjects(UUID regionUUID)
729 {
730 List<LandData> landDataForRegion = new List<LandData>();
731 lock (ds)
732 {
733 DataTable land = ds.Tables["land"];
734 DataTable landaccesslist = ds.Tables["landaccesslist"];
735 string searchExp = "RegionUUID = '" + regionUUID + "'";
736 DataRow[] rawDataForRegion = land.Select(searchExp);
737 foreach (DataRow rawDataLand in rawDataForRegion)
738 {
739 LandData newLand = buildLandData(rawDataLand);
740 string accessListSearchExp = "LandUUID = '" + newLand.GlobalID + "'";
741 DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp);
742 foreach (DataRow rawDataLandAccess in rawDataForLandAccessList)
743 {
744 newLand.ParcelAccessList.Add(buildLandAccessData(rawDataLandAccess));
745 }
746
747 landDataForRegion.Add(newLand);
748 }
749 }
750 return landDataForRegion;
751 }
752
753 /// <summary>
754 ///
755 /// </summary>
756 public void Commit()
757 {
758 lock (ds)
759 {
760 primDa.Update(ds, "prims");
761 shapeDa.Update(ds, "primshapes");
762
763 itemsDa.Update(ds, "primitems");
764
765 terrainDa.Update(ds, "terrain");
766 landDa.Update(ds, "land");
767 landAccessListDa.Update(ds, "landaccesslist");
768 try
769 {
770 regionSettingsDa.Update(ds, "regionsettings");
771 }
772 catch (SqliteExecutionException SqlEx)
773 {
774 if (SqlEx.Message.Contains("logic error"))
775 {
776 throw new Exception(
777 "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!",
778 SqlEx);
779 }
780 else
781 {
782 throw SqlEx;
783 }
784 }
785 ds.AcceptChanges();
786 }
787 }
788
789 /// <summary>
790 /// See <see cref="Commit"/>
791 /// </summary>
792 public void Shutdown()
793 {
794 Commit();
795 }
796
797 /***********************************************************************
798 *
799 * Database Definition Functions
800 *
801 * This should be db agnostic as we define them in ADO.NET terms
802 *
803 **********************************************************************/
804
805 /// <summary>
806 ///
807 /// </summary>
808 /// <param name="dt"></param>
809 /// <param name="name"></param>
810 /// <param name="type"></param>
811 private static void createCol(DataTable dt, string name, Type type)
812 {
813 DataColumn col = new DataColumn(name, type);
814 dt.Columns.Add(col);
815 }
816
817 /// <summary>
818 /// Creates the "terrain" table
819 /// </summary>
820 /// <returns>terrain table DataTable</returns>
821 private static DataTable createTerrainTable()
822 {
823 DataTable terrain = new DataTable("terrain");
824
825 createCol(terrain, "RegionUUID", typeof (String));
826 createCol(terrain, "Revision", typeof (Int32));
827 createCol(terrain, "Heightfield", typeof (Byte[]));
828
829 return terrain;
830 }
831
832 /// <summary>
833 /// Creates the "prims" table
834 /// </summary>
835 /// <returns>prim table DataTable</returns>
836 private static DataTable createPrimTable()
837 {
838 DataTable prims = new DataTable("prims");
839
840 createCol(prims, "UUID", typeof (String));
841 createCol(prims, "RegionUUID", typeof (String));
842 createCol(prims, "CreationDate", typeof (Int32));
843 createCol(prims, "Name", typeof (String));
844 createCol(prims, "SceneGroupID", typeof (String));
845 // various text fields
846 createCol(prims, "Text", typeof (String));
847 createCol(prims, "ColorR", typeof (Int32));
848 createCol(prims, "ColorG", typeof (Int32));
849 createCol(prims, "ColorB", typeof (Int32));
850 createCol(prims, "ColorA", typeof (Int32));
851 createCol(prims, "Description", typeof (String));
852 createCol(prims, "SitName", typeof (String));
853 createCol(prims, "TouchName", typeof (String));
854 // permissions
855 createCol(prims, "ObjectFlags", typeof (Int32));
856 createCol(prims, "CreatorID", typeof (String));
857 createCol(prims, "OwnerID", typeof (String));
858 createCol(prims, "GroupID", typeof (String));
859 createCol(prims, "LastOwnerID", typeof (String));
860 createCol(prims, "OwnerMask", typeof (Int32));
861 createCol(prims, "NextOwnerMask", typeof (Int32));
862 createCol(prims, "GroupMask", typeof (Int32));
863 createCol(prims, "EveryoneMask", typeof (Int32));
864 createCol(prims, "BaseMask", typeof (Int32));
865 // vectors
866 createCol(prims, "PositionX", typeof (Double));
867 createCol(prims, "PositionY", typeof (Double));
868 createCol(prims, "PositionZ", typeof (Double));
869 createCol(prims, "GroupPositionX", typeof (Double));
870 createCol(prims, "GroupPositionY", typeof (Double));
871 createCol(prims, "GroupPositionZ", typeof (Double));
872 createCol(prims, "VelocityX", typeof (Double));
873 createCol(prims, "VelocityY", typeof (Double));
874 createCol(prims, "VelocityZ", typeof (Double));
875 createCol(prims, "AngularVelocityX", typeof (Double));
876 createCol(prims, "AngularVelocityY", typeof (Double));
877 createCol(prims, "AngularVelocityZ", typeof (Double));
878 createCol(prims, "AccelerationX", typeof (Double));
879 createCol(prims, "AccelerationY", typeof (Double));
880 createCol(prims, "AccelerationZ", typeof (Double));
881 // quaternions
882 createCol(prims, "RotationX", typeof (Double));
883 createCol(prims, "RotationY", typeof (Double));
884 createCol(prims, "RotationZ", typeof (Double));
885 createCol(prims, "RotationW", typeof (Double));
886
887 // sit target
888 createCol(prims, "SitTargetOffsetX", typeof (Double));
889 createCol(prims, "SitTargetOffsetY", typeof (Double));
890 createCol(prims, "SitTargetOffsetZ", typeof (Double));
891
892 createCol(prims, "SitTargetOrientW", typeof (Double));
893 createCol(prims, "SitTargetOrientX", typeof (Double));
894 createCol(prims, "SitTargetOrientY", typeof (Double));
895 createCol(prims, "SitTargetOrientZ", typeof (Double));
896
897 createCol(prims, "PayPrice", typeof(Int32));
898 createCol(prims, "PayButton1", typeof(Int32));
899 createCol(prims, "PayButton2", typeof(Int32));
900 createCol(prims, "PayButton3", typeof(Int32));
901 createCol(prims, "PayButton4", typeof(Int32));
902
903 createCol(prims, "LoopedSound", typeof(String));
904 createCol(prims, "LoopedSoundGain", typeof(Double));
905 createCol(prims, "TextureAnimation", typeof(String));
906 createCol(prims, "ParticleSystem", typeof(String));
907
908 createCol(prims, "OmegaX", typeof(Double));
909 createCol(prims, "OmegaY", typeof(Double));
910 createCol(prims, "OmegaZ", typeof(Double));
911
912 createCol(prims, "CameraEyeOffsetX", typeof(Double));
913 createCol(prims, "CameraEyeOffsetY", typeof(Double));
914 createCol(prims, "CameraEyeOffsetZ", typeof(Double));
915
916 createCol(prims, "CameraAtOffsetX", typeof(Double));
917 createCol(prims, "CameraAtOffsetY", typeof(Double));
918 createCol(prims, "CameraAtOffsetZ", typeof(Double));
919
920 createCol(prims, "ForceMouselook", typeof(Int16));
921
922 createCol(prims, "ScriptAccessPin", typeof(Int32));
923
924 createCol(prims, "AllowedDrop", typeof(Int16));
925 createCol(prims, "DieAtEdge", typeof(Int16));
926
927 createCol(prims, "SalePrice", typeof(Int32));
928 createCol(prims, "SaleType", typeof(Int16));
929
930 // click action
931 createCol(prims, "ClickAction", typeof (Byte));
932
933 createCol(prims, "Material", typeof(Byte));
934
935 createCol(prims, "CollisionSound", typeof(String));
936 createCol(prims, "CollisionSoundVolume", typeof(Double));
937
938 createCol(prims, "VolumeDetect", typeof(Int16));
939
940 // Add in contraints
941 prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]};
942
943 return prims;
944 }
945
946 /// <summary>
947 /// Creates "primshapes" table
948 /// </summary>
949 /// <returns>shape table DataTable</returns>
950 private static DataTable createShapeTable()
951 {
952 DataTable shapes = new DataTable("primshapes");
953 createCol(shapes, "UUID", typeof (String));
954 // shape is an enum
955 createCol(shapes, "Shape", typeof (Int32));
956 // vectors
957 createCol(shapes, "ScaleX", typeof (Double));
958 createCol(shapes, "ScaleY", typeof (Double));
959 createCol(shapes, "ScaleZ", typeof (Double));
960 // paths
961 createCol(shapes, "PCode", typeof (Int32));
962 createCol(shapes, "PathBegin", typeof (Int32));
963 createCol(shapes, "PathEnd", typeof (Int32));
964 createCol(shapes, "PathScaleX", typeof (Int32));
965 createCol(shapes, "PathScaleY", typeof (Int32));
966 createCol(shapes, "PathShearX", typeof (Int32));
967 createCol(shapes, "PathShearY", typeof (Int32));
968 createCol(shapes, "PathSkew", typeof (Int32));
969 createCol(shapes, "PathCurve", typeof (Int32));
970 createCol(shapes, "PathRadiusOffset", typeof (Int32));
971 createCol(shapes, "PathRevolutions", typeof (Int32));
972 createCol(shapes, "PathTaperX", typeof (Int32));
973 createCol(shapes, "PathTaperY", typeof (Int32));
974 createCol(shapes, "PathTwist", typeof (Int32));
975 createCol(shapes, "PathTwistBegin", typeof (Int32));
976 // profile
977 createCol(shapes, "ProfileBegin", typeof (Int32));
978 createCol(shapes, "ProfileEnd", typeof (Int32));
979 createCol(shapes, "ProfileCurve", typeof (Int32));
980 createCol(shapes, "ProfileHollow", typeof (Int32));
981 createCol(shapes, "State", typeof(Int32));
982 // text TODO: this isn't right, but I'm not sure the right
983 // way to specify this as a blob atm
984 createCol(shapes, "Texture", typeof (Byte[]));
985 createCol(shapes, "ExtraParams", typeof (Byte[]));
986
987 shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]};
988
989 return shapes;
990 }
991
992 /// <summary>
993 /// creates "primitems" table
994 /// </summary>
995 /// <returns>item table DataTable</returns>
996 private static DataTable createItemsTable()
997 {
998 DataTable items = new DataTable("primitems");
999
1000 createCol(items, "itemID", typeof (String));
1001 createCol(items, "primID", typeof (String));
1002 createCol(items, "assetID", typeof (String));
1003 createCol(items, "parentFolderID", typeof (String));
1004
1005 createCol(items, "invType", typeof (Int32));
1006 createCol(items, "assetType", typeof (Int32));
1007
1008 createCol(items, "name", typeof (String));
1009 createCol(items, "description", typeof (String));
1010
1011 createCol(items, "creationDate", typeof (Int64));
1012 createCol(items, "creatorID", typeof (String));
1013 createCol(items, "ownerID", typeof (String));
1014 createCol(items, "lastOwnerID", typeof (String));
1015 createCol(items, "groupID", typeof (String));
1016
1017 createCol(items, "nextPermissions", typeof (UInt32));
1018 createCol(items, "currentPermissions", typeof (UInt32));
1019 createCol(items, "basePermissions", typeof (UInt32));
1020 createCol(items, "everyonePermissions", typeof (UInt32));
1021 createCol(items, "groupPermissions", typeof (UInt32));
1022 createCol(items, "flags", typeof (UInt32));
1023
1024 items.PrimaryKey = new DataColumn[] { items.Columns["itemID"] };
1025
1026 return items;
1027 }
1028
1029 /// <summary>
1030 /// Creates "land" table
1031 /// </summary>
1032 /// <returns>land table DataTable</returns>
1033 private static DataTable createLandTable()
1034 {
1035 DataTable land = new DataTable("land");
1036 createCol(land, "UUID", typeof (String));
1037 createCol(land, "RegionUUID", typeof (String));
1038 createCol(land, "LocalLandID", typeof (UInt32));
1039
1040 // Bitmap is a byte[512]
1041 createCol(land, "Bitmap", typeof (Byte[]));
1042
1043 createCol(land, "Name", typeof (String));
1044 createCol(land, "Desc", typeof (String));
1045 createCol(land, "OwnerUUID", typeof (String));
1046 createCol(land, "IsGroupOwned", typeof (Boolean));
1047 createCol(land, "Area", typeof (Int32));
1048 createCol(land, "AuctionID", typeof (Int32)); //Unemplemented
1049 createCol(land, "Category", typeof (Int32)); //Enum OpenMetaverse.Parcel.ParcelCategory
1050 createCol(land, "ClaimDate", typeof (Int32));
1051 createCol(land, "ClaimPrice", typeof (Int32));
1052 createCol(land, "GroupUUID", typeof (string));
1053 createCol(land, "SalePrice", typeof (Int32));
1054 createCol(land, "LandStatus", typeof (Int32)); //Enum. OpenMetaverse.Parcel.ParcelStatus
1055 createCol(land, "LandFlags", typeof (UInt32));
1056 createCol(land, "LandingType", typeof (Byte));
1057 createCol(land, "MediaAutoScale", typeof (Byte));
1058 createCol(land, "MediaTextureUUID", typeof (String));
1059 createCol(land, "MediaURL", typeof (String));
1060 createCol(land, "MusicURL", typeof (String));
1061 createCol(land, "PassHours", typeof (Double));
1062 createCol(land, "PassPrice", typeof (UInt32));
1063 createCol(land, "SnapshotUUID", typeof (String));
1064 createCol(land, "UserLocationX", typeof (Double));
1065 createCol(land, "UserLocationY", typeof (Double));
1066 createCol(land, "UserLocationZ", typeof (Double));
1067 createCol(land, "UserLookAtX", typeof (Double));
1068 createCol(land, "UserLookAtY", typeof (Double));
1069 createCol(land, "UserLookAtZ", typeof (Double));
1070 createCol(land, "AuthbuyerID", typeof(String));
1071 createCol(land, "OtherCleanTime", typeof(Int32));
1072
1073 land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]};
1074
1075 return land;
1076 }
1077
1078 /// <summary>
1079 /// create "landaccesslist" table
1080 /// </summary>
1081 /// <returns>Landacceslist DataTable</returns>
1082 private static DataTable createLandAccessListTable()
1083 {
1084 DataTable landaccess = new DataTable("landaccesslist");
1085 createCol(landaccess, "LandUUID", typeof (String));
1086 createCol(landaccess, "AccessUUID", typeof (String));
1087 createCol(landaccess, "Flags", typeof (UInt32));
1088
1089 return landaccess;
1090 }
1091
1092 private static DataTable createRegionSettingsTable()
1093 {
1094 DataTable regionsettings = new DataTable("regionsettings");
1095 createCol(regionsettings, "regionUUID", typeof(String));
1096 createCol(regionsettings, "block_terraform", typeof (Int32));
1097 createCol(regionsettings, "block_fly", typeof (Int32));
1098 createCol(regionsettings, "allow_damage", typeof (Int32));
1099 createCol(regionsettings, "restrict_pushing", typeof (Int32));
1100 createCol(regionsettings, "allow_land_resell", typeof (Int32));
1101 createCol(regionsettings, "allow_land_join_divide", typeof (Int32));
1102 createCol(regionsettings, "block_show_in_search", typeof (Int32));
1103 createCol(regionsettings, "agent_limit", typeof (Int32));
1104 createCol(regionsettings, "object_bonus", typeof (Double));
1105 createCol(regionsettings, "maturity", typeof (Int32));
1106 createCol(regionsettings, "disable_scripts", typeof (Int32));
1107 createCol(regionsettings, "disable_collisions", typeof (Int32));
1108 createCol(regionsettings, "disable_physics", typeof (Int32));
1109 createCol(regionsettings, "terrain_texture_1", typeof(String));
1110 createCol(regionsettings, "terrain_texture_2", typeof(String));
1111 createCol(regionsettings, "terrain_texture_3", typeof(String));
1112 createCol(regionsettings, "terrain_texture_4", typeof(String));
1113 createCol(regionsettings, "elevation_1_nw", typeof (Double));
1114 createCol(regionsettings, "elevation_2_nw", typeof (Double));
1115 createCol(regionsettings, "elevation_1_ne", typeof (Double));
1116 createCol(regionsettings, "elevation_2_ne", typeof (Double));
1117 createCol(regionsettings, "elevation_1_se", typeof (Double));
1118 createCol(regionsettings, "elevation_2_se", typeof (Double));
1119 createCol(regionsettings, "elevation_1_sw", typeof (Double));
1120 createCol(regionsettings, "elevation_2_sw", typeof (Double));
1121 createCol(regionsettings, "water_height", typeof (Double));
1122 createCol(regionsettings, "terrain_raise_limit", typeof (Double));
1123 createCol(regionsettings, "terrain_lower_limit", typeof (Double));
1124 createCol(regionsettings, "use_estate_sun", typeof (Int32));
1125 createCol(regionsettings, "sandbox", typeof (Int32));
1126 createCol(regionsettings, "sunvectorx",typeof (Double));
1127 createCol(regionsettings, "sunvectory",typeof (Double));
1128 createCol(regionsettings, "sunvectorz",typeof (Double));
1129 createCol(regionsettings, "fixed_sun", typeof (Int32));
1130 createCol(regionsettings, "sun_position", typeof (Double));
1131 createCol(regionsettings, "covenant", typeof(String));
1132 regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] };
1133 return regionsettings;
1134 }
1135
1136 /***********************************************************************
1137 *
1138 * Convert between ADO.NET <=> OpenSim Objects
1139 *
1140 * These should be database independant
1141 *
1142 **********************************************************************/
1143
1144 /// <summary>
1145 ///
1146 /// </summary>
1147 /// <param name="row"></param>
1148 /// <returns></returns>
1149 private SceneObjectPart buildPrim(DataRow row)
1150 {
1151 // Code commented. Uncomment to test the unit test inline.
1152
1153 // The unit test mentions this commented code for the purposes
1154 // of debugging a unit test failure
1155
1156 // SceneObjectGroup sog = new SceneObjectGroup();
1157 // SceneObjectPart sop = new SceneObjectPart();
1158 // sop.LocalId = 1;
1159 // sop.Name = "object1";
1160 // sop.Description = "object1";
1161 // sop.Text = "";
1162 // sop.SitName = "";
1163 // sop.TouchName = "";
1164 // sop.UUID = UUID.Random();
1165 // sop.Shape = PrimitiveBaseShape.Default;
1166 // sog.SetRootPart(sop);
1167 // Add breakpoint in above line. Check sop fields.
1168
1169 // TODO: this doesn't work yet because something more
1170 // interesting has to be done to actually get these values
1171 // back out. Not enough time to figure it out yet.
1172
1173 SceneObjectPart prim = new SceneObjectPart();
1174 prim.UUID = new UUID((String) row["UUID"]);
1175 // explicit conversion of integers is required, which sort
1176 // of sucks. No idea if there is a shortcut here or not.
1177 prim.CreationDate = Convert.ToInt32(row["CreationDate"]);
1178 prim.Name = row["Name"] == DBNull.Value ? string.Empty : (string)row["Name"];
1179 // various text fields
1180 prim.Text = (String) row["Text"];
1181 prim.Color = Color.FromArgb(Convert.ToInt32(row["ColorA"]),
1182 Convert.ToInt32(row["ColorR"]),
1183 Convert.ToInt32(row["ColorG"]),
1184 Convert.ToInt32(row["ColorB"]));
1185 prim.Description = (String) row["Description"];
1186 prim.SitName = (String) row["SitName"];
1187 prim.TouchName = (String) row["TouchName"];
1188 // permissions
1189 prim.Flags = (PrimFlags)Convert.ToUInt32(row["ObjectFlags"]);
1190 prim.CreatorID = new UUID((String) row["CreatorID"]);
1191 prim.OwnerID = new UUID((String) row["OwnerID"]);
1192 prim.GroupID = new UUID((String) row["GroupID"]);
1193 prim.LastOwnerID = new UUID((String) row["LastOwnerID"]);
1194 prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]);
1195 prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]);
1196 prim.GroupMask = Convert.ToUInt32(row["GroupMask"]);
1197 prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]);
1198 prim.BaseMask = Convert.ToUInt32(row["BaseMask"]);
1199 // vectors
1200 prim.OffsetPosition = new Vector3(
1201 Convert.ToSingle(row["PositionX"]),
1202 Convert.ToSingle(row["PositionY"]),
1203 Convert.ToSingle(row["PositionZ"])
1204 );
1205 prim.GroupPosition = new Vector3(
1206 Convert.ToSingle(row["GroupPositionX"]),
1207 Convert.ToSingle(row["GroupPositionY"]),
1208 Convert.ToSingle(row["GroupPositionZ"])
1209 );
1210 prim.Velocity = new Vector3(
1211 Convert.ToSingle(row["VelocityX"]),
1212 Convert.ToSingle(row["VelocityY"]),
1213 Convert.ToSingle(row["VelocityZ"])
1214 );
1215 prim.AngularVelocity = new Vector3(
1216 Convert.ToSingle(row["AngularVelocityX"]),
1217 Convert.ToSingle(row["AngularVelocityY"]),
1218 Convert.ToSingle(row["AngularVelocityZ"])
1219 );
1220 prim.Acceleration = new Vector3(
1221 Convert.ToSingle(row["AccelerationX"]),
1222 Convert.ToSingle(row["AccelerationY"]),
1223 Convert.ToSingle(row["AccelerationZ"])
1224 );
1225 // quaternions
1226 prim.RotationOffset = new Quaternion(
1227 Convert.ToSingle(row["RotationX"]),
1228 Convert.ToSingle(row["RotationY"]),
1229 Convert.ToSingle(row["RotationZ"]),
1230 Convert.ToSingle(row["RotationW"])
1231 );
1232
1233 prim.SitTargetPositionLL = new Vector3(
1234 Convert.ToSingle(row["SitTargetOffsetX"]),
1235 Convert.ToSingle(row["SitTargetOffsetY"]),
1236 Convert.ToSingle(row["SitTargetOffsetZ"]));
1237 prim.SitTargetOrientationLL = new Quaternion(
1238 Convert.ToSingle(
1239 row["SitTargetOrientX"]),
1240 Convert.ToSingle(
1241 row["SitTargetOrientY"]),
1242 Convert.ToSingle(
1243 row["SitTargetOrientZ"]),
1244 Convert.ToSingle(
1245 row["SitTargetOrientW"]));
1246
1247 prim.ClickAction = Convert.ToByte(row["ClickAction"]);
1248 prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]);
1249 prim.PayPrice[1] = Convert.ToInt32(row["PayButton1"]);
1250 prim.PayPrice[2] = Convert.ToInt32(row["PayButton2"]);
1251 prim.PayPrice[3] = Convert.ToInt32(row["PayButton3"]);
1252 prim.PayPrice[4] = Convert.ToInt32(row["PayButton4"]);
1253
1254 prim.Sound = new UUID(row["LoopedSound"].ToString());
1255 prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]);
1256 prim.SoundFlags = 1; // If it's persisted at all, it's looped
1257
1258 if (!row.IsNull("TextureAnimation"))
1259 prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString());
1260 if (!row.IsNull("ParticleSystem"))
1261 prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString());
1262
1263 prim.AngularVelocity = new Vector3(
1264 Convert.ToSingle(row["OmegaX"]),
1265 Convert.ToSingle(row["OmegaY"]),
1266 Convert.ToSingle(row["OmegaZ"])
1267 );
1268
1269 prim.SetCameraEyeOffset(new Vector3(
1270 Convert.ToSingle(row["CameraEyeOffsetX"]),
1271 Convert.ToSingle(row["CameraEyeOffsetY"]),
1272 Convert.ToSingle(row["CameraEyeOffsetZ"])
1273 ));
1274
1275 prim.SetCameraAtOffset(new Vector3(
1276 Convert.ToSingle(row["CameraAtOffsetX"]),
1277 Convert.ToSingle(row["CameraAtOffsetY"]),
1278 Convert.ToSingle(row["CameraAtOffsetZ"])
1279 ));
1280
1281 if (Convert.ToInt16(row["ForceMouselook"]) != 0)
1282 prim.SetForceMouselook(true);
1283
1284 prim.ScriptAccessPin = Convert.ToInt32(row["ScriptAccessPin"]);
1285
1286 if (Convert.ToInt16(row["AllowedDrop"]) != 0)
1287 prim.AllowedDrop = true;
1288
1289 if (Convert.ToInt16(row["DieAtEdge"]) != 0)
1290 prim.DIE_AT_EDGE = true;
1291
1292 prim.SalePrice = Convert.ToInt32(row["SalePrice"]);
1293 prim.ObjectSaleType = Convert.ToByte(row["SaleType"]);
1294
1295 prim.Material = Convert.ToByte(row["Material"]);
1296
1297 prim.CollisionSound = new UUID(row["CollisionSound"].ToString());
1298 prim.CollisionSoundVolume = Convert.ToSingle(row["CollisionSoundVolume"]);
1299
1300 if (Convert.ToInt16(row["VolumeDetect"]) != 0)
1301 prim.VolumeDetectActive = true;
1302
1303 return prim;
1304 }
1305
1306 /// <summary>
1307 /// Build a prim inventory item from the persisted data.
1308 /// </summary>
1309 /// <param name="row"></param>
1310 /// <returns></returns>
1311 private static TaskInventoryItem buildItem(DataRow row)
1312 {
1313 TaskInventoryItem taskItem = new TaskInventoryItem();
1314
1315 taskItem.ItemID = new UUID((String)row["itemID"]);
1316 taskItem.ParentPartID = new UUID((String)row["primID"]);
1317 taskItem.AssetID = new UUID((String)row["assetID"]);
1318 taskItem.ParentID = new UUID((String)row["parentFolderID"]);
1319
1320 taskItem.InvType = Convert.ToInt32(row["invType"]);
1321 taskItem.Type = Convert.ToInt32(row["assetType"]);
1322
1323 taskItem.Name = (String)row["name"];
1324 taskItem.Description = (String)row["description"];
1325 taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]);
1326 taskItem.CreatorID = new UUID((String)row["creatorID"]);
1327 taskItem.OwnerID = new UUID((String)row["ownerID"]);
1328 taskItem.LastOwnerID = new UUID((String)row["lastOwnerID"]);
1329 taskItem.GroupID = new UUID((String)row["groupID"]);
1330
1331 taskItem.NextPermissions = Convert.ToUInt32(row["nextPermissions"]);
1332 taskItem.CurrentPermissions = Convert.ToUInt32(row["currentPermissions"]);
1333 taskItem.BasePermissions = Convert.ToUInt32(row["basePermissions"]);
1334 taskItem.EveryonePermissions = Convert.ToUInt32(row["everyonePermissions"]);
1335 taskItem.GroupPermissions = Convert.ToUInt32(row["groupPermissions"]);
1336 taskItem.Flags = Convert.ToUInt32(row["flags"]);
1337
1338 return taskItem;
1339 }
1340
1341 /// <summary>
1342 /// Build a Land Data from the persisted data.
1343 /// </summary>
1344 /// <param name="row"></param>
1345 /// <returns></returns>
1346 private LandData buildLandData(DataRow row)
1347 {
1348 LandData newData = new LandData();
1349
1350 newData.GlobalID = new UUID((String) row["UUID"]);
1351 newData.LocalID = Convert.ToInt32(row["LocalLandID"]);
1352
1353 // Bitmap is a byte[512]
1354 newData.Bitmap = (Byte[]) row["Bitmap"];
1355
1356 newData.Name = (String) row["Name"];
1357 newData.Description = (String) row["Desc"];
1358 newData.OwnerID = (UUID)(String) row["OwnerUUID"];
1359 newData.IsGroupOwned = (Boolean) row["IsGroupOwned"];
1360 newData.Area = Convert.ToInt32(row["Area"]);
1361 newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented
1362 newData.Category = (ParcelCategory) Convert.ToInt32(row["Category"]);
1363 //Enum OpenMetaverse.Parcel.ParcelCategory
1364 newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]);
1365 newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]);
1366 newData.GroupID = new UUID((String) row["GroupUUID"]);
1367 newData.SalePrice = Convert.ToInt32(row["SalePrice"]);
1368 newData.Status = (ParcelStatus) Convert.ToInt32(row["LandStatus"]);
1369 //Enum. OpenMetaverse.Parcel.ParcelStatus
1370 newData.Flags = Convert.ToUInt32(row["LandFlags"]);
1371 newData.LandingType = (Byte) row["LandingType"];
1372 newData.MediaAutoScale = (Byte) row["MediaAutoScale"];
1373 newData.MediaID = new UUID((String) row["MediaTextureUUID"]);
1374 newData.MediaURL = (String) row["MediaURL"];
1375 newData.MusicURL = (String) row["MusicURL"];
1376 newData.PassHours = Convert.ToSingle(row["PassHours"]);
1377 newData.PassPrice = Convert.ToInt32(row["PassPrice"]);
1378 newData.SnapshotID = (UUID)(String) row["SnapshotUUID"];
1379 try
1380 {
1381
1382 newData.UserLocation =
1383 new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]),
1384 Convert.ToSingle(row["UserLocationZ"]));
1385 newData.UserLookAt =
1386 new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]),
1387 Convert.ToSingle(row["UserLookAtZ"]));
1388
1389 }
1390 catch (InvalidCastException)
1391 {
1392 m_log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name);
1393 newData.UserLocation = Vector3.Zero;
1394 newData.UserLookAt = Vector3.Zero;
1395 }
1396 newData.ParcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
1397 UUID authBuyerID = UUID.Zero;
1398
1399 UUID.TryParse((string)row["AuthbuyerID"], out authBuyerID);
1400
1401 newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
1402
1403 return newData;
1404 }
1405
1406 private RegionSettings buildRegionSettings(DataRow row)
1407 {
1408 RegionSettings newSettings = new RegionSettings();
1409
1410 newSettings.RegionUUID = new UUID((string) row["regionUUID"]);
1411 newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]);
1412 newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]);
1413 newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]);
1414 newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]);
1415 newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]);
1416 newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]);
1417 newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]);
1418 newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]);
1419 newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]);
1420 newSettings.Maturity = Convert.ToInt32(row["maturity"]);
1421 newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]);
1422 newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]);
1423 newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]);
1424 newSettings.TerrainTexture1 = new UUID((String) row["terrain_texture_1"]);
1425 newSettings.TerrainTexture2 = new UUID((String) row["terrain_texture_2"]);
1426 newSettings.TerrainTexture3 = new UUID((String) row["terrain_texture_3"]);
1427 newSettings.TerrainTexture4 = new UUID((String) row["terrain_texture_4"]);
1428 newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]);
1429 newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]);
1430 newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]);
1431 newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]);
1432 newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]);
1433 newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]);
1434 newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]);
1435 newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]);
1436 newSettings.WaterHeight = Convert.ToDouble(row["water_height"]);
1437 newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]);
1438 newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]);
1439 newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]);
1440 newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]);
1441 newSettings.SunVector = new Vector3 (
1442 Convert.ToSingle(row["sunvectorx"]),
1443 Convert.ToSingle(row["sunvectory"]),
1444 Convert.ToSingle(row["sunvectorz"])
1445 );
1446 newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]);
1447 newSettings.SunPosition = Convert.ToDouble(row["sun_position"]);
1448 newSettings.Covenant = new UUID((String) row["covenant"]);
1449
1450 return newSettings;
1451 }
1452
1453 /// <summary>
1454 /// Build a land access entry from the persisted data.
1455 /// </summary>
1456 /// <param name="row"></param>
1457 /// <returns></returns>
1458 private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row)
1459 {
1460 ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
1461 entry.AgentID = new UUID((string) row["AccessUUID"]);
1462 entry.Flags = (AccessList) row["Flags"];
1463 entry.Time = new DateTime();
1464 return entry;
1465 }
1466
1467 /// <summary>
1468 ///
1469 /// </summary>
1470 /// <param name="val"></param>
1471 /// <returns></returns>
1472 private static Array serializeTerrain(double[,] val)
1473 {
1474 MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) *sizeof (double));
1475 BinaryWriter bw = new BinaryWriter(str);
1476
1477 // TODO: COMPATIBILITY - Add byte-order conversions
1478 for (int x = 0; x < (int)Constants.RegionSize; x++)
1479 for (int y = 0; y < (int)Constants.RegionSize; y++)
1480 bw.Write(val[x, y]);
1481
1482 return str.ToArray();
1483 }
1484
1485// private void fillTerrainRow(DataRow row, UUID regionUUID, int rev, double[,] val)
1486// {
1487// row["RegionUUID"] = regionUUID;
1488// row["Revision"] = rev;
1489
1490 // MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize)*sizeof (double));
1491// BinaryWriter bw = new BinaryWriter(str);
1492
1493// // TODO: COMPATIBILITY - Add byte-order conversions
1494 // for (int x = 0; x < (int)Constants.RegionSize; x++)
1495 // for (int y = 0; y < (int)Constants.RegionSize; y++)
1496// bw.Write(val[x, y]);
1497
1498// row["Heightfield"] = str.ToArray();
1499// }
1500
1501 /// <summary>
1502 ///
1503 /// </summary>
1504 /// <param name="row"></param>
1505 /// <param name="prim"></param>
1506 /// <param name="sceneGroupID"></param>
1507 /// <param name="regionUUID"></param>
1508 private static void fillPrimRow(DataRow row, SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
1509 {
1510 row["UUID"] = prim.UUID.ToString();
1511 row["RegionUUID"] = regionUUID.ToString();
1512 row["CreationDate"] = prim.CreationDate;
1513 row["Name"] = prim.Name;
1514 row["SceneGroupID"] = sceneGroupID.ToString();
1515 // the UUID of the root part for this SceneObjectGroup
1516 // various text fields
1517 row["Text"] = prim.Text;
1518 row["Description"] = prim.Description;
1519 row["SitName"] = prim.SitName;
1520 row["TouchName"] = prim.TouchName;
1521 // permissions
1522 row["ObjectFlags"] = (uint)prim.Flags;
1523 row["CreatorID"] = prim.CreatorID.ToString();
1524 row["OwnerID"] = prim.OwnerID.ToString();
1525 row["GroupID"] = prim.GroupID.ToString();
1526 row["LastOwnerID"] = prim.LastOwnerID.ToString();
1527 row["OwnerMask"] = prim.OwnerMask;
1528 row["NextOwnerMask"] = prim.NextOwnerMask;
1529 row["GroupMask"] = prim.GroupMask;
1530 row["EveryoneMask"] = prim.EveryoneMask;
1531 row["BaseMask"] = prim.BaseMask;
1532 // vectors
1533 row["PositionX"] = prim.OffsetPosition.X;
1534 row["PositionY"] = prim.OffsetPosition.Y;
1535 row["PositionZ"] = prim.OffsetPosition.Z;
1536 row["GroupPositionX"] = prim.GroupPosition.X;
1537 row["GroupPositionY"] = prim.GroupPosition.Y;
1538 row["GroupPositionZ"] = prim.GroupPosition.Z;
1539 row["VelocityX"] = prim.Velocity.X;
1540 row["VelocityY"] = prim.Velocity.Y;
1541 row["VelocityZ"] = prim.Velocity.Z;
1542 row["AngularVelocityX"] = prim.AngularVelocity.X;
1543 row["AngularVelocityY"] = prim.AngularVelocity.Y;
1544 row["AngularVelocityZ"] = prim.AngularVelocity.Z;
1545 row["AccelerationX"] = prim.Acceleration.X;
1546 row["AccelerationY"] = prim.Acceleration.Y;
1547 row["AccelerationZ"] = prim.Acceleration.Z;
1548 // quaternions
1549 row["RotationX"] = prim.RotationOffset.X;
1550 row["RotationY"] = prim.RotationOffset.Y;
1551 row["RotationZ"] = prim.RotationOffset.Z;
1552 row["RotationW"] = prim.RotationOffset.W;
1553
1554 // Sit target
1555 Vector3 sitTargetPos = prim.SitTargetPositionLL;
1556 row["SitTargetOffsetX"] = sitTargetPos.X;
1557 row["SitTargetOffsetY"] = sitTargetPos.Y;
1558 row["SitTargetOffsetZ"] = sitTargetPos.Z;
1559
1560 Quaternion sitTargetOrient = prim.SitTargetOrientationLL;
1561 row["SitTargetOrientW"] = sitTargetOrient.W;
1562 row["SitTargetOrientX"] = sitTargetOrient.X;
1563 row["SitTargetOrientY"] = sitTargetOrient.Y;
1564 row["SitTargetOrientZ"] = sitTargetOrient.Z;
1565 row["ColorR"] = Convert.ToInt32(prim.Color.R);
1566 row["ColorG"] = Convert.ToInt32(prim.Color.G);
1567 row["ColorB"] = Convert.ToInt32(prim.Color.B);
1568 row["ColorA"] = Convert.ToInt32(prim.Color.A);
1569 row["PayPrice"] = prim.PayPrice[0];
1570 row["PayButton1"] = prim.PayPrice[1];
1571 row["PayButton2"] = prim.PayPrice[2];
1572 row["PayButton3"] = prim.PayPrice[3];
1573 row["PayButton4"] = prim.PayPrice[4];
1574
1575
1576 row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation);
1577 row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem);
1578
1579 row["OmegaX"] = prim.AngularVelocity.X;
1580 row["OmegaY"] = prim.AngularVelocity.Y;
1581 row["OmegaZ"] = prim.AngularVelocity.Z;
1582
1583 row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X;
1584 row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y;
1585 row["CameraEyeOffsetZ"] = prim.GetCameraEyeOffset().Z;
1586
1587 row["CameraAtOffsetX"] = prim.GetCameraAtOffset().X;
1588 row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y;
1589 row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z;
1590
1591
1592 if ((prim.SoundFlags & 1) != 0) // Looped
1593 {
1594 row["LoopedSound"] = prim.Sound.ToString();
1595 row["LoopedSoundGain"] = prim.SoundGain;
1596 }
1597 else
1598 {
1599 row["LoopedSound"] = UUID.Zero.ToString();
1600 row["LoopedSoundGain"] = 0.0f;
1601 }
1602
1603 if (prim.GetForceMouselook())
1604 row["ForceMouselook"] = 1;
1605 else
1606 row["ForceMouselook"] = 0;
1607
1608 row["ScriptAccessPin"] = prim.ScriptAccessPin;
1609
1610 if (prim.AllowedDrop)
1611 row["AllowedDrop"] = 1;
1612 else
1613 row["AllowedDrop"] = 0;
1614
1615 if (prim.DIE_AT_EDGE)
1616 row["DieAtEdge"] = 1;
1617 else
1618 row["DieAtEdge"] = 0;
1619
1620 row["SalePrice"] = prim.SalePrice;
1621 row["SaleType"] = Convert.ToInt16(prim.ObjectSaleType);
1622
1623 // click action
1624 row["ClickAction"] = prim.ClickAction;
1625
1626 row["SalePrice"] = prim.SalePrice;
1627 row["Material"] = prim.Material;
1628
1629 row["CollisionSound"] = prim.CollisionSound.ToString();
1630 row["CollisionSoundVolume"] = prim.CollisionSoundVolume;
1631 if (prim.VolumeDetectActive)
1632 row["VolumeDetect"] = 1;
1633 else
1634 row["VolumeDetect"] = 0;
1635
1636 }
1637
1638 /// <summary>
1639 ///
1640 /// </summary>
1641 /// <param name="row"></param>
1642 /// <param name="taskItem"></param>
1643 private static void fillItemRow(DataRow row, TaskInventoryItem taskItem)
1644 {
1645 row["itemID"] = taskItem.ItemID.ToString();
1646 row["primID"] = taskItem.ParentPartID.ToString();
1647 row["assetID"] = taskItem.AssetID.ToString();
1648 row["parentFolderID"] = taskItem.ParentID.ToString();
1649
1650 row["invType"] = taskItem.InvType;
1651 row["assetType"] = taskItem.Type;
1652
1653 row["name"] = taskItem.Name;
1654 row["description"] = taskItem.Description;
1655 row["creationDate"] = taskItem.CreationDate;
1656 row["creatorID"] = taskItem.CreatorID.ToString();
1657 row["ownerID"] = taskItem.OwnerID.ToString();
1658 row["lastOwnerID"] = taskItem.LastOwnerID.ToString();
1659 row["groupID"] = taskItem.GroupID.ToString();
1660 row["nextPermissions"] = taskItem.NextPermissions;
1661 row["currentPermissions"] = taskItem.CurrentPermissions;
1662 row["basePermissions"] = taskItem.BasePermissions;
1663 row["everyonePermissions"] = taskItem.EveryonePermissions;
1664 row["groupPermissions"] = taskItem.GroupPermissions;
1665 row["flags"] = taskItem.Flags;
1666 }
1667
1668 /// <summary>
1669 ///
1670 /// </summary>
1671 /// <param name="row"></param>
1672 /// <param name="land"></param>
1673 /// <param name="regionUUID"></param>
1674 private static void fillLandRow(DataRow row, LandData land, UUID regionUUID)
1675 {
1676 row["UUID"] = land.GlobalID.ToString();
1677 row["RegionUUID"] = regionUUID.ToString();
1678 row["LocalLandID"] = land.LocalID;
1679
1680 // Bitmap is a byte[512]
1681 row["Bitmap"] = land.Bitmap;
1682
1683 row["Name"] = land.Name;
1684 row["Desc"] = land.Description;
1685 row["OwnerUUID"] = land.OwnerID.ToString();
1686 row["IsGroupOwned"] = land.IsGroupOwned;
1687 row["Area"] = land.Area;
1688 row["AuctionID"] = land.AuctionID; //Unemplemented
1689 row["Category"] = land.Category; //Enum OpenMetaverse.Parcel.ParcelCategory
1690 row["ClaimDate"] = land.ClaimDate;
1691 row["ClaimPrice"] = land.ClaimPrice;
1692 row["GroupUUID"] = land.GroupID.ToString();
1693 row["SalePrice"] = land.SalePrice;
1694 row["LandStatus"] = land.Status; //Enum. OpenMetaverse.Parcel.ParcelStatus
1695 row["LandFlags"] = land.Flags;
1696 row["LandingType"] = land.LandingType;
1697 row["MediaAutoScale"] = land.MediaAutoScale;
1698 row["MediaTextureUUID"] = land.MediaID.ToString();
1699 row["MediaURL"] = land.MediaURL;
1700 row["MusicURL"] = land.MusicURL;
1701 row["PassHours"] = land.PassHours;
1702 row["PassPrice"] = land.PassPrice;
1703 row["SnapshotUUID"] = land.SnapshotID.ToString();
1704 row["UserLocationX"] = land.UserLocation.X;
1705 row["UserLocationY"] = land.UserLocation.Y;
1706 row["UserLocationZ"] = land.UserLocation.Z;
1707 row["UserLookAtX"] = land.UserLookAt.X;
1708 row["UserLookAtY"] = land.UserLookAt.Y;
1709 row["UserLookAtZ"] = land.UserLookAt.Z;
1710 row["AuthbuyerID"] = land.AuthBuyerID.ToString();
1711 row["OtherCleanTime"] = land.OtherCleanTime;
1712 }
1713
1714 /// <summary>
1715 ///
1716 /// </summary>
1717 /// <param name="row"></param>
1718 /// <param name="entry"></param>
1719 /// <param name="parcelID"></param>
1720 private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, UUID parcelID)
1721 {
1722 row["LandUUID"] = parcelID.ToString();
1723 row["AccessUUID"] = entry.AgentID.ToString();
1724 row["Flags"] = entry.Flags;
1725 }
1726
1727 private static void fillRegionSettingsRow(DataRow row, RegionSettings settings)
1728 {
1729 row["regionUUID"] = settings.RegionUUID.ToString();
1730 row["block_terraform"] = settings.BlockTerraform;
1731 row["block_fly"] = settings.BlockFly;
1732 row["allow_damage"] = settings.AllowDamage;
1733 row["restrict_pushing"] = settings.RestrictPushing;
1734 row["allow_land_resell"] = settings.AllowLandResell;
1735 row["allow_land_join_divide"] = settings.AllowLandJoinDivide;
1736 row["block_show_in_search"] = settings.BlockShowInSearch;
1737 row["agent_limit"] = settings.AgentLimit;
1738 row["object_bonus"] = settings.ObjectBonus;
1739 row["maturity"] = settings.Maturity;
1740 row["disable_scripts"] = settings.DisableScripts;
1741 row["disable_collisions"] = settings.DisableCollisions;
1742 row["disable_physics"] = settings.DisablePhysics;
1743 row["terrain_texture_1"] = settings.TerrainTexture1.ToString();
1744 row["terrain_texture_2"] = settings.TerrainTexture2.ToString();
1745 row["terrain_texture_3"] = settings.TerrainTexture3.ToString();
1746 row["terrain_texture_4"] = settings.TerrainTexture4.ToString();
1747 row["elevation_1_nw"] = settings.Elevation1NW;
1748 row["elevation_2_nw"] = settings.Elevation2NW;
1749 row["elevation_1_ne"] = settings.Elevation1NE;
1750 row["elevation_2_ne"] = settings.Elevation2NE;
1751 row["elevation_1_se"] = settings.Elevation1SE;
1752 row["elevation_2_se"] = settings.Elevation2SE;
1753 row["elevation_1_sw"] = settings.Elevation1SW;
1754 row["elevation_2_sw"] = settings.Elevation2SW;
1755 row["water_height"] = settings.WaterHeight;
1756 row["terrain_raise_limit"] = settings.TerrainRaiseLimit;
1757 row["terrain_lower_limit"] = settings.TerrainLowerLimit;
1758 row["use_estate_sun"] = settings.UseEstateSun;
1759 row["Sandbox"] = settings.Sandbox; // database uses upper case S for sandbox
1760 row["sunvectorx"] = settings.SunVector.X;
1761 row["sunvectory"] = settings.SunVector.Y;
1762 row["sunvectorz"] = settings.SunVector.Z;
1763 row["fixed_sun"] = settings.FixedSun;
1764 row["sun_position"] = settings.SunPosition;
1765 row["covenant"] = settings.Covenant.ToString();
1766 }
1767
1768 /// <summary>
1769 ///
1770 /// </summary>
1771 /// <param name="row"></param>
1772 /// <returns></returns>
1773 private PrimitiveBaseShape buildShape(DataRow row)
1774 {
1775 PrimitiveBaseShape s = new PrimitiveBaseShape();
1776 s.Scale = new Vector3(
1777 Convert.ToSingle(row["ScaleX"]),
1778 Convert.ToSingle(row["ScaleY"]),
1779 Convert.ToSingle(row["ScaleZ"])
1780 );
1781 // paths
1782 s.PCode = Convert.ToByte(row["PCode"]);
1783 s.PathBegin = Convert.ToUInt16(row["PathBegin"]);
1784 s.PathEnd = Convert.ToUInt16(row["PathEnd"]);
1785 s.PathScaleX = Convert.ToByte(row["PathScaleX"]);
1786 s.PathScaleY = Convert.ToByte(row["PathScaleY"]);
1787 s.PathShearX = Convert.ToByte(row["PathShearX"]);
1788 s.PathShearY = Convert.ToByte(row["PathShearY"]);
1789 s.PathSkew = Convert.ToSByte(row["PathSkew"]);
1790 s.PathCurve = Convert.ToByte(row["PathCurve"]);
1791 s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]);
1792 s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]);
1793 s.PathTaperX = Convert.ToSByte(row["PathTaperX"]);
1794 s.PathTaperY = Convert.ToSByte(row["PathTaperY"]);
1795 s.PathTwist = Convert.ToSByte(row["PathTwist"]);
1796 s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]);
1797 // profile
1798 s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]);
1799 s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]);
1800 s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]);
1801 s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]);
1802 s.State = Convert.ToByte(row["State"]);
1803
1804 byte[] textureEntry = (byte[])row["Texture"];
1805 s.TextureEntry = textureEntry;
1806
1807 s.ExtraParams = (byte[]) row["ExtraParams"];
1808 return s;
1809 }
1810
1811 /// <summary>
1812 ///
1813 /// </summary>
1814 /// <param name="row"></param>
1815 /// <param name="prim"></param>
1816 private static void fillShapeRow(DataRow row, SceneObjectPart prim)
1817 {
1818 PrimitiveBaseShape s = prim.Shape;
1819 row["UUID"] = prim.UUID.ToString();
1820 // shape is an enum
1821 row["Shape"] = 0;
1822 // vectors
1823 row["ScaleX"] = s.Scale.X;
1824 row["ScaleY"] = s.Scale.Y;
1825 row["ScaleZ"] = s.Scale.Z;
1826 // paths
1827 row["PCode"] = s.PCode;
1828 row["PathBegin"] = s.PathBegin;
1829 row["PathEnd"] = s.PathEnd;
1830 row["PathScaleX"] = s.PathScaleX;
1831 row["PathScaleY"] = s.PathScaleY;
1832 row["PathShearX"] = s.PathShearX;
1833 row["PathShearY"] = s.PathShearY;
1834 row["PathSkew"] = s.PathSkew;
1835 row["PathCurve"] = s.PathCurve;
1836 row["PathRadiusOffset"] = s.PathRadiusOffset;
1837 row["PathRevolutions"] = s.PathRevolutions;
1838 row["PathTaperX"] = s.PathTaperX;
1839 row["PathTaperY"] = s.PathTaperY;
1840 row["PathTwist"] = s.PathTwist;
1841 row["PathTwistBegin"] = s.PathTwistBegin;
1842 // profile
1843 row["ProfileBegin"] = s.ProfileBegin;
1844 row["ProfileEnd"] = s.ProfileEnd;
1845 row["ProfileCurve"] = s.ProfileCurve;
1846 row["ProfileHollow"] = s.ProfileHollow;
1847 row["State"] = s.State;
1848
1849 row["Texture"] = s.TextureEntry;
1850 row["ExtraParams"] = s.ExtraParams;
1851 }
1852
1853 /// <summary>
1854 ///
1855 /// </summary>
1856 /// <param name="prim"></param>
1857 /// <param name="sceneGroupID"></param>
1858 /// <param name="regionUUID"></param>
1859 private void addPrim(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
1860 {
1861
1862 DataTable prims = ds.Tables["prims"];
1863 DataTable shapes = ds.Tables["primshapes"];
1864
1865 DataRow primRow = prims.Rows.Find(prim.UUID.ToString());
1866 if (primRow == null)
1867 {
1868 primRow = prims.NewRow();
1869 fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
1870 prims.Rows.Add(primRow);
1871 }
1872 else
1873 {
1874 fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
1875 }
1876
1877 DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
1878 if (shapeRow == null)
1879 {
1880 shapeRow = shapes.NewRow();
1881 fillShapeRow(shapeRow, prim);
1882 shapes.Rows.Add(shapeRow);
1883 }
1884 else
1885 {
1886 fillShapeRow(shapeRow, prim);
1887 }
1888 }
1889
1890 /// <summary>
1891 /// see IRegionDatastore
1892 /// </summary>
1893 /// <param name="primID"></param>
1894 /// <param name="items"></param>
1895 public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
1896 {
1897 m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID);
1898
1899 DataTable dbItems = ds.Tables["primitems"];
1900
1901 // For now, we're just going to crudely remove all the previous inventory items
1902 // no matter whether they have changed or not, and replace them with the current set.
1903 lock (ds)
1904 {
1905 RemoveItems(primID);
1906
1907 // repalce with current inventory details
1908 foreach (TaskInventoryItem newItem in items)
1909 {
1910// m_log.InfoFormat(
1911// "[DATASTORE]: ",
1912// "Adding item {0}, {1} to prim ID {2}",
1913// newItem.Name, newItem.ItemID, newItem.ParentPartID);
1914
1915 DataRow newItemRow = dbItems.NewRow();
1916 fillItemRow(newItemRow, newItem);
1917 dbItems.Rows.Add(newItemRow);
1918 }
1919 }
1920
1921 Commit();
1922 }
1923
1924 /***********************************************************************
1925 *
1926 * SQL Statement Creation Functions
1927 *
1928 * These functions create SQL statements for update, insert, and create.
1929 * They can probably be factored later to have a db independant
1930 * portion and a db specific portion
1931 *
1932 **********************************************************************/
1933
1934 /// <summary>
1935 /// Create an insert command
1936 /// </summary>
1937 /// <param name="table">table name</param>
1938 /// <param name="dt">data table</param>
1939 /// <returns>the created command</returns>
1940 /// <remarks>
1941 /// This is subtle enough to deserve some commentary.
1942 /// Instead of doing *lots* and *lots of hardcoded strings
1943 /// for database definitions we'll use the fact that
1944 /// realistically all insert statements look like "insert
1945 /// into A(b, c) values(:b, :c) on the parameterized query
1946 /// front. If we just have a list of b, c, etc... we can
1947 /// generate these strings instead of typing them out.
1948 /// </remarks>
1949 private static SqliteCommand createInsertCommand(string table, DataTable dt)
1950 {
1951 string[] cols = new string[dt.Columns.Count];
1952 for (int i = 0; i < dt.Columns.Count; i++)
1953 {
1954 DataColumn col = dt.Columns[i];
1955 cols[i] = col.ColumnName;
1956 }
1957
1958 string sql = "insert into " + table + "(";
1959 sql += String.Join(", ", cols);
1960 // important, the first ':' needs to be here, the rest get added in the join
1961 sql += ") values (:";
1962 sql += String.Join(", :", cols);
1963 sql += ")";
1964 SqliteCommand cmd = new SqliteCommand(sql);
1965
1966 // this provides the binding for all our parameters, so
1967 // much less code than it used to be
1968 foreach (DataColumn col in dt.Columns)
1969 {
1970 cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
1971 }
1972 return cmd;
1973 }
1974
1975
1976 /// <summary>
1977 /// create an update command
1978 /// </summary>
1979 /// <param name="table">table name</param>
1980 /// <param name="pk"></param>
1981 /// <param name="dt"></param>
1982 /// <returns>the created command</returns>
1983 private static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
1984 {
1985 string sql = "update " + table + " set ";
1986 string subsql = String.Empty;
1987 foreach (DataColumn col in dt.Columns)
1988 {
1989 if (subsql.Length > 0)
1990 {
1991 // a map function would rock so much here
1992 subsql += ", ";
1993 }
1994 subsql += col.ColumnName + "= :" + col.ColumnName;
1995 }
1996 sql += subsql;
1997 sql += " where " + pk;
1998 SqliteCommand cmd = new SqliteCommand(sql);
1999
2000 // this provides the binding for all our parameters, so
2001 // much less code than it used to be
2002
2003 foreach (DataColumn col in dt.Columns)
2004 {
2005 cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
2006 }
2007 return cmd;
2008 }
2009
2010 /// <summary>
2011 /// create an update command
2012 /// </summary>
2013 /// <param name="table">table name</param>
2014 /// <param name="pk"></param>
2015 /// <param name="dt"></param>
2016 /// <returns>the created command</returns>
2017 private static SqliteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt)
2018 {
2019 string sql = "update " + table + " set ";
2020 string subsql = String.Empty;
2021 foreach (DataColumn col in dt.Columns)
2022 {
2023 if (subsql.Length > 0)
2024 {
2025 // a map function would rock so much here
2026 subsql += ", ";
2027 }
2028 subsql += col.ColumnName + "= :" + col.ColumnName;
2029 }
2030 sql += subsql;
2031 sql += " where " + pk1 + " and " + pk2;
2032 SqliteCommand cmd = new SqliteCommand(sql);
2033
2034 // this provides the binding for all our parameters, so
2035 // much less code than it used to be
2036
2037 foreach (DataColumn col in dt.Columns)
2038 {
2039 cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
2040 }
2041 return cmd;
2042 }
2043
2044 /// <summary>
2045 ///
2046 /// </summary>
2047 /// <param name="dt">Data Table</param>
2048 /// <returns></returns>
2049 // private static string defineTable(DataTable dt)
2050 // {
2051 // string sql = "create table " + dt.TableName + "(";
2052 // string subsql = String.Empty;
2053 // foreach (DataColumn col in dt.Columns)
2054 // {
2055 // if (subsql.Length > 0)
2056 // {
2057 // // a map function would rock so much here
2058 // subsql += ",\n";
2059 // }
2060 // subsql += col.ColumnName + " " + sqliteType(col.DataType);
2061 // if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0])
2062 // {
2063 // subsql += " primary key";
2064 // }
2065 // }
2066 // sql += subsql;
2067 // sql += ")";
2068 // return sql;
2069 // }
2070
2071 /***********************************************************************
2072 *
2073 * Database Binding functions
2074 *
2075 * These will be db specific due to typing, and minor differences
2076 * in databases.
2077 *
2078 **********************************************************************/
2079
2080 ///<summary>
2081 /// This is a convenience function that collapses 5 repetitive
2082 /// lines for defining SqliteParameters to 2 parameters:
2083 /// column name and database type.
2084 ///
2085 /// It assumes certain conventions like :param as the param
2086 /// name to replace in parametrized queries, and that source
2087 /// version is always current version, both of which are fine
2088 /// for us.
2089 ///</summary>
2090 ///<returns>a built sqlite parameter</returns>
2091 private static SqliteParameter createSqliteParameter(string name, Type type)
2092 {
2093 SqliteParameter param = new SqliteParameter();
2094 param.ParameterName = ":" + name;
2095 param.DbType = dbtypeFromType(type);
2096 param.SourceColumn = name;
2097 param.SourceVersion = DataRowVersion.Current;
2098 return param;
2099 }
2100
2101 /// <summary>
2102 ///
2103 /// </summary>
2104 /// <param name="da"></param>
2105 /// <param name="conn"></param>
2106 private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn)
2107 {
2108 da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]);
2109 da.InsertCommand.Connection = conn;
2110
2111 da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]);
2112 da.UpdateCommand.Connection = conn;
2113
2114 SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID");
2115 delete.Parameters.Add(createSqliteParameter("UUID", typeof (String)));
2116 delete.Connection = conn;
2117 da.DeleteCommand = delete;
2118 }
2119
2120 /// <summary>
2121 ///
2122 /// </summary>
2123 /// <param name="da"></param>
2124 /// <param name="conn"></param>
2125 private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
2126 {
2127 da.InsertCommand = createInsertCommand("primitems", ds.Tables["primitems"]);
2128 da.InsertCommand.Connection = conn;
2129
2130 da.UpdateCommand = createUpdateCommand("primitems", "itemID = :itemID", ds.Tables["primitems"]);
2131 da.UpdateCommand.Connection = conn;
2132
2133 SqliteCommand delete = new SqliteCommand("delete from primitems where itemID = :itemID");
2134 delete.Parameters.Add(createSqliteParameter("itemID", typeof (String)));
2135 delete.Connection = conn;
2136 da.DeleteCommand = delete;
2137 }
2138
2139 /// <summary>
2140 ///
2141 /// </summary>
2142 /// <param name="da"></param>
2143 /// <param name="conn"></param>
2144 private void setupTerrainCommands(SqliteDataAdapter da, SqliteConnection conn)
2145 {
2146 da.InsertCommand = createInsertCommand("terrain", ds.Tables["terrain"]);
2147 da.InsertCommand.Connection = conn;
2148 }
2149
2150 /// <summary>
2151 ///
2152 /// </summary>
2153 /// <param name="da"></param>
2154 /// <param name="conn"></param>
2155 private void setupLandCommands(SqliteDataAdapter da, SqliteConnection conn)
2156 {
2157 da.InsertCommand = createInsertCommand("land", ds.Tables["land"]);
2158 da.InsertCommand.Connection = conn;
2159
2160 da.UpdateCommand = createUpdateCommand("land", "UUID=:UUID", ds.Tables["land"]);
2161 da.UpdateCommand.Connection = conn;
2162
2163 SqliteCommand delete = new SqliteCommand("delete from land where UUID=:UUID");
2164 delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
2165 da.DeleteCommand = delete;
2166 da.DeleteCommand.Connection = conn;
2167 }
2168
2169 /// <summary>
2170 ///
2171 /// </summary>
2172 /// <param name="da"></param>
2173 /// <param name="conn"></param>
2174 private void setupLandAccessCommands(SqliteDataAdapter da, SqliteConnection conn)
2175 {
2176 da.InsertCommand = createInsertCommand("landaccesslist", ds.Tables["landaccesslist"]);
2177 da.InsertCommand.Connection = conn;
2178
2179 da.UpdateCommand = createUpdateCommand("landaccesslist", "LandUUID=:landUUID", "AccessUUID=:AccessUUID", ds.Tables["landaccesslist"]);
2180 da.UpdateCommand.Connection = conn;
2181
2182 SqliteCommand delete = new SqliteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID");
2183 delete.Parameters.Add(createSqliteParameter("LandUUID", typeof(String)));
2184 delete.Parameters.Add(createSqliteParameter("AccessUUID", typeof(String)));
2185 da.DeleteCommand = delete;
2186 da.DeleteCommand.Connection = conn;
2187
2188 }
2189
2190 private void setupRegionSettingsCommands(SqliteDataAdapter da, SqliteConnection conn)
2191 {
2192 da.InsertCommand = createInsertCommand("regionsettings", ds.Tables["regionsettings"]);
2193 da.InsertCommand.Connection = conn;
2194 da.UpdateCommand = createUpdateCommand("regionsettings", "regionUUID=:regionUUID", ds.Tables["regionsettings"]);
2195 da.UpdateCommand.Connection = conn;
2196 }
2197
2198 /// <summary>
2199 ///
2200 /// </summary>
2201 /// <param name="da"></param>
2202 /// <param name="conn"></param>
2203 private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn)
2204 {
2205 da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]);
2206 da.InsertCommand.Connection = conn;
2207
2208 da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]);
2209 da.UpdateCommand.Connection = conn;
2210
2211 SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID");
2212 delete.Parameters.Add(createSqliteParameter("UUID", typeof (String)));
2213 delete.Connection = conn;
2214 da.DeleteCommand = delete;
2215 }
2216
2217 /***********************************************************************
2218 *
2219 * Type conversion functions
2220 *
2221 **********************************************************************/
2222
2223 /// <summary>
2224 /// Type conversion function
2225 /// </summary>
2226 /// <param name="type"></param>
2227 /// <returns></returns>
2228 private static DbType dbtypeFromType(Type type)
2229 {
2230 if (type == typeof (String))
2231 {
2232 return DbType.String;
2233 }
2234 else if (type == typeof (Int32))
2235 {
2236 return DbType.Int32;
2237 }
2238 else if (type == typeof (Double))
2239 {
2240 return DbType.Double;
2241 }
2242 else if (type == typeof (Byte))
2243 {
2244 return DbType.Byte;
2245 }
2246 else if (type == typeof (Double))
2247 {
2248 return DbType.Double;
2249 }
2250 else if (type == typeof (Byte[]))
2251 {
2252 return DbType.Binary;
2253 }
2254 else
2255 {
2256 return DbType.String;
2257 }
2258 }
2259
2260 }
2261}