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