aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps')
-rw-r--r--OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs1070
-rw-r--r--OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshCost.cs727
2 files changed, 1575 insertions, 222 deletions
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
index 774202e..1236e83 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
@@ -26,6 +26,7 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Timers;
29using System.Collections; 30using System.Collections;
30using System.Collections.Generic; 31using System.Collections.Generic;
31using System.IO; 32using System.IO;
@@ -44,7 +45,6 @@ using OpenSim.Region.Framework.Scenes;
44using OpenSim.Region.Framework.Scenes.Serialization; 45using OpenSim.Region.Framework.Scenes.Serialization;
45using OpenSim.Framework.Servers; 46using OpenSim.Framework.Servers;
46using OpenSim.Framework.Servers.HttpServer; 47using OpenSim.Framework.Servers.HttpServer;
47using OpenSim.Framework.Client;
48using OpenSim.Services.Interfaces; 48using OpenSim.Services.Interfaces;
49 49
50using Caps = OpenSim.Framework.Capabilities.Caps; 50using Caps = OpenSim.Framework.Capabilities.Caps;
@@ -55,14 +55,16 @@ using PermissionMask = OpenSim.Framework.PermissionMask;
55namespace OpenSim.Region.ClientStack.Linden 55namespace OpenSim.Region.ClientStack.Linden
56{ 56{
57 public delegate void UpLoadedAsset( 57 public delegate void UpLoadedAsset(
58 string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder, 58 string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
59 byte[] data, string inventoryType, string assetType); 59 byte[] data, string inventoryType, string assetType,
60 int cost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
61 bool IsAtestUpload, ref string error);
60 62
61 public delegate UUID UpdateItem(UUID itemID, byte[] data); 63 public delegate UUID UpdateItem(UUID itemID, byte[] data);
62 64
63 public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors); 65 public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
64 66
65 public delegate void NewInventoryItem(UUID userID, InventoryItemBase item); 67 public delegate void NewInventoryItem(UUID userID, InventoryItemBase item, uint cost);
66 68
67 public delegate void NewAsset(AssetBase asset); 69 public delegate void NewAsset(AssetBase asset);
68 70
@@ -88,6 +90,7 @@ namespace OpenSim.Region.ClientStack.Linden
88 90
89 private Scene m_Scene; 91 private Scene m_Scene;
90 private Caps m_HostCapsObj; 92 private Caps m_HostCapsObj;
93 private ModelCost m_ModelCost;
91 94
92 private static readonly string m_requestPath = "0000/"; 95 private static readonly string m_requestPath = "0000/";
93 // private static readonly string m_mapLayerPath = "0001/"; 96 // private static readonly string m_mapLayerPath = "0001/";
@@ -99,8 +102,10 @@ namespace OpenSim.Region.ClientStack.Linden
99 private static readonly string m_copyFromNotecardPath = "0007/"; 102 private static readonly string m_copyFromNotecardPath = "0007/";
100 // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule. 103 // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
101 private static readonly string m_getObjectPhysicsDataPath = "0101/"; 104 private static readonly string m_getObjectPhysicsDataPath = "0101/";
102 /* 0102 - 0103 RESERVED */ 105 private static readonly string m_getObjectCostPath = "0102/";
106 private static readonly string m_ResourceCostSelectedPath = "0103/";
103 private static readonly string m_UpdateAgentInformationPath = "0500/"; 107 private static readonly string m_UpdateAgentInformationPath = "0500/";
108 private static readonly string m_animSetTaskUpdatePath = "0260/";
104 109
105 // These are callbacks which will be setup by the scene so that we can update scene data when we 110 // These are callbacks which will be setup by the scene so that we can update scene data when we
106 // receive capability calls 111 // receive capability calls
@@ -115,12 +120,50 @@ namespace OpenSim.Region.ClientStack.Linden
115 private IAssetService m_assetService; 120 private IAssetService m_assetService;
116 private bool m_dumpAssetsToFile = false; 121 private bool m_dumpAssetsToFile = false;
117 private string m_regionName; 122 private string m_regionName;
123
118 private int m_levelUpload = 0; 124 private int m_levelUpload = 0;
119 125
126 private bool m_enableFreeTestUpload = false; // allows "TEST-" prefix hack
127 private bool m_ForceFreeTestUpload = false; // forces all uploads to be test
128
129 private bool m_enableModelUploadTextureToInventory = false; // place uploaded textures also in inventory
130 // may not be visible till relog
131
132 private bool m_RestrictFreeTestUploadPerms = false; // reduces also the permitions. Needs a creator defined!!
133 private UUID m_testAssetsCreatorID = UUID.Zero;
134
135 private float m_PrimScaleMin = 0.001f;
136
137 private enum FileAgentInventoryState : int
138 {
139 idle = 0,
140 processRequest = 1,
141 waitUpload = 2,
142 processUpload = 3
143 }
144 private FileAgentInventoryState m_FileAgentInventoryState = FileAgentInventoryState.idle;
145
120 public BunchOfCaps(Scene scene, Caps caps) 146 public BunchOfCaps(Scene scene, Caps caps)
121 { 147 {
122 m_Scene = scene; 148 m_Scene = scene;
123 m_HostCapsObj = caps; 149 m_HostCapsObj = caps;
150
151 // create a model upload cost provider
152 m_ModelCost = new ModelCost();
153 // tell it about scene object limits
154 m_ModelCost.NonPhysicalPrimScaleMax = m_Scene.m_maxNonphys;
155 m_ModelCost.PhysicalPrimScaleMax = m_Scene.m_maxPhys;
156
157// m_ModelCost.ObjectLinkedPartsMax = ??
158// m_ModelCost.PrimScaleMin = ??
159
160 m_PrimScaleMin = m_ModelCost.PrimScaleMin;
161 float modelTextureUploadFactor = m_ModelCost.ModelTextureCostFactor;
162 float modelUploadFactor = m_ModelCost.ModelMeshCostFactor;
163 float modelMinUploadCostFactor = m_ModelCost.ModelMinCostFactor;
164 float modelPrimCreationCost = m_ModelCost.primCreationCost;
165 float modelMeshByteCost = m_ModelCost.bytecost;
166
124 IConfigSource config = m_Scene.Config; 167 IConfigSource config = m_Scene.Config;
125 if (config != null) 168 if (config != null)
126 { 169 {
@@ -135,6 +178,37 @@ namespace OpenSim.Region.ClientStack.Linden
135 { 178 {
136 m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures); 179 m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
137 } 180 }
181 // economy for model upload
182 IConfig EconomyConfig = config.Configs["Economy"];
183 if (EconomyConfig != null)
184 {
185 modelUploadFactor = EconomyConfig.GetFloat("MeshModelUploadCostFactor", modelUploadFactor);
186 modelTextureUploadFactor = EconomyConfig.GetFloat("MeshModelUploadTextureCostFactor", modelTextureUploadFactor);
187 modelMinUploadCostFactor = EconomyConfig.GetFloat("MeshModelMinCostFactor", modelMinUploadCostFactor);
188 // next 2 are normalized so final cost is afected by modelUploadFactor above and normal cost
189 modelPrimCreationCost = EconomyConfig.GetFloat("ModelPrimCreationCost", modelPrimCreationCost);
190 modelMeshByteCost = EconomyConfig.GetFloat("ModelMeshByteCost", modelMeshByteCost);
191
192 m_enableModelUploadTextureToInventory = EconomyConfig.GetBoolean("MeshModelAllowTextureToInventory", m_enableModelUploadTextureToInventory);
193
194 m_RestrictFreeTestUploadPerms = EconomyConfig.GetBoolean("m_RestrictFreeTestUploadPerms", m_RestrictFreeTestUploadPerms);
195 m_enableFreeTestUpload = EconomyConfig.GetBoolean("AllowFreeTestUpload", m_enableFreeTestUpload);
196 m_ForceFreeTestUpload = EconomyConfig.GetBoolean("ForceFreeTestUpload", m_ForceFreeTestUpload);
197 string testcreator = EconomyConfig.GetString("TestAssetsCreatorID", "");
198 if (testcreator != "")
199 {
200 UUID id;
201 UUID.TryParse(testcreator, out id);
202 if (id != null)
203 m_testAssetsCreatorID = id;
204 }
205
206 m_ModelCost.ModelMeshCostFactor = modelUploadFactor;
207 m_ModelCost.ModelTextureCostFactor = modelTextureUploadFactor;
208 m_ModelCost.ModelMinCostFactor = modelMinUploadCostFactor;
209 m_ModelCost.primCreationCost = modelPrimCreationCost;
210 m_ModelCost.bytecost = modelMeshByteCost;
211 }
138 } 212 }
139 213
140 m_assetService = m_Scene.AssetService; 214 m_assetService = m_Scene.AssetService;
@@ -146,6 +220,8 @@ namespace OpenSim.Region.ClientStack.Linden
146 ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset; 220 ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset;
147 TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset; 221 TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
148 GetClient = m_Scene.SceneGraph.GetControllingClient; 222 GetClient = m_Scene.SceneGraph.GetControllingClient;
223
224 m_FileAgentInventoryState = FileAgentInventoryState.idle;
149 } 225 }
150 226
151 /// <summary> 227 /// <summary>
@@ -173,13 +249,31 @@ namespace OpenSim.Region.ClientStack.Linden
173 //m_capsHandlers["MapLayer"] = 249 //m_capsHandlers["MapLayer"] =
174 // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST", 250 // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
175 // capsBase + m_mapLayerPath, 251 // capsBase + m_mapLayerPath,
176 // GetMapLayer); 252 // GetMapLayer);
253
254 IRequestHandler getObjectPhysicsDataHandler
255 = new RestStreamHandler(
256 "POST", capsBase + m_getObjectPhysicsDataPath, GetObjectPhysicsData, "GetObjectPhysicsData", null);
257 m_HostCapsObj.RegisterHandler("GetObjectPhysicsData", getObjectPhysicsDataHandler);
258
259 IRequestHandler getObjectCostHandler = new RestStreamHandler("POST", capsBase + m_getObjectCostPath, GetObjectCost);
260 m_HostCapsObj.RegisterHandler("GetObjectCost", getObjectCostHandler);
261 IRequestHandler ResourceCostSelectedHandler = new RestStreamHandler("POST", capsBase + m_ResourceCostSelectedPath, ResourceCostSelected);
262 m_HostCapsObj.RegisterHandler("ResourceCostSelected", ResourceCostSelectedHandler);
263
264
177 IRequestHandler req 265 IRequestHandler req
178 = new RestStreamHandler( 266 = new RestStreamHandler(
179 "POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory, "UpdateScript", null); 267 "POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory, "UpdateScript", null);
180 268
181 m_HostCapsObj.RegisterHandler("UpdateScriptTaskInventory", req); 269 m_HostCapsObj.RegisterHandler("UpdateScriptTaskInventory", req);
182 m_HostCapsObj.RegisterHandler("UpdateScriptTask", req); 270 m_HostCapsObj.RegisterHandler("UpdateScriptTask", req);
271
272// IRequestHandler animSetRequestHandler
273// = new RestStreamHandler(
274// "POST", capsBase + m_animSetTaskUpdatePath, AnimSetTaskInventory, "UpdateScript", null);
275
276// m_HostCapsObj.RegisterHandler("UpdateAnimSetTaskInventory", animSetRequestHandler);
183 } 277 }
184 catch (Exception e) 278 catch (Exception e)
185 { 279 {
@@ -191,7 +285,6 @@ namespace OpenSim.Region.ClientStack.Linden
191 { 285 {
192 try 286 try
193 { 287 {
194 // I don't think this one works...
195 m_HostCapsObj.RegisterHandler( 288 m_HostCapsObj.RegisterHandler(
196 "NewFileAgentInventory", 289 "NewFileAgentInventory",
197 new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>( 290 new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>(
@@ -206,13 +299,11 @@ namespace OpenSim.Region.ClientStack.Linden
206 "POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory, "Update*", null); 299 "POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory, "Update*", null);
207 300
208 m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req); 301 m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req);
302 m_HostCapsObj.RegisterHandler("UpdateAnimSetAgentInventory", req);
209 m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req); 303 m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req);
210 m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req); 304 m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req);
211 305
212 IRequestHandler getObjectPhysicsDataHandler 306
213 = new RestStreamHandler(
214 "POST", capsBase + m_getObjectPhysicsDataPath, GetObjectPhysicsData, "GetObjectPhysicsData", null);
215 m_HostCapsObj.RegisterHandler("GetObjectPhysicsData", getObjectPhysicsDataHandler);
216 307
217 IRequestHandler UpdateAgentInformationHandler 308 IRequestHandler UpdateAgentInformationHandler
218 = new RestStreamHandler( 309 = new RestStreamHandler(
@@ -268,8 +359,11 @@ namespace OpenSim.Region.ClientStack.Linden
268 public string SeedCapRequest(string request, string path, string param, 359 public string SeedCapRequest(string request, string path, string param,
269 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) 360 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
270 { 361 {
271// m_log.DebugFormat( 362 m_log.DebugFormat(
272// "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, m_HostCapsObj.AgentID); 363 "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, m_HostCapsObj.AgentID);
364
365 if (!m_HostCapsObj.WaitForActivation())
366 return string.Empty;
273 367
274 if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint)) 368 if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint))
275 { 369 {
@@ -400,62 +494,178 @@ namespace OpenSim.Region.ClientStack.Linden
400 //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString()); 494 //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
401 //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type); 495 //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
402 496
497 // start by getting the client
498 IClientAPI client = null;
499 m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
500
501 // check current state so we only have one service at a time
502 lock (m_ModelCost)
503 {
504 switch (m_FileAgentInventoryState)
505 {
506 case FileAgentInventoryState.processRequest:
507 case FileAgentInventoryState.processUpload:
508 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
509 resperror.message = "Uploader busy processing previus request";
510 resperror.identifier = UUID.Zero;
511
512 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
513 errorResponse.uploader = "";
514 errorResponse.state = "error";
515 errorResponse.error = resperror;
516 return errorResponse;
517 break;
518 case FileAgentInventoryState.waitUpload:
519 // todo stop current uploader server
520 break;
521 case FileAgentInventoryState.idle:
522 default:
523 break;
524 }
525
526 m_FileAgentInventoryState = FileAgentInventoryState.processRequest;
527 }
528
529 int cost = 0;
530 int nreqtextures = 0;
531 int nreqmeshs= 0;
532 int nreqinstances = 0;
533 bool IsAtestUpload = false;
534
535 string assetName = llsdRequest.name;
536
537 LLSDAssetUploadResponseData meshcostdata = new LLSDAssetUploadResponseData();
538
403 if (llsdRequest.asset_type == "texture" || 539 if (llsdRequest.asset_type == "texture" ||
404 llsdRequest.asset_type == "animation" || 540 llsdRequest.asset_type == "animation" ||
541 llsdRequest.asset_type == "animatn" || // this is the asset name actually used by viewers
542 llsdRequest.asset_type == "mesh" ||
405 llsdRequest.asset_type == "sound") 543 llsdRequest.asset_type == "sound")
406 { 544 {
407 ScenePresence avatar = null; 545 ScenePresence avatar = null;
408 IClientAPI client = null;
409 m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar); 546 m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
410 547
411 // check user level 548 // check user level
412 if (avatar != null) 549 if (avatar != null)
413 { 550 {
414 client = avatar.ControllingClient;
415
416 if (avatar.UserLevel < m_levelUpload) 551 if (avatar.UserLevel < m_levelUpload)
417 { 552 {
418 if (client != null) 553 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
419 client.SendAgentAlertMessage("Unable to upload asset. Insufficient permissions.", false); 554 resperror.message = "Insufficient permissions to upload";
555 resperror.identifier = UUID.Zero;
420 556
421 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse(); 557 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
422 errorResponse.uploader = ""; 558 errorResponse.uploader = "";
423 errorResponse.state = "error"; 559 errorResponse.state = "error";
560 errorResponse.error = resperror;
561 lock (m_ModelCost)
562 m_FileAgentInventoryState = FileAgentInventoryState.idle;
424 return errorResponse; 563 return errorResponse;
425 } 564 }
426 } 565 }
427 566
428 // check funds 567 // check test upload and funds
429 if (client != null) 568 if (client != null)
430 { 569 {
431 IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>(); 570 IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
432 571
572 int baseCost = 0;
433 if (mm != null) 573 if (mm != null)
574 baseCost = mm.UploadCharge;
575
576 string warning = String.Empty;
577
578 if (llsdRequest.asset_type == "mesh")
434 { 579 {
435 if (!mm.UploadCovered(client.AgentId, mm.UploadCharge)) 580 string error;
581 int modelcost;
582
583
584 if (!m_ModelCost.MeshModelCost(llsdRequest.asset_resources, baseCost, out modelcost,
585 meshcostdata, out error, ref warning))
436 { 586 {
437 client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); 587 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
588 resperror.message = error;
589 resperror.identifier = UUID.Zero;
438 590
439 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse(); 591 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
440 errorResponse.uploader = ""; 592 errorResponse.uploader = "";
441 errorResponse.state = "error"; 593 errorResponse.state = "error";
594 errorResponse.error = resperror;
595
596 lock (m_ModelCost)
597 m_FileAgentInventoryState = FileAgentInventoryState.idle;
442 return errorResponse; 598 return errorResponse;
443 } 599 }
600 cost = modelcost;
601 }
602 else
603 {
604 cost = baseCost;
605 }
606
607 if (cost > 0 && mm != null)
608 {
609 // check for test upload
610
611 if (m_ForceFreeTestUpload) // all are test
612 {
613 if (!(assetName.Length > 5 && assetName.StartsWith("TEST-"))) // has normal name lets change it
614 assetName = "TEST-" + assetName;
615
616 IsAtestUpload = true;
617 }
618
619 else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
620 {
621
622 IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
623 }
624
625
626 if(IsAtestUpload) // let user know, still showing cost estimation
627 warning += "Upload will have no cost, for testing purposes only. Other uses are prohibited. Items will not work after 48 hours or on other regions";
628
629 // check funds
630 else
631 {
632 if (!mm.UploadCovered(client.AgentId, (int)cost))
633 {
634 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
635 resperror.message = "Insuficient funds";
636 resperror.identifier = UUID.Zero;
637
638 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
639 errorResponse.uploader = "";
640 errorResponse.state = "error";
641 errorResponse.error = resperror;
642 lock (m_ModelCost)
643 m_FileAgentInventoryState = FileAgentInventoryState.idle;
644 return errorResponse;
645 }
646 }
444 } 647 }
648
649 if (client != null && warning != String.Empty)
650 client.SendAgentAlertMessage(warning, true);
445 } 651 }
446 } 652 }
447 653
448 string assetName = llsdRequest.name;
449 string assetDes = llsdRequest.description; 654 string assetDes = llsdRequest.description;
450 string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath; 655 string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
451 UUID newAsset = UUID.Random(); 656 UUID newAsset = UUID.Random();
452 UUID newInvItem = UUID.Random(); 657 UUID newInvItem = UUID.Random();
453 UUID parentFolder = llsdRequest.folder_id; 658 UUID parentFolder = llsdRequest.folder_id;
454 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000"); 659 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
660 UUID texturesFolder = UUID.Zero;
661
662 if(!IsAtestUpload && m_enableModelUploadTextureToInventory)
663 texturesFolder = llsdRequest.texture_folder_id;
455 664
456 AssetUploader uploader = 665 AssetUploader uploader =
457 new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type, 666 new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
458 llsdRequest.asset_type, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile); 667 llsdRequest.asset_type, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile, cost,
668 texturesFolder, nreqtextures, nreqmeshs, nreqinstances, IsAtestUpload);
459 669
460 m_HostCapsObj.HttpListener.AddStreamHandler( 670 m_HostCapsObj.HttpListener.AddStreamHandler(
461 new BinaryStreamHandler( 671 new BinaryStreamHandler(
@@ -473,10 +683,22 @@ namespace OpenSim.Region.ClientStack.Linden
473 string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase + 683 string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
474 uploaderPath; 684 uploaderPath;
475 685
686
476 LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse(); 687 LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
477 uploadResponse.uploader = uploaderURL; 688 uploadResponse.uploader = uploaderURL;
478 uploadResponse.state = "upload"; 689 uploadResponse.state = "upload";
690 uploadResponse.upload_price = (int)cost;
691
692 if (llsdRequest.asset_type == "mesh")
693 {
694 uploadResponse.data = meshcostdata;
695 }
696
479 uploader.OnUpLoad += UploadCompleteHandler; 697 uploader.OnUpLoad += UploadCompleteHandler;
698
699 lock (m_ModelCost)
700 m_FileAgentInventoryState = FileAgentInventoryState.waitUpload;
701
480 return uploadResponse; 702 return uploadResponse;
481 } 703 }
482 704
@@ -488,8 +710,14 @@ namespace OpenSim.Region.ClientStack.Linden
488 /// <param name="data"></param> 710 /// <param name="data"></param>
489 public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID, 711 public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
490 UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType, 712 UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
491 string assetType) 713 string assetType, int cost,
714 UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
715 bool IsAtestUpload, ref string error)
492 { 716 {
717
718 lock (m_ModelCost)
719 m_FileAgentInventoryState = FileAgentInventoryState.processUpload;
720
493 m_log.DebugFormat( 721 m_log.DebugFormat(
494 "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}", 722 "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
495 assetID, inventoryItem, inventoryType, assetType); 723 assetID, inventoryItem, inventoryType, assetType);
@@ -497,6 +725,34 @@ namespace OpenSim.Region.ClientStack.Linden
497 sbyte assType = 0; 725 sbyte assType = 0;
498 sbyte inType = 0; 726 sbyte inType = 0;
499 727
728 IClientAPI client = null;
729
730 UUID owner_id = m_HostCapsObj.AgentID;
731 UUID creatorID;
732
733 bool istest = IsAtestUpload && m_enableFreeTestUpload && (cost > 0);
734
735 bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;
736
737 if (istest && m_testAssetsCreatorID != UUID.Zero)
738 creatorID = m_testAssetsCreatorID;
739 else
740 creatorID = owner_id;
741
742 string creatorIDstr = creatorID.ToString();
743
744 IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
745 if (mm != null)
746 {
747 // make sure client still has enougth credit
748 if (!mm.UploadCovered(m_HostCapsObj.AgentID, (int)cost))
749 {
750 error = "Insufficient funds.";
751 return;
752 }
753 }
754
755 // strings to types
500 if (inventoryType == "sound") 756 if (inventoryType == "sound")
501 { 757 {
502 inType = (sbyte)InventoryType.Sound; 758 inType = (sbyte)InventoryType.Sound;
@@ -511,6 +767,12 @@ namespace OpenSim.Region.ClientStack.Linden
511 inType = (sbyte)InventoryType.Animation; 767 inType = (sbyte)InventoryType.Animation;
512 assType = (sbyte)AssetType.Animation; 768 assType = (sbyte)AssetType.Animation;
513 } 769 }
770 else if (inventoryType == "animset")
771 {
772 inType = (sbyte)CustomInventoryType.AnimationSet;
773 assType = (sbyte)CustomAssetType.AnimationSet;
774 m_log.Debug("got animset upload request");
775 }
514 else if (inventoryType == "wearable") 776 else if (inventoryType == "wearable")
515 { 777 {
516 inType = (sbyte)InventoryType.Wearable; 778 inType = (sbyte)InventoryType.Wearable;
@@ -526,159 +788,253 @@ namespace OpenSim.Region.ClientStack.Linden
526 } 788 }
527 else if (inventoryType == "object") 789 else if (inventoryType == "object")
528 { 790 {
529 inType = (sbyte)InventoryType.Object; 791 if (assetType == "mesh") // this code for now is for mesh models uploads only
530 assType = (sbyte)AssetType.Object;
531
532 List<Vector3> positions = new List<Vector3>();
533 List<Quaternion> rotations = new List<Quaternion>();
534 OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
535 OSDArray instance_list = (OSDArray)request["instance_list"];
536 OSDArray mesh_list = (OSDArray)request["mesh_list"];
537 OSDArray texture_list = (OSDArray)request["texture_list"];
538 SceneObjectGroup grp = null;
539
540 InventoryFolderBase textureUploadFolder = null;
541
542 List<InventoryFolderBase> foldersToUpdate = new List<InventoryFolderBase>();
543 List<InventoryItemBase> itemsToUpdate = new List<InventoryItemBase>();
544 IClientInventory clientInv = null;
545
546 if (texture_list.Count > 0)
547 { 792 {
548 ScenePresence avatar = null; 793 inType = (sbyte)InventoryType.Object;
549 m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar); 794 assType = (sbyte)AssetType.Object;
795
796 List<Vector3> positions = new List<Vector3>();
797 List<Quaternion> rotations = new List<Quaternion>();
798 OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
799
800 // compare and get updated information
801/* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation
802 bool mismatchError = true;
550 803
551 if (avatar != null) 804 while (mismatchError)
552 { 805 {
553 IClientCore core = (IClientCore)avatar.ControllingClient; 806 mismatchError = false;
807 }
808
809 if (mismatchError)
810 {
811 error = "Upload and fee estimation information don't match";
812 lock (m_ModelCost)
813 m_FileAgentInventoryState = FileAgentInventoryState.idle;
814
815 return;
816 }
817*/
818 OSDArray instance_list = (OSDArray)request["instance_list"];
819 OSDArray mesh_list = (OSDArray)request["mesh_list"];
820 OSDArray texture_list = (OSDArray)request["texture_list"];
821 SceneObjectGroup grp = null;
822
823 // create and store texture assets
824 bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
825 texturesFolder != UUID.Zero);
554 826
555 if (core.TryGet<IClientInventory>(out clientInv)) 827
828 List<UUID> textures = new List<UUID>();
829
830
831// if (doTextInv)
832 m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
833
834 if(client == null) // don't put textures in inventory if there is no client
835 doTextInv = false;
836
837 for (int i = 0; i < texture_list.Count; i++)
838 {
839 AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, creatorIDstr);
840 textureAsset.Data = texture_list[i].AsBinary();
841 if (istest)
842 textureAsset.Local = true;
843 m_assetService.Store(textureAsset);
844 textures.Add(textureAsset.FullID);
845
846 if (doTextInv)
556 { 847 {
557 var systemTextureFolder = m_Scene.InventoryService.GetFolderForType(m_HostCapsObj.AgentID, FolderType.Texture); 848 string name = assetName;
558 textureUploadFolder = new InventoryFolderBase(UUID.Random(), assetName, m_HostCapsObj.AgentID, (short)FolderType.None, systemTextureFolder.ID, 1); 849 if (name.Length > 25)
559 if (m_Scene.InventoryService.AddFolder(textureUploadFolder)) 850 name = name.Substring(0, 24);
560 { 851 name += "_Texture#" + i.ToString();
561 foldersToUpdate.Add(textureUploadFolder); 852 InventoryItemBase texitem = new InventoryItemBase();
853 texitem.Owner = m_HostCapsObj.AgentID;
854 texitem.CreatorId = creatorIDstr;
855 texitem.CreatorData = String.Empty;
856 texitem.ID = UUID.Random();
857 texitem.AssetID = textureAsset.FullID;
858 texitem.Description = "mesh model texture";
859 texitem.Name = name;
860 texitem.AssetType = (int)AssetType.Texture;
861 texitem.InvType = (int)InventoryType.Texture;
862 texitem.Folder = texturesFolder;
863
864 texitem.CurrentPermissions
865 = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
866
867 texitem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
868 texitem.EveryOnePermissions = 0;
869 texitem.NextPermissions = (uint)PermissionMask.All;
870 texitem.CreationDate = Util.UnixTimeSinceEpoch();
871
872 m_Scene.AddInventoryItem(client, texitem);
873 texitem = null;
874 }
875 }
562 876
563 m_log.DebugFormat( 877 // create and store meshs assets
564 "[BUNCH OF CAPS]: Created new folder '{0}' ({1}) for textures uploaded with mesh object {2}", 878 List<UUID> meshAssets = new List<UUID>();
565 textureUploadFolder.Name, textureUploadFolder.ID, assetName); 879 List<bool> meshAvatarSkeletons = new List<bool>();
566 } 880 List<bool> meshAvatarColliders = new List<bool>();
567 else 881
882 bool curAvSkeleton;
883 bool curAvCollider;
884 for (int i = 0; i < mesh_list.Count; i++)
885 {
886 curAvSkeleton = false;
887 curAvCollider = false;
888
889 // we do need to parse the mesh now
890 OSD osd = OSDParser.DeserializeLLSDBinary(mesh_list[i]);
891 if (osd is OSDMap)
892 {
893 OSDMap mosd = (OSDMap)osd;
894 if (mosd.ContainsKey("skeleton"))
568 { 895 {
569 textureUploadFolder = null; 896 OSDMap skeleton = (OSDMap)mosd["skeleton"];
897 int sksize = skeleton["size"].AsInteger();
898 if (sksize > 0)
899 curAvSkeleton = true;
570 } 900 }
571 } 901 }
572 }
573 }
574 902
575 List<UUID> textures = new List<UUID>(); 903 AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, creatorIDstr);
576 for (int i = 0; i < texture_list.Count; i++) 904 meshAsset.Data = mesh_list[i].AsBinary();
577 { 905 if (istest)
578 AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, ""); 906 meshAsset.Local = true;
579 textureAsset.Data = texture_list[i].AsBinary(); 907 m_assetService.Store(meshAsset);
580 m_assetService.Store(textureAsset); 908 meshAssets.Add(meshAsset.FullID);
581 textures.Add(textureAsset.FullID); 909 meshAvatarSkeletons.Add(curAvSkeleton);
910 meshAvatarColliders.Add(curAvCollider);
911
912 // test code
913 if (curAvSkeleton && client != null)
914 {
915 string name = assetName;
916 if (name.Length > 25)
917 name = name.Substring(0, 24);
918 name += "_Mesh#" + i.ToString();
919 InventoryItemBase meshitem = new InventoryItemBase();
920 meshitem.Owner = m_HostCapsObj.AgentID;
921 meshitem.CreatorId = creatorIDstr;
922 meshitem.CreatorData = String.Empty;
923 meshitem.ID = UUID.Random();
924 meshitem.AssetID = meshAsset.FullID;
925 meshitem.Description = "mesh ";
926 meshitem.Name = name;
927 meshitem.AssetType = (int)AssetType.Mesh;
928 meshitem.InvType = (int)InventoryType.Mesh;
929 // meshitem.Folder = UUID.Zero; // send to default
930
931 meshitem.Folder = parentFolder; // dont let it go to folder Meshes that viewers dont show
932
933 // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
934 // (owner) permissions. This becomes a problem if next permissions are changed.
935 meshitem.CurrentPermissions
936 = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);
937
938 meshitem.BasePermissions = (uint)PermissionMask.All;
939 meshitem.EveryOnePermissions = 0;
940 meshitem.NextPermissions = (uint)PermissionMask.All;
941 meshitem.CreationDate = Util.UnixTimeSinceEpoch();
942
943 m_Scene.AddInventoryItem(client, meshitem);
944 meshitem = null;
945 }
946 }
582 947
583 if (textureUploadFolder != null) 948 int skipedMeshs = 0;
949 // build prims from instances
950 for (int i = 0; i < instance_list.Count; i++)
584 { 951 {
585 InventoryItemBase textureItem = new InventoryItemBase(); 952 OSDMap inner_instance_list = (OSDMap)instance_list[i];
586 textureItem.Owner = m_HostCapsObj.AgentID;
587 textureItem.CreatorId = m_HostCapsObj.AgentID.ToString();
588 textureItem.CreatorData = String.Empty;
589 textureItem.ID = UUID.Random();
590 textureItem.AssetID = textureAsset.FullID;
591 textureItem.Description = assetDescription;
592 textureItem.Name = assetName + " - Texture " + (i + 1).ToString();
593 textureItem.AssetType = (int)AssetType.Texture;
594 textureItem.InvType = (int)InventoryType.Texture;
595 textureItem.Folder = textureUploadFolder.ID;
596 textureItem.CurrentPermissions
597 = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
598 textureItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
599 textureItem.EveryOnePermissions = 0;
600 textureItem.NextPermissions = (uint)PermissionMask.All;
601 textureItem.CreationDate = Util.UnixTimeSinceEpoch();
602 m_Scene.InventoryService.AddItem(textureItem);
603 itemsToUpdate.Add(textureItem);
604
605 m_log.DebugFormat(
606 "[BUNCH OF CAPS]: Created new inventory item '{0}' ({1}) for texture uploaded with mesh object {2}",
607 textureItem.Name, textureItem.ID, assetName);
608 }
609 }
610 953
611 if (clientInv != null && (foldersToUpdate.Count > 0 || itemsToUpdate.Count > 0)) 954 // skip prims that are 2 small
612 { 955 Vector3 scale = inner_instance_list["scale"].AsVector3();
613 clientInv.SendBulkUpdateInventory(foldersToUpdate.ToArray(), itemsToUpdate.ToArray());
614 }
615 956
616 for (int i = 0; i < mesh_list.Count; i++) 957 if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
617 { 958 {
618 PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); 959 skipedMeshs++;
960 continue;
961 }
619 962
620 Primitive.TextureEntry textureEntry 963 PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
621 = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
622 OSDMap inner_instance_list = (OSDMap)instance_list[i];
623 964
624 OSDArray face_list = (OSDArray)inner_instance_list["face_list"]; 965 Primitive.TextureEntry textureEntry
625 for (uint face = 0; face < face_list.Count; face++) 966 = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
626 {
627 OSDMap faceMap = (OSDMap)face_list[(int)face];
628 Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
629 if(faceMap.ContainsKey("fullbright"))
630 f.Fullbright = faceMap["fullbright"].AsBoolean();
631 if (faceMap.ContainsKey ("diffuse_color"))
632 f.RGBA = faceMap["diffuse_color"].AsColor4();
633 967
634 int textureNum = faceMap["image"].AsInteger();
635 float imagerot = faceMap["imagerot"].AsInteger();
636 float offsets = (float)faceMap["offsets"].AsReal();
637 float offsett = (float)faceMap["offsett"].AsReal();
638 float scales = (float)faceMap["scales"].AsReal();
639 float scalet = (float)faceMap["scalet"].AsReal();
640 968
641 if(imagerot != 0) 969 OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
642 f.Rotation = imagerot; 970 for (uint face = 0; face < face_list.Count; face++)
971 {
972 OSDMap faceMap = (OSDMap)face_list[(int)face];
973 Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
974 if (faceMap.ContainsKey("fullbright"))
975 f.Fullbright = faceMap["fullbright"].AsBoolean();
976 if (faceMap.ContainsKey("diffuse_color"))
977 f.RGBA = faceMap["diffuse_color"].AsColor4();
643 978
644 if(offsets != 0) 979 int textureNum = faceMap["image"].AsInteger();
645 f.OffsetU = offsets; 980 float imagerot = faceMap["imagerot"].AsInteger();
981 float offsets = (float)faceMap["offsets"].AsReal();
982 float offsett = (float)faceMap["offsett"].AsReal();
983 float scales = (float)faceMap["scales"].AsReal();
984 float scalet = (float)faceMap["scalet"].AsReal();
646 985
647 if (offsett != 0) 986 if (imagerot != 0)
648 f.OffsetV = offsett; 987 f.Rotation = imagerot;
649 988
650 if (scales != 0) 989 if (offsets != 0)
651 f.RepeatU = scales; 990 f.OffsetU = offsets;
652 991
653 if (scalet != 0) 992 if (offsett != 0)
654 f.RepeatV = scalet; 993 f.OffsetV = offsett;
655 994
656 if (textures.Count > textureNum) 995 if (scales != 0)
657 f.TextureID = textures[textureNum]; 996 f.RepeatU = scales;
658 else
659 f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
660 997
661 textureEntry.FaceTextures[face] = f; 998 if (scalet != 0)
662 } 999 f.RepeatV = scalet;
663 1000
664 pbs.TextureEntry = textureEntry.GetBytes(); 1001 if (textures.Count > textureNum)
1002 f.TextureID = textures[textureNum];
1003 else
1004 f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
665 1005
666 AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, ""); 1006 textureEntry.FaceTextures[face] = f;
667 meshAsset.Data = mesh_list[i].AsBinary(); 1007 }
668 m_assetService.Store(meshAsset);
669 1008
670 pbs.SculptEntry = true; 1009 pbs.TextureEntry = textureEntry.GetBytes();
671 pbs.SculptTexture = meshAsset.FullID;
672 pbs.SculptType = (byte)SculptType.Mesh;
673 pbs.SculptData = meshAsset.Data;
674 1010
675 Vector3 position = inner_instance_list["position"].AsVector3(); 1011 bool hasmesh = false;
676 Vector3 scale = inner_instance_list["scale"].AsVector3(); 1012 if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
677 Quaternion rotation = inner_instance_list["rotation"].AsQuaternion(); 1013 {
1014 int meshindx = inner_instance_list["mesh"].AsInteger();
1015 if (meshAssets.Count > meshindx)
1016 {
1017 pbs.SculptEntry = true;
1018 pbs.SculptType = (byte)SculptType.Mesh;
1019 pbs.SculptTexture = meshAssets[meshindx]; // actual asset UUID after meshs suport introduction
1020 // data will be requested from asset on rez (i hope)
1021 hasmesh = true;
1022 }
1023 }
1024
1025 Vector3 position = inner_instance_list["position"].AsVector3();
1026 Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
1027
1028 // for now viwers do send fixed defaults
1029 // but this may change
1030// int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
1031 byte physicsShapeType = (byte)PhysShapeType.prim; // default for mesh is simple convex
1032 if(hasmesh)
1033 physicsShapeType = (byte) PhysShapeType.convex; // default for mesh is simple convex
1034// int material = inner_instance_list["material"].AsInteger();
1035 byte material = (byte)Material.Wood;
678 1036
679// no longer used - begin ------------------------ 1037// no longer used - begin ------------------------
680// int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
681// int material = inner_instance_list["material"].AsInteger();
682// int mesh = inner_instance_list["mesh"].AsInteger(); 1038// int mesh = inner_instance_list["mesh"].AsInteger();
683 1039
684// OSDMap permissions = (OSDMap)inner_instance_list["permissions"]; 1040// OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
@@ -693,24 +1049,49 @@ namespace OpenSim.Region.ClientStack.Linden
693// UUID owner_id = permissions["owner_id"].AsUUID(); 1049// UUID owner_id = permissions["owner_id"].AsUUID();
694// int owner_mask = permissions["owner_mask"].AsInteger(); 1050// int owner_mask = permissions["owner_mask"].AsInteger();
695// no longer used - end ------------------------ 1051// no longer used - end ------------------------
1052
1053
1054 SceneObjectPart prim
1055 = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
1056
1057 prim.Scale = scale;
1058 rotations.Add(rotation);
1059 positions.Add(position);
1060 prim.UUID = UUID.Random();
1061 prim.CreatorID = creatorID;
1062 prim.OwnerID = owner_id;
1063 prim.GroupID = UUID.Zero;
1064 prim.LastOwnerID = creatorID;
1065 prim.CreationDate = Util.UnixTimeSinceEpoch();
1066
1067 if (grp == null)
1068 prim.Name = assetName;
1069 else
1070 prim.Name = assetName + "#" + i.ToString();
696 1071
697 UUID owner_id = m_HostCapsObj.AgentID; 1072 prim.EveryoneMask = 0;
1073 prim.GroupMask = 0;
698 1074
699 SceneObjectPart prim 1075 if (restrictPerms)
700 = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero); 1076 {
1077 prim.BaseMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
1078 prim.OwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
1079 prim.NextOwnerMask = 0;
1080 }
1081 else
1082 {
1083 prim.BaseMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
1084 prim.OwnerMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
1085 prim.NextOwnerMask = (uint)PermissionMask.Transfer;
1086 }
701 1087
702 prim.Scale = scale; 1088 if(istest)
703 //prim.OffsetPosition = position; 1089 prim.Description = "For testing only. Other uses are prohibited";
704 rotations.Add(rotation); 1090 else
705 positions.Add(position); 1091 prim.Description = "";
706 prim.UUID = UUID.Random(); 1092
707 prim.CreatorID = owner_id; 1093 prim.Material = material;
708 prim.OwnerID = owner_id; 1094 prim.PhysicsShapeType = physicsShapeType;
709 prim.GroupID = UUID.Zero;
710 prim.LastOwnerID = prim.OwnerID;
711 prim.CreationDate = Util.UnixTimeSinceEpoch();
712 prim.Name = assetName;
713 prim.Description = "";
714 1095
715// prim.BaseMask = (uint)base_mask; 1096// prim.BaseMask = (uint)base_mask;
716// prim.EveryoneMask = (uint)everyone_mask; 1097// prim.EveryoneMask = (uint)everyone_mask;
@@ -718,52 +1099,64 @@ namespace OpenSim.Region.ClientStack.Linden
718// prim.NextOwnerMask = (uint)next_owner_mask; 1099// prim.NextOwnerMask = (uint)next_owner_mask;
719// prim.OwnerMask = (uint)owner_mask; 1100// prim.OwnerMask = (uint)owner_mask;
720 1101
721 if (grp == null) 1102 if (grp == null)
722 grp = new SceneObjectGroup(prim); 1103 {
723 else 1104 grp = new SceneObjectGroup(prim);
724 grp.AddPart(prim); 1105 grp.LastOwnerID = creatorID;
725 } 1106 }
1107 else
1108 grp.AddPart(prim);
1109 }
726 1110
727 Vector3 rootPos = positions[0]; 1111 Vector3 rootPos = positions[0];
728 1112
729 if (grp.Parts.Length > 1) 1113 if (grp.Parts.Length > 1)
730 { 1114 {
731 // Fix first link number 1115 // Fix first link number
732 grp.RootPart.LinkNum++; 1116 grp.RootPart.LinkNum++;
733 1117
734 Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]); 1118 Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
735 Quaternion tmprot; 1119 Quaternion tmprot;
736 Vector3 offset; 1120 Vector3 offset;
737 1121
738 // fix children rotations and positions 1122 // fix children rotations and positions
739 for (int i = 1; i < rotations.Count; i++) 1123 for (int i = 1; i < rotations.Count; i++)
740 { 1124 {
741 tmprot = rotations[i]; 1125 tmprot = rotations[i];
742 tmprot = rootRotConj * tmprot; 1126 tmprot = rootRotConj * tmprot;
743 1127
744 grp.Parts[i].RotationOffset = tmprot; 1128 grp.Parts[i].RotationOffset = tmprot;
745 1129
746 offset = positions[i] - rootPos; 1130 offset = positions[i] - rootPos;
747 1131
748 offset *= rootRotConj; 1132 offset *= rootRotConj;
749 grp.Parts[i].OffsetPosition = offset; 1133 grp.Parts[i].OffsetPosition = offset;
1134 }
1135
1136 grp.AbsolutePosition = rootPos;
1137 grp.UpdateGroupRotationR(rotations[0]);
1138 }
1139 else
1140 {
1141 grp.AbsolutePosition = rootPos;
1142 grp.UpdateGroupRotationR(rotations[0]);
750 } 1143 }
751 1144
752 grp.AbsolutePosition = rootPos; 1145 data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
753 grp.UpdateGroupRotationR(rotations[0]);
754 } 1146 }
755 else 1147
1148 else // not a mesh model
756 { 1149 {
757 grp.AbsolutePosition = rootPos; 1150 m_log.ErrorFormat("[CAPS Asset Upload] got unsuported assetType for object upload");
758 grp.UpdateGroupRotationR(rotations[0]); 1151 return;
759 } 1152 }
760
761 data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
762 } 1153 }
763 1154
764 AssetBase asset; 1155 AssetBase asset;
765 asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString()); 1156 asset = new AssetBase(assetID, assetName, assType, creatorIDstr);
766 asset.Data = data; 1157 asset.Data = data;
1158 if (istest)
1159 asset.Local = true;
767 if (AddNewAsset != null) 1160 if (AddNewAsset != null)
768 AddNewAsset(asset); 1161 AddNewAsset(asset);
769 else if (m_assetService != null) 1162 else if (m_assetService != null)
@@ -771,11 +1164,17 @@ namespace OpenSim.Region.ClientStack.Linden
771 1164
772 InventoryItemBase item = new InventoryItemBase(); 1165 InventoryItemBase item = new InventoryItemBase();
773 item.Owner = m_HostCapsObj.AgentID; 1166 item.Owner = m_HostCapsObj.AgentID;
774 item.CreatorId = m_HostCapsObj.AgentID.ToString(); 1167 item.CreatorId = creatorIDstr;
775 item.CreatorData = String.Empty; 1168 item.CreatorData = String.Empty;
776 item.ID = inventoryItem; 1169 item.ID = inventoryItem;
777 item.AssetID = asset.FullID; 1170 item.AssetID = asset.FullID;
778 item.Description = assetDescription; 1171 if (istest)
1172 {
1173 item.Description = "For testing only. Other uses are prohibited";
1174 item.Flags = (uint) (InventoryItemFlags.SharedSingleReference);
1175 }
1176 else
1177 item.Description = assetDescription;
779 item.Name = assetName; 1178 item.Name = assetName;
780 item.AssetType = assType; 1179 item.AssetType = assType;
781 item.InvType = inType; 1180 item.InvType = inType;
@@ -783,18 +1182,61 @@ namespace OpenSim.Region.ClientStack.Linden
783 1182
784 // If we set PermissionMask.All then when we rez the item the next permissions will replace the current 1183 // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
785 // (owner) permissions. This becomes a problem if next permissions are changed. 1184 // (owner) permissions. This becomes a problem if next permissions are changed.
786 item.CurrentPermissions
787 = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
788 1185
789 item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export; 1186 if (inType == (sbyte)CustomInventoryType.AnimationSet)
790 item.EveryOnePermissions = 0; 1187 {
791 item.NextPermissions = (uint)PermissionMask.All; 1188 AnimationSet.setCreateItemPermitions(item);
1189 }
1190
1191 else if (restrictPerms)
1192 {
1193 item.BasePermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
1194 item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
1195 item.EveryOnePermissions = 0;
1196 item.NextPermissions = 0;
1197 }
1198 else
1199 {
1200 item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
1201 item.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
1202 item.EveryOnePermissions = 0;
1203 item.NextPermissions = (uint)PermissionMask.Transfer;
1204 }
1205
792 item.CreationDate = Util.UnixTimeSinceEpoch(); 1206 item.CreationDate = Util.UnixTimeSinceEpoch();
793 1207
1208 m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
1209
794 if (AddNewInventoryItem != null) 1210 if (AddNewInventoryItem != null)
795 { 1211 {
796 AddNewInventoryItem(m_HostCapsObj.AgentID, item); 1212 if (istest)
1213 {
1214 m_Scene.AddInventoryItem(client, item);
1215/*
1216 AddNewInventoryItem(m_HostCapsObj.AgentID, item, 0);
1217 if (client != null)
1218 client.SendAgentAlertMessage("Upload will have no cost, for personal test purposes only. Other uses are forbiden. Items may not work on a another region" , true);
1219 */
1220 }
1221 else
1222 {
1223 AddNewInventoryItem(m_HostCapsObj.AgentID, item, (uint)cost);
1224// if (client != null)
1225// {
1226// // let users see anything.. i don't so far
1227// string str;
1228// if (cost > 0)
1229// // dont remember where is money unit name to put here
1230// str = "Upload complete. charged " + cost.ToString() + "$";
1231// else
1232// str = "Upload complete";
1233// client.SendAgentAlertMessage(str, true);
1234// }
1235 }
797 } 1236 }
1237
1238 lock (m_ModelCost)
1239 m_FileAgentInventoryState = FileAgentInventoryState.idle;
798 } 1240 }
799 1241
800 /// <summary> 1242 /// <summary>
@@ -935,24 +1377,17 @@ namespace OpenSim.Region.ClientStack.Linden
935 { 1377 {
936 string message; 1378 string message;
937 copyItem = m_Scene.GiveInventoryItem(m_HostCapsObj.AgentID, item.Owner, itemID, folderID, out message); 1379 copyItem = m_Scene.GiveInventoryItem(m_HostCapsObj.AgentID, item.Owner, itemID, folderID, out message);
938 if (client != null) 1380 if (copyItem != null && client != null)
939 { 1381 {
940 if (copyItem != null) 1382 m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
941 { 1383 client.SendBulkUpdateInventory(copyItem);
942 m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
943 client.SendBulkUpdateInventory(copyItem);
944 }
945 else
946 {
947 client.SendAgentAlertMessage(message, false);
948 }
949 } 1384 }
950 } 1385 }
951 else 1386 else
952 { 1387 {
953 m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard - Failed to retrieve item {0} from notecard {1}", itemID, notecardID); 1388 m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard - Failed to retrieve item {0} from notecard {1}", itemID, notecardID);
954 if (client != null) 1389 if (client != null)
955 client.SendAgentAlertMessage("Failed to retrieve item", false); 1390 client.SendAlertMessage("Failed to retrieve item");
956 } 1391 }
957 } 1392 }
958 catch (Exception e) 1393 catch (Exception e)
@@ -995,18 +1430,142 @@ namespace OpenSim.Region.ClientStack.Linden
995 return response; 1430 return response;
996 } 1431 }
997 1432
998 public string UpdateAgentInformation(string request, string path, 1433 public string GetObjectCost(string request, string path,
1434 string param, IOSHttpRequest httpRequest,
1435 IOSHttpResponse httpResponse)
1436 {
1437 OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
1438 OSDMap resp = new OSDMap();
1439
1440 OSDArray object_ids = (OSDArray)req["object_ids"];
1441
1442 for (int i = 0; i < object_ids.Count; i++)
1443 {
1444 UUID uuid = object_ids[i].AsUUID();
1445
1446 SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
1447
1448 if (part != null)
1449 {
1450 SceneObjectGroup grp = part.ParentGroup;
1451 if (grp != null)
1452 {
1453 float linksetCost;
1454 float linksetPhysCost;
1455 float partCost;
1456 float partPhysCost;
1457
1458 grp.GetResourcesCosts(part, out linksetCost, out linksetPhysCost, out partCost, out partPhysCost);
1459
1460 OSDMap object_data = new OSDMap();
1461 object_data["linked_set_resource_cost"] = linksetCost;
1462 object_data["resource_cost"] = partCost;
1463 object_data["physics_cost"] = partPhysCost;
1464 object_data["linked_set_physics_cost"] = linksetPhysCost;
1465
1466 resp[uuid.ToString()] = object_data;
1467 }
1468 else
1469 {
1470 OSDMap object_data = new OSDMap();
1471 object_data["linked_set_resource_cost"] = 0;
1472 object_data["resource_cost"] = 0;
1473 object_data["physics_cost"] = 0;
1474 object_data["linked_set_physics_cost"] = 0;
1475
1476 resp[uuid.ToString()] = object_data;
1477 }
1478
1479 }
1480 }
1481
1482 string response = OSDParser.SerializeLLSDXmlString(resp);
1483 return response;
1484 }
1485
1486 public string ResourceCostSelected(string request, string path,
999 string param, IOSHttpRequest httpRequest, 1487 string param, IOSHttpRequest httpRequest,
1000 IOSHttpResponse httpResponse) 1488 IOSHttpResponse httpResponse)
1001 { 1489 {
1002 OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); 1490 OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
1003 OSDMap accessPrefs = (OSDMap)req["access_prefs"]; 1491 OSDMap resp = new OSDMap();
1004 string desiredMaturity = accessPrefs["max"]; 1492
1493
1494 float phys=0;
1495 float stream=0;
1496 float simul=0;
1497
1498 if (req.ContainsKey("selected_roots"))
1499 {
1500 OSDArray object_ids = (OSDArray)req["selected_roots"];
1501
1502 // should go by SOG suming costs for all parts
1503 // ll v3 works ok with several objects select we get the list and adds ok
1504 // FS calls per object so results are wrong guess fs bug
1505 for (int i = 0; i < object_ids.Count; i++)
1506 {
1507 UUID uuid = object_ids[i].AsUUID();
1508 float Physc;
1509 float simulc;
1510 float streamc;
1511
1512 SceneObjectGroup grp = m_Scene.GetGroupByPrim(uuid);
1513 if (grp != null)
1514 {
1515 grp.GetSelectedCosts(out Physc, out streamc, out simulc);
1516 phys += Physc;
1517 stream += streamc;
1518 simul += simulc;
1519 }
1520 }
1521 }
1522 else if (req.ContainsKey("selected_prims"))
1523 {
1524 OSDArray object_ids = (OSDArray)req["selected_prims"];
1525
1526 // don't see in use in any of the 2 viewers
1527 // guess it should be for edit linked but... nothing
1528 // should go to SOP per part
1529 for (int i = 0; i < object_ids.Count; i++)
1530 {
1531 UUID uuid = object_ids[i].AsUUID();
1532
1533 SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
1534 if (part != null)
1535 {
1536 phys += part.PhysicsCost;
1537 stream += part.StreamingCost;
1538 simul += part.SimulationCost;
1539 }
1540 }
1541 }
1542
1543 // if (simul != 0)
1544 {
1545 OSDMap object_data = new OSDMap();
1546
1547 object_data["physics"] = phys;
1548 object_data["streaming"] = stream;
1549 object_data["simulation"] = simul;
1550
1551 resp["selected"] = object_data;
1552 }
1553
1554 string response = OSDParser.SerializeLLSDXmlString(resp);
1555 return response;
1556 }
1005 1557
1558 public string UpdateAgentInformation(string request, string path,
1559 string param, IOSHttpRequest httpRequest,
1560 IOSHttpResponse httpResponse)
1561 {
1562// OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
1006 OSDMap resp = new OSDMap(); 1563 OSDMap resp = new OSDMap();
1007 OSDMap respAccessPrefs = new OSDMap(); 1564
1008 respAccessPrefs["max"] = desiredMaturity; // echoing the maturity back means success 1565 OSDMap accessPrefs = new OSDMap();
1009 resp["access_prefs"] = respAccessPrefs; 1566 accessPrefs["max"] = "A";
1567
1568 resp["access_prefs"] = accessPrefs;
1010 1569
1011 string response = OSDParser.SerializeLLSDXmlString(resp); 1570 string response = OSDParser.SerializeLLSDXmlString(resp);
1012 return response; 1571 return response;
@@ -1015,6 +1574,10 @@ namespace OpenSim.Region.ClientStack.Linden
1015 1574
1016 public class AssetUploader 1575 public class AssetUploader
1017 { 1576 {
1577 private static readonly ILog m_log =
1578 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
1579
1580
1018 public event UpLoadedAsset OnUpLoad; 1581 public event UpLoadedAsset OnUpLoad;
1019 private UpLoadedAsset handlerUpLoad = null; 1582 private UpLoadedAsset handlerUpLoad = null;
1020 1583
@@ -1029,10 +1592,21 @@ namespace OpenSim.Region.ClientStack.Linden
1029 1592
1030 private string m_invType = String.Empty; 1593 private string m_invType = String.Empty;
1031 private string m_assetType = String.Empty; 1594 private string m_assetType = String.Empty;
1032 1595 private int m_cost;
1596 private string m_error = String.Empty;
1597
1598 private Timer m_timeoutTimer = new Timer();
1599 private UUID m_texturesFolder;
1600 private int m_nreqtextures;
1601 private int m_nreqmeshs;
1602 private int m_nreqinstances;
1603 private bool m_IsAtestUpload;
1604
1033 public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem, 1605 public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
1034 UUID parentFolderID, string invType, string assetType, string path, 1606 UUID parentFolderID, string invType, string assetType, string path,
1035 IHttpServer httpServer, bool dumpAssetsToFile) 1607 IHttpServer httpServer, bool dumpAssetsToFile,
1608 int totalCost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
1609 bool IsAtestUpload)
1036 { 1610 {
1037 m_assetName = assetName; 1611 m_assetName = assetName;
1038 m_assetDes = description; 1612 m_assetDes = description;
@@ -1044,6 +1618,18 @@ namespace OpenSim.Region.ClientStack.Linden
1044 m_assetType = assetType; 1618 m_assetType = assetType;
1045 m_invType = invType; 1619 m_invType = invType;
1046 m_dumpAssetsToFile = dumpAssetsToFile; 1620 m_dumpAssetsToFile = dumpAssetsToFile;
1621 m_cost = totalCost;
1622
1623 m_texturesFolder = texturesFolder;
1624 m_nreqtextures = nreqtextures;
1625 m_nreqmeshs = nreqmeshs;
1626 m_nreqinstances = nreqinstances;
1627 m_IsAtestUpload = IsAtestUpload;
1628
1629 m_timeoutTimer.Elapsed += TimedOut;
1630 m_timeoutTimer.Interval = 120000;
1631 m_timeoutTimer.AutoReset = false;
1632 m_timeoutTimer.Start();
1047 } 1633 }
1048 1634
1049 /// <summary> 1635 /// <summary>
@@ -1058,12 +1644,14 @@ namespace OpenSim.Region.ClientStack.Linden
1058 UUID inv = inventoryItemID; 1644 UUID inv = inventoryItemID;
1059 string res = String.Empty; 1645 string res = String.Empty;
1060 LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); 1646 LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
1647/*
1061 uploadComplete.new_asset = newAssetID.ToString(); 1648 uploadComplete.new_asset = newAssetID.ToString();
1062 uploadComplete.new_inventory_item = inv; 1649 uploadComplete.new_inventory_item = inv;
1063 uploadComplete.state = "complete"; 1650 uploadComplete.state = "complete";
1064 1651
1065 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete); 1652 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1066 1653*/
1654 m_timeoutTimer.Stop();
1067 httpListener.RemoveStreamHandler("POST", uploaderPath); 1655 httpListener.RemoveStreamHandler("POST", uploaderPath);
1068 1656
1069 // TODO: probably make this a better set of extensions here 1657 // TODO: probably make this a better set of extensions here
@@ -1080,12 +1668,50 @@ namespace OpenSim.Region.ClientStack.Linden
1080 handlerUpLoad = OnUpLoad; 1668 handlerUpLoad = OnUpLoad;
1081 if (handlerUpLoad != null) 1669 if (handlerUpLoad != null)
1082 { 1670 {
1083 handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType); 1671 handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType,
1672 m_cost, m_texturesFolder, m_nreqtextures, m_nreqmeshs, m_nreqinstances, m_IsAtestUpload,
1673 ref m_error);
1674 }
1675 if (m_IsAtestUpload)
1676 {
1677 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
1678 resperror.message = "Upload SUCESSEFULL for testing purposes only. Other uses are prohibited. Item will not work after 48 hours or on other regions";
1679 resperror.identifier = inv;
1680
1681 uploadComplete.error = resperror;
1682 uploadComplete.state = "Upload4Testing";
1683 }
1684 else
1685 {
1686 if (m_error == String.Empty)
1687 {
1688 uploadComplete.new_asset = newAssetID.ToString();
1689 uploadComplete.new_inventory_item = inv;
1690 // if (m_texturesFolder != UUID.Zero)
1691 // uploadComplete.new_texture_folder_id = m_texturesFolder;
1692 uploadComplete.state = "complete";
1693 }
1694 else
1695 {
1696 LLSDAssetUploadError resperror = new LLSDAssetUploadError();
1697 resperror.message = m_error;
1698 resperror.identifier = inv;
1699
1700 uploadComplete.error = resperror;
1701 uploadComplete.state = "failed";
1702 }
1084 } 1703 }
1085 1704
1705 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1086 return res; 1706 return res;
1087 } 1707 }
1088 1708
1709 private void TimedOut(object sender, ElapsedEventArgs args)
1710 {
1711 m_log.InfoFormat("[CAPS]: Removing URL and handler for timed out mesh upload");
1712 httpListener.RemoveStreamHandler("POST", uploaderPath);
1713 }
1714
1089 ///Left this in and commented in case there are unforseen issues 1715 ///Left this in and commented in case there are unforseen issues
1090 //private void SaveAssetToFile(string filename, byte[] data) 1716 //private void SaveAssetToFile(string filename, byte[] data)
1091 //{ 1717 //{
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshCost.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshCost.cs
new file mode 100644
index 0000000..f6a950f
--- /dev/null
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshCost.cs
@@ -0,0 +1,727 @@
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
28
29using System;
30using System.IO;
31using System.Collections;
32using System.Collections.Generic;
33using System.Text;
34
35using OpenMetaverse;
36using OpenMetaverse.StructuredData;
37
38using OpenSim.Framework;
39using OpenSim.Region.Framework;
40using OpenSim.Region.Framework.Scenes;
41using OpenSim.Framework.Capabilities;
42
43using ComponentAce.Compression.Libs.zlib;
44
45using OSDArray = OpenMetaverse.StructuredData.OSDArray;
46using OSDMap = OpenMetaverse.StructuredData.OSDMap;
47
48namespace OpenSim.Region.ClientStack.Linden
49{
50 public struct ModelPrimLimits
51 {
52
53 }
54
55 public class ModelCost
56 {
57
58 // upload fee defaults
59 // fees are normalized to 1.0
60 // this parameters scale them to basic cost ( so 1.0 translates to 10 )
61
62 public float ModelMeshCostFactor = 0.0f; // scale total cost relative to basic (excluding textures)
63 public float ModelTextureCostFactor = 1.0f; // scale textures fee to basic.
64 public float ModelMinCostFactor = 0.0f; // 0.5f; // minimum total model free excluding textures
65
66 // itens costs in normalized values
67 // ie will be multiplied by basicCost and factors above
68 public float primCreationCost = 0.002f; // extra cost for each prim creation overhead
69 // weigthed size to normalized cost
70 public float bytecost = 1e-5f;
71
72 // mesh upload fees based on compressed data sizes
73 // several data sections are counted more that once
74 // to promote user optimization
75 // following parameters control how many extra times they are added
76 // to global size.
77 // LOD meshs
78 const float medSizeWth = 1f; // 2x
79 const float lowSizeWth = 1.5f; // 2.5x
80 const float lowestSizeWth = 2f; // 3x
81 // favor potencially physical optimized meshs versus automatic decomposition
82 const float physMeshSizeWth = 6f; // counts 7x
83 const float physHullSizeWth = 8f; // counts 9x
84
85 // stream cost area factors
86 // more or less like SL
87 const float highLodFactor = 17.36f;
88 const float midLodFactor = 277.78f;
89 const float lowLodFactor = 1111.11f;
90
91 // physics cost is below, identical to SL, assuming shape type convex
92 // server cost is below identical to SL assuming non scripted non physical object
93
94 // internal
95 const int bytesPerCoord = 6; // 3 coords, 2 bytes per each
96
97 // control prims dimensions
98 public float PrimScaleMin = 0.001f;
99 public float NonPhysicalPrimScaleMax = 256f;
100 public float PhysicalPrimScaleMax = 10f;
101 public int ObjectLinkedPartsMax = 512;
102
103 // storage for a single mesh asset cost parameters
104 private class ameshCostParam
105 {
106 // LOD sizes for size dependent streaming cost
107 public int highLODSize;
108 public int medLODSize;
109 public int lowLODSize;
110 public int lowestLODSize;
111 // normalized fee based on compressed data sizes
112 public float costFee;
113 // physics cost
114 public float physicsCost;
115 }
116
117 // calculates a mesh model costs
118 // returns false on error, with a reason on parameter error
119 // resources input LLSD request
120 // basicCost input region assets upload cost
121 // totalcost returns model total upload fee
122 // meshcostdata returns detailed costs for viewer
123 // avatarSkeleton if mesh includes a avatar skeleton
124 // useAvatarCollider if we should use physics mesh for avatar
125 public bool MeshModelCost(LLSDAssetResource resources, int basicCost, out int totalcost,
126 LLSDAssetUploadResponseData meshcostdata, out string error, ref string warning)
127 {
128 totalcost = 0;
129 error = string.Empty;
130
131 bool avatarSkeleton = false;
132
133 if (resources == null ||
134 resources.instance_list == null ||
135 resources.instance_list.Array.Count == 0)
136 {
137 error = "missing model information.";
138 return false;
139 }
140
141 int numberInstances = resources.instance_list.Array.Count;
142
143 if( numberInstances > ObjectLinkedPartsMax )
144 {
145 error = "Model whould have more than " + ObjectLinkedPartsMax.ToString() + " linked prims";
146 return false;
147 }
148
149 meshcostdata.model_streaming_cost = 0.0;
150 meshcostdata.simulation_cost = 0.0;
151 meshcostdata.physics_cost = 0.0;
152 meshcostdata.resource_cost = 0.0;
153
154 meshcostdata.upload_price_breakdown.mesh_instance = 0;
155 meshcostdata.upload_price_breakdown.mesh_physics = 0;
156 meshcostdata.upload_price_breakdown.mesh_streaming = 0;
157 meshcostdata.upload_price_breakdown.model = 0;
158
159 int itmp;
160
161 // textures cost
162 if (resources.texture_list != null && resources.texture_list.Array.Count > 0)
163 {
164 float textures_cost = (float)(resources.texture_list.Array.Count * basicCost);
165 textures_cost *= ModelTextureCostFactor;
166
167 itmp = (int)(textures_cost + 0.5f); // round
168 meshcostdata.upload_price_breakdown.texture = itmp;
169 totalcost += itmp;
170 }
171
172 // meshs assets cost
173 float meshsfee = 0;
174 int numberMeshs = 0;
175 bool haveMeshs = false;
176
177 bool curskeleton;
178 bool curAvatarPhys;
179
180 List<ameshCostParam> meshsCosts = new List<ameshCostParam>();
181
182 if (resources.mesh_list != null && resources.mesh_list.Array.Count > 0)
183 {
184 numberMeshs = resources.mesh_list.Array.Count;
185
186 for (int i = 0; i < numberMeshs; i++)
187 {
188 ameshCostParam curCost = new ameshCostParam();
189 byte[] data = (byte[])resources.mesh_list.Array[i];
190
191 if (!MeshCost(data, curCost,out curskeleton, out curAvatarPhys, out error))
192 {
193 return false;
194 }
195
196 if (curskeleton)
197 {
198 if (avatarSkeleton)
199 {
200 error = "model can only contain a avatar skeleton";
201 return false;
202 }
203 avatarSkeleton = true;
204 }
205 meshsCosts.Add(curCost);
206 meshsfee += curCost.costFee;
207 }
208 haveMeshs = true;
209 }
210
211 // instances (prims) cost
212
213
214 int mesh;
215 int skipedSmall = 0;
216 for (int i = 0; i < numberInstances; i++)
217 {
218 Hashtable inst = (Hashtable)resources.instance_list.Array[i];
219
220 ArrayList ascale = (ArrayList)inst["scale"];
221 Vector3 scale;
222 double tmp;
223 tmp = (double)ascale[0];
224 scale.X = (float)tmp;
225 tmp = (double)ascale[1];
226 scale.Y = (float)tmp;
227 tmp = (double)ascale[2];
228 scale.Z = (float)tmp;
229
230 if (scale.X < PrimScaleMin || scale.Y < PrimScaleMin || scale.Z < PrimScaleMin)
231 {
232 skipedSmall++;
233 continue;
234 }
235
236 if (scale.X > NonPhysicalPrimScaleMax || scale.Y > NonPhysicalPrimScaleMax || scale.Z > NonPhysicalPrimScaleMax)
237 {
238 error = "Model contains parts with sides larger than " + NonPhysicalPrimScaleMax.ToString() + "m. Please ajust scale";
239 return false;
240 }
241
242 if (haveMeshs && inst.ContainsKey("mesh"))
243 {
244 mesh = (int)inst["mesh"];
245
246 if (mesh >= numberMeshs)
247 {
248 error = "Incoerent model information.";
249 return false;
250 }
251
252 // streamming cost
253
254 float sqdiam = scale.LengthSquared();
255
256 ameshCostParam curCost = meshsCosts[mesh];
257 float mesh_streaming = streamingCost(curCost, sqdiam);
258
259 meshcostdata.model_streaming_cost += mesh_streaming;
260 meshcostdata.physics_cost += curCost.physicsCost;
261 }
262 else // instance as no mesh ??
263 {
264 // to do later if needed
265 meshcostdata.model_streaming_cost += 0.5f;
266 meshcostdata.physics_cost += 1.0f;
267 }
268
269 // assume unscripted and static prim server cost
270 meshcostdata.simulation_cost += 0.5f;
271 // charge for prims creation
272 meshsfee += primCreationCost;
273 }
274
275 if (skipedSmall > 0)
276 {
277 if (skipedSmall > numberInstances / 2)
278 {
279 error = "Model contains too many prims smaller than " + PrimScaleMin.ToString() +
280 "m minimum allowed size. Please check scalling";
281 return false;
282 }
283 else
284 warning += skipedSmall.ToString() + " of the requested " +numberInstances.ToString() +
285 " model prims will not upload because they are smaller than " + PrimScaleMin.ToString() +
286 "m minimum allowed size. Please check scalling ";
287 }
288
289 if (meshcostdata.physics_cost <= meshcostdata.model_streaming_cost)
290 meshcostdata.resource_cost = meshcostdata.model_streaming_cost;
291 else
292 meshcostdata.resource_cost = meshcostdata.physics_cost;
293
294 if (meshcostdata.resource_cost < meshcostdata.simulation_cost)
295 meshcostdata.resource_cost = meshcostdata.simulation_cost;
296
297 // scale cost
298 // at this point a cost of 1.0 whould mean basic cost
299 meshsfee *= ModelMeshCostFactor;
300
301 if (meshsfee < ModelMinCostFactor)
302 meshsfee = ModelMinCostFactor;
303
304 // actually scale it to basic cost
305 meshsfee *= (float)basicCost;
306
307 meshsfee += 0.5f; // rounding
308
309 totalcost += (int)meshsfee;
310
311 // breakdown prices
312 // don't seem to be in use so removed code for now
313
314 return true;
315 }
316
317 // single mesh asset cost
318 private bool MeshCost(byte[] data, ameshCostParam cost,out bool skeleton, out bool avatarPhys, out string error)
319 {
320 cost.highLODSize = 0;
321 cost.medLODSize = 0;
322 cost.lowLODSize = 0;
323 cost.lowestLODSize = 0;
324 cost.physicsCost = 0.0f;
325 cost.costFee = 0.0f;
326
327 error = string.Empty;
328
329 skeleton = false;
330 avatarPhys = false;
331
332 if (data == null || data.Length == 0)
333 {
334 error = "Missing model information.";
335 return false;
336 }
337
338 OSD meshOsd = null;
339 int start = 0;
340
341 error = "Invalid model data";
342
343 using (MemoryStream ms = new MemoryStream(data))
344 {
345 try
346 {
347 OSD osd = OSDParser.DeserializeLLSDBinary(ms);
348 if (osd is OSDMap)
349 meshOsd = (OSDMap)osd;
350 else
351 return false;
352 }
353 catch (Exception e)
354 {
355 return false;
356 }
357 start = (int)ms.Position;
358 }
359
360 OSDMap map = (OSDMap)meshOsd;
361 OSDMap tmpmap;
362
363 int highlod_size = 0;
364 int medlod_size = 0;
365 int lowlod_size = 0;
366 int lowestlod_size = 0;
367 int skin_size = 0;
368
369 int hulls_size = 0;
370 int phys_nhulls;
371 int phys_hullsvertices = 0;
372
373 int physmesh_size = 0;
374 int phys_ntriangles = 0;
375
376 int submesh_offset = -1;
377
378 if (map.ContainsKey("skeleton"))
379 {
380 tmpmap = (OSDMap)map["skeleton"];
381 if (tmpmap.ContainsKey("offset") && tmpmap.ContainsKey("size"))
382 {
383 int sksize = tmpmap["size"].AsInteger();
384 if(sksize > 0)
385 skeleton = true;
386 }
387 }
388
389 if (map.ContainsKey("physics_convex"))
390 {
391 tmpmap = (OSDMap)map["physics_convex"];
392 if (tmpmap.ContainsKey("offset"))
393 submesh_offset = tmpmap["offset"].AsInteger() + start;
394 if (tmpmap.ContainsKey("size"))
395 hulls_size = tmpmap["size"].AsInteger();
396 }
397
398 if (submesh_offset < 0 || hulls_size == 0)
399 {
400 error = "Missing physics_convex block";
401 return false;
402 }
403
404 if (!hulls(data, submesh_offset, hulls_size, out phys_hullsvertices, out phys_nhulls))
405 {
406 error = "Bad physics_convex block";
407 return false;
408 }
409
410 submesh_offset = -1;
411
412 // only look for LOD meshs sizes
413
414 if (map.ContainsKey("high_lod"))
415 {
416 tmpmap = (OSDMap)map["high_lod"];
417 // see at least if there is a offset for this one
418 if (tmpmap.ContainsKey("offset"))
419 submesh_offset = tmpmap["offset"].AsInteger() + start;
420 if (tmpmap.ContainsKey("size"))
421 highlod_size = tmpmap["size"].AsInteger();
422 }
423
424 if (submesh_offset < 0 || highlod_size <= 0)
425 {
426 error = "Missing high_lod block";
427 return false;
428 }
429
430 bool haveprev = true;
431
432 if (map.ContainsKey("medium_lod"))
433 {
434 tmpmap = (OSDMap)map["medium_lod"];
435 if (tmpmap.ContainsKey("size"))
436 medlod_size = tmpmap["size"].AsInteger();
437 else
438 haveprev = false;
439 }
440
441 if (haveprev && map.ContainsKey("low_lod"))
442 {
443 tmpmap = (OSDMap)map["low_lod"];
444 if (tmpmap.ContainsKey("size"))
445 lowlod_size = tmpmap["size"].AsInteger();
446 else
447 haveprev = false;
448 }
449
450 if (haveprev && map.ContainsKey("lowest_lod"))
451 {
452 tmpmap = (OSDMap)map["lowest_lod"];
453 if (tmpmap.ContainsKey("size"))
454 lowestlod_size = tmpmap["size"].AsInteger();
455 }
456
457 if (map.ContainsKey("skin"))
458 {
459 tmpmap = (OSDMap)map["skin"];
460 if (tmpmap.ContainsKey("size"))
461 skin_size = tmpmap["size"].AsInteger();
462 }
463
464 cost.highLODSize = highlod_size;
465 cost.medLODSize = medlod_size;
466 cost.lowLODSize = lowlod_size;
467 cost.lowestLODSize = lowestlod_size;
468
469 submesh_offset = -1;
470
471 tmpmap = null;
472 if(map.ContainsKey("physics_mesh"))
473 tmpmap = (OSDMap)map["physics_mesh"];
474 else if (map.ContainsKey("physics_shape")) // old naming
475 tmpmap = (OSDMap)map["physics_shape"];
476
477 if(tmpmap != null)
478 {
479 if (tmpmap.ContainsKey("offset"))
480 submesh_offset = tmpmap["offset"].AsInteger() + start;
481 if (tmpmap.ContainsKey("size"))
482 physmesh_size = tmpmap["size"].AsInteger();
483
484 if (submesh_offset >= 0 || physmesh_size > 0)
485 {
486
487 if (!submesh(data, submesh_offset, physmesh_size, out phys_ntriangles))
488 {
489 error = "Model data parsing error";
490 return false;
491 }
492 }
493 }
494
495 // upload is done in convex shape type so only one hull
496 phys_hullsvertices++;
497 cost.physicsCost = 0.04f * phys_hullsvertices;
498
499 float sfee;
500
501 sfee = data.Length; // start with total compressed data size
502
503 // penalize lod meshs that should be more builder optimized
504 sfee += medSizeWth * medlod_size;
505 sfee += lowSizeWth * lowlod_size;
506 sfee += lowestSizeWth * lowlod_size;
507
508 // physics
509 // favor potencial optimized meshs versus automatic decomposition
510 if (physmesh_size != 0)
511 sfee += physMeshSizeWth * (physmesh_size + hulls_size / 4); // reduce cost of mandatory convex hull
512 else
513 sfee += physHullSizeWth * hulls_size;
514
515 // bytes to money
516 sfee *= bytecost;
517
518 cost.costFee = sfee;
519 return true;
520 }
521
522 // parses a LOD or physics mesh component
523 private bool submesh(byte[] data, int offset, int size, out int ntriangles)
524 {
525 ntriangles = 0;
526
527 OSD decodedMeshOsd = new OSD();
528 byte[] meshBytes = new byte[size];
529 System.Buffer.BlockCopy(data, offset, meshBytes, 0, size);
530 try
531 {
532 using (MemoryStream inMs = new MemoryStream(meshBytes))
533 {
534 using (MemoryStream outMs = new MemoryStream())
535 {
536 using (ZOutputStream zOut = new ZOutputStream(outMs))
537 {
538 byte[] readBuffer = new byte[4096];
539 int readLen = 0;
540 while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
541 {
542 zOut.Write(readBuffer, 0, readLen);
543 }
544 zOut.Flush();
545 outMs.Seek(0, SeekOrigin.Begin);
546
547 byte[] decompressedBuf = outMs.GetBuffer();
548 decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
549 }
550 }
551 }
552 }
553 catch (Exception e)
554 {
555 return false;
556 }
557
558 OSDArray decodedMeshOsdArray = null;
559 if ((!decodedMeshOsd is OSDArray))
560 return false;
561
562 byte[] dummy;
563
564 decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
565 foreach (OSD subMeshOsd in decodedMeshOsdArray)
566 {
567 if (subMeshOsd is OSDMap)
568 {
569 OSDMap subtmpmap = (OSDMap)subMeshOsd;
570 if (subtmpmap.ContainsKey("NoGeometry") && ((OSDBoolean)subtmpmap["NoGeometry"]))
571 continue;
572
573 if (!subtmpmap.ContainsKey("Position"))
574 return false;
575
576 if (subtmpmap.ContainsKey("TriangleList"))
577 {
578 dummy = subtmpmap["TriangleList"].AsBinary();
579 ntriangles += dummy.Length / bytesPerCoord;
580 }
581 else
582 return false;
583 }
584 }
585
586 return true;
587 }
588
589 // parses convex hulls component
590 private bool hulls(byte[] data, int offset, int size, out int nvertices, out int nhulls)
591 {
592 nvertices = 0;
593 nhulls = 1;
594
595 OSD decodedMeshOsd = new OSD();
596 byte[] meshBytes = new byte[size];
597 System.Buffer.BlockCopy(data, offset, meshBytes, 0, size);
598 try
599 {
600 using (MemoryStream inMs = new MemoryStream(meshBytes))
601 {
602 using (MemoryStream outMs = new MemoryStream())
603 {
604 using (ZOutputStream zOut = new ZOutputStream(outMs))
605 {
606 byte[] readBuffer = new byte[4096];
607 int readLen = 0;
608 while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
609 {
610 zOut.Write(readBuffer, 0, readLen);
611 }
612 zOut.Flush();
613 outMs.Seek(0, SeekOrigin.Begin);
614
615 byte[] decompressedBuf = outMs.GetBuffer();
616 decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
617 }
618 }
619 }
620 }
621 catch (Exception e)
622 {
623 return false;
624 }
625
626 OSDMap cmap = (OSDMap)decodedMeshOsd;
627 if (cmap == null)
628 return false;
629
630 byte[] dummy;
631
632 // must have one of this
633 if (cmap.ContainsKey("BoundingVerts"))
634 {
635 dummy = cmap["BoundingVerts"].AsBinary();
636 nvertices = dummy.Length / bytesPerCoord;
637 }
638 else
639 return false;
640
641/* upload is done with convex shape type
642 if (cmap.ContainsKey("HullList"))
643 {
644 dummy = cmap["HullList"].AsBinary();
645 nhulls += dummy.Length;
646 }
647
648
649 if (cmap.ContainsKey("Positions"))
650 {
651 dummy = cmap["Positions"].AsBinary();
652 nvertices = dummy.Length / bytesPerCoord;
653 }
654 */
655
656 return true;
657 }
658
659 // returns streaming cost from on mesh LODs sizes in curCost and square of prim size length
660 private float streamingCost(ameshCostParam curCost, float sqdiam)
661 {
662 // compute efective areas
663 float ma = 262144f;
664
665 float mh = sqdiam * highLodFactor;
666 if (mh > ma)
667 mh = ma;
668 float mm = sqdiam * midLodFactor;
669 if (mm > ma)
670 mm = ma;
671
672 float ml = sqdiam * lowLodFactor;
673 if (ml > ma)
674 ml = ma;
675
676 float mlst = ma;
677
678 mlst -= ml;
679 ml -= mm;
680 mm -= mh;
681
682 if (mlst < 1.0f)
683 mlst = 1.0f;
684 if (ml < 1.0f)
685 ml = 1.0f;
686 if (mm < 1.0f)
687 mm = 1.0f;
688 if (mh < 1.0f)
689 mh = 1.0f;
690
691 ma = mlst + ml + mm + mh;
692
693 // get LODs compressed sizes
694 // giving 384 bytes bonus
695 int lst = curCost.lowestLODSize - 384;
696 int l = curCost.lowLODSize - 384;
697 int m = curCost.medLODSize - 384;
698 int h = curCost.highLODSize - 384;
699
700 // use previus higher LOD size on missing ones
701 if (m <= 0)
702 m = h;
703 if (l <= 0)
704 l = m;
705 if (lst <= 0)
706 lst = l;
707
708 // force minumum sizes
709 if (lst < 16)
710 lst = 16;
711 if (l < 16)
712 l = 16;
713 if (m < 16)
714 m = 16;
715 if (h < 16)
716 h = 16;
717
718 // compute cost weighted by relative effective areas
719 float cost = (float)lst * mlst + (float)l * ml + (float)m * mm + (float)h * mh;
720 cost /= ma;
721
722 cost *= 0.004f; // overall tunning parameter
723
724 return cost;
725 }
726 }
727}