DynamicTextureModule.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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.Drawing;
  30. using System.Drawing.Drawing2D;
  31. using System.Drawing.Imaging;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenMetaverse.Imaging;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using log4net;
  39. using System.Reflection;
  40. using Mono.Addins;
  41. namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
  42. {
  43. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")]
  44. public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager
  45. {
  46. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private const int ALL_SIDES = -1;
  48. public const int DISP_EXPIRE = 1;
  49. public const int DISP_TEMP = 2;
  50. /// <summary>
  51. /// If true then where possible dynamic textures are reused.
  52. /// </summary>
  53. public bool ReuseTextures { get; set; }
  54. /// <summary>
  55. /// If false, then textures which have a low data size are not reused when ReuseTextures = true.
  56. /// </summary>
  57. /// <remarks>
  58. /// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those
  59. /// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen
  60. /// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is
  61. /// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused
  62. /// to work around this problem.</remarks>
  63. public bool ReuseLowDataTextures { get; set; }
  64. private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>();
  65. private Dictionary<string, IDynamicTextureRender> RenderPlugins =
  66. new Dictionary<string, IDynamicTextureRender>();
  67. private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>();
  68. /// <summary>
  69. /// Record dynamic textures that we can reuse for a given data and parameter combination rather than
  70. /// regenerate.
  71. /// </summary>
  72. /// <remarks>
  73. /// Key is string.Format("{0}{1}", data
  74. /// </remarks>
  75. private Cache m_reuseableDynamicTextures;
  76. /// <summary>
  77. /// This constructor is only here because of the Unit Tests...
  78. /// Don't use it.
  79. /// </summary>
  80. public DynamicTextureModule()
  81. {
  82. m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
  83. m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
  84. }
  85. #region IDynamicTextureManager Members
  86. public void RegisterRender(string handleType, IDynamicTextureRender render)
  87. {
  88. if (!RenderPlugins.ContainsKey(handleType))
  89. {
  90. RenderPlugins.Add(handleType, render);
  91. }
  92. }
  93. /// <summary>
  94. /// Called by code which actually renders the dynamic texture to supply texture data.
  95. /// </summary>
  96. /// <param name="updaterId"></param>
  97. /// <param name="texture"></param>
  98. public void ReturnData(UUID updaterId, IDynamicTexture texture)
  99. {
  100. DynamicTextureUpdater updater = null;
  101. lock (Updaters)
  102. {
  103. if (Updaters.ContainsKey(updaterId))
  104. {
  105. updater = Updaters[updaterId];
  106. }
  107. }
  108. if (updater != null)
  109. {
  110. if (RegisteredScenes.ContainsKey(updater.SimUUID))
  111. {
  112. Scene scene = RegisteredScenes[updater.SimUUID];
  113. UUID newTextureID = updater.DataReceived(texture.Data, scene);
  114. if (ReuseTextures
  115. && !updater.BlendWithOldTexture
  116. && texture.IsReuseable
  117. && (ReuseLowDataTextures || IsDataSizeReuseable(texture)))
  118. {
  119. m_reuseableDynamicTextures.Store(
  120. GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID);
  121. }
  122. updater.newTextureID = newTextureID;
  123. }
  124. lock (Updaters)
  125. {
  126. if (Updaters.ContainsKey(updater.UpdaterID))
  127. Updaters.Remove(updater.UpdaterID);
  128. }
  129. }
  130. }
  131. /// <summary>
  132. /// Determines whether the texture is reuseable based on its data size.
  133. /// </summary>
  134. /// <remarks>
  135. /// This is a workaround for a viewer bug where very small data size textures relative to their pixel size
  136. /// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard
  137. /// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5).
  138. /// </remarks>
  139. /// <returns></returns>
  140. private bool IsDataSizeReuseable(IDynamicTexture texture)
  141. {
  142. // Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height);
  143. int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5);
  144. // m_log.DebugFormat(
  145. // "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}",
  146. // discardLevel2DataThreshold, texture.Data.Length);
  147. return discardLevel2DataThreshold < texture.Data.Length;
  148. }
  149. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  150. string extraParams)
  151. {
  152. return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, false, 255);
  153. }
  154. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  155. string extraParams, bool SetBlending, byte AlphaValue)
  156. {
  157. return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, SetBlending,
  158. (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
  159. }
  160. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  161. string extraParams, bool SetBlending,
  162. int disp, byte AlphaValue, int face)
  163. {
  164. if (RenderPlugins.ContainsKey(contentType))
  165. {
  166. DynamicTextureUpdater updater = new DynamicTextureUpdater();
  167. updater.SimUUID = simID;
  168. updater.PrimID = primID;
  169. updater.ContentType = contentType;
  170. updater.Url = url;
  171. updater.UpdaterID = UUID.Random();
  172. updater.Params = extraParams;
  173. updater.BlendWithOldTexture = SetBlending;
  174. updater.FrontAlpha = AlphaValue;
  175. updater.Face = face;
  176. updater.Disp = disp;
  177. lock (Updaters)
  178. {
  179. if (!Updaters.ContainsKey(updater.UpdaterID))
  180. {
  181. Updaters.Add(updater.UpdaterID, updater);
  182. }
  183. }
  184. RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
  185. return updater.newTextureID;
  186. }
  187. return UUID.Zero;
  188. }
  189. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  190. string extraParams)
  191. {
  192. return AddDynamicTextureData(simID, primID, contentType, data, extraParams, false,
  193. (DISP_TEMP|DISP_EXPIRE), 255, ALL_SIDES);
  194. }
  195. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  196. string extraParams, bool SetBlending, byte AlphaValue)
  197. {
  198. return AddDynamicTextureData(simID, primID, contentType, data, extraParams, SetBlending,
  199. (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
  200. }
  201. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  202. string extraParams, bool SetBlending, int disp, byte AlphaValue, int face)
  203. {
  204. if (!RenderPlugins.ContainsKey(contentType))
  205. return UUID.Zero;
  206. Scene scene;
  207. RegisteredScenes.TryGetValue(simID, out scene);
  208. if (scene == null)
  209. return UUID.Zero;
  210. SceneObjectPart part = scene.GetSceneObjectPart(primID);
  211. if (part == null)
  212. return UUID.Zero;
  213. // If we want to reuse dynamic textures then we have to ignore any request from the caller to expire
  214. // them.
  215. if (ReuseTextures)
  216. disp = disp & ~DISP_EXPIRE;
  217. DynamicTextureUpdater updater = new DynamicTextureUpdater();
  218. updater.SimUUID = simID;
  219. updater.PrimID = primID;
  220. updater.ContentType = contentType;
  221. updater.BodyData = data;
  222. updater.UpdaterID = UUID.Random();
  223. updater.Params = extraParams;
  224. updater.BlendWithOldTexture = SetBlending;
  225. updater.FrontAlpha = AlphaValue;
  226. updater.Face = face;
  227. updater.Url = "Local image";
  228. updater.Disp = disp;
  229. object objReusableTextureUUID = null;
  230. if (ReuseTextures && !updater.BlendWithOldTexture)
  231. {
  232. string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams);
  233. objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey);
  234. if (objReusableTextureUUID != null)
  235. {
  236. // If something else has removed this temporary asset from the cache, detect and invalidate
  237. // our cached uuid.
  238. if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null)
  239. {
  240. m_reuseableDynamicTextures.Invalidate(reuseableTextureKey);
  241. objReusableTextureUUID = null;
  242. }
  243. }
  244. }
  245. // We cannot reuse a dynamic texture if the data is going to be blended with something already there.
  246. if (objReusableTextureUUID == null)
  247. {
  248. lock (Updaters)
  249. {
  250. if (!Updaters.ContainsKey(updater.UpdaterID))
  251. {
  252. Updaters.Add(updater.UpdaterID, updater);
  253. }
  254. }
  255. // m_log.DebugFormat(
  256. // "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}",
  257. // part.Name, part.ParentGroup.Scene.Name);
  258. RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
  259. }
  260. else
  261. {
  262. // m_log.DebugFormat(
  263. // "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}",
  264. // objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name);
  265. // No need to add to updaters as the texture is always the same. Not that this functionality
  266. // apppears to be implemented anyway.
  267. updater.UpdatePart(part, (UUID)objReusableTextureUUID);
  268. }
  269. return updater.newTextureID;
  270. }
  271. private string GenerateReusableTextureKey(string data, string extraParams)
  272. {
  273. return string.Format("{0}{1}", data, extraParams);
  274. }
  275. public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
  276. out double xSize, out double ySize)
  277. {
  278. xSize = 0;
  279. ySize = 0;
  280. if (RenderPlugins.ContainsKey(contentType))
  281. {
  282. RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
  283. }
  284. }
  285. #endregion
  286. #region ISharedRegionModule Members
  287. public void Initialise(IConfigSource config)
  288. {
  289. IConfig texturesConfig = config.Configs["Textures"];
  290. if (texturesConfig != null)
  291. {
  292. ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false);
  293. ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false);
  294. if (ReuseTextures)
  295. {
  296. m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
  297. m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
  298. }
  299. }
  300. }
  301. public void PostInitialise()
  302. {
  303. }
  304. public void AddRegion(Scene scene)
  305. {
  306. if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
  307. {
  308. RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
  309. scene.RegisterModuleInterface<IDynamicTextureManager>(this);
  310. }
  311. }
  312. public void RegionLoaded(Scene scene)
  313. {
  314. }
  315. public void RemoveRegion(Scene scene)
  316. {
  317. if (RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
  318. RegisteredScenes.Remove(scene.RegionInfo.RegionID);
  319. }
  320. public void Close()
  321. {
  322. }
  323. public string Name
  324. {
  325. get { return "DynamicTextureModule"; }
  326. }
  327. public Type ReplaceableInterface
  328. {
  329. get { return null; }
  330. }
  331. #endregion
  332. #region Nested type: DynamicTextureUpdater
  333. public class DynamicTextureUpdater
  334. {
  335. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  336. public bool BlendWithOldTexture = false;
  337. public string BodyData;
  338. public string ContentType;
  339. public byte FrontAlpha = 255;
  340. public string Params;
  341. public UUID PrimID;
  342. public UUID SimUUID;
  343. public UUID UpdaterID;
  344. public int Face;
  345. public int Disp;
  346. public string Url;
  347. public UUID newTextureID;
  348. public DynamicTextureUpdater()
  349. {
  350. BodyData = null;
  351. }
  352. /// <summary>
  353. /// Update the given part with the new texture.
  354. /// </summary>
  355. /// <returns>
  356. /// The old texture UUID.
  357. /// </returns>
  358. public UUID UpdatePart(SceneObjectPart part, UUID textureID)
  359. {
  360. UUID oldID;
  361. lock (part)
  362. {
  363. // mostly keep the values from before
  364. Primitive.TextureEntry tmptex = part.Shape.Textures;
  365. // FIXME: Need to return the appropriate ID if only a single face is replaced.
  366. oldID = tmptex.DefaultTexture.TextureID;
  367. // not using parts number of faces because that fails on old meshs
  368. if (Face == ALL_SIDES)
  369. {
  370. oldID = tmptex.DefaultTexture.TextureID;
  371. tmptex.DefaultTexture.TextureID = textureID;
  372. for(int i = 0; i < tmptex.FaceTextures.Length; i++)
  373. {
  374. if(tmptex.FaceTextures[i] != null)
  375. tmptex.FaceTextures[i].TextureID = textureID;
  376. }
  377. }
  378. else
  379. {
  380. try
  381. {
  382. Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
  383. oldID = texface.TextureID;
  384. texface.TextureID = textureID;
  385. tmptex.FaceTextures[Face] = texface;
  386. }
  387. catch (Exception)
  388. {
  389. tmptex.DefaultTexture.TextureID = textureID;
  390. }
  391. }
  392. part.UpdateTextureEntry(tmptex);
  393. }
  394. return oldID;
  395. }
  396. /// <summary>
  397. /// Called once new texture data has been received for this updater.
  398. /// </summary>
  399. /// <param name="data"></param>
  400. /// <param name="scene"></param>
  401. /// <param name="isReuseable">True if the data given is reuseable.</param>
  402. /// <returns>The asset UUID given to the incoming data.</returns>
  403. public UUID DataReceived(byte[] data, Scene scene)
  404. {
  405. // this are local assets and will not work without cache
  406. IAssetCache iac = scene.RequestModuleInterface<IAssetCache>();
  407. if (iac == null)
  408. return UUID.Zero;
  409. SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
  410. if (part == null || data == null || data.Length <= 1)
  411. {
  412. string msg = string.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
  413. scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
  414. 0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
  415. return UUID.Zero;
  416. }
  417. byte[] assetData = null;
  418. AssetBase oldAsset = null;
  419. if (BlendWithOldTexture)
  420. {
  421. Primitive.TextureEntryFace curFace;
  422. if(Face == ALL_SIDES)
  423. curFace = part.Shape.Textures.DefaultTexture;
  424. else
  425. {
  426. try
  427. {
  428. curFace = part.Shape.Textures.GetFace((uint)Face);
  429. }
  430. catch
  431. {
  432. curFace = null;
  433. }
  434. }
  435. if (curFace != null)
  436. {
  437. oldAsset = scene.AssetService.Get(curFace.TextureID.ToString());
  438. if (oldAsset != null)
  439. assetData = BlendTextures(data, oldAsset.Data, FrontAlpha);
  440. }
  441. }
  442. else if(FrontAlpha < 255)
  443. assetData = BlendTextures(data, null, FrontAlpha);
  444. if (assetData == null)
  445. {
  446. assetData = new byte[data.Length];
  447. Array.Copy(data, assetData, data.Length);
  448. }
  449. // Create a new asset for user
  450. AssetBase asset = new AssetBase(
  451. UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
  452. part.OwnerID.ToString());
  453. asset.Data = assetData;
  454. asset.Description = string.Format("URL image : {0}", Url);
  455. if (asset.Description.Length > 128)
  456. asset.Description = asset.Description.Substring(0, 128);
  457. asset.Local = true; // dynamic images aren't saved in the assets server
  458. asset.Temporary = ((Disp & DISP_TEMP) != 0);
  459. iac.Cache(asset);
  460. UUID oldID = UpdatePart(part, asset.FullID);
  461. if (!oldID.IsZero() && ((Disp & DISP_EXPIRE) != 0))
  462. {
  463. if (oldAsset == null)
  464. oldAsset = scene.AssetService.Get(oldID.ToString());
  465. if (oldAsset != null)
  466. {
  467. if (oldAsset.Temporary)
  468. iac.Expire(oldID.ToString());
  469. }
  470. }
  471. return asset.FullID;
  472. }
  473. private byte[] BlendTextures(byte[] frontImage, byte[] backImage, byte newAlpha)
  474. {
  475. ManagedImage managedImage;
  476. Image image;
  477. if (!OpenJPEG.DecodeToImage(frontImage, out managedImage, out image) || image == null)
  478. return null;
  479. Bitmap image1 = new Bitmap(image);
  480. image.Dispose();
  481. if(backImage == null)
  482. {
  483. SetAlpha(ref image1, newAlpha);
  484. byte[] result = Array.Empty<byte>();
  485. try
  486. {
  487. result = OpenJPEG.EncodeFromImage(image1, false);
  488. }
  489. catch (Exception e)
  490. {
  491. m_log.ErrorFormat(
  492. "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
  493. e.Message, e.StackTrace);
  494. }
  495. image1.Dispose();
  496. return result;
  497. }
  498. if (!OpenJPEG.DecodeToImage(backImage, out managedImage, out image) || image == null)
  499. {
  500. image1.Dispose();
  501. return null;
  502. }
  503. Bitmap image2 = new Bitmap(image);
  504. image.Dispose();
  505. using(Bitmap joint = MergeBitMaps(image1, image2, newAlpha))
  506. {
  507. image1.Dispose();
  508. image2.Dispose();
  509. byte[] result = Array.Empty<byte>();
  510. try
  511. {
  512. result = OpenJPEG.EncodeFromImage(joint, false);
  513. }
  514. catch (Exception e)
  515. {
  516. m_log.ErrorFormat(
  517. "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
  518. e.Message, e.StackTrace);
  519. }
  520. return result;
  521. }
  522. }
  523. public Bitmap MergeBitMaps(Bitmap front, Bitmap back, byte alpha)
  524. {
  525. Bitmap joint;
  526. Graphics jG;
  527. int Width = back.Width;
  528. int Height = back.Height;
  529. PixelFormat format;
  530. if(alpha < 255 || front.PixelFormat == PixelFormat.Format32bppArgb || back.PixelFormat == PixelFormat.Format32bppArgb)
  531. format = PixelFormat.Format32bppArgb;
  532. else
  533. format = PixelFormat.Format32bppRgb;
  534. joint = new Bitmap(Width, Height, format);
  535. if (alpha >= 255)
  536. {
  537. using (jG = Graphics.FromImage(joint))
  538. {
  539. jG.CompositingQuality = CompositingQuality.HighQuality;
  540. jG.CompositingMode = CompositingMode.SourceCopy;
  541. jG.DrawImage(back, 0, 0, Width, Height);
  542. jG.CompositingMode = CompositingMode.SourceOver;
  543. jG.DrawImage(front, 0, 0, Width, Height);
  544. return joint;
  545. }
  546. }
  547. using (jG = Graphics.FromImage(joint))
  548. {
  549. jG.CompositingQuality = CompositingQuality.HighQuality;
  550. jG.CompositingMode = CompositingMode.SourceCopy;
  551. jG.DrawImage(back, 0, 0, Width, Height);
  552. if (alpha > 0)
  553. {
  554. ColorMatrix matrix = new ColorMatrix(new float[][]{
  555. new float[] {1F, 0, 0, 0, 0},
  556. new float[] {0, 1F, 0, 0, 0},
  557. new float[] {0, 0, 1F, 0, 0},
  558. new float[] {0, 0, 0, alpha/255f, 0},
  559. new float[] {0, 0, 0, 0, 1F}});
  560. ImageAttributes imageAttributes = new ImageAttributes();
  561. imageAttributes.SetColorMatrix(matrix);
  562. jG.CompositingMode = CompositingMode.SourceOver;
  563. jG.DrawImage(front, new Rectangle(0, 0, Width, Height), 0, 0, front.Width, front.Height, GraphicsUnit.Pixel, imageAttributes);
  564. }
  565. return joint;
  566. }
  567. }
  568. private void SetAlpha(ref Bitmap b, byte alpha)
  569. {
  570. int Width = b.Width;
  571. int Height = b.Height;
  572. Bitmap joint = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
  573. if(alpha > 0)
  574. {
  575. ColorMatrix matrix = new ColorMatrix(new float[][]{
  576. new float[] {1F, 0, 0, 0, 0},
  577. new float[] {0, 1F, 0, 0, 0},
  578. new float[] {0, 0, 1F, 0, 0},
  579. new float[] {0, 0, 0, alpha/255f, 0},
  580. new float[] {0, 0, 0, 0, 1F}});
  581. ImageAttributes imageAttributes = new ImageAttributes();
  582. imageAttributes.SetColorMatrix(matrix);
  583. using (Graphics jG = Graphics.FromImage(joint))
  584. {
  585. jG.CompositingQuality = CompositingQuality.HighQuality;
  586. jG.CompositingMode = CompositingMode.SourceCopy;
  587. jG.DrawImage(b, new Rectangle(0, 0, Width, Height), 0, 0, Width, Height, GraphicsUnit.Pixel, imageAttributes);
  588. }
  589. }
  590. Bitmap t = b;
  591. b = joint;
  592. t.Dispose();
  593. }
  594. }
  595. #endregion
  596. }
  597. }