Bot.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Timers;
  34. using log4net;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Assets;
  37. using OpenMetaverse.Packets;
  38. using Nini.Config;
  39. using OpenSim.Framework;
  40. using OpenSim.Framework.Console;
  41. using pCampBot.Interfaces;
  42. using Timer = System.Timers.Timer;
  43. using PermissionMask = OpenSim.Framework.PermissionMask;
  44. namespace pCampBot
  45. {
  46. public enum ConnectionState
  47. {
  48. Disconnected,
  49. Connecting,
  50. Connected,
  51. Disconnecting
  52. }
  53. public class Bot
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. public int PacketDebugLevel
  57. {
  58. get { return m_packetDebugLevel; }
  59. set
  60. {
  61. if (value == m_packetDebugLevel)
  62. return;
  63. m_packetDebugLevel = value;
  64. if (Client != null)
  65. {
  66. if (m_packetDebugLevel <= 0)
  67. Client.Network.UnregisterCallback(PacketType.Default, PacketReceivedDebugHandler);
  68. else
  69. Client.Network.RegisterCallback(PacketType.Default, PacketReceivedDebugHandler, false);
  70. }
  71. }
  72. }
  73. private int m_packetDebugLevel;
  74. public delegate void AnEvent(Bot callbot, EventType someevent); // event delegate for bot events
  75. /// <summary>
  76. /// Controls whether bots request textures for the object information they receive
  77. /// </summary>
  78. public bool RequestObjectTextures { get; set; }
  79. /// <summary>
  80. /// Bot manager.
  81. /// </summary>
  82. public BotManager Manager { get; private set; }
  83. /// <summary>
  84. /// Behaviours implemented by this bot.
  85. /// </summary>
  86. /// <remarks>
  87. /// Indexed by abbreviated name. There can only be one instance of a particular behaviour.
  88. /// Lock this structure before manipulating it.
  89. /// </remarks>
  90. public Dictionary<string, IBehaviour> Behaviours { get; private set; }
  91. /// <summary>
  92. /// Objects that the bot has discovered.
  93. /// </summary>
  94. /// <remarks>
  95. /// Returns a list copy. Inserting new objects manually will have no effect.
  96. /// </remarks>
  97. public Dictionary<UUID, Primitive> Objects
  98. {
  99. get
  100. {
  101. lock (m_objects)
  102. return new Dictionary<UUID, Primitive>(m_objects);
  103. }
  104. }
  105. private Dictionary<UUID, Primitive> m_objects = new Dictionary<UUID, Primitive>();
  106. /// <summary>
  107. /// Is this bot connected to the grid?
  108. /// </summary>
  109. public ConnectionState ConnectionState { get; private set; }
  110. public List<Simulator> Simulators
  111. {
  112. get
  113. {
  114. lock (Client.Network.Simulators)
  115. return new List<Simulator>(Client.Network.Simulators);
  116. }
  117. }
  118. /// <summary>
  119. /// The number of connections that this bot has to different simulators.
  120. /// </summary>
  121. /// <value>Includes both root and child connections.</value>
  122. public int SimulatorsCount
  123. {
  124. get
  125. {
  126. lock (Client.Network.Simulators)
  127. return Client.Network.Simulators.Count;
  128. }
  129. }
  130. public string FirstName { get; private set; }
  131. public string LastName { get; private set; }
  132. public string Name { get; private set; }
  133. public string Password { get; private set; }
  134. public string LoginUri { get; private set; }
  135. public string StartLocation { get; private set; }
  136. public string saveDir;
  137. public string wear;
  138. public event AnEvent OnConnected;
  139. public event AnEvent OnDisconnected;
  140. /// <summary>
  141. /// Keep a track of the continuously acting thread so that we can abort it.
  142. /// </summary>
  143. private Thread m_actionThread;
  144. protected List<uint> objectIDs = new List<uint>();
  145. /// <summary>
  146. /// Random number generator.
  147. /// </summary>
  148. public Random Random { get; private set; }
  149. /// <summary>
  150. /// New instance of a SecondLife client
  151. /// </summary>
  152. public GridClient Client { get; private set; }
  153. /// <summary>
  154. /// Constructor
  155. /// </summary>
  156. /// <param name="bm"></param>
  157. /// <param name="behaviours">Behaviours for this bot to perform</param>
  158. /// <param name="firstName"></param>
  159. /// <param name="lastName"></param>
  160. /// <param name="password"></param>
  161. /// <param name="loginUri"></param>
  162. /// <param name="behaviours"></param>
  163. public Bot(
  164. BotManager bm, List<IBehaviour> behaviours,
  165. string firstName, string lastName, string password, string startLocation, string loginUri)
  166. {
  167. ConnectionState = ConnectionState.Disconnected;
  168. Random = new Random(bm.Rng.Next());
  169. FirstName = firstName;
  170. LastName = lastName;
  171. Name = string.Format("{0} {1}", FirstName, LastName);
  172. Password = password;
  173. LoginUri = loginUri;
  174. StartLocation = startLocation;
  175. Manager = bm;
  176. Behaviours = new Dictionary<string, IBehaviour>();
  177. foreach (IBehaviour behaviour in behaviours)
  178. AddBehaviour(behaviour);
  179. // Only calling for use as a template.
  180. CreateLibOmvClient();
  181. }
  182. public bool TryGetBehaviour(string abbreviatedName, out IBehaviour behaviour)
  183. {
  184. lock (Behaviours)
  185. return Behaviours.TryGetValue(abbreviatedName, out behaviour);
  186. }
  187. public bool AddBehaviour(IBehaviour behaviour)
  188. {
  189. Dictionary<string, IBehaviour> updatedBehaviours = new Dictionary<string, IBehaviour>(Behaviours);
  190. if (!updatedBehaviours.ContainsKey(behaviour.AbbreviatedName))
  191. {
  192. behaviour.Initialize(this);
  193. updatedBehaviours.Add(behaviour.AbbreviatedName, behaviour);
  194. Behaviours = updatedBehaviours;
  195. return true;
  196. }
  197. return false;
  198. }
  199. public bool RemoveBehaviour(string abbreviatedName)
  200. {
  201. if (Behaviours.Count <= 0)
  202. return false;
  203. Dictionary<string, IBehaviour> updatedBehaviours = new Dictionary<string, IBehaviour>(Behaviours);
  204. IBehaviour behaviour;
  205. if (!updatedBehaviours.TryGetValue(abbreviatedName, out behaviour))
  206. return false;
  207. updatedBehaviours.Remove(abbreviatedName);
  208. Behaviours = updatedBehaviours;
  209. behaviour.Close();
  210. return true;
  211. }
  212. private void CreateLibOmvClient()
  213. {
  214. GridClient newClient = new GridClient();
  215. if (Client != null)
  216. {
  217. // Remove any registered debug handlers
  218. Client.Network.UnregisterCallback(PacketType.Default, PacketReceivedDebugHandler);
  219. newClient.Settings.LOGIN_SERVER = Client.Settings.LOGIN_SERVER;
  220. newClient.Settings.ALWAYS_DECODE_OBJECTS = Client.Settings.ALWAYS_DECODE_OBJECTS;
  221. newClient.Settings.AVATAR_TRACKING = Client.Settings.AVATAR_TRACKING;
  222. newClient.Settings.OBJECT_TRACKING = Client.Settings.OBJECT_TRACKING;
  223. newClient.Settings.SEND_AGENT_THROTTLE = Client.Settings.SEND_AGENT_THROTTLE;
  224. newClient.Settings.SEND_AGENT_UPDATES = Client.Settings.SEND_AGENT_UPDATES;
  225. newClient.Settings.SEND_PINGS = Client.Settings.SEND_PINGS;
  226. newClient.Settings.STORE_LAND_PATCHES = Client.Settings.STORE_LAND_PATCHES;
  227. newClient.Settings.USE_ASSET_CACHE = Client.Settings.USE_ASSET_CACHE;
  228. newClient.Settings.MULTIPLE_SIMS = Client.Settings.MULTIPLE_SIMS;
  229. newClient.Throttle.Asset = Client.Throttle.Asset;
  230. newClient.Throttle.Land = Client.Throttle.Land;
  231. newClient.Throttle.Task = Client.Throttle.Task;
  232. newClient.Throttle.Texture = Client.Throttle.Texture;
  233. newClient.Throttle.Wind = Client.Throttle.Wind;
  234. newClient.Throttle.Total = Client.Throttle.Total;
  235. }
  236. else
  237. {
  238. newClient.Settings.LOGIN_SERVER = LoginUri;
  239. newClient.Settings.ALWAYS_DECODE_OBJECTS = false;
  240. newClient.Settings.AVATAR_TRACKING = false;
  241. newClient.Settings.OBJECT_TRACKING = false;
  242. newClient.Settings.SEND_AGENT_THROTTLE = true;
  243. newClient.Settings.SEND_PINGS = true;
  244. newClient.Settings.STORE_LAND_PATCHES = false;
  245. newClient.Settings.USE_ASSET_CACHE = false;
  246. newClient.Settings.MULTIPLE_SIMS = true;
  247. newClient.Throttle.Asset = 100000;
  248. newClient.Throttle.Land = 100000;
  249. newClient.Throttle.Task = 100000;
  250. newClient.Throttle.Texture = 100000;
  251. newClient.Throttle.Wind = 100000;
  252. newClient.Throttle.Total = 400000;
  253. }
  254. newClient.Network.LoginProgress += Network_LoginProgress;
  255. newClient.Network.SimConnected += Network_SimConnected;
  256. newClient.Network.SimDisconnected += Network_SimDisconnected;
  257. newClient.Network.Disconnected += Network_OnDisconnected;
  258. newClient.Objects.ObjectUpdate += Objects_NewPrim;
  259. if (m_packetDebugLevel > 0)
  260. newClient.Network.RegisterCallback(PacketType.Default, PacketReceivedDebugHandler);
  261. Client = newClient;
  262. }
  263. //We do our actions here. This is where one would
  264. //add additional steps and/or things the bot should do
  265. private void Action()
  266. {
  267. while (ConnectionState == ConnectionState.Connected)
  268. {
  269. foreach (IBehaviour behaviour in Behaviours.Values)
  270. {
  271. // Thread.Sleep(Random.Next(3000, 10000));
  272. // m_log.DebugFormat("[pCAMPBOT]: For {0} performing action {1}", Name, b.GetType());
  273. behaviour.Action();
  274. }
  275. }
  276. foreach (IBehaviour b in Behaviours.Values)
  277. b.Close();
  278. }
  279. /// <summary>
  280. /// Tells LibSecondLife to logout and disconnect. Raises the disconnect events once it finishes.
  281. /// </summary>
  282. public void Disconnect()
  283. {
  284. ConnectionState = ConnectionState.Disconnecting;
  285. foreach (IBehaviour behaviour in Behaviours.Values)
  286. behaviour.Close();
  287. Client.Network.Logout();
  288. }
  289. public void Connect()
  290. {
  291. Thread connectThread = new Thread(ConnectInternal);
  292. connectThread.Name = Name;
  293. connectThread.IsBackground = true;
  294. connectThread.Start();
  295. }
  296. /// <summary>
  297. /// This is the bot startup loop.
  298. /// </summary>
  299. private void ConnectInternal()
  300. {
  301. ConnectionState = ConnectionState.Connecting;
  302. // Current create a new client on each connect. libomv doesn't seem to process new sim
  303. // information (e.g. EstablishAgentCommunication events) if connecting after a disceonnect with the same
  304. // client
  305. CreateLibOmvClient();
  306. if (Client.Network.Login(FirstName, LastName, Password, "pCampBot", StartLocation, "pCampBot"))
  307. {
  308. ConnectionState = ConnectionState.Connected;
  309. Thread.Sleep(Random.Next(1000, 10000));
  310. m_actionThread = new Thread(Action);
  311. m_actionThread.Start();
  312. // OnConnected(this, EventType.CONNECTED);
  313. if (wear == "save")
  314. {
  315. SaveDefaultAppearance();
  316. }
  317. else if (wear != "no")
  318. {
  319. MakeDefaultAppearance(wear);
  320. }
  321. // Extract nearby region information.
  322. Client.Grid.GridRegion += Manager.Grid_GridRegion;
  323. uint xUint, yUint;
  324. Utils.LongToUInts(Client.Network.CurrentSim.Handle, out xUint, out yUint);
  325. ushort minX, minY, maxX, maxY;
  326. minX = (ushort)Math.Min(0, xUint - 5);
  327. minY = (ushort)Math.Min(0, yUint - 5);
  328. maxX = (ushort)(xUint + 5);
  329. maxY = (ushort)(yUint + 5);
  330. Client.Grid.RequestMapBlocks(GridLayerType.Terrain, minX, minY, maxX, maxY, false);
  331. }
  332. else
  333. {
  334. ConnectionState = ConnectionState.Disconnected;
  335. m_log.ErrorFormat(
  336. "{0} {1} cannot login: {2}", FirstName, LastName, Client.Network.LoginMessage);
  337. if (OnDisconnected != null)
  338. {
  339. OnDisconnected(this, EventType.DISCONNECTED);
  340. }
  341. }
  342. }
  343. /// <summary>
  344. /// Sit this bot on the ground.
  345. /// </summary>
  346. public void SitOnGround()
  347. {
  348. if (ConnectionState == ConnectionState.Connected)
  349. Client.Self.SitOnGround();
  350. }
  351. /// <summary>
  352. /// Stand this bot
  353. /// </summary>
  354. public void Stand()
  355. {
  356. if (ConnectionState == ConnectionState.Connected)
  357. {
  358. // Unlike sit on ground, here libomv checks whether we have SEND_AGENT_UPDATES enabled.
  359. bool prevUpdatesSetting = Client.Settings.SEND_AGENT_UPDATES;
  360. Client.Settings.SEND_AGENT_UPDATES = true;
  361. Client.Self.Stand();
  362. Client.Settings.SEND_AGENT_UPDATES = prevUpdatesSetting;
  363. }
  364. }
  365. public void SaveDefaultAppearance()
  366. {
  367. saveDir = "MyAppearance/" + FirstName + "_" + LastName;
  368. if (!Directory.Exists(saveDir))
  369. {
  370. Directory.CreateDirectory(saveDir);
  371. }
  372. Array wtypes = Enum.GetValues(typeof(WearableType));
  373. foreach (WearableType wtype in wtypes)
  374. {
  375. UUID wearable = Client.Appearance.GetWearableAsset(wtype);
  376. if (wearable != UUID.Zero)
  377. {
  378. Client.Assets.RequestAsset(wearable, AssetType.Clothing, false, Asset_ReceivedCallback);
  379. Client.Assets.RequestAsset(wearable, AssetType.Bodypart, false, Asset_ReceivedCallback);
  380. }
  381. }
  382. }
  383. public void SaveAsset(AssetWearable asset)
  384. {
  385. if (asset != null)
  386. {
  387. try
  388. {
  389. if (asset.Decode())
  390. {
  391. File.WriteAllBytes(Path.Combine(saveDir, String.Format("{1}.{0}",
  392. asset.AssetType.ToString().ToLower(),
  393. asset.WearableType)), asset.AssetData);
  394. }
  395. else
  396. {
  397. m_log.WarnFormat("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID);
  398. }
  399. }
  400. catch (Exception e)
  401. {
  402. m_log.ErrorFormat("Exception: {0}{1}", e.Message, e.StackTrace);
  403. }
  404. }
  405. }
  406. public WearableType GetWearableType(string path)
  407. {
  408. string type = ((((path.Split('/'))[2]).Split('.'))[0]).Trim();
  409. switch (type)
  410. {
  411. case "Eyes":
  412. return WearableType.Eyes;
  413. case "Hair":
  414. return WearableType.Hair;
  415. case "Pants":
  416. return WearableType.Pants;
  417. case "Shape":
  418. return WearableType.Shape;
  419. case "Shirt":
  420. return WearableType.Shirt;
  421. case "Skin":
  422. return WearableType.Skin;
  423. default:
  424. return WearableType.Shape;
  425. }
  426. }
  427. public void MakeDefaultAppearance(string wear)
  428. {
  429. try
  430. {
  431. if (wear == "yes")
  432. {
  433. //TODO: Implement random outfit picking
  434. m_log.DebugFormat("Picks a random outfit. Not yet implemented.");
  435. }
  436. else if (wear != "save")
  437. saveDir = "MyAppearance/" + wear;
  438. saveDir = saveDir + "/";
  439. string[] clothing = Directory.GetFiles(saveDir, "*.clothing", SearchOption.TopDirectoryOnly);
  440. string[] bodyparts = Directory.GetFiles(saveDir, "*.bodypart", SearchOption.TopDirectoryOnly);
  441. InventoryFolder clothfolder = FindClothingFolder();
  442. UUID transid = UUID.Random();
  443. List<InventoryBase> listwearables = new List<InventoryBase>();
  444. for (int i = 0; i < clothing.Length; i++)
  445. {
  446. UUID assetID = UUID.Random();
  447. AssetClothing asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i]));
  448. asset.Decode();
  449. asset.Owner = Client.Self.AgentID;
  450. asset.WearableType = GetWearableType(clothing[i]);
  451. asset.Encode();
  452. transid = Client.Assets.RequestUpload(asset,true);
  453. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyClothing" + i.ToString(), "MyClothing", AssetType.Clothing,
  454. transid, InventoryType.Wearable, asset.WearableType, (OpenMetaverse.PermissionMask)PermissionMask.All, delegate(bool success, InventoryItem item)
  455. {
  456. if (success)
  457. {
  458. listwearables.Add(item);
  459. }
  460. else
  461. {
  462. m_log.WarnFormat("Failed to create item {0}", item.Name);
  463. }
  464. }
  465. );
  466. }
  467. for (int i = 0; i < bodyparts.Length; i++)
  468. {
  469. UUID assetID = UUID.Random();
  470. AssetBodypart asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i]));
  471. asset.Decode();
  472. asset.Owner = Client.Self.AgentID;
  473. asset.WearableType = GetWearableType(bodyparts[i]);
  474. asset.Encode();
  475. transid = Client.Assets.RequestUpload(asset,true);
  476. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyBodyPart" + i.ToString(), "MyBodyPart", AssetType.Bodypart,
  477. transid, InventoryType.Wearable, asset.WearableType, (OpenMetaverse.PermissionMask)PermissionMask.All, delegate(bool success, InventoryItem item)
  478. {
  479. if (success)
  480. {
  481. listwearables.Add(item);
  482. }
  483. else
  484. {
  485. m_log.WarnFormat("Failed to create item {0}", item.Name);
  486. }
  487. }
  488. );
  489. }
  490. Thread.Sleep(1000);
  491. if (listwearables == null || listwearables.Count == 0)
  492. {
  493. m_log.DebugFormat("Nothing to send on this folder!");
  494. }
  495. else
  496. {
  497. m_log.DebugFormat("Sending {0} wearables...", listwearables.Count);
  498. Client.Appearance.WearOutfit(listwearables, false);
  499. }
  500. }
  501. catch (Exception ex)
  502. {
  503. Console.WriteLine(ex.ToString());
  504. }
  505. }
  506. public InventoryFolder FindClothingFolder()
  507. {
  508. UUID rootfolder = Client.Inventory.Store.RootFolder.UUID;
  509. List<InventoryBase> listfolders = Client.Inventory.Store.GetContents(rootfolder);
  510. InventoryFolder clothfolder = new InventoryFolder(UUID.Random());
  511. foreach (InventoryBase folder in listfolders)
  512. {
  513. if (folder.Name == "Clothing")
  514. {
  515. clothfolder = (InventoryFolder)folder;
  516. break;
  517. }
  518. }
  519. return clothfolder;
  520. }
  521. public void Network_LoginProgress(object sender, LoginProgressEventArgs args)
  522. {
  523. m_log.DebugFormat("[BOT]: Bot {0} {1} in Network_LoginProcess", Name, args.Status);
  524. if (args.Status == LoginStatus.Success)
  525. {
  526. if (OnConnected != null)
  527. {
  528. OnConnected(this, EventType.CONNECTED);
  529. }
  530. }
  531. }
  532. public void Network_SimConnected(object sender, SimConnectedEventArgs args)
  533. {
  534. m_log.DebugFormat(
  535. "[BOT]: Bot {0} connected to region {1} at {2}", Name, args.Simulator.Name, args.Simulator.IPEndPoint);
  536. }
  537. public void Network_SimDisconnected(object sender, SimDisconnectedEventArgs args)
  538. {
  539. m_log.DebugFormat(
  540. "[BOT]: Bot {0} disconnected from region {1} at {2}", Name, args.Simulator.Name, args.Simulator.IPEndPoint);
  541. }
  542. public void Network_OnDisconnected(object sender, DisconnectedEventArgs args)
  543. {
  544. ConnectionState = ConnectionState.Disconnected;
  545. m_log.DebugFormat(
  546. "[BOT]: Bot {0} disconnected from grid, reason {1}, message {2}", Name, args.Reason, args.Message);
  547. // m_log.ErrorFormat("Fired Network_OnDisconnected");
  548. // if (
  549. // (args.Reason == NetworkManager.DisconnectType.SimShutdown
  550. // || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  551. // && OnDisconnected != null)
  552. if (
  553. (args.Reason == NetworkManager.DisconnectType.ClientInitiated
  554. || args.Reason == NetworkManager.DisconnectType.ServerInitiated
  555. || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  556. && OnDisconnected != null)
  557. // if (OnDisconnected != null)
  558. {
  559. OnDisconnected(this, EventType.DISCONNECTED);
  560. }
  561. }
  562. public void Objects_NewPrim(object sender, PrimEventArgs args)
  563. {
  564. if (!RequestObjectTextures)
  565. return;
  566. Primitive prim = args.Prim;
  567. if (prim != null)
  568. {
  569. lock (m_objects)
  570. m_objects[prim.ID] = prim;
  571. if (prim.Textures != null)
  572. {
  573. if (prim.Textures.DefaultTexture.TextureID != UUID.Zero)
  574. {
  575. GetTextureOrMesh(prim.Textures.DefaultTexture.TextureID, true);
  576. }
  577. for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
  578. {
  579. Primitive.TextureEntryFace face = prim.Textures.FaceTextures[i];
  580. if (face != null)
  581. {
  582. UUID textureID = prim.Textures.FaceTextures[i].TextureID;
  583. if (textureID != UUID.Zero)
  584. GetTextureOrMesh(textureID, true);
  585. }
  586. }
  587. }
  588. if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero)
  589. {
  590. bool mesh = (prim.Sculpt.Type == SculptType.Mesh);
  591. GetTextureOrMesh(prim.Sculpt.SculptTexture, !mesh);
  592. }
  593. }
  594. }
  595. private void GetTextureOrMesh(UUID assetID, bool texture)
  596. {
  597. lock (Manager.AssetsReceived)
  598. {
  599. // Don't request assets more than once.
  600. if (Manager.AssetsReceived.ContainsKey(assetID))
  601. return;
  602. Manager.AssetsReceived[assetID] = false;
  603. }
  604. try
  605. {
  606. if (texture)
  607. Client.Assets.RequestImage(assetID, ImageType.Normal, Asset_TextureCallback_Texture);
  608. else
  609. Client.Assets.RequestMesh(assetID, Asset_MeshCallback);
  610. }
  611. catch (Exception e)
  612. {
  613. m_log.Warn(string.Format("Error requesting {0} {1}", texture ? "texture" : "mesh", assetID), e);
  614. }
  615. }
  616. public void Asset_TextureCallback_Texture(TextureRequestState state, AssetTexture assetTexture)
  617. {
  618. if (state == TextureRequestState.Finished)
  619. {
  620. lock (Manager.AssetsReceived)
  621. Manager.AssetsReceived[assetTexture.AssetID] = true;
  622. }
  623. }
  624. private void Asset_MeshCallback(bool success, AssetMesh assetMesh)
  625. {
  626. lock (Manager.AssetsReceived)
  627. Manager.AssetsReceived[assetMesh.AssetID] = success;
  628. }
  629. public void Asset_ReceivedCallback(AssetDownload transfer, Asset asset)
  630. {
  631. lock (Manager.AssetsReceived)
  632. Manager.AssetsReceived[asset.AssetID] = true;
  633. // if (wear == "save")
  634. // {
  635. // SaveAsset((AssetWearable) asset);
  636. // }
  637. }
  638. private void PacketReceivedDebugHandler(object o, PacketReceivedEventArgs args)
  639. {
  640. Packet p = args.Packet;
  641. Header h = p.Header;
  642. Simulator s = args.Simulator;
  643. m_log.DebugFormat(
  644. "[BOT]: Bot {0} received from {1} packet {2} #{3}, rel {4}, res {5}",
  645. Name, s.Name, p.Type, h.Sequence, h.Reliable, h.Resent);
  646. }
  647. }
  648. }