clockwerk-opensim – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 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 using System;
29 using System.Collections.Generic;
30 using System.Reflection;
31 using System.Threading;
32 using System.Text;
33 using System.Timers;
34 using log4net;
35 using Nini.Config;
36 using OpenMetaverse;
37 using OpenSim.Framework;
38 using OpenSim.Region.Framework.Interfaces;
39 using OpenSim.Region.Framework.Scenes;
40 using OpenSim.Services.Interfaces;
41  
42 using Mono.Addins;
43 using PermissionMask = OpenSim.Framework.PermissionMask;
44  
45 namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
46 {
47 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")]
48 public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule
49 {
50 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51  
52 public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}";
53  
54 private Scene m_scene = null;
55  
56 private int m_savetime = 5; // seconds to wait before saving changed appearance
57 private int m_sendtime = 2; // seconds to wait before sending changed appearance
58 private bool m_reusetextures = false;
59  
60 private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates
61 private System.Timers.Timer m_updateTimer = new System.Timers.Timer();
62 private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>();
63 private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>();
64  
65 private object m_setAppearanceLock = new object();
66  
67 #region Region Module interface
68  
69 public void Initialise(IConfigSource config)
70 {
71  
72 IConfig appearanceConfig = config.Configs["Appearance"];
73 if (appearanceConfig != null)
74 {
75 m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime)));
76 m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime)));
77 m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures);
78  
79 // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime);
80 }
81  
82 }
83  
84 public void AddRegion(Scene scene)
85 {
86 if (m_scene == null)
87 m_scene = scene;
88  
89 scene.RegisterModuleInterface<IAvatarFactoryModule>(this);
90 scene.EventManager.OnNewClient += SubscribeToClientEvents;
91 }
92  
93 public void RemoveRegion(Scene scene)
94 {
95 if (scene == m_scene)
96 {
97 scene.UnregisterModuleInterface<IAvatarFactoryModule>(this);
98 scene.EventManager.OnNewClient -= SubscribeToClientEvents;
99 }
100  
101 m_scene = null;
102 }
103  
104 public void RegionLoaded(Scene scene)
105 {
106 m_updateTimer.Enabled = false;
107 m_updateTimer.AutoReset = true;
108 m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops
109 m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer);
110 }
111  
112 public void Close()
113 {
114 }
115  
116 public string Name
117 {
118 get { return "Default Avatar Factory"; }
119 }
120  
121 public bool IsSharedModule
122 {
123 get { return false; }
124 }
125  
126 public Type ReplaceableInterface
127 {
128 get { return null; }
129 }
130  
131  
132 private void SubscribeToClientEvents(IClientAPI client)
133 {
134 client.OnRequestWearables += Client_OnRequestWearables;
135 client.OnSetAppearance += Client_OnSetAppearance;
136 client.OnAvatarNowWearing += Client_OnAvatarNowWearing;
137 client.OnCachedTextureRequest += Client_OnCachedTextureRequest;
138 }
139  
140 #endregion
141  
142 #region IAvatarFactoryModule
143  
144 /// </summary>
145 /// <param name="sp"></param>
146 /// <param name="texture"></param>
147 /// <param name="visualParam"></param>
148 public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems)
149 {
150 SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems);
151 }
152  
153  
154 public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
155 {
156 float oldoff = sp.Appearance.AvatarFeetOffset;
157 Vector3 oldbox = sp.Appearance.AvatarBoxSize;
158  
159 SetAppearance(sp, textureEntry, visualParams, cacheItems);
160 sp.Appearance.SetSize(avSize);
161  
162 float off = sp.Appearance.AvatarFeetOffset;
163 Vector3 box = sp.Appearance.AvatarBoxSize;
164 if (oldoff != off || oldbox != box)
165 ((ScenePresence)sp).SetSize(box, off);
166 }
167  
168 /// <summary>
169 /// Set appearance data (texture asset IDs and slider settings)
170 /// </summary>
171 /// <param name="sp"></param>
172 /// <param name="texture"></param>
173 /// <param name="visualParam"></param>
174 public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems)
175 {
176 // m_log.DebugFormat(
177 // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}",
178 // sp.Name, textureEntry, visualParams);
179  
180 // TODO: This is probably not necessary any longer, just assume the
181 // textureEntry set implies that the appearance transaction is complete
182 bool changed = false;
183  
184 // Process the texture entry transactionally, this doesn't guarantee that Appearance is
185 // going to be handled correctly but it does serialize the updates to the appearance
186 lock (m_setAppearanceLock)
187 {
188 // Process the visual params, this may change height as well
189 if (visualParams != null)
190 {
191 // string[] visualParamsStrings = new string[visualParams.Length];
192 // for (int i = 0; i < visualParams.Length; i++)
193 // visualParamsStrings[i] = visualParams[i].ToString();
194 // m_log.DebugFormat(
195 // "[AVFACTORY]: Setting visual params for {0} to {1}",
196 // client.Name, string.Join(", ", visualParamsStrings));
197 /*
198 float oldHeight = sp.Appearance.AvatarHeight;
199 changed = sp.Appearance.SetVisualParams(visualParams);
200  
201 if (sp.Appearance.AvatarHeight != oldHeight && sp.Appearance.AvatarHeight > 0)
202 ((ScenePresence)sp).SetHeight(sp.Appearance.AvatarHeight);
203 */
204 // float oldoff = sp.Appearance.AvatarFeetOffset;
205 // Vector3 oldbox = sp.Appearance.AvatarBoxSize;
206 changed = sp.Appearance.SetVisualParams(visualParams);
207 // float off = sp.Appearance.AvatarFeetOffset;
208 // Vector3 box = sp.Appearance.AvatarBoxSize;
209 // if(oldoff != off || oldbox != box)
210 // ((ScenePresence)sp).SetSize(box,off);
211  
212 }
213  
214 // Process the baked texture array
215 if (textureEntry != null)
216 {
217 m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID);
218  
219 // WriteBakedTexturesReport(sp, m_log.DebugFormat);
220  
221 changed = sp.Appearance.SetTextureEntries(textureEntry) || changed;
222  
223 // WriteBakedTexturesReport(sp, m_log.DebugFormat);
224  
225 // If bake textures are missing and this is not an NPC, request a rebake from client
226 if (!ValidateBakedTextureCache(sp) && (((ScenePresence)sp).PresenceType != PresenceType.Npc))
227 RequestRebake(sp, true);
228  
229 // This appears to be set only in the final stage of the appearance
230 // update transaction. In theory, we should be able to do an immediate
231 // appearance send and save here.
232 }
233  
234 // NPC should send to clients immediately and skip saving appearance
235 if (((ScenePresence)sp).PresenceType == PresenceType.Npc)
236 {
237 SendAppearance((ScenePresence)sp);
238 return;
239 }
240  
241 // save only if there were changes, send no matter what (doesn't hurt to send twice)
242 if (changed)
243 QueueAppearanceSave(sp.ControllingClient.AgentId);
244  
245 QueueAppearanceSend(sp.ControllingClient.AgentId);
246 }
247  
248 // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString());
249 }
250  
251 private void SendAppearance(ScenePresence sp)
252 {
253 // Send the appearance to everyone in the scene
254 sp.SendAppearanceToAllOtherClients();
255  
256 // Send animations back to the avatar as well
257 sp.Animator.SendAnimPack();
258 }
259  
260 public bool SendAppearance(UUID agentId)
261 {
262 // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId);
263  
264 ScenePresence sp = m_scene.GetScenePresence(agentId);
265 if (sp == null)
266 {
267 // This is expected if the user has gone away.
268 // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId);
269 return false;
270 }
271  
272 SendAppearance(sp);
273 return true;
274 }
275  
276 public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId)
277 {
278 ScenePresence sp = m_scene.GetScenePresence(agentId);
279  
280 if (sp == null)
281 return new Dictionary<BakeType, Primitive.TextureEntryFace>();
282  
283 return GetBakedTextureFaces(sp);
284 }
285  
286 public WearableCacheItem[] GetCachedItems(UUID agentId)
287 {
288 ScenePresence sp = m_scene.GetScenePresence(agentId);
289 WearableCacheItem[] items = sp.Appearance.WearableCacheItems;
290 //foreach (WearableCacheItem item in items)
291 //{
292  
293 //}
294 return items;
295 }
296  
297 public bool SaveBakedTextures(UUID agentId)
298 {
299 ScenePresence sp = m_scene.GetScenePresence(agentId);
300  
301 if (sp == null)
302 return false;
303  
304 m_log.DebugFormat(
305 "[AV FACTORY]: Permanently saving baked textures for {0} in {1}",
306 sp.Name, m_scene.RegionInfo.RegionName);
307  
308 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp);
309  
310 if (bakedTextures.Count == 0)
311 return false;
312  
313 foreach (BakeType bakeType in bakedTextures.Keys)
314 {
315 Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType];
316  
317 if (bakedTextureFace == null)
318 {
319 // This can happen legitimately, since some baked textures might not exist
320 //m_log.WarnFormat(
321 // "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently",
322 // bakeType, sp.Name, m_scene.RegionInfo.RegionName);
323 continue;
324 }
325  
326 AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString());
327  
328 if (asset != null)
329 {
330 // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars
331 asset.ID = asset.FullID.ToString();
332  
333 asset.Temporary = false;
334 asset.Local = false;
335 m_scene.AssetService.Store(asset);
336 }
337 else
338 {
339 m_log.WarnFormat(
340 "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently",
341 bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName);
342 }
343 }
344 return true;
345 }
346  
347 /// <summary>
348 /// Queue up a request to send appearance.
349 /// </summary>
350 /// <remarks>
351 /// Makes it possible to accumulate changes without sending out each one separately.
352 /// </remarks>
353 /// <param name="agentId"></param>
354 public void QueueAppearanceSend(UUID agentid)
355 {
356 // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid);
357  
358 // 10000 ticks per millisecond, 1000 milliseconds per second
359 long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000);
360 lock (m_sendqueue)
361 {
362 m_sendqueue[agentid] = timestamp;
363 m_updateTimer.Start();
364 }
365 }
366  
367 public void QueueAppearanceSave(UUID agentid)
368 {
369 // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid);
370  
371 // 10000 ticks per millisecond, 1000 milliseconds per second
372 long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000);
373 lock (m_savequeue)
374 {
375 m_savequeue[agentid] = timestamp;
376 m_updateTimer.Start();
377 }
378 }
379  
380 public bool ValidateBakedTextureCache(IScenePresence sp)
381 {
382 bool defonly = true; // are we only using default textures
383 IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>();
384 IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
385 WearableCacheItem[] wearableCache = null;
386  
387 // Cache wearable data for teleport.
388 // Only makes sense if there's a bake module and a cache module
389 if (bakedModule != null && cache != null)
390 {
391 try
392 {
393 wearableCache = bakedModule.Get(sp.UUID);
394 }
395 catch (Exception)
396 {
397  
398 }
399 if (wearableCache != null)
400 {
401 for (int i = 0; i < wearableCache.Length; i++)
402 {
403 cache.Cache(wearableCache[i].TextureAsset);
404 }
405 }
406 }
407 /*
408 IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
409 if (invService.GetRootFolder(userID) != null)
410 {
411 WearableCacheItem[] wearableCache = null;
412 if (bakedModule != null)
413 {
414 try
415 {
416 wearableCache = bakedModule.Get(userID);
417 appearance.WearableCacheItems = wearableCache;
418 appearance.WearableCacheItemsDirty = false;
419 foreach (WearableCacheItem item in wearableCache)
420 {
421 appearance.Texture.FaceTextures[item.TextureIndex].TextureID = item.TextureID;
422 }
423 }
424 catch (Exception)
425 {
426  
427 }
428 }
429 */
430  
431 // Process the texture entry
432 for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
433 {
434 int idx = AvatarAppearance.BAKE_INDICES[i];
435 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
436  
437 // No face, so lets check our baked service cache, teleport or login.
438 if (face == null)
439 {
440 if (wearableCache != null)
441 {
442 // If we find the an appearance item, set it as the textureentry and the face
443 WearableCacheItem searchitem = WearableCacheItem.SearchTextureIndex((uint) idx, wearableCache);
444 if (searchitem != null)
445 {
446 sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx);
447 sp.Appearance.Texture.FaceTextures[idx].TextureID = searchitem.TextureID;
448 face = sp.Appearance.Texture.FaceTextures[idx];
449 }
450 else
451 {
452 // if there is no texture entry and no baked cache, skip it
453 continue;
454 }
455 }
456 else
457 {
458 //No texture entry face and no cache. Skip this face.
459 continue;
460 }
461 }
462  
463 // m_log.DebugFormat(
464 // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
465 // face.TextureID, idx, client.Name, client.AgentId);
466  
467 // if the texture is one of the "defaults" then skip it
468 // this should probably be more intelligent (skirt texture doesnt matter
469 // if the avatar isnt wearing a skirt) but if any of the main baked
470 // textures is default then the rest should be as well
471 if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
472 continue;
473  
474 defonly = false; // found a non-default texture reference
475  
476 if (m_scene.AssetService.Get(face.TextureID.ToString()) == null)
477 return false;
478 }
479  
480 // m_log.DebugFormat("[AVFACTORY]: Completed texture check for {0} {1}", sp.Name, sp.UUID);
481  
482 // If we only found default textures, then the appearance is not cached
483 return (defonly ? false : true);
484 }
485  
486 public int RequestRebake(IScenePresence sp, bool missingTexturesOnly)
487 {
488 int texturesRebaked = 0;
489 // IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>();
490  
491 for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
492 {
493 int idx = AvatarAppearance.BAKE_INDICES[i];
494 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
495  
496 // if there is no texture entry, skip it
497 if (face == null)
498 continue;
499  
500 // m_log.DebugFormat(
501 // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
502 // face.TextureID, idx, client.Name, client.AgentId);
503  
504 // if the texture is one of the "defaults" then skip it
505 // this should probably be more intelligent (skirt texture doesnt matter
506 // if the avatar isnt wearing a skirt) but if any of the main baked
507 // textures is default then the rest should be as well
508 if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
509 continue;
510  
511 if (missingTexturesOnly)
512 {
513 if (m_scene.AssetService.Get(face.TextureID.ToString()) != null)
514 {
515 continue;
516 }
517 else
518 {
519 // On inter-simulator teleports, this occurs if baked textures are not being stored by the
520 // grid asset service (which means that they are not available to the new region and so have
521 // to be re-requested from the client).
522 //
523 // The only available core OpenSimulator behaviour right now
524 // is not to store these textures, temporarily or otherwise.
525 m_log.DebugFormat(
526 "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
527 face.TextureID, idx, sp.Name);
528 }
529 }
530 else
531 {
532 m_log.DebugFormat(
533 "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.",
534 face.TextureID, idx, sp.Name);
535 }
536  
537 texturesRebaked++;
538 sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
539 }
540  
541 return texturesRebaked;
542 }
543  
544 #endregion
545  
546 #region AvatarFactoryModule private methods
547  
548 private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp)
549 {
550 if (sp.IsChildAgent)
551 return new Dictionary<BakeType, Primitive.TextureEntryFace>();
552  
553 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures
554 = new Dictionary<BakeType, Primitive.TextureEntryFace>();
555  
556 AvatarAppearance appearance = sp.Appearance;
557 Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures;
558  
559 foreach (int i in Enum.GetValues(typeof(BakeType)))
560 {
561 BakeType bakeType = (BakeType)i;
562  
563 if (bakeType == BakeType.Unknown)
564 continue;
565  
566 // m_log.DebugFormat(
567 // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}",
568 // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]);
569  
570 int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
571 Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture
572 bakedTextures[bakeType] = texture;
573 }
574  
575 return bakedTextures;
576 }
577  
578 private void HandleAppearanceUpdateTimer(object sender, EventArgs ea)
579 {
580 long now = DateTime.Now.Ticks;
581  
582 lock (m_sendqueue)
583 {
584 Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue);
585 foreach (KeyValuePair<UUID, long> kvp in sends)
586 {
587 // We have to load the key and value into local parameters to avoid a race condition if we loop
588 // around and load kvp with a different value before FireAndForget has launched its thread.
589 UUID avatarID = kvp.Key;
590 long sendTime = kvp.Value;
591  
592 // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now);
593  
594 if (sendTime < now)
595 {
596 Util.FireAndForget(o => SendAppearance(avatarID));
597 m_sendqueue.Remove(avatarID);
598 }
599 }
600 }
601  
602 lock (m_savequeue)
603 {
604 Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue);
605 foreach (KeyValuePair<UUID, long> kvp in saves)
606 {
607 // We have to load the key and value into local parameters to avoid a race condition if we loop
608 // around and load kvp with a different value before FireAndForget has launched its thread.
609 UUID avatarID = kvp.Key;
610 long sendTime = kvp.Value;
611  
612 if (sendTime < now)
613 {
614 Util.FireAndForget(o => SaveAppearance(avatarID));
615 m_savequeue.Remove(avatarID);
616 }
617 }
618  
619 // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on
620 // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread.
621 lock (m_sendqueue)
622 if (m_savequeue.Count == 0 && m_sendqueue.Count == 0)
623 m_updateTimer.Stop();
624 }
625 }
626  
627 private void SaveAppearance(UUID agentid)
628 {
629 // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved
630 // in a culture where decimal points are commas and then reloaded in a culture which just treats them as
631 // number seperators.
632 Culture.SetCurrentCulture();
633  
634 ScenePresence sp = m_scene.GetScenePresence(agentid);
635 if (sp == null)
636 {
637 // This is expected if the user has gone away.
638 // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid);
639 return;
640 }
641  
642 // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid);
643  
644 // This could take awhile since it needs to pull inventory
645 // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape
646 // assets and item asset id changes to complete.
647 // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids
648 // multiple save requests.
649 SetAppearanceAssets(sp.UUID, sp.Appearance);
650  
651 // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
652 // foreach (AvatarAttachment att in attachments)
653 // {
654 // m_log.DebugFormat(
655 // "[AVFACTORY]: For {0} saving attachment {1} at point {2}",
656 // sp.Name, att.ItemID, att.AttachPoint);
657 // }
658  
659 m_scene.AvatarService.SetAppearance(agentid, sp.Appearance);
660  
661 // Trigger this here because it's the final step in the set/queue/save process for appearance setting.
662 // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes).
663 m_scene.EventManager.TriggerAvatarAppearanceChanged(sp);
664 }
665  
666 /// <summary>
667 /// For a given set of appearance items, check whether the items are valid and add their asset IDs to
668 /// appearance data.
669 /// </summary>
670 /// <param name='userID'></param>
671 /// <param name='appearance'></param>
672 private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance)
673 {
674 IInventoryService invService = m_scene.InventoryService;
675  
676 if (invService.GetRootFolder(userID) != null)
677 {
678 for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
679 {
680 for (int j = 0; j < appearance.Wearables[i].Count; j++)
681 {
682 if (appearance.Wearables[i][j].ItemID == UUID.Zero)
683 {
684 m_log.WarnFormat(
685 "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.",
686 i, j, userID);
687  
688 continue;
689 }
690  
691 // Ignore ruth's assets
692 if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
693 continue;
694  
695 InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
696 baseItem = invService.GetItem(baseItem);
697  
698 if (baseItem != null)
699 {
700 appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
701 }
702 else
703 {
704 m_log.WarnFormat(
705 "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
706 appearance.Wearables[i][j].ItemID, (WearableType)i);
707  
708 appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID);
709 }
710 }
711 }
712 }
713 else
714 {
715 m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
716 }
717  
718 // IInventoryService invService = m_scene.InventoryService;
719 // bool resetwearable = false;
720 // if (invService.GetRootFolder(userID) != null)
721 // {
722 // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
723 // {
724 // for (int j = 0; j < appearance.Wearables[i].Count; j++)
725 // {
726 // // Check if the default wearables are not set
727 // if (appearance.Wearables[i][j].ItemID == UUID.Zero)
728 // {
729 // switch ((WearableType) i)
730 // {
731 // case WearableType.Eyes:
732 // case WearableType.Hair:
733 // case WearableType.Shape:
734 // case WearableType.Skin:
735 // //case WearableType.Underpants:
736 // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
737 // resetwearable = true;
738 // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values.");
739 // resetwearable = true;
740 // break;
741 //
742 // }
743 // continue;
744 // }
745 //
746 // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1
747 // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
748 // {
749 // switch ((WearableType)i)
750 // {
751 // case WearableType.Eyes:
752 // case WearableType.Hair:
753 // case WearableType.Shape:
754 // case WearableType.Skin:
755 // //case WearableType.Underpants:
756 // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
757 //
758 // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i);
759 // resetwearable = true;
760 // break;
761 //
762 // }
763 // continue;
764 // }
765 //
766 // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
767 // baseItem = invService.GetItem(baseItem);
768 //
769 // if (baseItem != null)
770 // {
771 // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
772 // int unmodifiedWearableIndexForClosure = i;
773 // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this,
774 // delegate(string x, object y, AssetBase z)
775 // {
776 // if (z == null)
777 // {
778 // TryAndRepairBrokenWearable(
779 // (WearableType)unmodifiedWearableIndexForClosure, invService,
780 // userID, appearance);
781 // }
782 // });
783 // }
784 // else
785 // {
786 // m_log.ErrorFormat(
787 // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
788 // appearance.Wearables[i][j].ItemID, (WearableType)i);
789 //
790 // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
791 // resetwearable = true;
792 //
793 // }
794 // }
795 // }
796 //
797 // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
798 // if (appearance.Wearables[(int) WearableType.Eyes] == null)
799 // {
800 // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes));
801 //
802 // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
803 // resetwearable = true;
804 // }
805 // else
806 // {
807 // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero)
808 // {
809 // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}",
810 // appearance.Wearables[(int) WearableType.Eyes][0].ItemID,
811 // appearance.Wearables[(int) WearableType.Eyes][0].AssetID);
812 // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
813 // resetwearable = true;
814 //
815 // }
816 //
817 // }
818 // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
819 // if (appearance.Wearables[(int)WearableType.Shape] == null)
820 // {
821 // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape));
822 //
823 // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
824 // resetwearable = true;
825 // }
826 // else
827 // {
828 // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero)
829 // {
830 // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}",
831 // appearance.Wearables[(int)WearableType.Shape][0].ItemID,
832 // appearance.Wearables[(int)WearableType.Shape][0].AssetID);
833 // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
834 // resetwearable = true;
835 //
836 // }
837 //
838 // }
839 // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
840 // if (appearance.Wearables[(int)WearableType.Hair] == null)
841 // {
842 // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair));
843 //
844 // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
845 // resetwearable = true;
846 // }
847 // else
848 // {
849 // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero)
850 // {
851 // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}",
852 // appearance.Wearables[(int)WearableType.Hair][0].ItemID,
853 // appearance.Wearables[(int)WearableType.Hair][0].AssetID);
854 // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
855 // resetwearable = true;
856 //
857 // }
858 //
859 // }
860 // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
861 // if (appearance.Wearables[(int)WearableType.Skin] == null)
862 // {
863 // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin));
864 //
865 // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
866 // resetwearable = true;
867 // }
868 // else
869 // {
870 // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero)
871 // {
872 // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}",
873 // appearance.Wearables[(int)WearableType.Skin][0].ItemID,
874 // appearance.Wearables[(int)WearableType.Skin][0].AssetID);
875 // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
876 // resetwearable = true;
877 //
878 // }
879 //
880 // }
881 // if (resetwearable)
882 // {
883 // ScenePresence presence = null;
884 // if (m_scene.TryGetScenePresence(userID, out presence))
885 // {
886 // presence.ControllingClient.SendWearables(presence.Appearance.Wearables,
887 // presence.Appearance.Serial++);
888 // }
889 // }
890 //
891 // }
892 // else
893 // {
894 // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
895 // }
896 }
897  
898 private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance)
899 {
900 UUID defaultwearable = GetDefaultItem(type);
901 if (defaultwearable != UUID.Zero)
902 {
903 UUID newInvItem = UUID.Random();
904 InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID)
905 {
906 AssetID =
907 defaultwearable,
908 AssetType
909 =
910 (int)
911 AssetType
912 .Bodypart,
913 CreatorId
914 =
915 userID
916 .ToString
917 (),
918 //InvType = (int)InventoryType.Wearable,
919  
920 Description
921 =
922 "Failed Wearable Replacement",
923 Folder =
924 invService
925 .GetFolderForType
926 (userID,
927 AssetType
928 .Bodypart)
929 .ID,
930 Flags = (uint) type,
931 Name = Enum.GetName(typeof (WearableType), type),
932 BasePermissions = (uint) PermissionMask.Copy,
933 CurrentPermissions = (uint) PermissionMask.Copy,
934 EveryOnePermissions = (uint) PermissionMask.Copy,
935 GroupPermissions = (uint) PermissionMask.Copy,
936 NextPermissions = (uint) PermissionMask.Copy
937 };
938 invService.AddItem(itembase);
939 UUID LinkInvItem = UUID.Random();
940 itembase = new InventoryItemBase(LinkInvItem, userID)
941 {
942 AssetID =
943 newInvItem,
944 AssetType
945 =
946 (int)
947 AssetType
948 .Link,
949 CreatorId
950 =
951 userID
952 .ToString
953 (),
954 InvType = (int) InventoryType.Wearable,
955  
956 Description
957 =
958 "Failed Wearable Replacement",
959 Folder =
960 invService
961 .GetFolderForType
962 (userID,
963 AssetType
964 .CurrentOutfitFolder)
965 .ID,
966 Flags = (uint) type,
967 Name = Enum.GetName(typeof (WearableType), type),
968 BasePermissions = (uint) PermissionMask.Copy,
969 CurrentPermissions = (uint) PermissionMask.Copy,
970 EveryOnePermissions = (uint) PermissionMask.Copy,
971 GroupPermissions = (uint) PermissionMask.Copy,
972 NextPermissions = (uint) PermissionMask.Copy
973 };
974 invService.AddItem(itembase);
975 appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type));
976 ScenePresence presence = null;
977 if (m_scene.TryGetScenePresence(userID, out presence))
978 {
979 m_scene.SendInventoryUpdate(presence.ControllingClient,
980 invService.GetFolderForType(userID,
981 AssetType
982 .CurrentOutfitFolder),
983 false, true);
984 }
985 }
986 }
987  
988 private UUID GetDefaultItem(WearableType wearable)
989 {
990 // These are ruth
991 UUID ret = UUID.Zero;
992 switch (wearable)
993 {
994 case WearableType.Eyes:
995 ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7");
996 break;
997 case WearableType.Hair:
998 ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66");
999 break;
1000 case WearableType.Pants:
1001 ret = new UUID("00000000-38f9-1111-024e-222222111120");
1002 break;
1003 case WearableType.Shape:
1004 ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73");
1005 break;
1006 case WearableType.Shirt:
1007 ret = new UUID("00000000-38f9-1111-024e-222222111110");
1008 break;
1009 case WearableType.Skin:
1010 ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb");
1011 break;
1012 case WearableType.Undershirt:
1013 ret = new UUID("16499ebb-3208-ec27-2def-481881728f47");
1014 break;
1015 case WearableType.Underpants:
1016 ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d");
1017 break;
1018 }
1019  
1020 return ret;
1021 }
1022 #endregion
1023  
1024 #region Client Event Handlers
1025 /// <summary>
1026 /// Tell the client for this scene presence what items it should be wearing now
1027 /// </summary>
1028 /// <param name="client"></param>
1029 private void Client_OnRequestWearables(IClientAPI client)
1030 {
1031 Util.FireAndForget(delegate(object x)
1032 {
1033 Thread.Sleep(4000);
1034  
1035 // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId);
1036 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
1037 if (sp != null)
1038 client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++);
1039 else
1040 m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId);
1041 });
1042 }
1043  
1044 /// <summary>
1045 /// Set appearance data (texture asset IDs and slider settings) received from a client
1046 /// </summary>
1047 /// <param name="client"></param>
1048 /// <param name="texture"></param>
1049 /// <param name="visualParam"></param>
1050 private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
1051 {
1052 // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId);
1053 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
1054 if (sp != null)
1055 SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems);
1056 else
1057 m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId);
1058 }
1059  
1060 /// <summary>
1061 /// Update what the avatar is wearing using an item from their inventory.
1062 /// </summary>
1063 /// <param name="client"></param>
1064 /// <param name="e"></param>
1065 private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e)
1066 {
1067 // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId);
1068 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
1069 if (sp == null)
1070 {
1071 m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId);
1072 return;
1073 }
1074  
1075 // we need to clean out the existing textures
1076 sp.Appearance.ResetAppearance();
1077  
1078 // operate on a copy of the appearance so we don't have to lock anything yet
1079 AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false);
1080  
1081 foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
1082 {
1083 if (wear.Type < AvatarWearable.MAX_WEARABLES)
1084 avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
1085 }
1086  
1087 avatAppearance.GetAssetsFrom(sp.Appearance);
1088  
1089 lock (m_setAppearanceLock)
1090 {
1091 // Update only those fields that we have changed. This is important because the viewer
1092 // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing
1093 // shouldn't overwrite the changes made in SetAppearance.
1094 sp.Appearance.Wearables = avatAppearance.Wearables;
1095 sp.Appearance.Texture = avatAppearance.Texture;
1096  
1097 // We don't need to send the appearance here since the "iswearing" will trigger a new set
1098 // of visual param and baked texture changes. When those complete, the new appearance will be sent
1099  
1100 QueueAppearanceSave(client.AgentId);
1101 }
1102 }
1103  
1104 /// <summary>
1105 /// Respond to the cached textures request from the client
1106 /// </summary>
1107 /// <param name="client"></param>
1108 /// <param name="serial"></param>
1109 /// <param name="cachedTextureRequest"></param>
1110 private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest)
1111 {
1112 // m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId);
1113 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
1114  
1115 List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>();
1116 foreach (CachedTextureRequestArg request in cachedTextureRequest)
1117 {
1118 UUID texture = UUID.Zero;
1119 int index = request.BakedTextureIndex;
1120  
1121 if (m_reusetextures)
1122 {
1123 // this is the most insanely dumb way to do this... however it seems to
1124 // actually work. if the appearance has been reset because wearables have
1125 // changed then the texture entries are zero'd out until the bakes are
1126 // uploaded. on login, if the textures exist in the cache (eg if you logged
1127 // into the simulator recently, then the appearance will pull those and send
1128 // them back in the packet and you won't have to rebake. if the textures aren't
1129 // in the cache then the intial makeroot() call in scenepresence will zero
1130 // them out.
1131 //
1132 // a better solution (though how much better is an open question) is to
1133 // store the hashes in the appearance and compare them. Thats's coming.
1134  
1135 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index];
1136 if (face != null)
1137 texture = face.TextureID;
1138  
1139 // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index);
1140 }
1141  
1142 CachedTextureResponseArg response = new CachedTextureResponseArg();
1143 response.BakedTextureIndex = index;
1144 response.BakedTextureID = texture;
1145 response.HostName = null;
1146  
1147 cachedTextureResponse.Add(response);
1148 }
1149  
1150 // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial);
1151 // The serial number appears to be used to match requests and responses
1152 // in the texture transaction. We just send back the serial number
1153 // that was provided in the request. The viewer bumps this for us.
1154 client.SendCachedTextureResponse(sp, serial, cachedTextureResponse);
1155 }
1156  
1157  
1158 #endregion
1159  
1160 public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction)
1161 {
1162 outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName);
1163 outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID");
1164  
1165 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID);
1166  
1167 foreach (BakeType bt in bakedTextures.Keys)
1168 {
1169 string rawTextureID;
1170  
1171 if (bakedTextures[bt] == null)
1172 {
1173 rawTextureID = "not set";
1174 }
1175 else
1176 {
1177 rawTextureID = bakedTextures[bt].TextureID.ToString();
1178  
1179 if (m_scene.AssetService.Get(rawTextureID) == null)
1180 rawTextureID += " (not found)";
1181 else
1182 rawTextureID += " (uploaded)";
1183 }
1184  
1185 outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID);
1186 }
1187  
1188 bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp);
1189 outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
1190 }
1191 }
1192 }