private static void ReplaceIfNecessary(string name, bool normalMap, bool mipmaps, bool readable, bool compressed) { if (GameDatabase.Instance.ExistsTexture(name)) { GameDatabase.TextureInfo info = GameDatabase.Instance.GetTextureInfo(name); bool isReadable = false; try { info.texture.GetPixel(0, 0); isReadable = true; } catch { } bool hasMipmaps = info.texture.mipmapCount > 0; bool isCompressed = (info.texture.format == TextureFormat.DXT1 || info.texture.format == TextureFormat.DXT5); bool isNormalMap = info.isNormalMap; if (!isReadable || (isCompressed && !compressed) || (isNormalMap != normalMap)) { //Pretty ineficient to not check beforehand, but makes the logic much simpler by simply reloading the textures. info.isNormalMap = normalMap; info.isReadable = readable; info.isCompressed = compressed; TextureConverter.Reload(info, false, default(Vector2), null, mipmaps); info.texture.name = name; } else if (isReadable != readable || isCompressed != compressed || hasMipmaps != mipmaps) { if (compressed) { info.texture.Compress(true); } info.texture.Apply(mipmaps, !readable); } } }
/// <summary> /// Returns an inspector for the object or null if there isn't one. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static Inspector GetInspector(object obj) { switch (obj) { case Texture i: return(new ImageInspector(TextureConverter.ToBitmap(i, 0))); case string s: return(new StringInspector(s)); case SongData d: return(new SongDataInspector(d)); case RBMid m: return(new RBMidiInspector(m)); case HxMesh m: return(new MeshInspector(m)); case MiloFile mf: return(new PropertyInspector(mf)); case LibForge.Fuser.FuserAsset a: return(new Inspectors.FuserInspector(a)); case object o: return(new ObjectInspector(obj)); } return(null); }
public override List <Vertices> Process(TextureContent input, ContentProcessorContext context) { BitmapContent bitmap = input.Faces[0][0]; byte[] bytes = bitmap.GetPixelData(); Debug.Assert(bytes.Length % 4 == 0); // Note(manu): If this were C/C++, we could simply reinterpret the byte-array as a uint-array... uint[] data = new uint[bytes.Length / 4]; for (int dataIndex = 0; dataIndex < data.Length; dataIndex++) { int byteIndex = dataIndex * 4; data[dataIndex] = BitConverter.ToUInt32(bytes, byteIndex); } DateTime vertStart = DateTime.Now; TextureConverter textureConverter = new TextureConverter(data, bitmap.Width) { PolygonDetectionType = PolygonDetectionType, HoleDetection = HoleDetection, MultipartDetection = MultipartDetection, PixelOffsetOptimization = PixelOffsetOptimization, Transform = Matrix.CreateScale(UniformScale * Conversion.RenderScale), // TODO(manu): Use z=1 instead? AlphaTolerance = (byte)AlphaTolerance, HullTolerance = HullTolerance, }; List <Vertices> vertices = textureConverter.DetectVertices(); TimeSpan vertDuration = DateTime.Now - vertStart; Diagnostic(context.Logger, $"Parsing vertices took {vertDuration.TotalSeconds.ToString("0.000")} seconds (VelcroPhysics)."); return(vertices); }
public Bitmap GetImage(int index, PLT0Node plt) { try { if (SharesData && SourceNode != this) { return(SourceNode.GetImage(index, plt)); } if (WorkingUncompressed != DataSource.Empty) { if (plt != null) { return(TextureConverter.DecodeIndexed( (VoidPtr)CommonHeader + _headerLen, _width, _height, plt.Palette, index + 1, _format)); } else { return(TextureConverter.Decode( (VoidPtr)CommonHeader + _headerLen, _width, _height, index + 1, _format)); } } else { return(null); } } catch { return(null); } }
public override void OnRebuild(VoidPtr address, int length, bool force) { PLT0v1 *header = (PLT0v1 *)address; *header = new PLT0v1(Palette.Entries.Length, _format); TextureConverter.EncodePalette(address + 0x40, Palette, _format); }
/// <summary> /// Generates the bodies for each of the pieces of the sheet. /// </summary> /// <param name="levelWorld">The world to create bodies in</param> /// <param name="collisionCategory">The FULL category of what these bodies should collide with</param> public void GenerateBodies(World levelWorld, Category collisionCategory) //TODO get scale { BodiesGenerated = true; int SpriteSheetSize = SpriteSheet.Width * SpriteSheet.Height; int IndividualSize = ImageSize.X * ImageSize.Y; uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into SpriteSheet.GetData <uint>(TextureData); //Gets which pixels of the texture are actually filled List <uint[]> IndividualData = new List <uint[]>(); for (int Processed = 0; Processed < SpriteSheetSize && IndividualData.Count < Bodies.Length; Processed += IndividualSize) { //TODO CHECK IF THIS WORKS TESTING TO CUT OFF ARRAY ARGUMENT EXCEPTION uint[] TempArray = new uint[IndividualSize]; try { Array.Copy(TextureData, Processed, TempArray, 0, IndividualSize); } catch (ArgumentException) { //At the end of textures the amount of data left might be to small Array.Copy(TextureData, Processed, TempArray, 0, TextureData.Length - Processed); } IndividualData.Add(TempArray); } int BodyIndex = 0; for (int count = 0; count < IndividualData.Count; ++count) { uint[] I = IndividualData[count]; Vertices vertices = TextureConverter.DetectVertices(I, ImageSize.X); List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Earclip); //error with bayazit and deluny //Siedle doesnt wortk //Earclip & flipcode results in glitches //Earclip works very well Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(Scale)); foreach (Vertices vert in VertexList) { vert.Scale(ref VertScale); //Scales the vertices to match the size we specified } Vector2 Centroid = -vertices.GetCentroid(); vertices.Translate(ref Centroid); //basketOrigin = -centroid; //This actually creates the body Bodies[BodyIndex] = BodyFactory.CreateCompoundPolygon(levelWorld, VertexList, 1, Vector2.Zero); Bodies[BodyIndex].BodyType = BodyType.Dynamic; Bodies[BodyIndex].Enabled = false; //Bodies[BodyIndex].CollisionCategories = collisionCategory; ++BodyIndex; } }
// TODO in case we need this somewhere else it might be a good idea to move this to the EntityFactory private void CreateAsteroid(FarPosition position, IUniformRandom random, ContentManager content) { // Randomly scale and rotate it. var scale = (float)random.NextDouble(0.5f, 1f); var angle = (float)random.NextDouble() * MathHelper.TwoPi; // Determine shape for physics system. var textureName = "Textures/Asteroids/rock_" + random.NextInt32(1, 14); var texture = content.Load <Texture2D>(textureName); var hull = new List <Vector2>(TextureConverter.DetectVertices(texture, 8f, textureName: textureName)[0]); for (var k = 0; k < hull.Count; ++k) { hull[k] -= new Vector2(texture.Width / 2f, texture.Height / 2f); hull[k] = XnaUnitConversion.ToSimulationUnits(hull[k]) * scale; } var polygons = EarClipDecomposer.ConvexPartition(hull); // Create physical representation. var entity = Manager.AddEntity(); var body = Manager.AddBody(entity, position, angle, Body.BodyType.Dynamic); foreach (var polygon in polygons) { Manager.AttachPolygon(body, polygon, density: 1000f, restitution: 0.2f); } // Slow down to allow reaching sleep state again. body.LinearDamping = 0.05f * Space.Util.Settings.TicksPerSecond; body.AngularDamping = 0.025f * Space.Util.Settings.TicksPerSecond; // Bounds of the asteroid for rendering culling. We use the diagonal for a loose fit that // contains every possible rotated state of the texture. var width = UnitConversion.ToSimulationUnits(texture.Width); var height = UnitConversion.ToSimulationUnits(texture.Height); var diagonal = (float)Math.Sqrt(width * width + height * height); var bounds = new FarRectangle(-diagonal / 2, -diagonal / 2, diagonal, diagonal); // Rendering stuff. Manager.AddComponent <Indexable>(entity).Initialize(bounds, CameraSystem.IndexId); Manager.AddComponent <Indexable>(entity).Initialize(bounds, InterpolationSystem.IndexId); Manager.AddComponent <SimpleTextureDrawable>(entity).Initialize(textureName, scale); // Auto removal. Manager.AddComponent <CellDeath>(entity).Initialize(true); Manager.AddComponent <Indexable>(entity).Initialize(CellSystem.CellDeathAutoRemoveIndexId); // Make it destructible. var health = Manager.AddComponent <Health>(entity); health.Value = health.MaxValue = 200 * scale; health.Regeneration = 0f; // As they don't move on their own, start asteroids as sleeping to save performance. body.IsAwake = false; }
private void UpdateSize() { if (_source == null) { return; } int w = _source.Width, h = _source.Height; int palSize = grpPalette.Enabled ? (((int)numPaletteCount.Value * 2) + 0x40) : 0; lblDataSize.Text = String.Format("{0:n0}B", TextureConverter.Get((WiiPixelFormat)cboFormat.SelectedItem).GetMipOffset(ref w, ref h, (int)numLOD.Value + 1) + 0x40 + palSize); }
public void UpdateFromModel() { var material = Controller.Material; if (material.Diffuse.Albedo is Texture) { diffuseTexture.Image = TextureConverter.Convert(material.Diffuse.Albedo as Texture); } else { diffuseTexture.BackColor = material.Diffuse.Albedo[0, 0].ToSystemDrawing(); diffuseTexture.Image = null; } if (material.Emissive.Albedo is Texture) { emissiveTexture.Image = TextureConverter.Convert(material.Emissive.Albedo as Texture); } else { emissiveTexture.BackColor = material.Emissive.Albedo[0, 0].ToSystemDrawing(); emissiveTexture.Image = null; } if (material.Reflective.Albedo is Texture) { reflectiveTexture.Image = TextureConverter.Convert(material.Reflective.Albedo as Texture); } else { reflectiveTexture.BackColor = material.Reflective.Albedo[0, 0].ToSystemDrawing(); reflectiveTexture.Image = null; } if (material.Refractive.Albedo is Texture) { refractiveTexture.Image = TextureConverter.Convert(material.Refractive.Albedo as Texture); } else { refractiveTexture.BackColor = material.Refractive.Albedo[0, 0].ToSystemDrawing(); refractiveTexture.Image = null; } refractiveIndexUpDown.Value = (decimal)material.Refractive.RefractiveIndex; reflectiveDisturbanceUpDown.Value = (decimal)material.Reflective.Disturbance; diffuseShareUpDown.Value = (decimal)material.Parts.diffuse; reflectiveShareUpDown.Value = (decimal)material.Parts.reflective; refractiveShareUpDown.Value = (decimal)material.Parts.refractive; emissiveShareUpDown.Value = (decimal)material.Parts.emissive; ampUpDown.Value = (decimal)material.Emissive.Amplification; }
public Bitmap GetImage(int index) { PLT0Node plt = GetPaletteNode(); if (plt != null) { return(TextureConverter.DecodeIndexed(Header, plt.Palette, index + 1)); } else { return(TextureConverter.Decode(Header, index + 1)); } }
private void refractiveFile_Click(object sender, EventArgs e) { var texturePath = ChooseTexture(); if (string.IsNullOrEmpty(texturePath)) { return; } var texture = new Texture(texturePath); Controller.Material.Refractive.Albedo = texture; refractiveTexture.Image = TextureConverter.Convert(texture); }
/// <summary> /// Creates a list of vertices from a texture. /// </summary> /// <param name="texture">The texture to make a body from</param> /// <param name="scale">The scale of the texture</param> /// <param name="imageSize">The size of each individual image in the hitbox</param> /// <param name="density">The density of the object (Will almost always be one</param> /// <param name="algorithm">The decomposition algorithm to use</param> /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks> /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as /// clean as the texture you give it, so avoid partically transparent areas and little edges. private List <Vertices>[] CreateVerticesFromTexture(Texture2D texture, float scale, Point imageSize, float density = 1, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Earclip) { int SpriteSheetSize = texture.Width * texture.Height; int IndividualSize = imageSize.X * imageSize.Y; uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into texture.GetData(TextureData); //Gets which pixels of the texture are actually filled List <uint[]> IndividualData = new List <uint[]>(); for (int Processed = 0; Processed < SpriteSheetSize; Processed += IndividualSize) { uint[] TempArray = new uint[IndividualSize]; try { Array.Copy(TextureData, Processed, TempArray, 0, IndividualSize); } catch (ArgumentException) { //At the end of textures the amount of data left might be to small Array.Copy(TextureData, Processed, TempArray, 0, TextureData.Length - Processed); } IndividualData.Add(TempArray); } List <Vertices>[] TextureVertices = new List <Vertices> [IndividualData.Count]; for (int count = 0; count < IndividualData.Count; ++count) { uint[] I = IndividualData[count]; Vertices vertices = TextureConverter.DetectVertices(I, texture.Width); List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, algorithm); Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(scale)); foreach (Vertices vert in VertexList) { vert.Scale(ref VertScale); //Scales the vertices to match the size we specified } Vector2 Centroid = -vertices.GetCentroid(); vertices.Translate(ref Centroid); //basketOrigin = -centroid; TextureVertices[count] = VertexList; } return(TextureVertices); }
public void Update(bool convertImagesToDds) { var colliderUpdater = new ColliderUpdater(gltf, colliders); colliderUpdater.UpdateColliders(); if (convertImagesToDds) { var texConverter = new TextureConverter(gltfPath, gltf); texConverter.ConvertImagesToDds(); } gltf.SaveModel(gltfPath); }
public void Replace(Bitmap bmp) { FileMap tMap; if (HasPlt) { tMap = TextureConverter.Get(_format).EncodeREFTTextureIndexed(bmp, LevelOfDetail, Palette.Entries.Length, PaletteFormat, QuantizationAlgorithm.MedianCut); } else { tMap = TextureConverter.Get(_format).EncodeREFTTexture(bmp, LevelOfDetail, WiiPaletteFormat.IA8); } ReplaceRaw(tMap); }
public Bitmap GetImage(int index, PLT0Node plt) { try { if (plt != null) { return(TextureConverter.DecodeIndexed(Header, plt.Palette, index + 1)); } else { return(TextureConverter.Decode(Header, index + 1)); } } catch { return(null); } }
public static void Replace(this TEX0Node tex0, Bitmap bmp, int paletteSize) { FileMap tMap, pMap; if (tex0.HasPalette) { PLT0Node pn = tex0.GetPaletteNode(); tMap = TextureConverter.Get(tex0.Format).EncodeTextureIndexed(bmp, tex0.LevelOfDetail, paletteSize, pn.Format, QuantizationAlgorithm.MedianCut, out pMap); pn.ReplaceRaw(pMap); } else { tMap = TextureConverter.Get(tex0.Format).EncodeTEX0Texture(bmp, tex0.LevelOfDetail); } tex0.ReplaceRaw(tMap); }
public void Replace(Bitmap bmp) { FileMap tMap, pMap; if (HasPalette) { PLT0Node pn = this.GetPaletteNode(); tMap = TextureConverter.Get(Format).EncodeTextureIndexed(bmp, LevelOfDetail, pn.Colors, pn.Format, QuantizationAlgorithm.MedianCut, out pMap); pn.ReplaceRaw(pMap); } else { tMap = TextureConverter.Get(Format).EncodeTexture(bmp, LevelOfDetail); } ReplaceRaw(tMap); }
/// <summary> /// Replace the MenSelmapMark texture in toReplace with the image in newBitmap, flipping the channels if the image has solid black in all four corners. /// </summary> /// <param name="newBitmap">The new texture to use</param> /// <param name="toReplace">The TEX0 to insert the texture in</param> /// <param name="createNew">If true, the format of the existing texture will not be used as a fallback, even if useExistingAsFallback is true</param> private void ReplaceSelmapMark(Bitmap newBitmap, TEX0Node toReplace, bool createNew) { WiiPixelFormat format = selmapMarkFormat != null ? selmapMarkFormat.Value : useExistingAsFallback && !createNew ? toReplace.Format : BitmapUtilities.HasAlpha(newBitmap) ? WiiPixelFormat.IA4 : WiiPixelFormat.I4; Console.WriteLine(format); Bitmap toEncode = BitmapUtilities.HasSolidCorners(newBitmap) ? BitmapUtilities.AlphaSwap(newBitmap) : newBitmap; BrawlLib.IO.FileMap tMap = TextureConverter.Get(format).EncodeTEX0Texture(toEncode, 1); toReplace.ReplaceRaw(tMap); }
public static Vector2[] GetVerticesTexture(Texture2D texture) { // Get vertices of Texture uint[] texData = new uint[texture.Width * texture.Height]; texture.GetData <uint>(texData); Vertices verticesList = TextureConverter.detectVertices(texData, texture.Width); Vector2[] verticesArray = verticesList.ToArray(); // PolygonCollider has offset in center, so vertices does too for (int i = 0; i < verticesArray.Length; i++) { verticesArray[i].X -= texture.Width / 2; verticesArray[i].Y -= texture.Height / 2; } return(verticesArray); }
public Bitmap GetImage(int index) { try { if (HasPlt == true) { return(TextureConverter.DecodeIndexed((byte *)Header + 0x20, Width, Height, Palette, index + 1, _format)); } else { return(TextureConverter.Decode((byte *)Header + 0x20, Width, Height, index + 1, _format)); } } catch { return(null); } }
public TEX0v1(int width, int height, WiiPixelFormat format, int mipLevels) { _header._tag = Tag; _header._size = TextureConverter.Get(format).GetMipOffset(width, height, mipLevels + 1) + Size; _header._version = 1; _header._bresOffset = 0; _headerLen = Size; _stringOffset = 0; _hasPalette = ((format == WiiPixelFormat.CI4) || (format == WiiPixelFormat.CI8)) ? 1 : 0; _width = (short)width; _height = (short)height; _pixelFormat = (int)format; _levelOfDetail = mipLevels; _minLod = 0; _maxLod = mipLevels - 1.0f; _origPathOffset = 0; }
public void WriteJson_Should_InvokeMethodsProperly() { var converter = new TextureConverter(); var texture = new Texture(); var mockedWriter = new Mock <JsonWriter>(); converter.WriteJson(mockedWriter.Object, texture, JsonSerializer.CreateDefault()); mockedWriter.Verify(jsonWriter => jsonWriter.WriteStartObject(), Times.Once); mockedWriter.Verify(jsonWriter => jsonWriter.WriteEndObject(), Times.Once); mockedWriter.Verify(jsonWriter => jsonWriter.WritePropertyName(It.IsAny <string>()), Times.Exactly(4)); mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <string>()), Times.Exactly(2)); mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <int>()), Times.Exactly(2)); mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <WrappingType>()), Times.Exactly(2)); mockedWriter.Verify(jsonWriter => jsonWriter.WriteStartArray(), Times.Exactly(2)); mockedWriter.Verify(jsonWriter => jsonWriter.WriteEnd(), Times.Exactly(2)); }
/// <summary> /// Returns an inspector for the object or null if there isn't one. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static Inspector GetInspector(object obj) { switch (obj) { case Texture i: return(new ImageInspector(TextureConverter.ToBitmap(i, 0))); case string s: return(new StringInspector(s)); case SongData d: return(new SongDataInspector(d)); case RBMid m: return(new RBMidiInspector(m)); case object o: return(new ObjectInspector(obj)); } return(null); }
public Body CreatePolygonFromTexture(Texture2D tex, World world, float density, Vector2 position, float scale, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Bayazit) { uint[] texData = new uint[tex.Width * tex.Height]; tex.GetData <uint>(texData); Vertices vertices = TextureConverter.DetectVertices(texData, tex.Width); List <Vertices> vertexList = Triangulate.ConvexPartition(vertices, algorithm); Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(scale)); foreach (Vertices vert in vertexList) { vert.Scale(ref vertScale); } Vector2 centroid = vertices.GetCentroid(); vertices.Translate(ref centroid); //basketOrigin = -centroid; return(BodyFactory.CreateCompoundPolygon(world, vertexList, density, position, 100)); }
public void WriteJson_Should_OutputCorrectValues() { var converter = new TextureConverter(); var texture = new Texture() { UUID = "testUuid", ImageId = "testImageId", WrapS = WrappingType.MirroredRepeat, WrapT = WrappingType.ClampToEdge, Repeat = new Tuple <int, int>(1, 1) }; var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); var jsonWriter = new JsonTextWriter(stringWriter); converter.WriteJson(jsonWriter, texture, JsonSerializer.CreateDefault()); string expected = "{\"uuid\":\"testUuid\",\"image\":\"testImageId\",\"wrap\":[1002,1001],\"repeat\":[1,1]}"; Assert.Equal(expected, stringBuilder.ToString()); }
public Bitmap GetImage(int index, PLT0Node plt) { try { if (WorkingUncompressed != DataSource.Empty) { if (plt != null) { return(TextureConverter.DecodeIndexed(Header1, plt.Palette, index + 1)); } else { return(TextureConverter.Decode(Header1, index + 1)); } } else { return(null); } } catch { return(null); } }
private void DrawParameters(int method) { ParameterInfo[] mParameters = currentPreset.conversionMethods [currentPreset.chosenMethods [method]].GetParameters(); int paramLength = mParameters.Length; foreach (var item in mParameters) { if (item.ParameterType == typeof(UnityEngine.Vector2)) { paramLength++; } } if (paramLength != currentPreset.chosenMethodsParameters [method].Length) { TextureConverter.LoadMethodParameters(currentPreset, method); } int iOffset = 0; for (int i = 0; i < mParameters.Length; i++) { if (mParameters [i].ParameterType == typeof(UnityEngine.Vector2)) { // Undo.RecordObject (currentPreset, "TextureConvereter Preset Change"); currentPreset.chosenMethodsParameters [method] [i + iOffset] = TextureConverterDrawUtility.DrawParameterInput(typeof(PositionOrValue), currentPreset.chosenMethodsParameters [method] [i + iOffset]); if ((PositionOrValue)currentPreset.chosenMethodsParameters [method] [i + iOffset] == PositionOrValue.UseValue) { // Undo.RecordObject (currentPreset, "TextureConvereter Preset Change"); currentPreset.chosenMethodsParameters [method] [i + iOffset + 1] = TextureConverterDrawUtility.DrawParameterInput(mParameters [i].ParameterType, currentPreset.chosenMethodsParameters [method] [i + iOffset + 1]); } iOffset++; } else { // Undo.RecordObject (currentPreset, "TextureConvereter Preset Change"); currentPreset.chosenMethodsParameters [method] [i + iOffset] = TextureConverterDrawUtility.DrawParameterInput(mParameters [i].ParameterType, currentPreset.chosenMethodsParameters [method] [i + iOffset]); } } }
/// <summary> /// Creates a polygon from a texture. This is the important function here. /// </summary> /// <param name="texture">The texture to make a body from</param> /// <param name="density">The density of the object (Will almost always be one</param> /// <param name="position">The position (in meters) of the object in the world</param> /// <param name="scale">The scale of the object (how much to change its size)</param> /// <param name="algorithm">The decomposition algorithm to use</param> /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks> /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as /// clean as the texture you give it, so avoid partically transparent areas and little edges. private Body CreatePolygonFromTexture(Texture2D texture, float density, Vector2 position, float scale, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Bayazit) { uint[] TextureData = new uint[texture.Width * texture.Height]; //Array to copy texture info into texture.GetData <uint>(TextureData); //Gets which pixels of the texture are actually filled Vertices vertices = TextureConverter.DetectVertices(TextureData, texture.Width); List <Vertices> vertexList = Triangulate.ConvexPartition(vertices, algorithm); Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(scale)); foreach (Vertices vert in vertexList) { vert.Scale(ref vertScale); //Scales the vertices to match the size we specified } Vector2 centroid = -vertices.GetCentroid(); vertices.Translate(ref centroid); //basketOrigin = -centroid; //This actually creates the body return(BodyFactory.CreateCompoundPolygon(LevelWorld, vertexList, density, position)); }
public TEX0(int width, int height, WiiPixelFormat format, int mipLevels) { _header._tag = Tag; _header._size = TextureConverter.Get(format).GetMipOffset(width, height, mipLevels + 1) + Size; _header._version = 1; _header._bresOffset = 0; _headerLen = Size; _stringOffset = 0; _hasPalette = ((format == WiiPixelFormat.CI4) || (format == WiiPixelFormat.CI8)) ? 1 : 0; _width = (short)width; _height = (short)height; _pixelFormat = (int)format; _levelOfDetail = mipLevels; _unknown = 0; _lodBias = mipLevels - 1.0f; fixed(uint *p = _padding) for (int i = 0; i < 4; i++) { p[i] = 0; } }
/// <summary> /// Creates a list of vertices from a texture. /// </summary> /// <param name="texture">The texture to make a body from</param> /// <param name="scale">The scale of the texture</param> /// <param name="algorithm">The decomposition algorithm to use</param> /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks> /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as /// clean as the texture you give it, so avoid partically transparent areas and little edges. private List <Vertices> CreateVerticesFromTexture(Texture2D texture, float scale, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Earclip) { int SpriteSheetSize = texture.Width * texture.Height; uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into texture.GetData(TextureData); //Gets which pixels of the texture are actually filled Vertices vertices = TextureConverter.DetectVertices(TextureData, texture.Width); List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, algorithm); Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(scale)); foreach (Vertices vert in VertexList) { vert.Scale(ref VertScale); //Scales the vertices to match the size we specified } Vector2 Centroid = -vertices.GetCentroid(); vertices.Translate(ref Centroid); //basketOrigin = -centroid; return(VertexList); }
/// <summary> /// Detects the vertices of the supplied texture data. /// </summary> /// <param name="data">The texture data.</param> /// <param name="width">The texture width.</param> /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param> /// <param name="hullTolerance">The hull tolerance.</param> /// <param name="alphaTolerance">The alpha tolerance.</param> /// <param name="multiPartDetection">if set to <c>true</c> it will perform multi part detection.</param> /// <returns></returns> public static List<Vertices> DetectVertices(uint[] data, int width, float hullTolerance, byte alphaTolerance, bool multiPartDetection, bool holeDetection) { TextureConverter tc = new TextureConverter(data, width) { HullTolerance = hullTolerance, AlphaTolerance = alphaTolerance, MultipartDetection = multiPartDetection, HoleDetection = holeDetection }; List<Vertices> detectedVerticesList = tc.DetectVertices(); List<Vertices> result = new List<Vertices>(); for (int i = 0; i < detectedVerticesList.Count; i++) { result.Add(detectedVerticesList[i]); } return result; }
/// <summary> /// Detects the vertices of the supplied texture data. /// </summary> /// <param name="data">The texture data.</param> /// <param name="width">The texture width.</param> /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param> /// <returns></returns> public static Vertices DetectVertices(uint[] data, int width, bool holeDetection) { TextureConverter tc = new TextureConverter(data, width) { HoleDetection = holeDetection }; List<Vertices> detectedVerticesList = tc.DetectVertices(); return detectedVerticesList[0]; }