PageRenderTime 53ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/OpenMetaverse/Modules/AppearanceManager.cs

https://bitbucket.org/VirtualReality/3rdparty-addon-modules
C# | 2342 lines | 1523 code | 316 blank | 503 comment | 258 complexity | bd3eb7a2090604a507f5d95d74e59da0 MD5 | raw file
  1. /*
  2. * Copyright (c) 2006-2008, openmetaverse.org
  3. * All rights reserved.
  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. *
  8. * - Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. * - Neither the name of the openmetaverse.org nor the names
  11. * of its contributors may be used to endorse or promote products derived from
  12. * this software without specific prior written permission.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. * POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. using System;
  27. using System.Collections.Generic;
  28. using System.Threading;
  29. using System.Drawing;
  30. using OpenMetaverse;
  31. using OpenMetaverse.Packets;
  32. using OpenMetaverse.Imaging;
  33. using OpenMetaverse.Assets;
  34. namespace OpenMetaverse
  35. {
  36. #region Enums
  37. /// <summary>
  38. /// Index of TextureEntry slots for avatar appearances
  39. /// </summary>
  40. public enum AvatarTextureIndex
  41. {
  42. Unknown = -1,
  43. HeadBodypaint = 0,
  44. UpperShirt,
  45. LowerPants,
  46. EyesIris,
  47. Hair,
  48. UpperBodypaint,
  49. LowerBodypaint,
  50. LowerShoes,
  51. HeadBaked,
  52. UpperBaked,
  53. LowerBaked,
  54. EyesBaked,
  55. LowerSocks,
  56. UpperJacket,
  57. LowerJacket,
  58. UpperGloves,
  59. UpperUndershirt,
  60. LowerUnderpants,
  61. Skirt,
  62. SkirtBaked,
  63. HairBaked,
  64. LowerAlpha,
  65. UpperAlpha,
  66. HeadAlpha,
  67. EyesAlpha,
  68. HairAlpha,
  69. HeadTattoo,
  70. UpperTattoo,
  71. LowerTattoo,
  72. NumberOfEntries
  73. }
  74. /// <summary>
  75. /// Bake layers for avatar appearance
  76. /// </summary>
  77. public enum BakeType
  78. {
  79. Unknown = -1,
  80. Head = 0,
  81. UpperBody = 1,
  82. LowerBody = 2,
  83. Eyes = 3,
  84. Skirt = 4,
  85. Hair = 5
  86. }
  87. #endregion Enums
  88. public class AppearanceManager
  89. {
  90. #region Constants
  91. /// <summary>Mask for multiple attachments</summary>
  92. public static readonly byte ATTACHMENT_ADD = 0x80;
  93. /// <summary>Mapping between BakeType and AvatarTextureIndex</summary>
  94. public static readonly byte[] BakeIndexToTextureIndex = new byte[BAKED_TEXTURE_COUNT] { 8, 9, 10, 11, 19, 20 };
  95. /// <summary>Maximum number of concurrent downloads for wearable assets and textures</summary>
  96. const int MAX_CONCURRENT_DOWNLOADS = 5;
  97. /// <summary>Maximum number of concurrent uploads for baked textures</summary>
  98. const int MAX_CONCURRENT_UPLOADS = 6;
  99. /// <summary>Timeout for fetching inventory listings</summary>
  100. const int INVENTORY_TIMEOUT = 1000 * 30;
  101. /// <summary>Timeout for fetching a single wearable, or receiving a single packet response</summary>
  102. const int WEARABLE_TIMEOUT = 1000 * 30;
  103. /// <summary>Timeout for fetching a single texture</summary>
  104. const int TEXTURE_TIMEOUT = 1000 * 120;
  105. /// <summary>Timeout for uploading a single baked texture</summary>
  106. const int UPLOAD_TIMEOUT = 1000 * 90;
  107. /// <summary>Number of times to retry bake upload</summary>
  108. const int UPLOAD_RETRIES = 2;
  109. /// <summary>When changing outfit, kick off rebake after
  110. /// 20 seconds has passed since the last change</summary>
  111. const int REBAKE_DELAY = 1000 * 20;
  112. /// <summary>Total number of wearables for each avatar</summary>
  113. public const int WEARABLE_COUNT = 16;
  114. /// <summary>Total number of baked textures on each avatar</summary>
  115. public const int BAKED_TEXTURE_COUNT = 6;
  116. /// <summary>Total number of wearables per bake layer</summary>
  117. public const int WEARABLES_PER_LAYER = 9;
  118. /// <summary>Map of what wearables are included in each bake</summary>
  119. public static readonly WearableType[][] WEARABLE_BAKE_MAP = new WearableType[][]
  120. {
  121. new WearableType[] { WearableType.Shape, WearableType.Skin, WearableType.Tattoo, WearableType.Hair, WearableType.Alpha, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid },
  122. new WearableType[] { WearableType.Shape, WearableType.Skin, WearableType.Tattoo, WearableType.Shirt, WearableType.Jacket, WearableType.Gloves, WearableType.Undershirt, WearableType.Alpha, WearableType.Invalid },
  123. new WearableType[] { WearableType.Shape, WearableType.Skin, WearableType.Tattoo, WearableType.Pants, WearableType.Shoes, WearableType.Socks, WearableType.Jacket, WearableType.Underpants, WearableType.Alpha },
  124. new WearableType[] { WearableType.Eyes, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid },
  125. new WearableType[] { WearableType.Skirt, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid },
  126. new WearableType[] { WearableType.Hair, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid, WearableType.Invalid }
  127. };
  128. /// <summary>Magic values to finalize the cache check hashes for each
  129. /// bake</summary>
  130. public static readonly UUID[] BAKED_TEXTURE_HASH = new UUID[]
  131. {
  132. new UUID("18ded8d6-bcfc-e415-8539-944c0f5ea7a6"),
  133. new UUID("338c29e3-3024-4dbb-998d-7c04cf4fa88f"),
  134. new UUID("91b4a2c7-1b1a-ba16-9a16-1f8f8dcc1c3f"),
  135. new UUID("b2cf28af-b840-1071-3c6a-78085d8128b5"),
  136. new UUID("ea800387-ea1a-14e0-56cb-24f2022f969a"),
  137. new UUID("0af1ef7c-ad24-11dd-8790-001f5bf833e8")
  138. };
  139. /// <summary>Default avatar texture, used to detect when a custom
  140. /// texture is not set for a face</summary>
  141. public static readonly UUID DEFAULT_AVATAR_TEXTURE = new UUID("c228d1cf-4b5d-4ba8-84f4-899a0796aa97");
  142. #endregion Constants
  143. #region Structs / Classes
  144. /// <summary>
  145. /// Contains information about a wearable inventory item
  146. /// </summary>
  147. public class WearableData
  148. {
  149. /// <summary>Inventory ItemID of the wearable</summary>
  150. public UUID ItemID;
  151. /// <summary>AssetID of the wearable asset</summary>
  152. public UUID AssetID;
  153. /// <summary>WearableType of the wearable</summary>
  154. public WearableType WearableType;
  155. /// <summary>AssetType of the wearable</summary>
  156. public AssetType AssetType;
  157. /// <summary>Asset data for the wearable</summary>
  158. public AssetWearable Asset;
  159. public override string ToString()
  160. {
  161. return String.Format("ItemID: {0}, AssetID: {1}, WearableType: {2}, AssetType: {3}, Asset: {4}",
  162. ItemID, AssetID, WearableType, AssetType, Asset != null ? Asset.Name : "(null)");
  163. }
  164. }
  165. /// <summary>
  166. /// Data collected from visual params for each wearable
  167. /// needed for the calculation of the color
  168. /// </summary>
  169. private struct ColorParamInfo
  170. {
  171. public VisualParam VisualParam;
  172. public VisualColorParam VisualColorParam;
  173. public float Value;
  174. public WearableType WearableType;
  175. }
  176. /// <summary>
  177. /// Holds a texture assetID and the data needed to bake this layer into
  178. /// an outfit texture. Used to keep track of currently worn textures
  179. /// and baking data
  180. /// </summary>
  181. public struct TextureData
  182. {
  183. /// <summary>A texture AssetID</summary>
  184. public UUID TextureID;
  185. /// <summary>Asset data for the texture</summary>
  186. public AssetTexture Texture;
  187. /// <summary>Collection of alpha masks that needs applying</summary>
  188. public Dictionary<VisualAlphaParam, float> AlphaMasks;
  189. /// <summary>Tint that should be applied to the texture</summary>
  190. public Color4 Color;
  191. /// <summary>Where on avatar does this texture belong</summary>
  192. public AvatarTextureIndex TextureIndex;
  193. public override string ToString()
  194. {
  195. return String.Format("TextureID: {0}, Texture: {1}",
  196. TextureID, Texture != null ? Texture.AssetData.Length + " bytes" : "(null)");
  197. }
  198. }
  199. #endregion Structs / Classes
  200. #region Event delegates, Raise Events
  201. /// <summary>The event subscribers. null if no subcribers</summary>
  202. private EventHandler<AgentWearablesReplyEventArgs> m_AgentWearablesReply;
  203. /// <summary>Raises the AgentWearablesReply event</summary>
  204. /// <param name="e">An AgentWearablesReplyEventArgs object containing the
  205. /// data returned from the data server</param>
  206. protected virtual void OnAgentWearables(AgentWearablesReplyEventArgs e)
  207. {
  208. EventHandler<AgentWearablesReplyEventArgs> handler = m_AgentWearablesReply;
  209. if (handler != null)
  210. handler(this, e);
  211. }
  212. /// <summary>Thread sync lock object</summary>
  213. private readonly object m_AgentWearablesLock = new object();
  214. /// <summary>Triggered when an AgentWearablesUpdate packet is received,
  215. /// telling us what our avatar is currently wearing
  216. /// <see cref="RequestAgentWearables"/> request.</summary>
  217. public event EventHandler<AgentWearablesReplyEventArgs> AgentWearablesReply
  218. {
  219. add { lock (m_AgentWearablesLock) { m_AgentWearablesReply += value; } }
  220. remove { lock (m_AgentWearablesLock) { m_AgentWearablesReply -= value; } }
  221. }
  222. /// <summary>The event subscribers. null if no subcribers</summary>
  223. private EventHandler<AgentCachedBakesReplyEventArgs> m_AgentCachedBakesReply;
  224. /// <summary>Raises the CachedBakesReply event</summary>
  225. /// <param name="e">An AgentCachedBakesReplyEventArgs object containing the
  226. /// data returned from the data server AgentCachedTextureResponse</param>
  227. protected virtual void OnAgentCachedBakes(AgentCachedBakesReplyEventArgs e)
  228. {
  229. EventHandler<AgentCachedBakesReplyEventArgs> handler = m_AgentCachedBakesReply;
  230. if (handler != null)
  231. handler(this, e);
  232. }
  233. /// <summary>Thread sync lock object</summary>
  234. private readonly object m_AgentCachedBakesLock = new object();
  235. /// <summary>Raised when an AgentCachedTextureResponse packet is
  236. /// received, giving a list of cached bakes that were found on the
  237. /// simulator
  238. /// <seealso cref="RequestCachedBakes"/> request.</summary>
  239. public event EventHandler<AgentCachedBakesReplyEventArgs> CachedBakesReply
  240. {
  241. add { lock (m_AgentCachedBakesLock) { m_AgentCachedBakesReply += value; } }
  242. remove { lock (m_AgentCachedBakesLock) { m_AgentCachedBakesReply -= value; } }
  243. }
  244. /// <summary>The event subscribers. null if no subcribers</summary>
  245. private EventHandler<AppearanceSetEventArgs> m_AppearanceSet;
  246. /// <summary>Raises the AppearanceSet event</summary>
  247. /// <param name="e">An AppearanceSetEventArgs object indicating if the operatin was successfull</param>
  248. protected virtual void OnAppearanceSet(AppearanceSetEventArgs e)
  249. {
  250. EventHandler<AppearanceSetEventArgs> handler = m_AppearanceSet;
  251. if (handler != null)
  252. handler(this, e);
  253. }
  254. /// <summary>Thread sync lock object</summary>
  255. private readonly object m_AppearanceSetLock = new object();
  256. /// <summary>
  257. /// Raised when appearance data is sent to the simulator, also indicates
  258. /// the main appearance thread is finished.
  259. /// </summary>
  260. /// <seealso cref="RequestAgentSetAppearance"/> request.
  261. public event EventHandler<AppearanceSetEventArgs> AppearanceSet
  262. {
  263. add { lock (m_AppearanceSetLock) { m_AppearanceSet += value; } }
  264. remove { lock (m_AppearanceSetLock) { m_AppearanceSet -= value; } }
  265. }
  266. /// <summary>The event subscribers. null if no subcribers</summary>
  267. private EventHandler<RebakeAvatarTexturesEventArgs> m_RebakeAvatarReply;
  268. /// <summary>Raises the RebakeAvatarRequested event</summary>
  269. /// <param name="e">An RebakeAvatarTexturesEventArgs object containing the
  270. /// data returned from the data server</param>
  271. protected virtual void OnRebakeAvatar(RebakeAvatarTexturesEventArgs e)
  272. {
  273. EventHandler<RebakeAvatarTexturesEventArgs> handler = m_RebakeAvatarReply;
  274. if (handler != null)
  275. handler(this, e);
  276. }
  277. /// <summary>Thread sync lock object</summary>
  278. private readonly object m_RebakeAvatarLock = new object();
  279. /// <summary>
  280. /// Triggered when the simulator requests the agent rebake its appearance.
  281. /// </summary>
  282. /// <seealso cref="RebakeAvatarRequest"/>
  283. public event EventHandler<RebakeAvatarTexturesEventArgs> RebakeAvatarRequested
  284. {
  285. add { lock (m_RebakeAvatarLock) { m_RebakeAvatarReply += value; } }
  286. remove { lock (m_RebakeAvatarLock) { m_RebakeAvatarReply -= value; } }
  287. }
  288. #endregion
  289. #region Properties and public fields
  290. /// <summary>
  291. /// Returns true if AppearanceManager is busy and trying to set or change appearance will fail
  292. /// </summary>
  293. public bool ManagerBusy
  294. {
  295. get
  296. {
  297. return AppearanceThreadRunning != 0;
  298. }
  299. }
  300. /// <summary>Visual parameters last sent to the sim</summary>
  301. public byte[] MyVisualParameters = null;
  302. /// <summary>Textures about this client sent to the sim</summary>
  303. public Primitive.TextureEntry MyTextures = null;
  304. #endregion Properties
  305. #region Private Members
  306. /// <summary>A cache of wearables currently being worn</summary>
  307. private Dictionary<WearableType, WearableData> Wearables = new Dictionary<WearableType, WearableData>();
  308. /// <summary>A cache of textures currently being worn</summary>
  309. private TextureData[] Textures = new TextureData[(int)AvatarTextureIndex.NumberOfEntries];
  310. /// <summary>Incrementing serial number for AgentCachedTexture packets</summary>
  311. private int CacheCheckSerialNum = -1;
  312. /// <summary>Incrementing serial number for AgentSetAppearance packets</summary>
  313. private int SetAppearanceSerialNum = 0;
  314. /// <summary>Indicates whether or not the appearance thread is currently
  315. /// running, to prevent multiple appearance threads from running
  316. /// simultaneously</summary>
  317. private int AppearanceThreadRunning = 0;
  318. /// <summary>Reference to our agent</summary>
  319. private GridClient Client;
  320. /// <summary>
  321. /// Timer used for delaying rebake on changing outfit
  322. /// </summary>
  323. private Timer RebakeScheduleTimer;
  324. /// <summary>
  325. /// Main appearance thread
  326. /// </summary>
  327. private Thread AppearanceThread;
  328. #endregion Private Members
  329. /// <summary>
  330. /// Default constructor
  331. /// </summary>
  332. /// <param name="client">A reference to our agent</param>
  333. public AppearanceManager(GridClient client)
  334. {
  335. Client = client;
  336. Client.Network.RegisterCallback(PacketType.AgentWearablesUpdate, AgentWearablesUpdateHandler);
  337. Client.Network.RegisterCallback(PacketType.AgentCachedTextureResponse, AgentCachedTextureResponseHandler);
  338. Client.Network.RegisterCallback(PacketType.RebakeAvatarTextures, RebakeAvatarTexturesHandler);
  339. Client.Network.EventQueueRunning += Network_OnEventQueueRunning;
  340. Client.Network.Disconnected += Network_OnDisconnected;
  341. }
  342. #region Publics Methods
  343. /// <summary>
  344. /// Obsolete method for setting appearance. This function no longer does anything.
  345. /// Use RequestSetAppearance() to manually start the appearance thread
  346. /// </summary>
  347. [Obsolete("Appearance is now handled automatically")]
  348. public void SetPreviousAppearance()
  349. {
  350. }
  351. /// <summary>
  352. /// Obsolete method for setting appearance. This function no longer does anything.
  353. /// Use RequestSetAppearance() to manually start the appearance thread
  354. /// </summary>
  355. /// <param name="allowBake">Unused parameter</param>
  356. [Obsolete("Appearance is now handled automatically")]
  357. public void SetPreviousAppearance(bool allowBake)
  358. {
  359. }
  360. /// <summary>
  361. /// Starts the appearance setting thread
  362. /// </summary>
  363. public void RequestSetAppearance()
  364. {
  365. RequestSetAppearance(false);
  366. }
  367. /// <summary>
  368. /// Starts the appearance setting thread
  369. /// </summary>
  370. /// <param name="forceRebake">True to force rebaking, otherwise false</param>
  371. public void RequestSetAppearance(bool forceRebake)
  372. {
  373. if (Interlocked.CompareExchange(ref AppearanceThreadRunning, 1, 0) != 0)
  374. {
  375. Logger.Log("Appearance thread is already running, skipping", Helpers.LogLevel.Warning);
  376. return;
  377. }
  378. // If we have an active delayed scheduled appearance bake, we dispose of it
  379. if (RebakeScheduleTimer != null)
  380. {
  381. RebakeScheduleTimer.Dispose();
  382. RebakeScheduleTimer = null;
  383. }
  384. // This is the first time setting appearance, run through the entire sequence
  385. AppearanceThread = new Thread(
  386. delegate()
  387. {
  388. bool success = true;
  389. try
  390. {
  391. if (forceRebake)
  392. {
  393. // Set all of the baked textures to UUID.Zero to force rebaking
  394. for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
  395. Textures[(int)BakeTypeToAgentTextureIndex((BakeType)bakedIndex)].TextureID = UUID.Zero;
  396. }
  397. if (SetAppearanceSerialNum == 0)
  398. {
  399. // Fetch a list of the current agent wearables
  400. if (!GetAgentWearables())
  401. {
  402. Logger.Log("Failed to retrieve a list of current agent wearables, appearance cannot be set",
  403. Helpers.LogLevel.Error, Client);
  404. throw new Exception("Failed to retrieve a list of current agent wearables, appearance cannot be set");
  405. }
  406. }
  407. // Download and parse all of the agent wearables
  408. if (!DownloadWearables())
  409. {
  410. success = false;
  411. Logger.Log("One or more agent wearables failed to download, appearance will be incomplete",
  412. Helpers.LogLevel.Warning, Client);
  413. }
  414. // If this is the first time setting appearance and we're not forcing rebakes, check the server
  415. // for cached bakes
  416. if (SetAppearanceSerialNum == 0 && !forceRebake)
  417. {
  418. // Compute hashes for each bake layer and compare against what the simulator currently has
  419. if (!GetCachedBakes())
  420. {
  421. Logger.Log("Failed to get a list of cached bakes from the simulator, appearance will be rebaked",
  422. Helpers.LogLevel.Warning, Client);
  423. }
  424. }
  425. // Download textures, compute bakes, and upload for any cache misses
  426. if (!CreateBakes())
  427. {
  428. success = false;
  429. Logger.Log("Failed to create or upload one or more bakes, appearance will be incomplete",
  430. Helpers.LogLevel.Warning, Client);
  431. }
  432. // Send the appearance packet
  433. RequestAgentSetAppearance();
  434. }
  435. catch (Exception)
  436. {
  437. success = false;
  438. }
  439. finally
  440. {
  441. AppearanceThreadRunning = 0;
  442. OnAppearanceSet(new AppearanceSetEventArgs(success));
  443. }
  444. }
  445. );
  446. AppearanceThread.Name = "Appearance";
  447. AppearanceThread.IsBackground = true;
  448. AppearanceThread.Start();
  449. }
  450. /// <summary>
  451. /// Ask the server what textures our agent is currently wearing
  452. /// </summary>
  453. public void RequestAgentWearables()
  454. {
  455. AgentWearablesRequestPacket request = new AgentWearablesRequestPacket();
  456. request.AgentData.AgentID = Client.Self.AgentID;
  457. request.AgentData.SessionID = Client.Self.SessionID;
  458. Client.Network.SendPacket(request);
  459. }
  460. /// <summary>
  461. /// Build hashes out of the texture assetIDs for each baking layer to
  462. /// ask the simulator whether it has cached copies of each baked texture
  463. /// </summary>
  464. public void RequestCachedBakes()
  465. {
  466. List<AgentCachedTexturePacket.WearableDataBlock> hashes = new List<AgentCachedTexturePacket.WearableDataBlock>();
  467. // Build hashes for each of the bake layers from the individual components
  468. lock (Wearables)
  469. {
  470. for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
  471. {
  472. // Don't do a cache request for a skirt bake if we're not wearing a skirt
  473. if (bakedIndex == (int)BakeType.Skirt && !Wearables.ContainsKey(WearableType.Skirt))
  474. continue;
  475. // Build a hash of all the texture asset IDs in this baking layer
  476. UUID hash = UUID.Zero;
  477. for (int wearableIndex = 0; wearableIndex < WEARABLES_PER_LAYER; wearableIndex++)
  478. {
  479. WearableType type = WEARABLE_BAKE_MAP[bakedIndex][wearableIndex];
  480. WearableData wearable;
  481. if (type != WearableType.Invalid && Wearables.TryGetValue(type, out wearable))
  482. hash ^= wearable.AssetID;
  483. }
  484. if (hash != UUID.Zero)
  485. {
  486. // Hash with our secret value for this baked layer
  487. hash ^= BAKED_TEXTURE_HASH[bakedIndex];
  488. // Add this to the list of hashes to send out
  489. AgentCachedTexturePacket.WearableDataBlock block = new AgentCachedTexturePacket.WearableDataBlock();
  490. block.ID = hash;
  491. block.TextureIndex = (byte)bakedIndex;
  492. hashes.Add(block);
  493. Logger.DebugLog("Checking cache for " + (BakeType)block.TextureIndex + ", hash=" + block.ID, Client);
  494. }
  495. }
  496. }
  497. // Only send the packet out if there's something to check
  498. if (hashes.Count > 0)
  499. {
  500. AgentCachedTexturePacket cache = new AgentCachedTexturePacket();
  501. cache.AgentData.AgentID = Client.Self.AgentID;
  502. cache.AgentData.SessionID = Client.Self.SessionID;
  503. cache.AgentData.SerialNum = Interlocked.Increment(ref CacheCheckSerialNum);
  504. cache.WearableData = hashes.ToArray();
  505. Client.Network.SendPacket(cache);
  506. }
  507. }
  508. /// <summary>
  509. /// Returns the AssetID of the asset that is currently being worn in a
  510. /// given WearableType slot
  511. /// </summary>
  512. /// <param name="type">WearableType slot to get the AssetID for</param>
  513. /// <returns>The UUID of the asset being worn in the given slot, or
  514. /// UUID.Zero if no wearable is attached to the given slot or wearables
  515. /// have not been downloaded yet</returns>
  516. public UUID GetWearableAsset(WearableType type)
  517. {
  518. WearableData wearable;
  519. if (Wearables.TryGetValue(type, out wearable))
  520. return wearable.AssetID;
  521. else
  522. return UUID.Zero;
  523. }
  524. /// <summary>
  525. /// Add a wearable to the current outfit and set appearance
  526. /// </summary>
  527. /// <param name="wearableItem">Wearable to be added to the outfit</param>
  528. public void AddToOutfit(InventoryItem wearableItem)
  529. {
  530. List<InventoryItem> wearableItems = new List<InventoryItem> { wearableItem };
  531. AddToOutfit(wearableItems);
  532. }
  533. /// <summary>
  534. /// Add a list of wearables to the current outfit and set appearance
  535. /// </summary>
  536. /// <param name="wearableItems">List of wearable inventory items to
  537. /// be added to the outfit</param>
  538. public void AddToOutfit(List<InventoryItem> wearableItems)
  539. {
  540. List<InventoryWearable> wearables = new List<InventoryWearable>();
  541. List<InventoryItem> attachments = new List<InventoryItem>();
  542. for (int i = 0; i < wearableItems.Count; i++)
  543. {
  544. InventoryItem item = wearableItems[i];
  545. if (item is InventoryWearable)
  546. wearables.Add((InventoryWearable)item);
  547. else if (item is InventoryAttachment || item is InventoryObject)
  548. attachments.Add(item);
  549. }
  550. lock (Wearables)
  551. {
  552. // Add the given wearables to the wearables collection
  553. for (int i = 0; i < wearables.Count; i++)
  554. {
  555. InventoryWearable wearableItem = wearables[i];
  556. WearableData wd = new WearableData();
  557. wd.AssetID = wearableItem.AssetUUID;
  558. wd.AssetType = wearableItem.AssetType;
  559. wd.ItemID = wearableItem.UUID;
  560. wd.WearableType = wearableItem.WearableType;
  561. Wearables[wearableItem.WearableType] = wd;
  562. }
  563. }
  564. if (attachments.Count > 0)
  565. {
  566. AddAttachments(attachments, false, false);
  567. }
  568. if (wearables.Count > 0)
  569. {
  570. SendAgentIsNowWearing();
  571. DelayedRequestSetAppearance();
  572. }
  573. }
  574. /// <summary>
  575. /// Remove a wearable from the current outfit and set appearance
  576. /// </summary>
  577. /// <param name="wearableItem">Wearable to be removed from the outfit</param>
  578. public void RemoveFromOutfit(InventoryItem wearableItem)
  579. {
  580. List<InventoryItem> wearableItems = new List<InventoryItem>();
  581. wearableItems.Add(wearableItem);
  582. RemoveFromOutfit(wearableItems);
  583. }
  584. /// <summary>
  585. /// Removes a list of wearables from the current outfit and set appearance
  586. /// </summary>
  587. /// <param name="wearableItems">List of wearable inventory items to
  588. /// be removed from the outfit</param>
  589. public void RemoveFromOutfit(List<InventoryItem> wearableItems)
  590. {
  591. List<InventoryWearable> wearables = new List<InventoryWearable>();
  592. List<InventoryItem> attachments = new List<InventoryItem>();
  593. for (int i = 0; i < wearableItems.Count; i++)
  594. {
  595. InventoryItem item = wearableItems[i];
  596. if (item is InventoryWearable)
  597. wearables.Add((InventoryWearable)item);
  598. else if (item is InventoryAttachment || item is InventoryObject)
  599. attachments.Add(item);
  600. }
  601. bool needSetAppearance = false;
  602. lock (Wearables)
  603. {
  604. // Remove the given wearables from the wearables collection
  605. for (int i = 0; i < wearables.Count; i++)
  606. {
  607. InventoryWearable wearableItem = wearables[i];
  608. if (wearables[i].AssetType != AssetType.Bodypart // Remove if it's not a body part
  609. && Wearables.ContainsKey(wearableItem.WearableType) // And we have that wearabe type
  610. && Wearables[wearableItem.WearableType].ItemID == wearableItem.UUID // And we are wearing it
  611. )
  612. {
  613. Wearables.Remove(wearableItem.WearableType);
  614. needSetAppearance = true;
  615. }
  616. }
  617. }
  618. for (int i = 0; i < attachments.Count; i++)
  619. {
  620. Detach(attachments[i].UUID);
  621. }
  622. if (needSetAppearance)
  623. {
  624. SendAgentIsNowWearing();
  625. DelayedRequestSetAppearance();
  626. }
  627. }
  628. /// <summary>
  629. /// Replace the current outfit with a list of wearables and set appearance
  630. /// </summary>
  631. /// <param name="wearableItems">List of wearable inventory items that
  632. /// define a new outfit</param>
  633. public void ReplaceOutfit(List<InventoryItem> wearableItems)
  634. {
  635. ReplaceOutfit(wearableItems, true);
  636. }
  637. /// <summary>
  638. /// Replace the current outfit with a list of wearables and set appearance
  639. /// </summary>
  640. /// <param name="wearableItems">List of wearable inventory items that
  641. /// define a new outfit</param>
  642. /// <param name="safe">Check if we have all body parts, set this to false only
  643. /// if you know what you're doing</param>
  644. public void ReplaceOutfit(List<InventoryItem> wearableItems, bool safe)
  645. {
  646. List<InventoryWearable> wearables = new List<InventoryWearable>();
  647. List<InventoryItem> attachments = new List<InventoryItem>();
  648. for (int i = 0; i < wearableItems.Count; i++)
  649. {
  650. InventoryItem item = wearableItems[i];
  651. if (item is InventoryWearable)
  652. wearables.Add((InventoryWearable)item);
  653. else if (item is InventoryAttachment || item is InventoryObject)
  654. attachments.Add(item);
  655. }
  656. if (safe)
  657. {
  658. // If we don't already have a the current agent wearables downloaded, updating to a
  659. // new set of wearables that doesn't have all of the bodyparts can leave the avatar
  660. // in an inconsistent state. If any bodypart entries are empty, we need to fetch the
  661. // current wearables first
  662. bool needsCurrentWearables = false;
  663. lock (Wearables)
  664. {
  665. for (int i = 0; i < WEARABLE_COUNT; i++)
  666. {
  667. WearableType wearableType = (WearableType)i;
  668. if (WearableTypeToAssetType(wearableType) == AssetType.Bodypart && !Wearables.ContainsKey(wearableType))
  669. {
  670. needsCurrentWearables = true;
  671. break;
  672. }
  673. }
  674. }
  675. if (needsCurrentWearables && !GetAgentWearables())
  676. {
  677. Logger.Log("Failed to fetch the current agent wearables, cannot safely replace outfit",
  678. Helpers.LogLevel.Error);
  679. return;
  680. }
  681. }
  682. // Replace our local Wearables collection, send the packet(s) to update our
  683. // attachments, tell sim what we are wearing now, and start the baking process
  684. if (!safe)
  685. {
  686. SetAppearanceSerialNum++;
  687. }
  688. ReplaceOutfit(wearables);
  689. AddAttachments(attachments, true, false);
  690. SendAgentIsNowWearing();
  691. DelayedRequestSetAppearance();
  692. }
  693. /// <summary>
  694. /// Checks if an inventory item is currently being worn
  695. /// </summary>
  696. /// <param name="item">The inventory item to check against the agent
  697. /// wearables</param>
  698. /// <returns>The WearableType slot that the item is being worn in,
  699. /// or WearbleType.Invalid if it is not currently being worn</returns>
  700. public WearableType IsItemWorn(InventoryItem item)
  701. {
  702. lock (Wearables)
  703. {
  704. foreach (KeyValuePair<WearableType, WearableData> entry in Wearables)
  705. {
  706. if (entry.Value.ItemID == item.UUID)
  707. return entry.Key;
  708. }
  709. }
  710. return WearableType.Invalid;
  711. }
  712. /// <summary>
  713. /// Returns a copy of the agents currently worn wearables
  714. /// </summary>
  715. /// <returns>A copy of the agents currently worn wearables</returns>
  716. /// <remarks>Avoid calling this function multiple times as it will make
  717. /// a copy of all of the wearable data each time</remarks>
  718. public Dictionary<WearableType, WearableData> GetWearables()
  719. {
  720. lock (Wearables)
  721. return new Dictionary<WearableType, WearableData>(Wearables);
  722. }
  723. /// <summary>
  724. /// Calls either <seealso cref="ReplaceOutfit"/> or
  725. /// <seealso cref="AddToOutfit"/> depending on the value of
  726. /// replaceItems
  727. /// </summary>
  728. /// <param name="wearables">List of wearable inventory items to add
  729. /// to the outfit or become a new outfit</param>
  730. /// <param name="replaceItems">True to replace existing items with the
  731. /// new list of items, false to add these items to the existing outfit</param>
  732. public void WearOutfit(List<InventoryBase> wearables, bool replaceItems)
  733. {
  734. List<InventoryItem> wearableItems = new List<InventoryItem>(wearables.Count);
  735. for (int i = 0; i < wearables.Count; i++)
  736. {
  737. if (wearables[i] is InventoryItem)
  738. wearableItems.Add((InventoryItem)wearables[i]);
  739. }
  740. if (replaceItems)
  741. ReplaceOutfit(wearableItems);
  742. else
  743. AddToOutfit(wearableItems);
  744. }
  745. #endregion Publics Methods
  746. #region Attachments
  747. /// <summary>
  748. /// Adds a list of attachments to our agent
  749. /// </summary>
  750. /// <param name="attachments">A List containing the attachments to add</param>
  751. /// <param name="removeExistingFirst">If true, tells simulator to remove existing attachment
  752. /// first</param>
  753. public void AddAttachments(List<InventoryItem> attachments, bool removeExistingFirst)
  754. {
  755. AddAttachments(attachments, removeExistingFirst, true);
  756. }
  757. /// <summary>
  758. /// Adds a list of attachments to our agent
  759. /// </summary>
  760. /// <param name="attachments">A List containing the attachments to add</param>
  761. /// <param name="removeExistingFirst">If true, tells simulator to remove existing attachment
  762. /// <param name="replace">If true replace existing attachment on this attachment point, otherwise add to it (multi-attachments)</param>
  763. /// first</param>
  764. public void AddAttachments(List<InventoryItem> attachments, bool removeExistingFirst, bool replace)
  765. {
  766. // Use RezMultipleAttachmentsFromInv to clear out current attachments, and attach new ones
  767. RezMultipleAttachmentsFromInvPacket attachmentsPacket = new RezMultipleAttachmentsFromInvPacket();
  768. attachmentsPacket.AgentData.AgentID = Client.Self.AgentID;
  769. attachmentsPacket.AgentData.SessionID = Client.Self.SessionID;
  770. attachmentsPacket.HeaderData.CompoundMsgID = UUID.Random();
  771. attachmentsPacket.HeaderData.FirstDetachAll = removeExistingFirst;
  772. attachmentsPacket.HeaderData.TotalObjects = (byte)attachments.Count;
  773. attachmentsPacket.ObjectData = new RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[attachments.Count];
  774. for (int i = 0; i < attachments.Count; i++)
  775. {
  776. if (attachments[i] is InventoryAttachment)
  777. {
  778. InventoryAttachment attachment = (InventoryAttachment)attachments[i];
  779. attachmentsPacket.ObjectData[i] = new RezMultipleAttachmentsFromInvPacket.ObjectDataBlock();
  780. attachmentsPacket.ObjectData[i].AttachmentPt = replace ? (byte)attachment.AttachmentPoint : (byte)(ATTACHMENT_ADD | (byte)attachment.AttachmentPoint);
  781. attachmentsPacket.ObjectData[i].EveryoneMask = (uint)attachment.Permissions.EveryoneMask;
  782. attachmentsPacket.ObjectData[i].GroupMask = (uint)attachment.Permissions.GroupMask;
  783. attachmentsPacket.ObjectData[i].ItemFlags = (uint)attachment.Flags;
  784. attachmentsPacket.ObjectData[i].ItemID = attachment.UUID;
  785. attachmentsPacket.ObjectData[i].Name = Utils.StringToBytes(attachment.Name);
  786. attachmentsPacket.ObjectData[i].Description = Utils.StringToBytes(attachment.Description);
  787. attachmentsPacket.ObjectData[i].NextOwnerMask = (uint)attachment.Permissions.NextOwnerMask;
  788. attachmentsPacket.ObjectData[i].OwnerID = attachment.OwnerID;
  789. }
  790. else if (attachments[i] is InventoryObject)
  791. {
  792. InventoryObject attachment = (InventoryObject)attachments[i];
  793. attachmentsPacket.ObjectData[i] = new RezMultipleAttachmentsFromInvPacket.ObjectDataBlock();
  794. attachmentsPacket.ObjectData[i].AttachmentPt = replace ? (byte)0 : ATTACHMENT_ADD;
  795. attachmentsPacket.ObjectData[i].EveryoneMask = (uint)attachment.Permissions.EveryoneMask;
  796. attachmentsPacket.ObjectData[i].GroupMask = (uint)attachment.Permissions.GroupMask;
  797. attachmentsPacket.ObjectData[i].ItemFlags = (uint)attachment.Flags;
  798. attachmentsPacket.ObjectData[i].ItemID = attachment.UUID;
  799. attachmentsPacket.ObjectData[i].Name = Utils.StringToBytes(attachment.Name);
  800. attachmentsPacket.ObjectData[i].Description = Utils.StringToBytes(attachment.Description);
  801. attachmentsPacket.ObjectData[i].NextOwnerMask = (uint)attachment.Permissions.NextOwnerMask;
  802. attachmentsPacket.ObjectData[i].OwnerID = attachment.OwnerID;
  803. }
  804. else
  805. {
  806. Logger.Log("Cannot attach inventory item " + attachments[i].Name, Helpers.LogLevel.Warning, Client);
  807. }
  808. }
  809. Client.Network.SendPacket(attachmentsPacket);
  810. }
  811. /// <summary>
  812. /// Attach an item to our agent at a specific attach point
  813. /// </summary>
  814. /// <param name="item">A <seealso cref="OpenMetaverse.InventoryItem"/> to attach</param>
  815. /// <param name="attachPoint">the <seealso cref="OpenMetaverse.AttachmentPoint"/> on the avatar
  816. /// to attach the item to</param>
  817. public void Attach(InventoryItem item, AttachmentPoint attachPoint)
  818. {
  819. Attach(item, attachPoint, true);
  820. }
  821. /// <summary>
  822. /// Attach an item to our agent at a specific attach point
  823. /// </summary>
  824. /// <param name="item">A <seealso cref="OpenMetaverse.InventoryItem"/> to attach</param>
  825. /// <param name="attachPoint">the <seealso cref="OpenMetaverse.AttachmentPoint"/> on the avatar
  826. /// <param name="replace">If true replace existing attachment on this attachment point, otherwise add to it (multi-attachments)</param>
  827. /// to attach the item to</param>
  828. public void Attach(InventoryItem item, AttachmentPoint attachPoint, bool replace)
  829. {
  830. Attach(item.UUID, item.OwnerID, item.Name, item.Description, item.Permissions, item.Flags,
  831. attachPoint, replace);
  832. }
  833. /// <summary>
  834. /// Attach an item to our agent specifying attachment details
  835. /// </summary>
  836. /// <param name="itemID">The <seealso cref="OpenMetaverse.UUID"/> of the item to attach</param>
  837. /// <param name="ownerID">The <seealso cref="OpenMetaverse.UUID"/> attachments owner</param>
  838. /// <param name="name">The name of the attachment</param>
  839. /// <param name="description">The description of the attahment</param>
  840. /// <param name="perms">The <seealso cref="OpenMetaverse.Permissions"/> to apply when attached</param>
  841. /// <param name="itemFlags">The <seealso cref="OpenMetaverse.InventoryItemFlags"/> of the attachment</param>
  842. /// <param name="attachPoint">The <seealso cref="OpenMetaverse.AttachmentPoint"/> on the agent
  843. /// to attach the item to</param>
  844. public void Attach(UUID itemID, UUID ownerID, string name, string description,
  845. Permissions perms, uint itemFlags, AttachmentPoint attachPoint)
  846. {
  847. Attach(itemID, ownerID, name, description, perms, itemFlags, attachPoint, true);
  848. }
  849. /// <summary>
  850. /// Attach an item to our agent specifying attachment details
  851. /// </summary>
  852. /// <param name="itemID">The <seealso cref="OpenMetaverse.UUID"/> of the item to attach</param>
  853. /// <param name="ownerID">The <seealso cref="OpenMetaverse.UUID"/> attachments owner</param>
  854. /// <param name="name">The name of the attachment</param>
  855. /// <param name="description">The description of the attahment</param>
  856. /// <param name="perms">The <seealso cref="OpenMetaverse.Permissions"/> to apply when attached</param>
  857. /// <param name="itemFlags">The <seealso cref="OpenMetaverse.InventoryItemFlags"/> of the attachment</param>
  858. /// <param name="attachPoint">The <seealso cref="OpenMetaverse.AttachmentPoint"/> on the agent
  859. /// <param name="replace">If true replace existing attachment on this attachment point, otherwise add to it (multi-attachments)</param>
  860. /// to attach the item to</param>
  861. public void Attach(UUID itemID, UUID ownerID, string name, string description,
  862. Permissions perms, uint itemFlags, AttachmentPoint attachPoint, bool replace)
  863. {
  864. // TODO: At some point it might be beneficial to have AppearanceManager track what we
  865. // are currently wearing for attachments to make enumeration and detachment easier
  866. RezSingleAttachmentFromInvPacket attach = new RezSingleAttachmentFromInvPacket();
  867. attach.AgentData.AgentID = Client.Self.AgentID;
  868. attach.AgentData.SessionID = Client.Self.SessionID;
  869. attach.ObjectData.AttachmentPt = replace ? (byte)attachPoint : (byte)(ATTACHMENT_ADD | (byte)attachPoint);
  870. attach.ObjectData.Description = Utils.StringToBytes(description);
  871. attach.ObjectData.EveryoneMask = (uint)perms.EveryoneMask;
  872. attach.ObjectData.GroupMask = (uint)perms.GroupMask;
  873. attach.ObjectData.ItemFlags = itemFlags;
  874. attach.ObjectData.ItemID = itemID;
  875. attach.ObjectData.Name = Utils.StringToBytes(name);
  876. attach.ObjectData.NextOwnerMask = (uint)perms.NextOwnerMask;
  877. attach.ObjectData.OwnerID = ownerID;
  878. Client.Network.SendPacket(attach);
  879. }
  880. /// <summary>
  881. /// Detach an item from our agent using an <seealso cref="OpenMetaverse.InventoryItem"/> object
  882. /// </summary>
  883. /// <param name="item">An <seealso cref="OpenMetaverse.InventoryItem"/> object</param>
  884. public void Detach(InventoryItem item)
  885. {
  886. Detach(item.UUID);
  887. }
  888. /// <summary>
  889. /// Detach an item from our agent
  890. /// </summary>
  891. /// <param name="itemID">The inventory itemID of the item to detach</param>
  892. public void Detach(UUID itemID)
  893. {
  894. DetachAttachmentIntoInvPacket detach = new DetachAttachmentIntoInvPacket();
  895. detach.ObjectData.AgentID = Client.Self.AgentID;
  896. detach.ObjectData.ItemID = itemID;
  897. Client.Network.SendPacket(detach);
  898. }
  899. #endregion Attachments
  900. #region Appearance Helpers
  901. /// <summary>
  902. /// Inform the sim which wearables are part of our current outfit
  903. /// </summary>
  904. private void SendAgentIsNowWearing()
  905. {
  906. AgentIsNowWearingPacket wearing = new AgentIsNowWearingPacket();
  907. wearing.AgentData.AgentID = Client.Self.AgentID;
  908. wearing.AgentData.SessionID = Client.Self.SessionID;
  909. wearing.WearableData = new AgentIsNowWearingPacket.WearableDataBlock[WEARABLE_COUNT];
  910. lock (Wearables)
  911. {
  912. for (int i = 0; i < WEARABLE_COUNT; i++)
  913. {
  914. WearableType type = (WearableType)i;
  915. wearing.WearableData[i] = new AgentIsNowWearingPacket.WearableDataBlock();
  916. wearing.WearableData[i].WearableType = (byte)i;
  917. if (Wearables.ContainsKey(type))
  918. wearing.WearableData[i].ItemID = Wearables[type].ItemID;
  919. else
  920. wearing.WearableData[i].ItemID = UUID.Zero;
  921. }
  922. }
  923. Client.Network.SendPacket(wearing);
  924. }
  925. /// <summary>
  926. /// Replaces the Wearables collection with a list of new wearable items
  927. /// </summary>
  928. /// <param name="wearableItems">Wearable items to replace the Wearables collection with</param>
  929. private void ReplaceOutfit(List<InventoryWearable> wearableItems)
  930. {
  931. Dictionary<WearableType, WearableData> newWearables = new Dictionary<WearableType, WearableData>();
  932. lock (Wearables)
  933. {
  934. // Preserve body parts from the previous set of wearables. They may be overwritten,
  935. // but cannot be missing in the new set
  936. foreach (KeyValuePair<WearableType, WearableData> entry in Wearables)
  937. {
  938. if (entry.Value.AssetType == AssetType.Bodypart)
  939. newWearables[entry.Key] = entry.Value;
  940. }
  941. // Add the given wearables to the new wearables collection
  942. for (int i = 0; i < wearableItems.Count; i++)
  943. {
  944. InventoryWearable wearableItem = wearableItems[i];
  945. WearableData wd = new WearableData();
  946. wd.AssetID = wearableItem.AssetUUID;
  947. wd.AssetType = wearableItem.AssetType;
  948. wd.ItemID = wearableItem.UUID;
  949. wd.WearableType = wearableItem.WearableType;
  950. newWearables[wearableItem.WearableType] = wd;
  951. }
  952. // Replace the Wearables collection
  953. Wearables = newWearables;
  954. }
  955. }
  956. /// <summary>
  957. /// Calculates base color/tint for a specific wearable
  958. /// based on its params
  959. /// </summary>
  960. /// <param name="param">All the color info gathered from wearable's VisualParams
  961. /// passed as list of ColorParamInfo tuples</param>
  962. /// <returns>Base color/tint for the wearable</returns>
  963. private Color4 GetColorFromParams(List<ColorParamInfo> param)
  964. {
  965. // Start off with a blank slate, black, fully transparent
  966. Color4 res = new Color4(0, 0, 0, 0);
  967. // Apply color modification from each color parameter
  968. foreach (ColorParamInfo p in param)
  969. {
  970. int n = p.VisualColorParam.Colors.Length;
  971. Color4 paramColor = new Color4(0, 0, 0, 0);
  972. if (n == 1)
  973. {
  974. // We got only one color in this param, use it for application
  975. // to the final color
  976. paramColor = p.VisualColorParam.Colors[0];
  977. }
  978. else if (n > 1)
  979. {
  980. // We have an array of colors in this parameter
  981. // First, we need to find out, based on param value
  982. // between which two elements of the array our value lands
  983. // Size of the step using which we iterate from Min to Max
  984. float step = (p.VisualParam.MaxValue - p.VisualParam.MinValue) / ((float)n - 1);
  985. // Our color should land inbetween colors in the array with index a and b
  986. int indexa = 0;
  987. int indexb = 0;
  988. int i = 0;
  989. for (float a = p.VisualParam.MinValue; a <= p.VisualParam.MaxValue; a += step)
  990. {
  991. if (a <= p.Value)
  992. {
  993. indexa = i;
  994. }
  995. else
  996. {
  997. break;
  998. }
  999. i++;
  1000. }
  1001. // Sanity check that we don't go outside bounds of the array
  1002. if (indexa > n - 1)
  1003. indexa = n - 1;
  1004. indexb = (indexa == n - 1) ? indexa : indexa + 1;
  1005. // How far is our value from Index A on the
  1006. // line from Index A to Index B
  1007. float distance = p.Value - (float)indexa * step;
  1008. // We are at Index A (allowing for some floating point math fuzz),
  1009. // use the color on that index
  1010. if (distance < 0.00001f || indexa == indexb)
  1011. {
  1012. paramColor = p.VisualColorParam.Colors[indexa];
  1013. }
  1014. else
  1015. {
  1016. // Not so simple as being precisely on the index eh? No problem.
  1017. // We take the two colors that our param value places us between
  1018. // and then find the value for each ARGB element that is
  1019. // somewhere on the line between color1 and color2 at some
  1020. // distance from the first color
  1021. Color4 c1 = paramColor = p.VisualColorParam.Colors[indexa];
  1022. Color4 c2 = paramColor = p.VisualColorParam.Colors[indexb];
  1023. // Distance is some fraction of the step, use that fraction
  1024. // to find the value in the range from color1 to color2
  1025. paramColor = Color4.Lerp(c1, c2, distance / step);
  1026. }
  1027. // Please leave this fragment even if its commented out
  1028. // might prove useful should ($deity forbid) there be bugs in this code
  1029. //string carray = "";
  1030. //foreach (Color c in p.VisualColorParam.Colors)
  1031. //{
  1032. // carray += c.ToString() + " - ";
  1033. //}
  1034. //Logger.DebugLog("Calculating color for " + p.WearableType + " from " + p.VisualParam.Name + ", value is " + p.Value + " in range " + p.VisualParam.MinValue + " - " + p.VisualParam.MaxValue + " step " + step + " with " + n + " elements " + carray + " A: " + indexa + " B: " + indexb + " at distance " + distance);
  1035. }
  1036. // Now that we have calculated color from the scale of colors
  1037. // that visual params provided, lets apply it to the result
  1038. switch (p.VisualColorParam.Operation)
  1039. {
  1040. case VisualColorOperation.Add:
  1041. res += paramColor;
  1042. break;
  1043. case VisualColorOperation.Multiply:
  1044. res *= paramColor;
  1045. break;
  1046. case VisualColorOperation.Blend:
  1047. res = Color4.Lerp(res, paramColor, p.Value);
  1048. break;
  1049. }
  1050. }
  1051. return res;
  1052. }
  1053. /// <summary>
  1054. /// Blocking method to populate the Wearables dictionary
  1055. /// </summary>
  1056. /// <returns>True on success, otherwise false</returns>
  1057. bool GetAgentWearables()
  1058. {
  1059. AutoResetEvent wearablesEvent = new AutoResetEvent(false);
  1060. EventHandler<AgentWearablesReplyEventArgs> wearablesCallback = ((s, e) => wearablesEvent.Set());
  1061. AgentWearablesReply += wearablesCallback;
  1062. RequestAgentWearables();
  1063. bool success = wearablesEvent.WaitOne(WEARABLE_TIMEOUT, false);
  1064. AgentWearablesReply -= wearablesCallback;
  1065. return success;
  1066. }
  1067. /// <summary>
  1068. /// Blocking method to populate the Textures array with cached bakes
  1069. /// </summary>
  1070. /// <returns>True on success, otherwise false</returns>
  1071. bool GetCachedBakes()
  1072. {
  1073. AutoResetEvent cacheCheckEvent = new AutoResetEvent(false);
  1074. EventHandler<AgentCachedBakesReplyEventArgs> cacheCallback = (sender, e) => cacheCheckEvent.Set();
  1075. CachedBakesReply += cacheCallback;
  1076. RequestCachedBakes();
  1077. bool success = cacheCheckEvent.WaitOne(WEARABLE_TIMEOUT, false);
  1078. CachedBakesReply -= cacheCallback;
  1079. return success;
  1080. }
  1081. /// <summary>
  1082. /// Populates textures and visual params from a decoded asset
  1083. /// </summary>
  1084. /// <param name="wearable">Wearable to decode</param>
  1085. private void DecodeWearableParams(WearableData wearable)
  1086. {
  1087. Dictionary<VisualAlphaParam, float> alphaMasks = new Dictionary<VisualAlphaParam, float>();
  1088. List<ColorParamInfo> colorParams = new List<ColorParamInfo>();
  1089. // Populate collection of alpha masks from visual params
  1090. // also add color tinting information
  1091. foreach (KeyValuePair<int, float> kvp in wearable.Asset.Params)
  1092. {
  1093. if (!VisualParams.Params.ContainsKey(kvp.Key)) continue;
  1094. VisualParam p = VisualParams.Params[kvp.Key];
  1095. ColorParamInfo colorInfo = new ColorParamInfo();
  1096. colorInfo.WearableType = wearable.WearableType;
  1097. colorInfo.VisualParam = p;
  1098. colorInfo.Value = kvp.Value;
  1099. // Color params
  1100. if (p.ColorParams.HasValue)
  1101. {
  1102. colorInfo.VisualColorParam = p.ColorParams.Value;
  1103. // If this is not skin, just add params directly
  1104. if (wearable.WearableType != WearableType.Skin)
  1105. {
  1106. colorParams.Add(colorInfo);
  1107. }
  1108. else
  1109. {
  1110. // For skin we skip makeup params for now and use only the 3
  1111. // that are used to determine base skin tone
  1112. // Param 108 - Rainbow Color
  1113. // Param 110 - Red Skin (Ruddiness)
  1114. // Param 111 - Pigment
  1115. if (kvp.Key == 108 || kvp.Key == 110 || kvp.Key == 111)
  1116. {
  1117. colorParams.Add(colorInfo);
  1118. }
  1119. }
  1120. }
  1121. // Add alpha mask
  1122. if (p.AlphaParams.HasValue && p.AlphaParams.Value.TGAFile != string.Empty && !p.IsBumpAttribute && !alphaMasks.ContainsKey(p.AlphaParams.Value))
  1123. {
  1124. alphaMasks.Add(p.AlphaParams.Value, kvp.Value);
  1125. }
  1126. // Alhpa masks can also be specified in sub "driver" params
  1127. if (p.Drivers != null)
  1128. {
  1129. for (int i = 0; i < p.Drivers.Length; i++)
  1130. {
  1131. if (VisualParams.Params.ContainsKey(p.Drivers[i]))
  1132. {
  1133. VisualParam driver = VisualParams.Params[p.Drivers[i]];
  1134. if (driver.AlphaParams.HasValue && driver.AlphaParams.Value.TGAFile != string.Empty && !driver.IsBumpAttribute && !alphaMasks.ContainsKey(driver.AlphaParams.Value))
  1135. {
  1136. alphaMasks.Add(driver.AlphaParams.Value, kvp.Value);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. Color4 wearableColor = Color4.White; // Never actually used
  1143. if (colorParams.Count > 0)
  1144. {
  1145. wearableColor = GetColorFromParams(colorParams);
  1146. Logger.DebugLog("Setting tint " + wearableColor + " for " + wearable.WearableType);
  1147. }
  1148. // Loop through all of the texture IDs in this decoded asset and put them in our cache of worn textures
  1149. foreach (KeyValuePair<AvatarTextureIndex, UUID> entry in wearable.Asset.Textures)
  1150. {
  1151. int i = (int)entry.Key;
  1152. // Update information about color and alpha masks for this texture
  1153. Textures[i].AlphaMasks = alphaMasks;
  1154. Textures[i].Color = wearableColor;
  1155. // If this texture changed, update the TextureID and clear out the old cached texture asset
  1156. if (Textures[i].TextureID != entry.Value)
  1157. {
  1158. // Treat DEFAULT_AVATAR_TEXTURE as null
  1159. if (entry.Value != DEFAULT_AVATAR_TEXTURE)
  1160. Textures[i].TextureID = entry.Value;
  1161. else
  1162. Textures[i].TextureID = UUID.Zero;
  1163. Logger.DebugLog("Set " + entry.Key + " to " + Textures[i].TextureID, Client);
  1164. Textures[i].Texture = null;
  1165. }
  1166. }
  1167. }
  1168. /// <summary>
  1169. /// Blocking method to download and parse currently worn wearable assets
  1170. /// </summary>
  1171. /// <returns>True on success, otherwise false</returns>
  1172. private bool DownloadWearables()
  1173. {
  1174. bool success = true;
  1175. // Make a copy of the wearables dictionary to enumerate over
  1176. Dictionary<WearableType, WearableData> wearables;
  1177. lock (Wearables)
  1178. wearables = new Dictionary<WearableType, WearableData>(Wearables);
  1179. // We will refresh the textures (zero out all non bake textures)
  1180. for (int i = 0; i < Textures.Length; i++)
  1181. {
  1182. bool isBake = false;
  1183. for (int j = 0; j < BakeIndexToTextureIndex.Length; j++)
  1184. {
  1185. if (BakeIndexToTextureIndex[j] == i)
  1186. {
  1187. isBake = true;
  1188. break;
  1189. }
  1190. }
  1191. if (!isBake)
  1192. Textures[i] = new TextureData();
  1193. }
  1194. int pendingWearables = wearables.Count;
  1195. foreach (WearableData wearable in wearables.Values)
  1196. {
  1197. if (wearable.Asset != null)
  1198. {
  1199. DecodeWearableParams(wearable);
  1200. --pendingWearables;
  1201. }
  1202. }
  1203. if (pendingWearables == 0)
  1204. return true;
  1205. Logger.DebugLog("Downloading " + pendingWearables + " wearable assets");
  1206. Parallel.ForEach<WearableData>(Math.Min(pendingWearables, MAX_CONCURRENT_DOWNLOADS), wearables.Values,
  1207. delegate(WearableData wearable)
  1208. {
  1209. if (wearable.Asset == null)
  1210. {
  1211. AutoResetEvent downloadEvent = new AutoResetEvent(false);
  1212. // Fetch this wearable asset
  1213. Client.Assets.RequestAsset(wearable.AssetID, wearable.AssetType, true,
  1214. delegate(AssetDownload transfer, Asset asset)
  1215. {
  1216. if (transfer.Success && asset is AssetWearable)
  1217. {
  1218. // Update this wearable with the freshly downloaded asset
  1219. wearable.Asset = (AssetWearable)asset;
  1220. if (wearable.Asset.Decode())
  1221. {
  1222. DecodeWearableParams(wearable);
  1223. Logger.DebugLog("Downloaded wearable asset " + wearable.WearableType + " with " + wearable.Asset.Params.Count +
  1224. " visual params and " + wearable.Asset.Textures.Count + " textures", Client);
  1225. }
  1226. else
  1227. {
  1228. wearable.Asset = null;
  1229. Logger.Log("Failed to decode asset:" + Environment.NewLine +
  1230. Utils.BytesToString(asset.AssetData), Helpers.LogLevel.Error, Client);
  1231. }
  1232. }
  1233. else
  1234. {
  1235. Logger.Log("Wearable " + wearable.AssetID + "(" + wearable.WearableType + ") failed to download, " +
  1236. transfer.Status, Helpers.LogLevel.Warning, Client);
  1237. }
  1238. downloadEvent.Set();
  1239. }
  1240. );
  1241. if (!downloadEvent.WaitOne(WEARABLE_TIMEOUT, false))
  1242. {
  1243. Logger.Log("Timed out downloading wearable asset " + wearable.AssetID + " (" + wearable.WearableType + ")",
  1244. Helpers.LogLevel.Error, Client);
  1245. success = false;
  1246. }
  1247. --pendingWearables;
  1248. }
  1249. }
  1250. );
  1251. return success;
  1252. }
  1253. /// <summary>
  1254. /// Get a list of all of the textures that need to be downloaded for a
  1255. /// single bake layer
  1256. /// </summary>
  1257. /// <param name="bakeType">Bake layer to get texture AssetIDs for</param>
  1258. /// <returns>A list of texture AssetIDs to download</returns>
  1259. private List<UUID> GetTextureDownloadList(BakeType bakeType)
  1260. {
  1261. List<AvatarTextureIndex> indices = BakeTypeToTextures(bakeType);
  1262. List<UUID> textures = new List<UUID>();
  1263. for (int i = 0; i < indices.Count; i++)
  1264. {
  1265. AvatarTextureIndex index = indices[i];
  1266. if (index == AvatarTextureIndex.Skirt && !Wearables.ContainsKey(WearableType.Skirt))
  1267. continue;
  1268. AddTextureDownload(index, textures);
  1269. }
  1270. return textures;
  1271. }
  1272. /// <summary>
  1273. /// Helper method to lookup the TextureID for a single layer and add it
  1274. /// to a list if it is not already present
  1275. /// </summary>
  1276. /// <param name="index"></param>
  1277. /// <param name="textures"></param>
  1278. private void AddTextureDownload(AvatarTextureIndex index, List<UUID> textures)
  1279. {
  1280. TextureData textureData = Textures[(int)index];
  1281. // Add the textureID to the list if this layer has a valid textureID set, it has not already
  1282. // been downloaded, and it is not already in the download list
  1283. if (textureData.TextureID != UUID.Zero && textureData.Texture == null && !textures.Contains(textureData.TextureID))
  1284. textures.Add(textureData.TextureID);
  1285. }
  1286. /// <summary>
  1287. /// Blocking method to download all of the textures needed for baking
  1288. /// the given bake layers
  1289. /// </summary>
  1290. /// <param name="bakeLayers">A list of layers that need baking</param>
  1291. /// <remarks>No return value is given because the baking will happen
  1292. /// whether or not all textures are successfully downloaded</remarks>
  1293. private void DownloadTextures(List<BakeType> bakeLayers)
  1294. {
  1295. List<UUID> textureIDs = new List<UUID>();
  1296. for (int i = 0; i < bakeLayers.Count; i++)
  1297. {
  1298. List<UUID> layerTextureIDs = GetTextureDownloadList(bakeLayers[i]);
  1299. for (int j = 0; j < layerTextureIDs.Count; j++)
  1300. {
  1301. UUID uuid = layerTextureIDs[j];
  1302. if (!textureIDs.Contains(uuid))
  1303. textureIDs.Add(uuid);
  1304. }
  1305. }
  1306. Logger.DebugLog("Downloading " + textureIDs.Count + " textures for baking");
  1307. Parallel.ForEach<UUID>(MAX_CONCURRENT_DOWNLOADS, textureIDs,
  1308. delegate(UUID textureID)
  1309. {
  1310. AutoResetEvent downloadEvent = new AutoResetEvent(false);
  1311. Client.Assets.RequestImage(textureID,
  1312. delegate(TextureRequestState state, AssetTexture assetTexture)
  1313. {
  1314. if (state == TextureRequestState.Finished)
  1315. {
  1316. assetTexture.Decode();
  1317. for (int i = 0; i < Textures.Length; i++)
  1318. {
  1319. if (Textures[i].TextureID == textureID)
  1320. Textures[i].Texture = assetTexture;
  1321. }
  1322. }
  1323. else
  1324. {
  1325. Logger.Log("Texture " + textureID + " failed to download, one or more bakes will be incomplete",
  1326. Helpers.LogLevel.Warning);
  1327. }
  1328. downloadEvent.Set();
  1329. }
  1330. );
  1331. downloadEvent.WaitOne(TEXTURE_TIMEOUT, false);
  1332. }
  1333. );
  1334. }
  1335. /// <summary>
  1336. /// Blocking method to create and upload baked textures for all of the
  1337. /// missing bakes
  1338. /// </summary>
  1339. /// <returns>True on success, otherwise false</returns>
  1340. private bool CreateBakes()
  1341. {
  1342. bool success = true;
  1343. List<BakeType> pendingBakes = new List<BakeType>();
  1344. // Check each bake layer in the Textures array for missing bakes
  1345. for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
  1346. {
  1347. AvatarTextureIndex textureIndex = BakeTypeToAgentTextureIndex((BakeType)bakedIndex);
  1348. if (Textures[(int)textureIndex].TextureID == UUID.Zero)
  1349. {
  1350. // If this is the skirt layer and we're not wearing a skirt then skip it
  1351. if (bakedIndex == (int)BakeType.Skirt && !Wearables.ContainsKey(WearableType.Skirt))
  1352. continue;
  1353. pendingBakes.Add((BakeType)bakedIndex);
  1354. }
  1355. }
  1356. if (pendingBakes.Count > 0)
  1357. {
  1358. DownloadTextures(pendingBakes);
  1359. Parallel.ForEach<BakeType>(Math.Min(MAX_CONCURRENT_UPLOADS, pendingBakes.Count), pendingBakes,
  1360. delegate(BakeType bakeType)
  1361. {
  1362. if (!CreateBake(bakeType))
  1363. success = false;
  1364. }
  1365. );
  1366. }
  1367. // Free up all the textures we're holding on to
  1368. for (int i = 0; i < Textures.Length; i++)
  1369. {
  1370. Textures[i].Texture = null;
  1371. }
  1372. // We just allocated and freed a ridiculous amount of memory while
  1373. // baking. Signal to the GC to clean up
  1374. GC.Collect();
  1375. return success;
  1376. }
  1377. /// <summary>
  1378. /// Blocking method to create and upload a baked texture for a single
  1379. /// bake layer
  1380. /// </summary>
  1381. /// <param name="bakeType">Layer to bake</param>
  1382. /// <returns>True on success, otherwise false</returns>
  1383. private bool CreateBake(BakeType bakeType)
  1384. {
  1385. List<AvatarTextureIndex> textureIndices = BakeTypeToTextures(bakeType);
  1386. Baker oven = new Baker(bakeType);
  1387. for (int i = 0; i < textureIndices.Count; i++)
  1388. {
  1389. AvatarTextureIndex textureIndex = textureIndices[i];
  1390. TextureData texture = Textures[(int)textureIndex];
  1391. texture.TextureIndex = textureIndex;
  1392. oven.AddTexture(texture);
  1393. }
  1394. int start = Environment.TickCount;
  1395. oven.Bake();
  1396. Logger.DebugLog("Baking " + bakeType + " took " + (Environment.TickCount - start) + "ms");
  1397. UUID newAssetID = UUID.Zero;
  1398. int retries = UPLOAD_RETRIES;
  1399. while (newAssetID == UUID.Zero && retries > 0)
  1400. {
  1401. newAssetID = UploadBake(oven.BakedTexture.AssetData);
  1402. --retries;
  1403. }
  1404. Textures[(int)BakeTypeToAgentTextureIndex(bakeType)].TextureID = newAssetID;
  1405. if (newAssetID == UUID.Zero)
  1406. {
  1407. Logger.Log("Failed uploading bake " + bakeType, Helpers.LogLevel.Warning);
  1408. return false;
  1409. }
  1410. return true;
  1411. }
  1412. /// <summary>
  1413. /// Blocking method to upload a baked texture
  1414. /// </summary>
  1415. /// <param name="textureData">Five channel JPEG2000 texture data to upload</param>
  1416. /// <returns>UUID of the newly created asset on success, otherwise UUID.Zero</returns>
  1417. private UUID UploadBake(byte[] textureData)
  1418. {
  1419. UUID bakeID = UUID.Zero;
  1420. AutoResetEvent uploadEvent = new AutoResetEvent(false);
  1421. Client.Assets.RequestUploadBakedTexture(textureData,
  1422. delegate(UUID newAssetID)
  1423. {
  1424. bakeID = newAssetID;
  1425. uploadEvent.Set();
  1426. }
  1427. );
  1428. // FIXME: evalute the need for timeout here, RequestUploadBakedTexture() will
  1429. // timout either on Client.Settings.TRANSFER_TIMEOUT or Client.Settings.CAPS_TIMEOUT
  1430. // depending on which upload method is used.
  1431. uploadEvent.WaitOne(UPLOAD_TIMEOUT, false);
  1432. return bakeID;
  1433. }
  1434. /// <summary>
  1435. /// Creates a dictionary of visual param values from the downloaded wearables
  1436. /// </summary>
  1437. /// <returns>A dictionary of visual param indices mapping to visual param
  1438. /// values for our agent that can be fed to the Baker class</returns>
  1439. private Dictionary<int, float> MakeParamValues()
  1440. {
  1441. Dictionary<int, float> paramValues = new Dictionary<int, float>(VisualParams.Params.Count);
  1442. lock (Wearables)
  1443. {
  1444. foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params)
  1445. {
  1446. // Only Group-0 parameters are sent in AgentSetAppearance packets
  1447. if (kvp.Value.Group == 0)
  1448. {
  1449. bool found = false;
  1450. VisualParam vp = kvp.Value;
  1451. // Try and find this value in our collection of downloaded wearables
  1452. foreach (WearableData data in Wearables.Values)
  1453. {
  1454. float paramValue;
  1455. if (data.Asset != null && data.Asset.Params.TryGetValue(vp.ParamID, out paramValue))
  1456. {
  1457. paramValues.Add(vp.ParamID, paramValue);
  1458. found = true;
  1459. break;
  1460. }
  1461. }
  1462. // Use a default value if we don't have one set for it
  1463. if (!found) paramValues.Add(vp.ParamID, vp.DefaultValue);
  1464. }
  1465. }
  1466. }
  1467. return paramValues;
  1468. }
  1469. /// <summary>
  1470. /// Create an AgentSetAppearance packet from Wearables data and the
  1471. /// Textures array and send it
  1472. /// </summary>
  1473. private void RequestAgentSetAppearance()
  1474. {
  1475. AgentSetAppearancePacket set = MakeAppearancePacket();
  1476. Client.Network.SendPacket(set);
  1477. Logger.DebugLog("Send AgentSetAppearance packet");
  1478. }
  1479. public AgentSetAppearancePacket MakeAppearancePacket()
  1480. {
  1481. AgentSetAppearancePacket set = new AgentSetAppearancePacket();
  1482. set.AgentData.AgentID = Client.Self.AgentID;
  1483. set.AgentData.SessionID = Client.Self.SessionID;
  1484. set.AgentData.SerialNum = (uint)Interlocked.Increment(ref SetAppearanceSerialNum);
  1485. // Visual params used in the agent height calculation
  1486. float agentSizeVPHeight = 0.0f;
  1487. float agentSizeVPHeelHeight = 0.0f;
  1488. float agentSizeVPPlatformHeight = 0.0f;
  1489. float agentSizeVPHeadSize = 0.5f;
  1490. float agentSizeVPLegLength = 0.0f;
  1491. float agentSizeVPNeckLength = 0.0f;
  1492. float agentSizeVPHipLength = 0.0f;
  1493. lock (Wearables)
  1494. {
  1495. #region VisualParam
  1496. int vpIndex = 0;
  1497. int nrParams;
  1498. bool wearingPhysics = false;
  1499. foreach (WearableData wearable in Wearables.Values)
  1500. {
  1501. if (wearable.WearableType == WearableType.Physics)
  1502. {
  1503. wearingPhysics = true;
  1504. break;
  1505. }
  1506. }
  1507. if (wearingPhysics)
  1508. {
  1509. nrParams = 251;
  1510. }
  1511. else
  1512. {
  1513. nrParams = 218;
  1514. }
  1515. set.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[nrParams];
  1516. foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params)
  1517. {
  1518. VisualParam vp = kvp.Value;
  1519. float paramValue = 0f;
  1520. bool found = false;
  1521. // Try and find this value in our collection of downloaded wearables
  1522. foreach (WearableData data in Wearables.Values)
  1523. {
  1524. if (data.Asset != null && data.Asset.Params.TryGetValue(vp.ParamID, out paramValue))
  1525. {
  1526. found = true;
  1527. break;
  1528. }
  1529. }
  1530. // Use a default value if we don't have one set for it
  1531. if (!found)
  1532. paramValue = vp.DefaultValue;
  1533. // Only Group-0 parameters are sent in AgentSetAppearance packets
  1534. if (kvp.Value.Group == 0)
  1535. {
  1536. set.VisualParam[vpIndex] = new AgentSetAppearancePacket.VisualParamBlock();
  1537. set.VisualParam[vpIndex].ParamValue = Utils.FloatToByte(paramValue, vp.MinValue, vp.MaxValue);
  1538. ++vpIndex;
  1539. }
  1540. // Check if this is one of the visual params used in the agent height calculation
  1541. switch (vp.ParamID)
  1542. {
  1543. case 33:
  1544. agentSizeVPHeight = paramValue;
  1545. break;
  1546. case 198:
  1547. agentSizeVPHeelHeight = paramValue;
  1548. break;
  1549. case 503:
  1550. agentSizeVPPlatformHeight = paramValue;
  1551. break;
  1552. case 682:
  1553. agentSizeVPHeadSize = paramValue;
  1554. break;
  1555. case 692:
  1556. agentSizeVPLegLength = paramValue;
  1557. break;
  1558. case 756:
  1559. agentSizeVPNeckLength = paramValue;
  1560. break;
  1561. case 842:
  1562. agentSizeVPHipLength = paramValue;
  1563. break;
  1564. }
  1565. if (vpIndex == nrParams) break;
  1566. }
  1567. MyVisualParameters = new byte[set.VisualParam.Length];
  1568. for (int i = 0; i < set.VisualParam.Length; i++)
  1569. {
  1570. MyVisualParameters[i] = set.VisualParam[i].ParamValue;
  1571. }
  1572. #endregion VisualParam
  1573. #region TextureEntry
  1574. Primitive.TextureEntry te = new Primitive.TextureEntry(DEFAULT_AVATAR_TEXTURE);
  1575. for (uint i = 0; i < Textures.Length; i++)
  1576. {
  1577. if ((i == 0 || i == 5 || i == 6) && Client.Settings.CLIENT_IDENTIFICATION_TAG != UUID.Zero)
  1578. {
  1579. Primitive.TextureEntryFace face = te.CreateFace(i);
  1580. face.TextureID = Client.Settings.CLIENT_IDENTIFICATION_TAG;
  1581. Logger.DebugLog("Sending client identification tag: " + Client.Settings.CLIENT_IDENTIFICATION_TAG, Client);
  1582. }
  1583. else if (Textures[i].TextureID != UUID.Zero)
  1584. {
  1585. Primitive.TextureEntryFace face = te.CreateFace(i);
  1586. face.TextureID = Textures[i].TextureID;
  1587. Logger.DebugLog("Sending texture entry for " + (AvatarTextureIndex)i + " to " + Textures[i].TextureID, Client);
  1588. }
  1589. }
  1590. set.ObjectData.TextureEntry = te.GetBytes();
  1591. MyTextures = te;
  1592. #endregion TextureEntry
  1593. #region WearableData
  1594. set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[BAKED_TEXTURE_COUNT];
  1595. // Build hashes for each of the bake layers from the individual components
  1596. for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
  1597. {
  1598. UUID hash = UUID.Zero;
  1599. for (int wearableIndex = 0; wearableIndex < WEARABLES_PER_LAYER; wearableIndex++)
  1600. {
  1601. WearableType type = WEARABLE_BAKE_MAP[bakedIndex][wearableIndex];
  1602. WearableData wearable;
  1603. if (type != WearableType.Invalid && Wearables.TryGetValue(type, out wearable))
  1604. hash ^= wearable.AssetID;
  1605. }
  1606. if (hash != UUID.Zero)
  1607. {
  1608. // Hash with our magic value for this baked layer
  1609. hash ^= BAKED_TEXTURE_HASH[bakedIndex];
  1610. }
  1611. // Tell the server what cached texture assetID to use for each bake layer
  1612. set.WearableData[bakedIndex] = new AgentSetAppearancePacket.WearableDataBlock();
  1613. set.WearableData[bakedIndex].TextureIndex = BakeIndexToTextureIndex[bakedIndex];
  1614. set.WearableData[bakedIndex].CacheID = hash;
  1615. Logger.DebugLog("Sending TextureIndex " + (BakeType)bakedIndex + " with CacheID " + hash, Client);
  1616. }
  1617. #endregion WearableData
  1618. #region Agent Size
  1619. // Takes into account the Shoe Heel/Platform offsets but not the HeadSize offset. Seems to work.
  1620. double agentSizeBase = 1.706;
  1621. // The calculation for the HeadSize scalar may be incorrect, but it seems to work
  1622. double agentHeight = agentSizeBase + (agentSizeVPLegLength * .1918) + (agentSizeVPHipLength * .0375) +
  1623. (agentSizeVPHeight * .12022) + (agentSizeVPHeadSize * .01117) + (agentSizeVPNeckLength * .038) +
  1624. (agentSizeVPHeelHeight * .08) + (agentSizeVPPlatformHeight * .07);
  1625. set.AgentData.Size = new Vector3(0.45f, 0.6f, (float)agentHeight);
  1626. #endregion Agent Size
  1627. if (Client.Settings.AVATAR_TRACKING)
  1628. {
  1629. Avatar me;
  1630. if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.LocalID, out me))
  1631. {
  1632. me.Textures = MyTextures;
  1633. me.VisualParameters = MyVisualParameters;
  1634. }
  1635. }
  1636. }
  1637. return set;
  1638. }
  1639. private void DelayedRequestSetAppearance()
  1640. {
  1641. if (RebakeScheduleTimer == null)
  1642. {
  1643. RebakeScheduleTimer = new Timer(RebakeScheduleTimerTick);
  1644. }
  1645. try { RebakeScheduleTimer.Change(REBAKE_DELAY, Timeout.Infinite); }
  1646. catch { }
  1647. }
  1648. private void RebakeScheduleTimerTick(Object state)
  1649. {
  1650. RequestSetAppearance(true);
  1651. }
  1652. #endregion Appearance Helpers
  1653. #region Inventory Helpers
  1654. private bool GetFolderWearables(string[] folderPath, out List<InventoryWearable> wearables, out List<InventoryItem> attachments)
  1655. {
  1656. UUID folder = Client.Inventory.FindObjectByPath(
  1657. Client.Inventory.Store.RootFolder.UUID, Client.Self.AgentID, String.Join("/", folderPath), INVENTORY_TIMEOUT);
  1658. if (folder != UUID.Zero)
  1659. {
  1660. return GetFolderWearables(folder, out wearables, out attachments);
  1661. }
  1662. else
  1663. {
  1664. Logger.Log("Failed to resolve outfit folder path " + folderPath, Helpers.LogLevel.Error, Client);
  1665. wearables = null;
  1666. attachments = null;
  1667. return false;
  1668. }
  1669. }
  1670. private bool GetFolderWearables(UUID folder, out List<InventoryWearable> wearables, out List<InventoryItem> attachments)
  1671. {
  1672. wearables = new List<InventoryWearable>();
  1673. attachments = new List<InventoryItem>();
  1674. List<InventoryBase> objects = Client.Inventory.FolderContents(folder, Client.Self.AgentID, false, true,
  1675. InventorySortOrder.ByName, INVENTORY_TIMEOUT);
  1676. if (objects != null)
  1677. {
  1678. foreach (InventoryBase ib in objects)
  1679. {
  1680. if (ib is InventoryWearable)
  1681. {
  1682. Logger.DebugLog("Adding wearable " + ib.Name, Client);
  1683. wearables.Add((InventoryWearable)ib);
  1684. }
  1685. else if (ib is InventoryAttachment)
  1686. {
  1687. Logger.DebugLog("Adding attachment (attachment) " + ib.Name, Client);
  1688. attachments.Add((InventoryItem)ib);
  1689. }
  1690. else if (ib is InventoryObject)
  1691. {
  1692. Logger.DebugLog("Adding attachment (object) " + ib.Name, Client);
  1693. attachments.Add((InventoryItem)ib);
  1694. }
  1695. else
  1696. {
  1697. Logger.DebugLog("Ignoring inventory item " + ib.Name, Client);
  1698. }
  1699. }
  1700. }
  1701. else
  1702. {
  1703. Logger.Log("Failed to download folder contents of + " + folder, Helpers.LogLevel.Error, Client);
  1704. return false;
  1705. }
  1706. return true;
  1707. }
  1708. #endregion Inventory Helpers
  1709. #region Callbacks
  1710. protected void AgentWearablesUpdateHandler(object sender, PacketReceivedEventArgs e)
  1711. {
  1712. bool changed = false;
  1713. AgentWearablesUpdatePacket update = (AgentWearablesUpdatePacket)e.Packet;
  1714. lock (Wearables)
  1715. {
  1716. #region Test if anything changed in this update
  1717. for (int i = 0; i < update.WearableData.Length; i++)
  1718. {
  1719. AgentWearablesUpdatePacket.WearableDataBlock block = update.WearableData[i];
  1720. if (block.AssetID != UUID.Zero)
  1721. {
  1722. WearableData wearable;
  1723. if (Wearables.TryGetValue((WearableType)block.WearableType, out wearable))
  1724. {
  1725. if (wearable.AssetID != block.AssetID || wearable.ItemID != block.ItemID)
  1726. {
  1727. // A different wearable is now set for this index
  1728. changed = true;
  1729. break;
  1730. }
  1731. }
  1732. else
  1733. {
  1734. // A wearable is now set for this index
  1735. changed = true;
  1736. break;
  1737. }
  1738. }
  1739. else if (Wearables.ContainsKey((WearableType)block.WearableType))
  1740. {
  1741. // This index is now empty
  1742. changed = true;
  1743. break;
  1744. }
  1745. }
  1746. #endregion Test if anything changed in this update
  1747. if (changed)
  1748. {
  1749. Logger.DebugLog("New wearables received in AgentWearablesUpdate");
  1750. Wearables.Clear();
  1751. for (int i = 0; i < update.WearableData.Length; i++)
  1752. {
  1753. AgentWearablesUpdatePacket.WearableDataBlock block = update.WearableData[i];
  1754. if (block.AssetID != UUID.Zero)
  1755. {
  1756. WearableType type = (WearableType)block.WearableType;
  1757. WearableData data = new WearableData();
  1758. data.Asset = null;
  1759. data.AssetID = block.AssetID;
  1760. data.AssetType = WearableTypeToAssetType(type);
  1761. data.ItemID = block.ItemID;
  1762. data.WearableType = type;
  1763. // Add this wearable to our collection
  1764. Wearables[type] = data;
  1765. }
  1766. }
  1767. }
  1768. else
  1769. {
  1770. Logger.DebugLog("Duplicate AgentWearablesUpdate received, discarding");
  1771. }
  1772. }
  1773. if (changed)
  1774. {
  1775. // Fire the callback
  1776. OnAgentWearables(new AgentWearablesReplyEventArgs());
  1777. }
  1778. }
  1779. protected void RebakeAvatarTexturesHandler(object sender, PacketReceivedEventArgs e)
  1780. {
  1781. RebakeAvatarTexturesPacket rebake = (RebakeAvatarTexturesPacket)e.Packet;
  1782. // allow the library to do the rebake
  1783. if (Client.Settings.SEND_AGENT_APPEARANCE)
  1784. {
  1785. RequestSetAppearance(true);
  1786. }
  1787. OnRebakeAvatar(new RebakeAvatarTexturesEventArgs(rebake.TextureData.TextureID));
  1788. }
  1789. protected void AgentCachedTextureResponseHandler(object sender, PacketReceivedEventArgs e)
  1790. {
  1791. AgentCachedTextureResponsePacket response = (AgentCachedTextureResponsePacket)e.Packet;
  1792. for (int i = 0; i < response.WearableData.Length; i++)
  1793. {
  1794. AgentCachedTextureResponsePacket.WearableDataBlock block = response.WearableData[i];
  1795. BakeType bakeType = (BakeType)block.TextureIndex;
  1796. AvatarTextureIndex index = BakeTypeToAgentTextureIndex(bakeType);
  1797. Logger.DebugLog("Cache response for " + bakeType + ", TextureID=" + block.TextureID, Client);
  1798. if (block.TextureID != UUID.Zero)
  1799. {
  1800. // A simulator has a cache of this bake layer
  1801. // FIXME: Use this. Right now we don't bother to check if this is a foreign host
  1802. string host = Utils.BytesToString(block.HostName);
  1803. Textures[(int)index].TextureID = block.TextureID;
  1804. }
  1805. else
  1806. {
  1807. // The server does not have a cache of this bake layer
  1808. // FIXME:
  1809. }
  1810. }
  1811. OnAgentCachedBakes(new AgentCachedBakesReplyEventArgs());
  1812. }
  1813. private void Network_OnEventQueueRunning(object sender, EventQueueRunningEventArgs e)
  1814. {
  1815. if (e.Simulator == Client.Network.CurrentSim && Client.Settings.SEND_AGENT_APPEARANCE)
  1816. {
  1817. // Update appearance each time we enter a new sim and capabilities have been retrieved
  1818. Client.Appearance.RequestSetAppearance();
  1819. }
  1820. }
  1821. private void Network_OnDisconnected(object sender, DisconnectedEventArgs e)
  1822. {
  1823. if (RebakeScheduleTimer != null)
  1824. {
  1825. RebakeScheduleTimer.Dispose();
  1826. RebakeScheduleTimer = null;
  1827. }
  1828. if (AppearanceThread != null)
  1829. {
  1830. if (AppearanceThread.IsAlive)
  1831. {
  1832. AppearanceThread.Abort();
  1833. }
  1834. AppearanceThread = null;
  1835. AppearanceThreadRunning = 0;
  1836. }
  1837. }
  1838. #endregion Callbacks
  1839. #region Static Helpers
  1840. /// <summary>
  1841. /// Converts a WearableType to a bodypart or clothing WearableType
  1842. /// </summary>
  1843. /// <param name="type">A WearableType</param>
  1844. /// <returns>AssetType.Bodypart or AssetType.Clothing or AssetType.Unknown</returns>
  1845. public static AssetType WearableTypeToAssetType(WearableType type)
  1846. {
  1847. switch (type)
  1848. {
  1849. case WearableType.Shape:
  1850. case WearableType.Skin:
  1851. case WearableType.Hair:
  1852. case WearableType.Eyes:
  1853. return AssetType.Bodypart;
  1854. case WearableType.Shirt:
  1855. case WearableType.Pants:
  1856. case WearableType.Shoes:
  1857. case WearableType.Socks:
  1858. case WearableType.Jacket:
  1859. case WearableType.Gloves:
  1860. case WearableType.Undershirt:
  1861. case WearableType.Underpants:
  1862. case WearableType.Skirt:
  1863. case WearableType.Tattoo:
  1864. case WearableType.Alpha:
  1865. case WearableType.Physics:
  1866. return AssetType.Clothing;
  1867. default:
  1868. return AssetType.Unknown;
  1869. }
  1870. }
  1871. /// <summary>
  1872. /// Converts a BakeType to the corresponding baked texture slot in AvatarTextureIndex
  1873. /// </summary>
  1874. /// <param name="index">A BakeType</param>
  1875. /// <returns>The AvatarTextureIndex slot that holds the given BakeType</returns>
  1876. public static AvatarTextureIndex BakeTypeToAgentTextureIndex(BakeType index)
  1877. {
  1878. switch (index)
  1879. {
  1880. case BakeType.Head:
  1881. return AvatarTextureIndex.HeadBaked;
  1882. case BakeType.UpperBody:
  1883. return AvatarTextureIndex.UpperBaked;
  1884. case BakeType.LowerBody:
  1885. return AvatarTextureIndex.LowerBaked;
  1886. case BakeType.Eyes:
  1887. return AvatarTextureIndex.EyesBaked;
  1888. case BakeType.Skirt:
  1889. return AvatarTextureIndex.SkirtBaked;
  1890. case BakeType.Hair:
  1891. return AvatarTextureIndex.HairBaked;
  1892. default:
  1893. return AvatarTextureIndex.Unknown;
  1894. }
  1895. }
  1896. /// <summary>
  1897. /// Gives the layer number that is used for morph mask
  1898. /// </summary>
  1899. /// <param name="bakeType">>A BakeType</param>
  1900. /// <returns>Which layer number as defined in BakeTypeToTextures is used for morph mask</returns>
  1901. public static AvatarTextureIndex MorphLayerForBakeType(BakeType bakeType)
  1902. {
  1903. // Indexes return here correspond to those returned
  1904. // in BakeTypeToTextures(), those two need to be in sync.
  1905. // Which wearable layer is used for morph is defined in avatar_lad.xml
  1906. // by looking for <layer> that has <morph_mask> defined in it, and
  1907. // looking up which wearable is defined in that layer. Morph mask
  1908. // is never combined, it's always a straight copy of one single clothing
  1909. // item's alpha channel per bake.
  1910. switch (bakeType)
  1911. {
  1912. case BakeType.Head:
  1913. return AvatarTextureIndex.Hair; // hair
  1914. case BakeType.UpperBody:
  1915. return AvatarTextureIndex.UpperShirt; // shirt
  1916. case BakeType.LowerBody:
  1917. return AvatarTextureIndex.LowerPants; // lower pants
  1918. case BakeType.Skirt:
  1919. return AvatarTextureIndex.Skirt; // skirt
  1920. case BakeType.Hair:
  1921. return AvatarTextureIndex.Hair; // hair
  1922. default:
  1923. return AvatarTextureIndex.Unknown;
  1924. }
  1925. }
  1926. /// <summary>
  1927. /// Converts a BakeType to a list of the texture slots that make up that bake
  1928. /// </summary>
  1929. /// <param name="bakeType">A BakeType</param>
  1930. /// <returns>A list of texture slots that are inputs for the given bake</returns>
  1931. public static List<AvatarTextureIndex> BakeTypeToTextures(BakeType bakeType)
  1932. {
  1933. List<AvatarTextureIndex> textures = new List<AvatarTextureIndex>();
  1934. switch (bakeType)
  1935. {
  1936. case BakeType.Head:
  1937. textures.Add(AvatarTextureIndex.HeadBodypaint);
  1938. textures.Add(AvatarTextureIndex.HeadTattoo);
  1939. textures.Add(AvatarTextureIndex.Hair);
  1940. textures.Add(AvatarTextureIndex.HeadAlpha);
  1941. break;
  1942. case BakeType.UpperBody:
  1943. textures.Add(AvatarTextureIndex.UpperBodypaint);
  1944. textures.Add(AvatarTextureIndex.UpperTattoo);
  1945. textures.Add(AvatarTextureIndex.UpperGloves);
  1946. textures.Add(AvatarTextureIndex.UpperUndershirt);
  1947. textures.Add(AvatarTextureIndex.UpperShirt);
  1948. textures.Add(AvatarTextureIndex.UpperJacket);
  1949. textures.Add(AvatarTextureIndex.UpperAlpha);
  1950. break;
  1951. case BakeType.LowerBody:
  1952. textures.Add(AvatarTextureIndex.LowerBodypaint);
  1953. textures.Add(AvatarTextureIndex.LowerTattoo);
  1954. textures.Add(AvatarTextureIndex.LowerUnderpants);
  1955. textures.Add(AvatarTextureIndex.LowerSocks);
  1956. textures.Add(AvatarTextureIndex.LowerShoes);
  1957. textures.Add(AvatarTextureIndex.LowerPants);
  1958. textures.Add(AvatarTextureIndex.LowerJacket);
  1959. textures.Add(AvatarTextureIndex.LowerAlpha);
  1960. break;
  1961. case BakeType.Eyes:
  1962. textures.Add(AvatarTextureIndex.EyesIris);
  1963. textures.Add(AvatarTextureIndex.EyesAlpha);
  1964. break;
  1965. case BakeType.Skirt:
  1966. textures.Add(AvatarTextureIndex.Skirt);
  1967. break;
  1968. case BakeType.Hair:
  1969. textures.Add(AvatarTextureIndex.Hair);
  1970. textures.Add(AvatarTextureIndex.HairAlpha);
  1971. break;
  1972. }
  1973. return textures;
  1974. }
  1975. #endregion Static Helpers
  1976. }
  1977. #region AppearanceManager EventArgs Classes
  1978. /// <summary>Contains the Event data returned from the data server from an AgentWearablesRequest</summary>
  1979. public class AgentWearablesReplyEventArgs : EventArgs
  1980. {
  1981. /// <summary>Construct a new instance of the AgentWearablesReplyEventArgs class</summary>
  1982. public AgentWearablesReplyEventArgs()
  1983. {
  1984. }
  1985. }
  1986. /// <summary>Contains the Event data returned from the data server from an AgentCachedTextureResponse</summary>
  1987. public class AgentCachedBakesReplyEventArgs : EventArgs
  1988. {
  1989. /// <summary>Construct a new instance of the AgentCachedBakesReplyEventArgs class</summary>
  1990. public AgentCachedBakesReplyEventArgs()
  1991. {
  1992. }
  1993. }
  1994. /// <summary>Contains the Event data returned from an AppearanceSetRequest</summary>
  1995. public class AppearanceSetEventArgs : EventArgs
  1996. {
  1997. private readonly bool m_success;
  1998. /// <summary>Indicates whether appearance setting was successful</summary>
  1999. public bool Success { get { return m_success; } }
  2000. /// <summary>
  2001. /// Triggered when appearance data is sent to the sim and
  2002. /// the main appearance thread is done.</summary>
  2003. /// <param name="success">Indicates whether appearance setting was successful</param>
  2004. public AppearanceSetEventArgs(bool success)
  2005. {
  2006. this.m_success = success;
  2007. }
  2008. }
  2009. /// <summary>Contains the Event data returned from the data server from an RebakeAvatarTextures</summary>
  2010. public class RebakeAvatarTexturesEventArgs : EventArgs
  2011. {
  2012. private readonly UUID m_textureID;
  2013. /// <summary>The ID of the Texture Layer to bake</summary>
  2014. public UUID TextureID { get { return m_textureID; } }
  2015. /// <summary>
  2016. /// Triggered when the simulator sends a request for this agent to rebake
  2017. /// its appearance
  2018. /// </summary>
  2019. /// <param name="textureID">The ID of the Texture Layer to bake</param>
  2020. public RebakeAvatarTexturesEventArgs(UUID textureID)
  2021. {
  2022. this.m_textureID = textureID;
  2023. }
  2024. }
  2025. #endregion
  2026. }