Bot.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using pCampBot.Interfaces;
  41. using Timer = System.Timers.Timer;
  42. using PermissionMask = OpenSim.Framework.PermissionMask;
  43. namespace pCampBot
  44. {
  45. public enum ConnectionState
  46. {
  47. Disconnected,
  48. Connecting,
  49. Connected,
  50. Disconnecting
  51. }
  52. public class Bot
  53. {
  54. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. public delegate void AnEvent(Bot callbot, EventType someevent); // event delegate for bot events
  56. /// <summary>
  57. /// Bot manager.
  58. /// </summary>
  59. public BotManager Manager { get; private set; }
  60. /// <summary>
  61. /// Bot config, passed from BotManager.
  62. /// </summary>
  63. private IConfig startupConfig;
  64. /// <summary>
  65. /// Behaviours implemented by this bot.
  66. /// </summary>
  67. /// <remarks>
  68. /// Lock this list before manipulating it.
  69. /// </remarks>
  70. public List<IBehaviour> Behaviours { get; private set; }
  71. /// <summary>
  72. /// Objects that the bot has discovered.
  73. /// </summary>
  74. /// <remarks>
  75. /// Returns a list copy. Inserting new objects manually will have no effect.
  76. /// </remarks>
  77. public Dictionary<UUID, Primitive> Objects
  78. {
  79. get
  80. {
  81. lock (m_objects)
  82. return new Dictionary<UUID, Primitive>(m_objects);
  83. }
  84. }
  85. private Dictionary<UUID, Primitive> m_objects = new Dictionary<UUID, Primitive>();
  86. /// <summary>
  87. /// Is this bot connected to the grid?
  88. /// </summary>
  89. public ConnectionState ConnectionState { get; private set; }
  90. public string FirstName { get; private set; }
  91. public string LastName { get; private set; }
  92. public string Name { get; private set; }
  93. public string Password { get; private set; }
  94. public string LoginUri { get; private set; }
  95. public string saveDir;
  96. public string wear;
  97. public event AnEvent OnConnected;
  98. public event AnEvent OnDisconnected;
  99. /// <summary>
  100. /// Keep a track of the continuously acting thread so that we can abort it.
  101. /// </summary>
  102. private Thread m_actionThread;
  103. protected List<uint> objectIDs = new List<uint>();
  104. /// <summary>
  105. /// Random number generator.
  106. /// </summary>
  107. public Random Random { get; private set; }
  108. /// <summary>
  109. /// New instance of a SecondLife client
  110. /// </summary>
  111. public GridClient Client { get; private set; }
  112. /// <summary>
  113. /// Constructor
  114. /// </summary>
  115. /// <param name="bm"></param>
  116. /// <param name="behaviours">Behaviours for this bot to perform</param>
  117. /// <param name="firstName"></param>
  118. /// <param name="lastName"></param>
  119. /// <param name="password"></param>
  120. /// <param name="loginUri"></param>
  121. /// <param name="behaviours"></param>
  122. public Bot(
  123. BotManager bm, List<IBehaviour> behaviours,
  124. string firstName, string lastName, string password, string loginUri)
  125. {
  126. ConnectionState = ConnectionState.Disconnected;
  127. behaviours.ForEach(b => b.Initialize(this));
  128. Client = new GridClient();
  129. Random = new Random(Environment.TickCount);// We do stuff randomly here
  130. FirstName = firstName;
  131. LastName = lastName;
  132. Name = string.Format("{0} {1}", FirstName, LastName);
  133. Password = password;
  134. LoginUri = loginUri;
  135. Manager = bm;
  136. startupConfig = bm.Config;
  137. readconfig();
  138. Behaviours = behaviours;
  139. }
  140. //We do our actions here. This is where one would
  141. //add additional steps and/or things the bot should do
  142. private void Action()
  143. {
  144. while (true)
  145. lock (Behaviours)
  146. Behaviours.ForEach(
  147. b =>
  148. {
  149. Thread.Sleep(Random.Next(3000, 10000));
  150. // m_log.DebugFormat("[pCAMPBOT]: For {0} performing action {1}", Name, b.GetType());
  151. b.Action();
  152. }
  153. );
  154. }
  155. /// <summary>
  156. /// Read the Nini config and initialize
  157. /// </summary>
  158. public void readconfig()
  159. {
  160. wear = startupConfig.GetString("wear", "no");
  161. }
  162. /// <summary>
  163. /// Tells LibSecondLife to logout and disconnect. Raises the disconnect events once it finishes.
  164. /// </summary>
  165. public void shutdown()
  166. {
  167. ConnectionState = ConnectionState.Disconnecting;
  168. if (m_actionThread != null)
  169. m_actionThread.Abort();
  170. Client.Network.Logout();
  171. }
  172. /// <summary>
  173. /// This is the bot startup loop.
  174. /// </summary>
  175. public void startup()
  176. {
  177. Client.Settings.LOGIN_SERVER = LoginUri;
  178. Client.Settings.ALWAYS_DECODE_OBJECTS = false;
  179. Client.Settings.AVATAR_TRACKING = false;
  180. Client.Settings.OBJECT_TRACKING = false;
  181. Client.Settings.SEND_AGENT_THROTTLE = true;
  182. Client.Settings.SEND_PINGS = true;
  183. Client.Settings.STORE_LAND_PATCHES = false;
  184. Client.Settings.USE_ASSET_CACHE = false;
  185. Client.Settings.MULTIPLE_SIMS = true;
  186. Client.Throttle.Asset = 100000;
  187. Client.Throttle.Land = 100000;
  188. Client.Throttle.Task = 100000;
  189. Client.Throttle.Texture = 100000;
  190. Client.Throttle.Wind = 100000;
  191. Client.Throttle.Total = 400000;
  192. Client.Network.LoginProgress += this.Network_LoginProgress;
  193. Client.Network.SimConnected += this.Network_SimConnected;
  194. Client.Network.Disconnected += this.Network_OnDisconnected;
  195. Client.Objects.ObjectUpdate += Objects_NewPrim;
  196. ConnectionState = ConnectionState.Connecting;
  197. if (Client.Network.Login(FirstName, LastName, Password, "pCampBot", "Your name"))
  198. {
  199. ConnectionState = ConnectionState.Connected;
  200. Thread.Sleep(Random.Next(1000, 10000));
  201. m_actionThread = new Thread(Action);
  202. m_actionThread.Start();
  203. // OnConnected(this, EventType.CONNECTED);
  204. if (wear == "save")
  205. {
  206. Client.Appearance.SetPreviousAppearance();
  207. SaveDefaultAppearance();
  208. }
  209. else if (wear != "no")
  210. {
  211. MakeDefaultAppearance(wear);
  212. }
  213. // Extract nearby region information.
  214. Client.Grid.GridRegion += Manager.Grid_GridRegion;
  215. uint xUint, yUint;
  216. Utils.LongToUInts(Client.Network.CurrentSim.Handle, out xUint, out yUint);
  217. ushort minX, minY, maxX, maxY;
  218. minX = (ushort)Math.Min(0, xUint - 5);
  219. minY = (ushort)Math.Min(0, yUint - 5);
  220. maxX = (ushort)(xUint + 5);
  221. maxY = (ushort)(yUint + 5);
  222. Client.Grid.RequestMapBlocks(GridLayerType.Terrain, minX, minY, maxX, maxY, false);
  223. }
  224. else
  225. {
  226. ConnectionState = ConnectionState.Disconnected;
  227. m_log.ErrorFormat(
  228. "{0} {1} cannot login: {2}", FirstName, LastName, Client.Network.LoginMessage);
  229. if (OnDisconnected != null)
  230. {
  231. OnDisconnected(this, EventType.DISCONNECTED);
  232. }
  233. }
  234. }
  235. public void SaveDefaultAppearance()
  236. {
  237. saveDir = "MyAppearance/" + FirstName + "_" + LastName;
  238. if (!Directory.Exists(saveDir))
  239. {
  240. Directory.CreateDirectory(saveDir);
  241. }
  242. Array wtypes = Enum.GetValues(typeof(WearableType));
  243. foreach (WearableType wtype in wtypes)
  244. {
  245. UUID wearable = Client.Appearance.GetWearableAsset(wtype);
  246. if (wearable != UUID.Zero)
  247. {
  248. Client.Assets.RequestAsset(wearable, AssetType.Clothing, false, Asset_ReceivedCallback);
  249. Client.Assets.RequestAsset(wearable, AssetType.Bodypart, false, Asset_ReceivedCallback);
  250. }
  251. }
  252. }
  253. public void SaveAsset(AssetWearable asset)
  254. {
  255. if (asset != null)
  256. {
  257. try
  258. {
  259. if (asset.Decode())
  260. {
  261. File.WriteAllBytes(Path.Combine(saveDir, String.Format("{1}.{0}",
  262. asset.AssetType.ToString().ToLower(),
  263. asset.WearableType)), asset.AssetData);
  264. }
  265. else
  266. {
  267. m_log.WarnFormat("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID);
  268. }
  269. }
  270. catch (Exception e)
  271. {
  272. m_log.ErrorFormat("Exception: {0}{1}", e.Message, e.StackTrace);
  273. }
  274. }
  275. }
  276. public WearableType GetWearableType(string path)
  277. {
  278. string type = ((((path.Split('/'))[2]).Split('.'))[0]).Trim();
  279. switch (type)
  280. {
  281. case "Eyes":
  282. return WearableType.Eyes;
  283. case "Hair":
  284. return WearableType.Hair;
  285. case "Pants":
  286. return WearableType.Pants;
  287. case "Shape":
  288. return WearableType.Shape;
  289. case "Shirt":
  290. return WearableType.Shirt;
  291. case "Skin":
  292. return WearableType.Skin;
  293. default:
  294. return WearableType.Shape;
  295. }
  296. }
  297. public void MakeDefaultAppearance(string wear)
  298. {
  299. try
  300. {
  301. if (wear == "yes")
  302. {
  303. //TODO: Implement random outfit picking
  304. m_log.DebugFormat("Picks a random outfit. Not yet implemented.");
  305. }
  306. else if (wear != "save")
  307. saveDir = "MyAppearance/" + wear;
  308. saveDir = saveDir + "/";
  309. string[] clothing = Directory.GetFiles(saveDir, "*.clothing", SearchOption.TopDirectoryOnly);
  310. string[] bodyparts = Directory.GetFiles(saveDir, "*.bodypart", SearchOption.TopDirectoryOnly);
  311. InventoryFolder clothfolder = FindClothingFolder();
  312. UUID transid = UUID.Random();
  313. List<InventoryBase> listwearables = new List<InventoryBase>();
  314. for (int i = 0; i < clothing.Length; i++)
  315. {
  316. UUID assetID = UUID.Random();
  317. AssetClothing asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i]));
  318. asset.Decode();
  319. asset.Owner = Client.Self.AgentID;
  320. asset.WearableType = GetWearableType(clothing[i]);
  321. asset.Encode();
  322. transid = Client.Assets.RequestUpload(asset,true);
  323. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyClothing" + i.ToString(), "MyClothing", AssetType.Clothing,
  324. transid, InventoryType.Wearable, asset.WearableType, (OpenMetaverse.PermissionMask)PermissionMask.All, delegate(bool success, InventoryItem item)
  325. {
  326. if (success)
  327. {
  328. listwearables.Add(item);
  329. }
  330. else
  331. {
  332. m_log.WarnFormat("Failed to create item {0}", item.Name);
  333. }
  334. }
  335. );
  336. }
  337. for (int i = 0; i < bodyparts.Length; i++)
  338. {
  339. UUID assetID = UUID.Random();
  340. AssetBodypart asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i]));
  341. asset.Decode();
  342. asset.Owner = Client.Self.AgentID;
  343. asset.WearableType = GetWearableType(bodyparts[i]);
  344. asset.Encode();
  345. transid = Client.Assets.RequestUpload(asset,true);
  346. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyBodyPart" + i.ToString(), "MyBodyPart", AssetType.Bodypart,
  347. transid, InventoryType.Wearable, asset.WearableType, (OpenMetaverse.PermissionMask)PermissionMask.All, delegate(bool success, InventoryItem item)
  348. {
  349. if (success)
  350. {
  351. listwearables.Add(item);
  352. }
  353. else
  354. {
  355. m_log.WarnFormat("Failed to create item {0}", item.Name);
  356. }
  357. }
  358. );
  359. }
  360. Thread.Sleep(1000);
  361. if (listwearables == null || listwearables.Count == 0)
  362. {
  363. m_log.DebugFormat("Nothing to send on this folder!");
  364. }
  365. else
  366. {
  367. m_log.DebugFormat("Sending {0} wearables...", listwearables.Count);
  368. Client.Appearance.WearOutfit(listwearables, false);
  369. }
  370. }
  371. catch (Exception ex)
  372. {
  373. Console.WriteLine(ex.ToString());
  374. }
  375. }
  376. public InventoryFolder FindClothingFolder()
  377. {
  378. UUID rootfolder = Client.Inventory.Store.RootFolder.UUID;
  379. List<InventoryBase> listfolders = Client.Inventory.Store.GetContents(rootfolder);
  380. InventoryFolder clothfolder = new InventoryFolder(UUID.Random());
  381. foreach (InventoryBase folder in listfolders)
  382. {
  383. if (folder.Name == "Clothing")
  384. {
  385. clothfolder = (InventoryFolder)folder;
  386. break;
  387. }
  388. }
  389. return clothfolder;
  390. }
  391. public void Network_LoginProgress(object sender, LoginProgressEventArgs args)
  392. {
  393. m_log.DebugFormat("[BOT]: Bot {0} {1} in Network_LoginProcess", Name, args.Status);
  394. if (args.Status == LoginStatus.Success)
  395. {
  396. if (OnConnected != null)
  397. {
  398. OnConnected(this, EventType.CONNECTED);
  399. }
  400. }
  401. }
  402. public void Network_SimConnected(object sender, SimConnectedEventArgs args)
  403. {
  404. m_log.DebugFormat(
  405. "[BOT]: Bot {0} connected to {1} at {2}", Name, args.Simulator.Name, args.Simulator.IPEndPoint);
  406. }
  407. public void Network_OnDisconnected(object sender, DisconnectedEventArgs args)
  408. {
  409. ConnectionState = ConnectionState.Disconnected;
  410. m_log.DebugFormat(
  411. "[BOT]: Bot {0} disconnected reason {1}, message {2}", Name, args.Reason, args.Message);
  412. // m_log.ErrorFormat("Fired Network_OnDisconnected");
  413. // if (
  414. // (args.Reason == NetworkManager.DisconnectType.SimShutdown
  415. // || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  416. // && OnDisconnected != null)
  417. if (
  418. (args.Reason == NetworkManager.DisconnectType.ClientInitiated
  419. || args.Reason == NetworkManager.DisconnectType.ServerInitiated
  420. || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  421. && OnDisconnected != null)
  422. // if (OnDisconnected != null)
  423. {
  424. OnDisconnected(this, EventType.DISCONNECTED);
  425. }
  426. }
  427. public void Objects_NewPrim(object sender, PrimEventArgs args)
  428. {
  429. // if (Name.EndsWith("4"))
  430. // throw new Exception("Aaargh");
  431. Primitive prim = args.Prim;
  432. if (prim != null)
  433. {
  434. lock (m_objects)
  435. m_objects[prim.ID] = prim;
  436. if (prim.Textures != null)
  437. {
  438. if (prim.Textures.DefaultTexture.TextureID != UUID.Zero)
  439. {
  440. GetTexture(prim.Textures.DefaultTexture.TextureID);
  441. }
  442. for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
  443. {
  444. Primitive.TextureEntryFace face = prim.Textures.FaceTextures[i];
  445. if (face != null)
  446. {
  447. UUID textureID = prim.Textures.FaceTextures[i].TextureID;
  448. if (textureID != UUID.Zero)
  449. GetTexture(textureID);
  450. }
  451. }
  452. }
  453. if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero)
  454. GetTexture(prim.Sculpt.SculptTexture);
  455. }
  456. }
  457. private void GetTexture(UUID textureID)
  458. {
  459. lock (Manager.AssetsReceived)
  460. {
  461. // Don't request assets more than once.
  462. if (Manager.AssetsReceived.ContainsKey(textureID))
  463. return;
  464. Manager.AssetsReceived[textureID] = false;
  465. Client.Assets.RequestImage(textureID, ImageType.Normal, Asset_TextureCallback_Texture);
  466. }
  467. }
  468. public void Asset_TextureCallback_Texture(TextureRequestState state, AssetTexture assetTexture)
  469. {
  470. //TODO: Implement texture saving and applying
  471. }
  472. public void Asset_ReceivedCallback(AssetDownload transfer, Asset asset)
  473. {
  474. lock (Manager.AssetsReceived)
  475. Manager.AssetsReceived[asset.AssetID] = true;
  476. // if (wear == "save")
  477. // {
  478. // SaveAsset((AssetWearable) asset);
  479. // }
  480. }
  481. }
  482. }