TextureHandler.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text.RegularExpressions;
  9. namespace OpenVIII
  10. {
  11. /// <summary>
  12. /// This contains functions to Load Highres mod versions of textures and get scale vector.
  13. /// </summary>
  14. public class TextureHandler
  15. {
  16. #region Fields
  17. private static ConcurrentDictionary<string, Texture2D> _pngs = new ConcurrentDictionary<string, Texture2D>();
  18. private static ConcurrentDictionary<string, TextureHandler> _ths = new ConcurrentDictionary<string, TextureHandler>();
  19. private static string[] pngs;
  20. private Texture_Base _classic;
  21. #endregion Fields
  22. #region Constructors
  23. #endregion Constructors
  24. #region Properties
  25. /// <summary>
  26. /// Original sub 256x265 texture, required for fallback when issues happen.
  27. /// </summary>
  28. public Texture_Base Classic { get => _classic; private set { _classic = value; if (value != null) ClassicSize = new Vector2(value.GetWidth, value.GetHeight); } }
  29. public int ClassicHeight => (int)(ClassicSize == Vector2.Zero ? Size.Y : ClassicSize.Y);
  30. /// <summary>
  31. /// X = width and Y = height. The Size of original texture. Will be used in scaling
  32. /// </summary>
  33. public Vector2 ClassicSize { get; private set; }
  34. public int ClassicWidth => (int)(ClassicSize == Vector2.Zero ? Size.X : ClassicSize.X);
  35. public Color[] Colors { get; private set; }
  36. public uint Count { get; protected set; }
  37. public int Height => (int)Size.Y;
  38. public bool Modded { get; private set; } = false;
  39. public ushort Palette { get; protected set; }
  40. /// <summary>
  41. /// Scale vector from big to original
  42. /// </summary>
  43. public Vector2 ReverseScaleFactor => Size == Vector2.Zero || ClassicSize == Vector2.Zero ? Vector2.One : ClassicSize / Size;
  44. /// <summary>
  45. /// Scale vector from original to big
  46. /// </summary>
  47. public Vector2 ScaleFactor => Size == Vector2.Zero || ClassicSize == Vector2.Zero ? Vector2.One : Size / ClassicSize;
  48. /// <summary>
  49. /// X = width and Y = height. The Size of big version texture. Will be used in scaling
  50. /// </summary>
  51. public Vector2 Size { get; private set; }
  52. public int Width => (int)Size.X;
  53. protected uint Cols { get; set; }
  54. protected string Filename { get; set; }
  55. protected uint Rows { get; set; }
  56. protected uint StartOffset { get; set; }
  57. protected Texture2D[,] Textures { get; private set; }
  58. public string ModdedFilename { get; private set; }
  59. #endregion Properties
  60. #region Indexers
  61. public Texture2D this[int c, int r] => Textures[c, r];
  62. #endregion Indexers
  63. #region Methods
  64. public static Vector2 Abs(Vector2 v) => new Vector2(Math.Abs(v.X), Math.Abs(v.Y));
  65. public static TextureHandler Create(string filename, uint cols) => Create(filename, cols, 1);
  66. public static TextureHandler Create(string filename, uint cols, uint rows) => Create(filename, null, cols, rows);
  67. public static TextureHandler Create(string filename, Texture_Base classic, ushort palette = 0, Color[] colors = null) => Create(filename, classic, 1, 1, palette: palette, colors: colors);
  68. public static TextureHandler Create(string filename, Texture_Base classic, uint cols, uint rows, ushort palette = 0, Color[] colors = null)
  69. {
  70. string s = FindPNG(filename, palette);
  71. if (string.IsNullOrWhiteSpace(s) || !_ths.TryGetValue(s, out TextureHandler ret))
  72. {
  73. ret = new TextureHandler
  74. {
  75. ModdedFilename = s,
  76. //Modded = string.IsNullOrWhiteSpace(s),
  77. Filename = filename,
  78. Classic = classic,
  79. Cols = cols,
  80. Rows = rows,
  81. Palette = palette,
  82. Colors = colors
  83. };
  84. ret.Init();
  85. if (ret.Modded && !string.IsNullOrWhiteSpace(ret.ModdedFilename))
  86. {
  87. _ths.TryAdd(ret.ModdedFilename, ret);
  88. //if (_pngs.ContainsKey(ret.ModdedFilename))
  89. // _pngs.TryRemove(ret.ModdedFilename,out Texture2D none);
  90. }
  91. }
  92. return ret;
  93. }
  94. public static explicit operator Texture2D(TextureHandler t)
  95. {
  96. if (t.Count == 1)
  97. return t[0, 0];
  98. throw new Exception("TextureHandler can only be cast to Texture2D if there is only one texture in the array use [cols,rows] instead");
  99. //return null;
  100. }
  101. public static Vector2 GetOffset(Rectangle old, Rectangle @new) => GetOffset(old.Location.ToVector2(), @new.Location.ToVector2());
  102. public static Vector2 GetOffset(Point oldLoc, Point newLoc) => GetOffset(oldLoc.ToVector2(), newLoc.ToVector2());
  103. public static Vector2 GetOffset(Vector2 oldLoc, Vector2 newLoc) => Abs(oldLoc - newLoc);
  104. public static Vector2 GetScale(Vector2 _old, Vector2 _new)
  105. {
  106. if (_new.Y == 0 && _new.X != 0)
  107. return new Vector2(_new.X / _old.X);
  108. else if (_new.Y != 0 && _new.X == 0)
  109. return new Vector2(_new.Y / _old.Y);
  110. else if (_new.Y == 0 && _new.X == 0)
  111. return Vector2.One;
  112. return _new / _old;
  113. }
  114. public static Vector2 GetScale(Vector2 _old, Texture2D _new) => new Vector2(_new.Width / _old.X, _new.Height / _old.Y);
  115. public static Vector2 GetScale(Texture_Base _old, Texture2D _new) => new Vector2((float)_new.Width / _old.GetWidth, (float)_new.Height / _old.GetHeight);
  116. public static Vector2 GetScale(Texture2D _old, Texture2D _new) => new Vector2((float)_new.Width / _old.Width, (float)_new.Height / _old.Height);
  117. public static Vector2 GetScale(Point oldSize, Point newSize) => GetScale(oldSize.ToVector2(), newSize.ToVector2());
  118. public static implicit operator Rectangle(TextureHandler v) => new Rectangle(new Point(0), v.Size.ToPoint());
  119. /// <summary>
  120. /// Load Texture from a mod
  121. /// </summary>
  122. /// <param name="path"></param>
  123. /// <returns></returns>
  124. public static Texture2D LoadPNG(string path, int palette = -1)
  125. {
  126. string pngpath = File.Exists(path) ? path : FindPNG(path, palette);
  127. Texture2D tex = null;
  128. if (!string.IsNullOrWhiteSpace(pngpath) && !_pngs.TryGetValue(pngpath, out tex))
  129. {
  130. using (FileStream fs = File.OpenRead(pngpath))
  131. {
  132. tex = Texture2D.FromStream(Memory.graphics.GraphicsDevice, fs);
  133. _pngs.TryAdd(pngpath, tex);
  134. }
  135. }
  136. return tex;
  137. }
  138. public static string FindPNG(string path, int palette = -1)
  139. {
  140. string bn = Path.GetFileNameWithoutExtension(path);
  141. string textures = Path.Combine(Memory.FF8DIR, "textures");
  142. if (Directory.Exists(textures))
  143. {
  144. if (pngs == null)
  145. pngs = Directory.GetFiles(textures, "*.png", SearchOption.AllDirectories);
  146. string tex;
  147. if (palette < 0 || (tex = _findPNG($"{bn}+ _{ (palette + 1).ToString("D2")}")) == null)
  148. tex = _findPNG(bn);
  149. if(tex !=null)
  150. return tex;
  151. }
  152. return null;
  153. string _findPNG(string testname)
  154. {
  155. return pngs.Where(x => x.IndexOf(testname, StringComparison.OrdinalIgnoreCase) >= 0).OrderBy(x => x.Length).ThenBy(x=>x).FirstOrDefault();
  156. }
  157. }
  158. public static Rectangle Scale(Rectangle src, Vector2 scale)
  159. {
  160. src.Location = (src.Location.ToVector2() * scale).ToPoint();//.RoundedPoint();
  161. src.Size = (src.Size.ToVector2() * scale).ToPoint();//.RoundedPoint();
  162. return src;
  163. }
  164. public static Rectangle ToRectangle(Texture2D t) => new Rectangle(0, 0, t.Width, t.Height);
  165. public static Rectangle ToRectangle(TextureHandler t) => new Rectangle(0, 0, (int)t.ClassicSize.X, (int)t.ClassicSize.Y);
  166. public static Rectangle ToRectangle(Vector2 loc, Vector2 size) => new Rectangle(loc.ToPoint(), size.ToPoint());
  167. public static Vector2 ToVector2(Texture2D t) => new Vector2(t.Width, t.Height);
  168. public static Vector2 ToVector2(TextureHandler t) => new Vector2(t.ClassicSize.X, t.ClassicSize.Y);
  169. public static Texture2D UseBest(Texture2D _old, Texture2D _new) => UseBest(_old, _new, out Vector2 scale);
  170. public static Texture2D UseBest(Texture2D _old, Texture2D _new, out Vector2 scale)
  171. {
  172. if (_new == null)
  173. {
  174. scale = Vector2.One;
  175. return _old;
  176. }
  177. else
  178. {
  179. scale = GetScale(_old, _new);
  180. _old.Dispose();
  181. return _new;
  182. }
  183. }
  184. public static Texture2D UseBest(Texture_Base _old, Texture2D _new, ushort palette = 0, Color[] colors = null) => UseBest(_old, _new, out Vector2 scale, palette, colors);
  185. public static Texture2D UseBest(Texture_Base _old, Texture2D _new, out Vector2 scale, ushort palette = 0, Color[] colors = null)
  186. {
  187. Texture2D tex;
  188. if (_new == null)
  189. {
  190. scale = Vector2.One;
  191. if (_old.GetClutCount <= 1)
  192. return _old.GetTexture();
  193. tex = colors != null ? _old.GetTexture(colors) : _old.GetTexture(palette);
  194. return tex;
  195. }
  196. else
  197. {
  198. scale = GetScale(_old, _new);
  199. return _new;
  200. }
  201. }
  202. public void Draw(Rectangle dst, Rectangle? src, Color color)
  203. {
  204. if (src != null)
  205. {
  206. _Draw(dst, src.Value, color);
  207. return;
  208. }
  209. //drawing texture directly
  210. else
  211. {
  212. _Draw(dst, color);
  213. }
  214. }
  215. public void Draw(Rectangle dst, Color color) => Draw(dst, null, color);
  216. public void Draw(Rectangle dst, Color color, float rotation, Vector2 origin, SpriteEffects effects, float depth)
  217. {
  218. if (Rows == 1 && Cols == 1)
  219. Memory.spriteBatch.Draw(Textures[0, 0], dst, null, color, rotation, origin, effects, depth);
  220. else
  221. {
  222. throw new Exception("had not coded this to draw from multiple textures");
  223. }
  224. }
  225. public Vector2 GetScale(int cols = 0, int rows = 0) => ScaleFactor;
  226. public void Merge()
  227. {
  228. if (Rows * Cols > 1)
  229. {
  230. if (Memory.IsMainThread)
  231. {
  232. int width = 0;
  233. int height = 0;
  234. for (int r = 0; r < (int)Rows; r++)
  235. {
  236. int rowwidth = 0;
  237. int rowheight = 0;
  238. for (int c = 0; c < (int)Cols; c++)
  239. {
  240. rowwidth += Textures[c, r].Width;
  241. if (rowheight < Textures[c, r].Height)
  242. rowheight = Textures[c, r].Height;
  243. }
  244. if (width < rowwidth)
  245. width = rowwidth;
  246. height += rowheight;
  247. }
  248. Texture2D tex = new Texture2D(Memory.graphics.GraphicsDevice, width, height, false, SurfaceFormat.Color);
  249. Rectangle dst = new Rectangle();
  250. for (int r = 0; r < (int)Rows; r++)
  251. {
  252. dst.Y += r > 0 ? Textures[0, r - 1].Height : 0;
  253. for (int c = 0; c < (int)Cols; c++)
  254. {
  255. dst.Height = Textures[c, r].Height;
  256. dst.Width = Textures[c, r].Width;
  257. dst.X += c > 0 ? Textures[c - 1, r].Width : 0;
  258. Color[] buffer = new Color[dst.Height * dst.Width];
  259. Textures[c, r].GetData<Color>(buffer);
  260. tex.SetData(0, dst, buffer, 0, buffer.Length);
  261. //Textures[c, r].Dispose();
  262. }
  263. dst.X = 0;
  264. }
  265. foreach (Texture2D t in Textures)
  266. t.Dispose();
  267. Textures = new Texture2D[1, 1];
  268. Textures[0, 0] = tex;
  269. Rows = 1;
  270. Cols = 1;
  271. Count = 1;
  272. }
  273. else
  274. {
  275. Memory.MainThreadOnlyActions.Enqueue(this.Merge);
  276. }
  277. }
  278. }
  279. public void Save()
  280. {
  281. string clean = Path.GetFileNameWithoutExtension(Regex.Replace(Filename, @"{[^}]+}", ""));
  282. string outpath = Path.Combine(Path.GetTempPath(), Path.GetFileName(clean) + $"_{(Palette + 1).ToString("D2")}.png");
  283. if (Textures != null && Textures.Length > 0 && Textures[0, 0] != null)
  284. using (FileStream fs = File.Create(outpath))
  285. Textures[0, 0].SaveAsPng(fs, Textures[0, 0].Width, Textures[0, 0].Height);
  286. else
  287. Debug.WriteLine($"{this} :: Textures is null or empty! :: {Filename}");
  288. }
  289. /// <summary>
  290. /// Remove all transparenct rows and cols of pixels
  291. /// </summary>
  292. /// <param name="src"></param>
  293. /// <returns></returns>
  294. public Rectangle Trim(Rectangle src) => _process(Rectangle.Empty, src, Color.TransparentBlack, _Trim_SingleTexture);
  295. protected void Process()
  296. {
  297. Vector2 size = Vector2.Zero;
  298. Vector2 oldsize = Vector2.Zero;
  299. Texture_Base tex = null;
  300. uint c2 = 0;
  301. uint r2 = 0;
  302. for (uint r = 0; r < Rows; r++)
  303. {
  304. for (uint c = 0; c < Cols && Memory.graphics?.GraphicsDevice != null; c++)
  305. {
  306. Texture2D pngTex;
  307. ArchiveWorker aw = new ArchiveWorker(Memory.Archives.A_MENU);
  308. string path = aw.GetListOfFiles().FirstOrDefault(x => (x.IndexOf(string.Format(Filename, c + r * Cols + StartOffset), StringComparison.OrdinalIgnoreCase) >= 0));
  309. if (!string.IsNullOrWhiteSpace(path))
  310. {
  311. tex = Texture_Base.Open(ArchiveWorker.GetBinaryFile(Memory.Archives.A_MENU, path));
  312. if (Classic == null && c2 < Cols) oldsize.X += tex.GetWidth;
  313. pngTex = LoadPNG(path, Palette);
  314. }
  315. else
  316. {
  317. pngTex = !string.IsNullOrWhiteSpace(ModdedFilename) ? LoadPNG(ModdedFilename, Palette) : LoadPNG(Filename, Palette);
  318. }
  319. if (tex == null) tex = Classic;
  320. Textures[c, r] = (UseBest(tex, pngTex, Palette, Colors));
  321. if (pngTex != null) Modded = true;
  322. if (c2 < Cols && Textures[c2, r2] != null) size.X += Textures[c2++, r2].Width;
  323. }
  324. if (Classic == null && r2 < Rows) oldsize.Y += tex.GetHeight;
  325. if (r2 < Rows && Textures.LongLength > r2 + c2 - 1 && Textures[c2 - 1, r2] != null) size.Y += Textures[c2 - 1, r2++].Height;
  326. }
  327. Size = size;
  328. if (Classic == null) ClassicSize = oldsize;
  329. }
  330. private void _Draw(Rectangle dst, Rectangle src, Color color)
  331. => _process(dst, src, color, _Draw);
  332. private Rectangle _Draw(Texture2D tex, Rectangle dst, Rectangle src, Color color)
  333. {
  334. Memory.spriteBatch.Draw(tex, dst, src, color);
  335. return src;
  336. }
  337. private void _Draw(Rectangle dst, Color color)
  338. {
  339. if (Rows == 1 && Cols == 1 && dst.Height > 0 && dst.Width > 0)
  340. Memory.spriteBatch.Draw(Textures[0, 0], dst, color);
  341. else
  342. {
  343. //throw new Exception($"{this}::code broken for multiple pcs. I think");
  344. Vector2 dstOffset = Vector2.Zero;
  345. Vector2 dstV = Vector2.Zero;
  346. dstOffset.X = dst.X;
  347. dstOffset.Y = dst.Y;
  348. for (uint r = 0; r < Rows; r++)
  349. {
  350. for (uint c = 0; c < Cols; c++)
  351. {
  352. Vector2 scale = GetScale(Size, dst.Size.ToVector2());
  353. dstV = ToVector2(Textures[c, r]) * scale;
  354. Memory.spriteBatch.Draw(Textures[c, r], dstOffset, null, color, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
  355. dstOffset.X += dstV.X;
  356. }
  357. dstOffset.Y += dstV.Y;
  358. }
  359. }
  360. }
  361. /// <summary>
  362. /// Process the texture with the given varibles.
  363. /// <para>Only used by trim and draw.</para>
  364. /// <para>Trim really only needs src varible</para>
  365. /// </summary>
  366. /// <param name="dst"></param>
  367. /// <param name="src"></param>
  368. /// <param name="color"></param>
  369. /// <param name="single"></param>
  370. /// <returns></returns>
  371. private Rectangle _process(
  372. Rectangle dst, Rectangle src, Color color,
  373. Func<Texture2D, Rectangle, Rectangle, Color, Rectangle> single)
  374. {
  375. Rectangle ret = Rectangle.Empty;
  376. if (Memory.IsMainThread) // Some code may only work on main thread.
  377. {
  378. //all extra code is only used for multiple pcs
  379. Vector2 dstOffset = Vector2.Zero; // only if Intersects
  380. Rectangle dst2 = Rectangle.Empty; // only if Intersects
  381. Vector2 offset = Vector2.Zero;
  382. Rectangle cnt = Rectangle.Empty;
  383. for (uint r = 0; r < Rows; r++)
  384. {
  385. bool drawn = false; // only if Intersects
  386. offset.X = 0;
  387. for (uint c = 0; c < Cols; c++)
  388. {
  389. //Start: if were always only one texture pcs
  390. Rectangle _src = Scale(src, ScaleFactor);
  391. cnt = ContainerRectangle(offset, Textures[c, r]);
  392. if (cnt.Contains(_src))
  393. {
  394. _src.Location = (GetOffset(cnt, _src)).ToPoint();
  395. return single(Textures[c, r], dst, _src, color);
  396. }
  397. //End
  398. //This part is for if a given src rectangle overlaps >=2 textures
  399. else if (cnt.Intersects(_src))
  400. {
  401. Rectangle src2 = Rectangle.Intersect(cnt, _src);
  402. src2.Location = (GetOffset(cnt, src2)).ToPoint();
  403. dst2 = Scale(dst, GetScale(_src.Size, src2.Size));
  404. dst2.Location = (dst.Location);
  405. dst2.Offset(dstOffset);
  406. if (ret == Rectangle.Empty)
  407. ret = single(Textures[c, r], dst2, src2, color);
  408. else
  409. Rectangle.Union(ret, single(Textures[c, r], dst2, src2, color));
  410. drawn = true;
  411. dstOffset.X += dst2.Width;
  412. }
  413. offset.X += cnt.Width;
  414. }
  415. offset.Y += cnt.Height;
  416. if (drawn)
  417. dstOffset.Y += dst2.Height;
  418. }
  419. }
  420. else throw new InvalidOperationException($"{this} Must run in main thread.");
  421. return ret;
  422. }
  423. private Rectangle _Trim_SingleTexture(Texture2D tex, Rectangle dst, Rectangle src, Color color)
  424. {
  425. Rectangle ret = Rectangle.Empty;
  426. ret.Offset(-1, -1);
  427. // storage of colors.
  428. Color[] tmp = new Color[src.Width * src.Height];
  429. // colors of all pixels
  430. tex.GetData<Color>(0, src, tmp, 0, tmp.Length);
  431. // max x and y values
  432. int x2 = src.Width;
  433. int y2 = src.Height;
  434. // check each pixel's color
  435. for (int y1 = 0; y1 < y2; y1++)
  436. {
  437. for (int x1 = 0; x1 < x2; x1++)
  438. {
  439. Color a = tmp[x1 + y1 * src.Width];
  440. if (a.A != 0)
  441. {
  442. // grab high and low bounds of non transparent pixels.
  443. if (ret.Y < 0 || ret.X > x1)
  444. {
  445. ret.X = x1;
  446. }
  447. else if (ret.Width == 0 || ret.Width < x1)
  448. ret.Width = x1;
  449. // do same for Y axis.
  450. if (ret.Y < 0 || ret.Y > y1)
  451. {
  452. ret.Y = y1;
  453. }
  454. else if (ret.Height == 0 || ret.Height < y1)
  455. ret.Height = y1;
  456. }
  457. }
  458. }
  459. //using height and width as a bottom and right x/y
  460. //converting them back to height and width.
  461. ret.Width -= ret.X;
  462. ret.Height -= ret.Y;
  463. ret.Width += 1;
  464. ret.Height += 1;
  465. ret.Offset(src.X, src.Y);
  466. ret = Scale(ret, ReverseScaleFactor);
  467. src = Scale(src, ReverseScaleFactor);
  468. return ret;
  469. }
  470. private Rectangle ContainerRectangle(Vector2 offset, Texture2D tex)
  471. {
  472. Rectangle cnt = ToRectangle(tex);
  473. cnt.Offset(offset);
  474. return cnt;
  475. }
  476. private void Init()
  477. {
  478. Size = Vector2.Zero;
  479. Count = Cols * Rows;
  480. Textures = new Texture2D[Cols, Rows];
  481. StartOffset = 0;
  482. //load textures;
  483. Process();
  484. //unload Classic
  485. Classic = null;
  486. //Merge the texture pieces into one.
  487. Merge();
  488. if (!Modded && Memory.EnableDumpingData)
  489. Memory.MainThreadOnlyActions.Enqueue(this.Save);
  490. //if(ScaleFactor.X > ScaleFactor.Y && ScaleFactor.X/ScaleFactor.Y == 2f)
  491. //{
  492. // var t = new Texture2D(Memory.graphics.GraphicsDevice, (int)(ClassicWidth * ScaleFactor.Y), Height);
  493. // var c = new Color[t.Width * t.Height];
  494. // Textures[0, 0].GetData(0, new Rectangle(0, 0, t.Width, t.Height), c, 0, c.Length);
  495. // t.SetData(c);
  496. // Textures[0, 0] = t;
  497. // Memory.MainThreadOnlyActions.Enqueue(this.Save);
  498. //}
  499. }
  500. #endregion Methods
  501. }
  502. }