Background.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. namespace OpenVIII.Fields
  10. {
  11. /// <summary>
  12. /// Background Tiles for field
  13. /// </summary>
  14. /// <see cref="https://github.com/myst6re/deling/blob/master/files/BackgroundFile.cpp"/>
  15. /// <seealso cref="https://github.com/myst6re/deling/blob/master/files/BackgroundFile.h"/>
  16. /// <seealso cref="http://wiki.ffrtt.ru/index.php?title=FF8/FileFormat_MAP"/>
  17. /// <seealso cref="http://wiki.ffrtt.ru/index.php?title=FF8/FileFormat_MIM"/>
  18. /// <seealso cref="http://forums.qhimm.com/index.php?topic=13444.msg264595#msg264595"/>
  19. /// <seealso cref="http://forums.qhimm.com/index.php?topic=13444.0"/>
  20. public partial class Background : IDisposable
  21. {
  22. #region Fields
  23. private const int bytesPerPalette = 2 * colorsPerPalette;
  24. private const int colorsPerPalette = 256;
  25. /// <summary>
  26. /// 4 bit has 2 columns per every byte so it expands to twice the width.
  27. /// </summary>
  28. private const int fourBitTexturePageWidth = 2 * texturePageWidth;
  29. /// <summary>
  30. /// Standard texture page width.
  31. /// </summary>
  32. private const int texturePageWidth = 128;
  33. private Dictionary<byte, List<TileQuadTexture>> Animations;
  34. private AlphaTestEffect ate;
  35. private Vector3 camPosition;
  36. private Vector3 camTarget;
  37. /// <summary>
  38. /// Palettes/Color Lookup Tables
  39. /// </summary>
  40. private Cluts Cluts;
  41. private float degrees;
  42. private bool disposedValue = false;
  43. private BasicEffect effect;
  44. private FPS_Camera fps_camera;
  45. private Rectangle OutputDims;
  46. private Matrix projectionMatrix, viewMatrix, worldMatrix;
  47. private List<TileQuadTexture> quads;
  48. private Dictionary<byte, TextureHandler> TextureIDs;
  49. private Dictionary<TextureIDPaletteID, TextureHandler> TextureIDsPalettes;
  50. private ConcurrentDictionary<ushort, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>>> Textures;
  51. private BackgroundTextureType TextureType;
  52. private Tiles tiles;
  53. #endregion Fields
  54. #region Destructors
  55. // To detect redundant calls
  56. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  57. ~Background()
  58. {
  59. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  60. Dispose(false);
  61. }
  62. #endregion Destructors
  63. #region Properties
  64. public TimeSpan CurrentTime { get; private set; }
  65. public bool HasSpriteBatchTexturesLoaded => drawtextures()?.Count > 0;
  66. public int Height { get => OutputDims.Height; private set => OutputDims.Height = value; }
  67. public bool Is4Bit => tiles?.Any(x => x.Is4Bit) ?? false;
  68. public bool IsAddBlendMode => tiles?.Any(x => x.BlendMode == BlendMode.add) ?? false;
  69. public bool IsHalfBlendMode => tiles?.Any(x => x.BlendMode == BlendMode.halfadd) ?? false;
  70. public bool IsQuarterBlendMode => tiles?.Any(x => x.BlendMode == BlendMode.quarteradd) ?? false;
  71. public bool IsSubtractBlendMode => tiles?.Any(x => x.BlendMode == BlendMode.subtract) ?? false;
  72. public Vector3 MouseLocation { get; private set; }
  73. public TimeSpan TotalTime { get; private set; }
  74. public int Width { get => OutputDims.Width; private set => OutputDims.Width = value; }
  75. #endregion Properties
  76. #region Methods
  77. public static Background Load(byte[] mimb, byte[] mapb)
  78. {
  79. if (mimb == null || mapb == null)
  80. return null;
  81. Background r = new Background
  82. {
  83. TextureType = BackgroundTextureType.GetTextureType(mimb),
  84. ate = new AlphaTestEffect(Memory.graphics.GraphicsDevice),
  85. effect = new BasicEffect(Memory.graphics.GraphicsDevice),
  86. camTarget = Vector3.Zero,
  87. camPosition = new Vector3(0f, 0f, -10f),
  88. fps_camera = new FPS_Camera(),
  89. degrees = 90f
  90. };
  91. r.worldMatrix = Matrix.CreateWorld(r.camPosition, Vector3.
  92. Forward, Vector3.Up);
  93. r.viewMatrix = Matrix.CreateLookAt(r.camPosition, r.camTarget,
  94. Vector3.Up);
  95. r.GetTiles(mapb);
  96. r.GetPalettes(mimb);
  97. Stopwatch watch = Stopwatch.StartNew();
  98. try
  99. {
  100. if (!r.ParseBackgroundQuads(mimb, mapb))
  101. {
  102. return null;
  103. }
  104. }
  105. finally
  106. {
  107. watch.Stop();
  108. Debug.WriteLine($"{nameof(ParseBackgroundQuads)} took {watch.ElapsedMilliseconds / 1000f} seconds.");
  109. }
  110. try
  111. {
  112. if (!r.ParseBackground2D(mimb, mapb))
  113. {
  114. return null;
  115. }
  116. }
  117. finally
  118. {
  119. watch.Stop();
  120. Debug.WriteLine($"{nameof(ParseBackground2D)} took {watch.ElapsedMilliseconds / 1000f} seconds.");
  121. }
  122. return r;
  123. }
  124. // This code added to correctly implement the disposable pattern.
  125. public void Dispose() =>
  126. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  127. Dispose(true);
  128. public void Draw()
  129. {
  130. Memory.spriteBatch.GraphicsDevice.Clear(Color.Black);
  131. DrawBackground();
  132. DrawWalkMesh();
  133. DrawSpriteBatch();
  134. }
  135. public Tiles TilesUnderMouse() => new Tiles(tiles.Where(x =>
  136. x.X < MouseLocation.X && x.X + 16 > MouseLocation.X &&
  137. x.Y < MouseLocation.Y && x.Y + 16 > MouseLocation.Y).ToList());
  138. public void Update()
  139. {
  140. if ((CurrentTime += Memory.gameTime.ElapsedGameTime) > TotalTime)
  141. {
  142. CurrentTime = TimeSpan.Zero;
  143. foreach (KeyValuePair<byte, List<TileQuadTexture>> a in Animations)
  144. {
  145. int i = a.Value.FirstOrDefault(x => x.Enabled)?.AnimationState ?? 0;
  146. int max = a.Value.Max(k => k.AnimationState);
  147. a.Value.Where(x => x.AnimationState == i).ForEach(x => x.Hide());
  148. if (++i >= max)
  149. i = 0;
  150. a.Value.Where(x => x.AnimationState == i).ForEach(x => x.Show());
  151. }
  152. }
  153. float Width = tiles.Width;
  154. float Height = tiles.Height;
  155. if (Module.Toggles.HasFlag(Module._Toggles.Perspective)) //perspective mode shows gabs in the tiles.
  156. {
  157. //finds the min zoom out to fit the entire image in frame.
  158. Vector2 half = new Vector2(Width / 2f, Height / 2f);
  159. float fieldOfView = MathHelper.ToRadians(70);
  160. float getOppositeSide(float side, float angle)
  161. {
  162. return (float)(Math.Tan(angle) * side);
  163. }
  164. half.X = getOppositeSide(half.X, MathHelper.ToRadians(45));
  165. half.Y = getOppositeSide(half.Y, MathHelper.ToRadians(45));
  166. float minDistancefromBG = -Math.Max(half.X, half.Y);
  167. if (camPosition.Z > minDistancefromBG)
  168. camPosition.Z = minDistancefromBG;
  169. projectionMatrix = Matrix.CreatePerspectiveFieldOfView(fieldOfView, Memory.graphics.GraphicsDevice.Viewport.AspectRatio, float.Epsilon, 1000f);
  170. if (!Module.Toggles.HasFlag(Module._Toggles.Menu))
  171. viewMatrix = fps_camera.Update(ref camPosition, ref camTarget, ref degrees);
  172. else viewMatrix = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
  173. }
  174. else
  175. {
  176. Viewport vp = Memory.graphics.GraphicsDevice.Viewport;
  177. Vector2 scale = Memory.Scale(Width, Height, Memory.ScaleMode.FitBoth);
  178. projectionMatrix = Matrix.CreateOrthographic(vp.Width / scale.X, vp.Height / scale.Y, 0f, 100f);
  179. viewMatrix = Matrix.CreateLookAt(Vector3.Forward * 10f, Vector3.Zero, Vector3.Up);
  180. }
  181. Vector2 ml = InputMouse.Location.ToVector2();
  182. MouseLocation = Memory.graphics.GraphicsDevice.Viewport.Unproject(ml.ToVector3(), projectionMatrix, viewMatrix, worldMatrix);
  183. }
  184. protected virtual void Dispose(bool disposing)
  185. {
  186. if (!disposedValue)
  187. {
  188. if (disposing)
  189. {
  190. // TODO: dispose managed state (managed objects).
  191. }
  192. //TextureIDs?.ForEach(x => x.Value?.Dispose());
  193. //TextureIDsPalettes?.ForEach(x => x.Value?.Dispose());
  194. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  195. // TODO: set large fields to null.
  196. disposedValue = true;
  197. }
  198. }
  199. private static Color blend0(Color baseColor, Color color)
  200. {
  201. Color r;
  202. r.R = (byte)MathHelper.Clamp(baseColor.R + color.R / 2, 0, 255);
  203. r.G = (byte)MathHelper.Clamp(baseColor.R + color.G / 2, 0, 255);
  204. r.B = (byte)MathHelper.Clamp(baseColor.B + color.B / 2, 0, 255);
  205. r.A = 0xFF;
  206. return r;
  207. }
  208. private static Color blend1(Color baseColor, Color color)
  209. {
  210. Color r;
  211. r.R = (byte)MathHelper.Clamp(baseColor.R + color.R, 0, 255);
  212. r.G = (byte)MathHelper.Clamp(baseColor.G + color.G, 0, 255);
  213. r.B = (byte)MathHelper.Clamp(baseColor.B + color.B, 0, 255);
  214. r.A = 0xFF;
  215. return r;
  216. }
  217. private static Color blend2(Color baseColor, Color color)
  218. {
  219. Color r;
  220. r.R = (byte)MathHelper.Clamp(baseColor.R - color.R, 0, 255);
  221. r.G = (byte)MathHelper.Clamp(baseColor.G - color.G, 0, 255);
  222. r.B = (byte)MathHelper.Clamp(baseColor.B - color.B, 0, 255);
  223. r.A = 0xFF;
  224. return r;
  225. }
  226. private static Color blend3(Color baseColor, Color color)
  227. {
  228. Color r;
  229. r.R = (byte)MathHelper.Clamp((byte)(baseColor.R + (color.R / 4)), 0, 255);
  230. r.G = (byte)MathHelper.Clamp((byte)(baseColor.G + (color.G / 4)), 0, 255);
  231. r.B = (byte)MathHelper.Clamp((byte)(baseColor.B + (color.B / 4)), 0, 255);
  232. r.A = 0xFF;
  233. return r;
  234. }
  235. private void DrawBackground()
  236. {
  237. if (!Module.Toggles.HasFlag(Module._Toggles.Quad)) return;
  238. Memory.graphics.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
  239. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  240. ate.Projection = projectionMatrix; ate.View = viewMatrix; ate.World = worldMatrix;
  241. effect.Projection = projectionMatrix; effect.View = viewMatrix; effect.World = worldMatrix;
  242. Memory.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  243. effect.TextureEnabled = true;
  244. //seeing if sorting will matter.
  245. IOrderedEnumerable<TileQuadTexture> sorted = quads.Where(x => x.Enabled).OrderByDescending(x => x.GetTile.Z).ThenBy(x => x.GetTile.LayerID).ThenBy(x => x.GetTile.AnimationID).ThenBy(x => x.GetTile.AnimationState).ThenBy(x => x.GetTile.BlendMode);
  246. //foreach (IGrouping<BlendMode, TileQuadTexture> BlendModeGroup in quads.Where(x => x.Enabled).GroupBy(x => x.BlendMode))
  247. ate.VertexColorEnabled = false;
  248. effect.VertexColorEnabled = false;
  249. foreach (TileQuadTexture quad in sorted)
  250. {
  251. Color half = new Color(.5f, .5f, .5f, 1f);
  252. Color quarter = new Color(.25f, .25f, .25f, 1f);
  253. Color full = Color.White;
  254. Tile tile = (Tile)quad;
  255. ate.Texture = quad;
  256. switch (tile.BlendMode)
  257. {
  258. case BlendMode.none:
  259. default:
  260. Memory.graphics.GraphicsDevice.BlendFactor = full;
  261. Memory.graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
  262. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  263. break;
  264. case BlendMode.add:
  265. Memory.graphics.GraphicsDevice.BlendFactor = full;
  266. Memory.graphics.GraphicsDevice.BlendState = Memory.blendState_Add;
  267. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  268. break;
  269. case BlendMode.subtract:
  270. Memory.graphics.GraphicsDevice.BlendFactor = full;
  271. Memory.graphics.GraphicsDevice.BlendState = Memory.blendState_Subtract;
  272. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  273. break;
  274. case BlendMode.halfadd:
  275. Memory.graphics.GraphicsDevice.BlendFactor = half;
  276. Memory.graphics.GraphicsDevice.BlendState = Memory.blendState_Add_BlendFactor;
  277. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  278. break;
  279. case BlendMode.quarteradd:
  280. Memory.graphics.GraphicsDevice.BlendFactor = quarter;
  281. Memory.graphics.GraphicsDevice.BlendState = Memory.blendState_Add_BlendFactor;
  282. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  283. break;
  284. }
  285. foreach (EffectPass pass in ate.CurrentTechnique.Passes)
  286. {
  287. pass.Apply();
  288. Memory.graphics.GraphicsDevice.DrawUserPrimitives(primitiveType: PrimitiveType.TriangleList,
  289. vertexData: (VertexPositionTexture[])quad, vertexOffset: 0, primitiveCount: 2);
  290. }
  291. }
  292. }
  293. private void DrawSpriteBatch()
  294. {
  295. if (!Module.Toggles.HasFlag(Module._Toggles.ClassicSpriteBatch)) return;
  296. List<KeyValuePair<BlendMode, Texture2D>> _drawtextures = drawtextures();
  297. bool open = false;
  298. BlendMode lastbm = BlendMode.none;
  299. float alpha = 1f;
  300. if (_drawtextures != null)
  301. foreach (KeyValuePair<BlendMode, Texture2D> kvp in _drawtextures)
  302. {
  303. if (!open || lastbm != kvp.Key)
  304. {
  305. if (open)
  306. Memory.SpriteBatchEnd();
  307. open = true;
  308. alpha = 1f;
  309. switch (kvp.Key)
  310. {
  311. default:
  312. Memory.SpriteBatchStartAlpha();
  313. break;
  314. case BlendMode.halfadd:
  315. Memory.SpriteBatchStart(bs: Memory.blendState_Add, ss: SamplerState.AnisotropicClamp);
  316. break;
  317. case BlendMode.quarteradd:
  318. Memory.SpriteBatchStart(bs: Memory.blendState_Add, ss: SamplerState.AnisotropicClamp);
  319. break;
  320. case BlendMode.add:
  321. Memory.SpriteBatchStart(bs: Memory.blendState_Add, ss: SamplerState.AnisotropicClamp);
  322. break;
  323. case BlendMode.subtract:
  324. alpha = .9f;
  325. Memory.SpriteBatchStart(bs: Memory.blendState_Subtract, ss: SamplerState.AnisotropicClamp);
  326. break;
  327. }
  328. lastbm = kvp.Key;
  329. }
  330. Texture2D tex = kvp.Value;
  331. Rectangle src = new Rectangle(0, 0, tex.Width, tex.Height);
  332. Rectangle dst = src;
  333. dst.Size = (dst.Size.ToVector2() * Memory.Scale(tex.Width, tex.Height, Memory.ScaleMode.FitBoth)).ToPoint();
  334. //In game I think we'd keep the field from leaving the screen edge but would center on the Squall and the party when it can.
  335. //I setup scaling after noticing the field didn't size with the screen. I set it to center on screen.
  336. dst.Offset(Memory.Center.X - dst.Center.X, Memory.Center.Y - dst.Center.Y);
  337. Memory.spriteBatch.Draw(tex, dst, src, Color.White * alpha);
  338. //new Microsoft.Xna.Framework.Rectangle(0, 0, 1280 + (width - 320), 720 + (height - 224)),
  339. //new Microsoft.Xna.Framework.Rectangle(0, 0, tex.Width, tex.Height)
  340. }
  341. if (open)
  342. Memory.SpriteBatchEnd();
  343. }
  344. private List<KeyValuePair<BlendMode, Texture2D>> drawtextures() =>
  345. Textures?.OrderByDescending(kvp_Z => kvp_Z.Key)
  346. .SelectMany(kvp_LayerID => kvp_LayerID.Value.OrderBy(x => kvp_LayerID.Key)
  347. .SelectMany(kvp_AnimationID => kvp_AnimationID.Value.OrderBy(x => kvp_AnimationID.Key))
  348. .SelectMany(kvp_AnimationState => kvp_AnimationState.Value.OrderBy(x => kvp_AnimationState.Key))
  349. .SelectMany(kvp_OverlapID => kvp_OverlapID.Value.OrderBy(x => kvp_OverlapID.Key))
  350. .SelectMany(kvp_BlendMode => kvp_BlendMode.Value)).ToList();
  351. private void DrawWalkMesh()
  352. {
  353. if (!Module.Toggles.HasFlag(Module._Toggles.WalkMesh)) return;
  354. effect.TextureEnabled = false;
  355. Memory.graphics.GraphicsDevice.BlendFactor = Color.White;
  356. Memory.graphics.GraphicsDevice.BlendState = BlendState.Opaque;
  357. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  358. //using (DepthStencilState depthStencilState = new DepthStencilState() { DepthBufferEnable = true })
  359. using (RasterizerState rasterizerState = new RasterizerState() { CullMode = CullMode.None })
  360. {
  361. Memory.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;//depthStencilState;
  362. Memory.graphics.GraphicsDevice.RasterizerState = rasterizerState;
  363. ate.Texture = null;
  364. ate.VertexColorEnabled = true;
  365. effect.VertexColorEnabled = true;
  366. //camPosition = Module.Cameras[0].Position;
  367. effect.World = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);// Module.Cameras[0].CreateWorld();
  368. float fieldOfView = MathHelper.ToRadians(70);
  369. //effect.View = //Module.Cameras[0].CreateLookAt();
  370. //effect.Projection = Module.Cameras[0].CreateProjection();
  371. effect.Projection = Matrix.CreatePerspectiveFieldOfView(fieldOfView, Memory.graphics.GraphicsDevice.Viewport.AspectRatio, float.Epsilon, 1000f);
  372. if (!Module.Toggles.HasFlag(Module._Toggles.Menu))
  373. effect.View = fps_camera.Update(ref camPosition, ref camTarget, ref degrees);
  374. else
  375. effect.View = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
  376. foreach (EffectPass pass in effect.CurrentTechnique.Passes)
  377. {
  378. pass.Apply();
  379. Memory.graphics.GraphicsDevice.DrawUserPrimitives(primitiveType: PrimitiveType.TriangleList,
  380. vertexData: Module.WalkMesh.Vertices.ToArray(), vertexOffset: 0, primitiveCount: Module.WalkMesh.Count);
  381. }
  382. }
  383. }
  384. private void FindOverlappingTiles() => (from t1 in tiles
  385. from t2 in tiles
  386. where t1.TileID < t2.TileID
  387. where t1.BlendMode == BlendMode.none
  388. where t1.Intersect(t2)
  389. orderby t1.TileID, t2.TileID ascending
  390. select new[] { t1, t2 }
  391. ).ForEach(x => x[1].OverLapID = checked((byte)(x[0].OverLapID + 1)));
  392. private byte GetColorKey(byte[] mimb, int textureWidth, int startPixel, int x, int y, bool is8Bit)
  393. {
  394. if (is8Bit)
  395. return mimb[startPixel + x + (y * textureWidth)];
  396. else
  397. {
  398. byte tempKey = mimb[startPixel + x / 2 + (y * textureWidth)];
  399. if (x % 2 == 1)
  400. return checked((byte)((tempKey & 0xf0) >> 4));
  401. else
  402. return checked((byte)(tempKey & 0xf));
  403. }
  404. }
  405. private void GetPalettes(byte[] mimb)
  406. {
  407. int Offset = TextureType?.BytesSkippedPalettes ?? 0;
  408. Cluts CLUT = tiles != null ? new Cluts(tiles.Select(x => x.PaletteID).Distinct().ToDictionary(x => x, x => new Color[colorsPerPalette]), false) :
  409. new Cluts(Enumerable.Range(0, 15).Select(x => (byte)x).ToDictionary(x => x, x => new Color[colorsPerPalette]), false);
  410. using (BinaryReader br = new BinaryReader(new MemoryStream(mimb)))
  411. foreach (KeyValuePair<byte, Color[]> clut in CLUT)
  412. {
  413. int palettePointer = Offset + ((clut.Key) * bytesPerPalette);
  414. br.BaseStream.Seek(palettePointer, SeekOrigin.Begin);
  415. for (int i = 0; i < colorsPerPalette; i++)
  416. clut.Value[i] = Texture_Base.ABGR1555toRGBA32bit(br.ReadUInt16());
  417. }
  418. Cluts = CLUT;
  419. }
  420. private TextureHandler GetTexture(Tile tile)
  421. {
  422. if (TextureIDsPalettes != null)
  423. {
  424. TextureHandler tidp = TextureIDsPalettes.FirstOrDefault(x => x.Key.PaletteID == tile.PaletteID && x.Key.TextureID == tile.TextureID).Value;
  425. if (tidp != default)
  426. return tidp;
  427. }
  428. if (TextureIDs != null)
  429. {
  430. TextureHandler tid = TextureIDs.FirstOrDefault(x => x.Key == tile.TextureID).Value;
  431. if (tid != default)
  432. return tid;
  433. }
  434. return null;
  435. }
  436. private bool GetTextureType(byte[] mimb, byte[] mapb)
  437. {
  438. if (mimb == null || mapb == null)
  439. return false;
  440. TextureType = BackgroundTextureType.GetTextureType(mimb);
  441. if (TextureType == default)
  442. {//unsupported feild dump data so can check it.
  443. string path = Path.Combine(Path.GetTempPath(), "Fields", $"{Memory.FieldHolder.fields[Memory.FieldHolder.FieldID]}");
  444. using (BinaryWriter bw = new BinaryWriter(new FileStream($"{path}.mim", FileMode.Create, FileAccess.Write, FileShare.ReadWrite)))
  445. {
  446. bw.Write(mimb);
  447. Debug.WriteLine($"Saved {path}.mim");
  448. }
  449. using (BinaryWriter bw = new BinaryWriter(new FileStream($"{path}.map", FileMode.Create, FileAccess.Write, FileShare.ReadWrite)))
  450. {
  451. bw.Write(mapb);
  452. Debug.WriteLine($"Saved {path}.map");
  453. }
  454. return false;
  455. }
  456. return true;
  457. }
  458. private void GetTiles(byte[] mapb) => tiles = mapb == null ? default : Tiles.Load(mapb, TextureType.Type);
  459. private bool ParseBackground2D(byte[] mimb, byte[] mapb)
  460. {
  461. if (!Module.Toggles.HasFlag(Module._Toggles.ClassicSpriteBatch)) return true;
  462. if (mimb == null || mapb == null)
  463. return false;
  464. FindOverlappingTiles();
  465. //FindSameXYTilesSource();
  466. Point lowest = new Point(tiles.Min(x => x.X), tiles.Min(x => x.Y));
  467. Point maximum = new Point(tiles.Max(x => x.X), tiles.Max(x => x.Y));
  468. Height = Math.Abs(lowest.Y) + maximum.Y + Tile.size; //224
  469. Width = Math.Abs(lowest.X) + maximum.X + Tile.size; //320
  470. //Color[] finalImage = new Color[height * width]; //ARGB;
  471. //Color[] finalOverlapImage = new Color[height * width];
  472. //tex = new Texture2D(Memory.graphics.GraphicsDevice, width, height);
  473. //texOverlap = new Texture2D(Memory.graphics.GraphicsDevice, width, height);
  474. IOrderedEnumerable<byte> layers = tiles.Select(x => x.LayerID).Distinct().OrderBy(x => x);
  475. Debug.WriteLine($"FieldID: {Memory.FieldHolder.FieldID}, Layers: {layers.Count()}, ({string.Join(",", layers.ToArray())}) ");
  476. byte MaximumLayer = layers.Max();
  477. byte MinimumLayer = layers.Min();
  478. IOrderedEnumerable<ushort> BufferDepth = tiles.Select(x => x.Z).Distinct().OrderByDescending(x => x); // larger number is farther away.
  479. List<Tile> sortedtiles = tiles.OrderBy(x => x.OverLapID).ThenByDescending(x => x.Z).ThenBy(x => x.LayerID).ThenBy(x => x.AnimationID).ThenBy(x => x.AnimationState).ThenBy(x => x.BlendMode).ToList();
  480. if (Textures != null)
  481. {
  482. foreach (Texture2D tex in drawtextures().Select(x => x.Value))
  483. tex.Dispose();
  484. }
  485. Textures = new ConcurrentDictionary<ushort, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>>>();
  486. ushort z = 0;
  487. byte layerID = 0;
  488. byte animationID = 0;
  489. byte animationState = 0;
  490. byte overlapID = 0;
  491. BlendMode blendmode = BlendMode.none;
  492. TextureBuffer texturebuffer = null;
  493. bool hasColor = false;
  494. void convertColorToTexture2d()
  495. {
  496. if (!hasColor || texturebuffer == null) return;
  497. hasColor = false;
  498. ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>> dictLayerID = Textures.GetOrAdd(z, new ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>>());
  499. ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>> dictAnimationID = dictLayerID.GetOrAdd(layerID, new ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>());
  500. ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>> dictAnimationState = dictAnimationID.GetOrAdd(animationID, new ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>());
  501. ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>> dictOverlapID = dictAnimationState.GetOrAdd(animationState, new ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>());
  502. ConcurrentDictionary<BlendMode, Texture2D> dictblend = dictOverlapID.GetOrAdd(overlapID, new ConcurrentDictionary<BlendMode, Texture2D>());
  503. Texture2D tex = dictblend.GetOrAdd(blendmode, new Texture2D(Memory.graphics.GraphicsDevice, Width, Height));
  504. texturebuffer.SetData(tex);
  505. }
  506. for (int i = 0; i < sortedtiles.Count; i++)
  507. {
  508. Tile previousTile = (i > 0) ? previousTile = sortedtiles[i - 1] : null;
  509. Tile tile = sortedtiles[i];
  510. if (texturebuffer == null || previousTile == null ||
  511. (previousTile.Z != tile.Z ||
  512. previousTile.LayerID != tile.LayerID ||
  513. previousTile.BlendMode != tile.BlendMode ||
  514. previousTile.AnimationID != tile.AnimationID ||
  515. previousTile.AnimationState != tile.AnimationState ||
  516. previousTile.OverLapID != tile.OverLapID))
  517. {
  518. convertColorToTexture2d();
  519. texturebuffer = new TextureBuffer(Width, Height, false);
  520. z = tile.Z;
  521. layerID = tile.LayerID;
  522. blendmode = tile.BlendMode;
  523. animationID = tile.AnimationID;
  524. animationState = tile.AnimationState;
  525. overlapID = tile.OverLapID;
  526. }
  527. int palettePointer = TextureType.BytesSkippedPalettes + ((tile.PaletteID) * bytesPerPalette);
  528. int sourceImagePointer = bytesPerPalette * TextureType.Palettes;
  529. const int texturewidth = 128;
  530. int startPixel = sourceImagePointer + tile.SourceX + texturewidth * tile.TextureID + (TextureType.Width * tile.SourceY);
  531. Point real = new Point(Math.Abs(lowest.X) + tile.X, Math.Abs(lowest.Y) + tile.Y);
  532. int realDestinationPixel = ((real.Y * Width) + real.X);
  533. Rectangle dst = new Rectangle(real.X, real.Y, Tile.size, Tile.size);
  534. if (tile.Is4Bit)
  535. {
  536. startPixel -= tile.SourceX / 2;
  537. }
  538. for (int y = 0; y < Tile.size; y++)
  539. for (int x = 0; x < Tile.size; x++)
  540. {
  541. byte colorKey = GetColorKey(mimb, TextureType.Width, startPixel, x, y, tile.Is8Bit);
  542. ushort color16bit = BitConverter.ToUInt16(mimb, 2 * colorKey + palettePointer);
  543. if (color16bit == 0) // 0 is Color.TransparentBlack So we skip it.
  544. continue;
  545. Color color = Texture_Base.ABGR1555toRGBA32bit(color16bit);
  546. int pos = realDestinationPixel + (x) + (y * Width);
  547. Color bufferedcolor = texturebuffer[pos];
  548. if (blendmode < BlendMode.none)
  549. {
  550. if (color == Color.Black)
  551. continue;
  552. if (blendmode == BlendMode.subtract)
  553. {
  554. if (bufferedcolor != Color.TransparentBlack)
  555. color = blend2(bufferedcolor, color);
  556. }
  557. else
  558. {
  559. if (blendmode == BlendMode.quarteradd)
  560. color = Color.Multiply(color, .25f);
  561. else if (blendmode == BlendMode.halfadd)
  562. color = Color.Multiply(color, .5f);
  563. if (bufferedcolor != Color.TransparentBlack)
  564. color = blend1(bufferedcolor, color);
  565. }
  566. }
  567. else if (bufferedcolor != Color.TransparentBlack)
  568. {
  569. throw new Exception("Color is already set something may be wrong.");
  570. }
  571. color.A = 0xFF;
  572. texturebuffer[pos] = color;
  573. hasColor = true;
  574. }
  575. }
  576. convertColorToTexture2d(); // gets leftover colors from last batch and makes a texture.
  577. SaveTextures();
  578. return true;
  579. }
  580. private bool ParseBackgroundQuads(byte[] mimb, byte[] mapb)
  581. {
  582. if (mimb == null || mapb == null)
  583. return false;
  584. //FindOverlappingTiles();
  585. var UniqueSetOfTileData = tiles.Select(x => new { x.TextureID, loc = new Point(x.SourceX, x.SourceY), x.Is4Bit, x.PaletteID, x.AnimationID }).Distinct().ToList();
  586. // Create a swizzeled Textures with one palette.
  587. // 4bit has 2 pixels per byte. So will need a seperate texture for those.
  588. Width = UniqueSetOfTileData.Max(x => x.loc.X + Tile.size);
  589. Height = UniqueSetOfTileData.Max(x => x.loc.Y + Tile.size);
  590. Dictionary<byte, Texture2D> TextureIDs = UniqueSetOfTileData.Select(x => x.TextureID).Distinct().ToDictionary(x => x, x => new Texture2D(Memory.graphics.GraphicsDevice, 256, 256));
  591. //var dup = (from t1 in UniqueSetOfTileData
  592. // from t2 in UniqueSetOfTileData
  593. // where t1 != t2 && t1.TextureID == t1.TextureID && t1.loc == t2.loc
  594. // select new[] { t1, t2 }).ToList();
  595. //foreach(var i in UniqueSetOfTileData.GroupBy(x => x.TextureID))
  596. //{
  597. // foreach(var j in i.GroupBy(x=>x.loc))
  598. // {
  599. // var m = j.ToList();
  600. // if(m.Count>1 && m[0].loc.X == 240 && m[0].loc.Y == 192)
  601. // {
  602. // m[1].PaletteID = 5;
  603. // }
  604. // }
  605. //}
  606. bool overlap = false;
  607. using (BinaryReader br = new BinaryReader(new MemoryStream(mimb)))
  608. {
  609. foreach (KeyValuePair<byte, Texture2D> kvp in TextureIDs)
  610. {
  611. GenTexture(kvp.Key, kvp.Value);
  612. }
  613. SaveSwizzled(TextureIDs);
  614. string fieldname = Module.GetFieldName();
  615. this.TextureIDs = TextureIDs.ToDictionary(x => x.Key, x => TextureHandler.Create($"{ fieldname }_{x.Key}", new Texture2DWrapper(x.Value), ushort.MaxValue));
  616. SaveCluts();
  617. if (overlap)
  618. {
  619. Dictionary<TextureIDPaletteID, Texture2D> TextureIDsPalettes = UniqueSetOfTileData.Where(x => x.AnimationID != 0xFF || x.Is4Bit).Select(x => new TextureIDPaletteID { TextureID = x.TextureID, PaletteID = x.PaletteID }).Distinct().ToDictionary(x => x, x => new Texture2D(Memory.graphics.GraphicsDevice, 256, 256));
  620. this.TextureIDsPalettes = TextureIDsPalettes.ToDictionary(x => x.Key, x => TextureHandler.Create($"{ fieldname }_{x.Key.TextureID}", new Texture2DWrapper(x.Value), x.Key.PaletteID));
  621. foreach (KeyValuePair<TextureIDPaletteID, Texture2D> kvp in TextureIDsPalettes)
  622. {
  623. GenTexture(kvp.Key.TextureID, kvp.Value, kvp.Key.PaletteID);
  624. }
  625. foreach (IGrouping<byte, KeyValuePair<TextureIDPaletteID, Texture2D>> groups in TextureIDsPalettes.Where(x => TextureIDsPalettes.Count(y => y.Key.TextureID == x.Key.TextureID) > 1).GroupBy(x => x.Key.PaletteID))
  626. foreach (KeyValuePair<TextureIDPaletteID, Texture2D> kvp_group in groups)
  627. {
  628. Dictionary<byte, Texture2D> _TextureIDs = groups.ToDictionary(x => x.Key.TextureID, x => x.Value);
  629. SaveSwizzled(_TextureIDs, $"_{kvp_group.Key.PaletteID}");
  630. break;
  631. }
  632. }
  633. void GenTexture(byte texID, Texture2D tex2d, byte? inpaletteID = null)
  634. {
  635. TextureBuffer tex = new TextureBuffer(tex2d.Width, tex2d.Height, true);
  636. //foreach (var textureID in UniqueSetOfTileData.GroupBy(x=>x.TextureID == kvp.Key))
  637. foreach (var tile in UniqueSetOfTileData.Where(x => x.TextureID == texID && (!inpaletteID.HasValue || inpaletteID.Value == x.PaletteID)))
  638. {
  639. long startPixel = TextureType.PaletteSectionSize + (tile.loc.X / (tile.Is4Bit ? 2 : 1)) + (texturePageWidth * tile.TextureID) + (TextureType.Width * tile.loc.Y);
  640. //int readlength = Tile.size + (Tile.size * TextureType.Width);
  641. for (int y = 0; y < 16; y++)
  642. {
  643. br.BaseStream.Seek(startPixel + (y * TextureType.Width), SeekOrigin.Begin);
  644. byte Colorkey = 0;
  645. int _y = y + tile.loc.Y;
  646. for (int x = 0; x < 16; x++)
  647. {
  648. int _x = x + tile.loc.X;
  649. byte paletteID = tile.PaletteID;
  650. //if (tile.loc.X == 240 && tile.loc.Y == 192)
  651. // paletteID = 9;
  652. Color color = default;
  653. if (!tile.Is4Bit)
  654. {
  655. color = Cluts[paletteID][br.ReadByte()];
  656. }
  657. else
  658. {
  659. if (x % 2 == 0)
  660. {
  661. Colorkey = br.ReadByte();
  662. color = Cluts[paletteID][Colorkey & 0xf];
  663. }
  664. else
  665. {
  666. color = Cluts[paletteID][(Colorkey & 0xf0) >> 4];
  667. }
  668. }
  669. if (color != Color.TransparentBlack)
  670. {
  671. if (tex[_x, _y] != Color.TransparentBlack)
  672. {
  673. //if ()//excluding 8bit overlap for now.
  674. overlap = true;
  675. if (tex[_x, _y] != color)
  676. {
  677. Debug.WriteLine($"x={_x},y={_y} :: {Memory.FieldHolder.fields[Memory.FieldHolder.FieldID]} :: {tile} \n existed_color {tex[_x, _y]} :: failed_color={color}");
  678. break;
  679. }
  680. }
  681. else
  682. tex[_x, _y] = color;
  683. }
  684. }
  685. }
  686. //(from b in br.ReadBytes(readlength)
  687. // select dictPalettes[tile.PaletteID][b]).ToArray();
  688. }
  689. tex.SetData(tex2d);
  690. }
  691. }
  692. //Memory.Scale(Width, Height, Memory.ScaleMode.FitBoth).X
  693. quads = tiles.Select(x => new TileQuadTexture(x, GetTexture(x), 1f)).ToList();
  694. Animations = quads.Where(x => x.AnimationID != 0xFF).Select(x => x.AnimationID).Distinct().ToDictionary(x => x, x => quads.Where(y => y.AnimationID == x).OrderBy(y => y.AnimationState).ToList());
  695. Animations.ForEach(x => x.Value.Where(y => y.AnimationState != x.Value.Max(k => k.AnimationState)).ForEach(y => y.Hide()));
  696. TotalTime = TimeSpan.FromMilliseconds(1000f / 10f);
  697. CurrentTime = TimeSpan.Zero;
  698. return true;
  699. }
  700. private void SaveCluts()
  701. {
  702. if (Memory.EnableDumpingData || Module.Toggles.HasFlag(Module._Toggles.DumpingData))
  703. {
  704. string path = Path.Combine(Module.GetFolder(),
  705. $"{Module.GetFieldName()}_Clut.png");
  706. Cluts.Save(path);
  707. }
  708. }
  709. private void SaveSwizzled(Dictionary<byte, Texture2D> _TextureIDs, string suf = "")
  710. {
  711. if (Memory.EnableDumpingData || Module.Toggles.HasFlag(Module._Toggles.DumpingData))
  712. {
  713. string fieldname = Module.GetFieldName();
  714. string folder = Module.GetFolder(fieldname);
  715. string path;
  716. foreach (KeyValuePair<byte, Texture2D> kvp in _TextureIDs)
  717. {
  718. path = Path.Combine(folder,
  719. $"{fieldname}_{kvp.Key}{suf}.png");
  720. if (File.Exists(path))
  721. continue;
  722. using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
  723. { kvp.Value.SaveAsPng(fs, kvp.Value.Width, kvp.Value.Height); }
  724. }
  725. }
  726. }
  727. //private void SaveSwizzled(string suf = "") => SaveSwizzled(TextureIDs, suf);
  728. private void SaveTextures()
  729. {
  730. if (Memory.EnableDumpingData || (Module.Toggles.HasFlag(Module._Toggles.DumpingData) && Module.Toggles.HasFlag(Module._Toggles.Deswizzle)))
  731. {
  732. string fieldname = Module.GetFieldName();
  733. string folder = Module.GetFolder(fieldname);
  734. string path;
  735. //List<KeyValuePair<BlendModes, Texture2D>> _drawtextures = drawtextures();
  736. foreach (KeyValuePair<ushort, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>>> kvp_Z in Textures)
  737. foreach (KeyValuePair<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>>> kvp_Layer in kvp_Z.Value)
  738. foreach (KeyValuePair<byte, ConcurrentDictionary<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>>> kvp_AnimationID in kvp_Layer.Value)
  739. foreach (KeyValuePair<byte, ConcurrentDictionary<byte, ConcurrentDictionary<BlendMode, Texture2D>>> kvp_AnimationState in kvp_AnimationID.Value)
  740. foreach (KeyValuePair<byte, ConcurrentDictionary<BlendMode, Texture2D>> kvp_OverlapID in kvp_AnimationState.Value)
  741. foreach (KeyValuePair<BlendMode, Texture2D> kvp in kvp_OverlapID.Value)
  742. {
  743. path = Path.Combine(folder,
  744. $"{fieldname}_{kvp_Z.Key.ToString("D4")}.{kvp_Layer.Key}.{kvp_AnimationID.Key}.{kvp_AnimationState.Key}.{kvp_OverlapID.Key}.{(int)kvp.Key}.png");
  745. using (FileStream fs = new FileStream(path,
  746. FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
  747. kvp.Value.SaveAsPng(
  748. fs,
  749. kvp.Value.Width, kvp.Value.Height);
  750. }
  751. }
  752. }
  753. #endregion Methods
  754. // TODO: uncomment the following line if the finalizer is overridden above.// GC.SuppressFinalize(this);
  755. }
  756. }