Exemplo n.º 1
0
 public IVertex SetColorBytes(
     int colorIndex,
     byte r,
     byte g,
     byte b,
     byte a)
 => this.SetColor(colorIndex, ColorImpl.FromRgbaBytes(r, g, b, a));
Exemplo n.º 2
0
        private IColor[] DecodeCmprPalette_(ushort color1Value, ushort color2Value)
        {
            var palette = new IColor[4];

            var color1 = ColorUtil.ParseRgb565(color1Value);
            var color2 = ColorUtil.ParseRgb565(color2Value);

            IColor color3, color4;

            if (color1Value > color2Value)
            {
                color3 = ColorUtil.Interpolate(color1, color2, 1d / 3);
                color4 = ColorUtil.Interpolate(color1, color2, 2d / 3);
            }
            else
            {
                color3 = ColorUtil.Interpolate(color1, color2, .5);
                color4 = ColorImpl.FromRgbaBytes(0, 0, 0, 0);
            }

            palette[0] = color1;
            palette[1] = color2;
            palette[2] = color3;
            palette[3] = color4;

            return(palette);
        }
Exemplo n.º 3
0
        protected override IColor[] DecodeBlock(IList <byte> block, int position)
        {
            var bl = new IColor[8 * 4];
            var s  = new VectorReader(block, position, Endianness.Big);

            for (var j = 0; j < 4; ++j)
            {
                for (var i = 0; i < 8; ++i)
                {
                    var intensity = s.ReadU8();
                    bl[j * 8 + i] = ColorImpl.FromIntensityByte(intensity);
                }
            }

            return(bl);
        }
Exemplo n.º 4
0
        protected override IColor[] DecodeBlock(IList <byte> block, int position)
        {
            var bl = new IColor[4 * 4];
            var s  = new VectorReader(block, position, Endianness.Big);

            for (var j = 0; j < 4; ++j)
            {
                for (var i = 0; i < 4; ++i)
                {
                    var intensity = s.ReadU8();
                    var alpha     = s.ReadU8();

                    bl[j * 4 + i] = ColorImpl.FromRgbaBytes(intensity, intensity, intensity, alpha);
                }
            }

            return(bl);
        }
Exemplo n.º 5
0
        protected override IColor[] DecodeBlock(IList <byte> block, int position)
        {
            var bl = new IColor[8 * 4];
            var s  = new VectorReader(block, position, Endianness.Big);

            for (var j = 0; j < 4; ++j)
            {
                for (var i = 0; i < 8; ++i)
                {
                    var pixes = s.ReadU8();

                    var intensity = ColorUtil.ExtractScaled(pixes, 4, 4, 17);
                    var alpha     = ColorUtil.ExtractScaled(pixes, 0, 4, 17);

                    bl[j * 8 + i] = ColorImpl.FromRgbaBytes(intensity, intensity, intensity, alpha);
                }
            }

            return(bl);
        }
Exemplo n.º 6
0
        protected override IColor[] DecodeBlock(IList <byte> block, int position)
        {
            var bl = new IColor[8 * 8];
            var s  = new VectorReader(block, position, Endianness.Big);

            for (var j = 0; j < 8; ++j)
            {
                for (var i = 0; i < 4; ++i)
                {
                    var pixes = s.ReadU8();

                    var intensity1 = ColorUtil.ExtractScaled(pixes, 4, 4, 17);
                    var intensity2 = ColorUtil.ExtractScaled(pixes, 0, 4, 17);

                    bl[j * 8 + 2 * i]     = ColorImpl.FromIntensityByte(intensity1);
                    bl[j * 8 + 2 * i + 1] = ColorImpl.FromIntensityByte(intensity2);
                }
            }

            return(bl);
        }
Exemplo n.º 7
0
        protected override IColor[] DecodeBlock(IList <byte> block, int position)
        {
            var bl = new IColor[4 * 4];
            var s  = new VectorReader(block, position, Endianness.Big);

            for (var j = 0; j < 4; ++j)
            {
                for (var i = 0; i < 4; ++i)
                {
                    var pix = s.ReadU16();

                    var alphaFlag = BitLogic.ExtractFromRight(pix, 15, 1);

                    byte r, g, b, a;
                    if (alphaFlag == 1)
                    {
                        a = 255;
                        r = ColorUtil.ExtractScaled(pix, 10, 5);
                        g = ColorUtil.ExtractScaled(pix, 5, 5);
                        b = ColorUtil.ExtractScaled(pix, 0, 5);
                    }
                    else
                    {
                        a = ColorUtil.ExtractScaled(pix, 12, 3);

                        r = ColorUtil.ExtractScaled(pix, 8, 4, 17);
                        g = ColorUtil.ExtractScaled(pix, 4, 4, 17);
                        b = ColorUtil.ExtractScaled(pix, 0, 4, 17);
                    }

                    bl[j * 4 + i] = ColorImpl.FromRgbaBytes(r, g, b, a);
                }
            }

            return(bl);
        }
Exemplo n.º 8
0
        public unsafe IModel LoadModel(GloModelFileBundle gloModelFileBundle)
        {
            var gloFile            = gloModelFileBundle.GloFile;
            var textureDirectories = gloModelFileBundle.TextureDirectories;
            var fps = 20;

            var glo = gloFile.Impl.ReadNew <Glo>(Endianness.LittleEndian);

            var textureFilesByName = new Dictionary <string, IFileHierarchyFile>();

            foreach (var textureDirectory in textureDirectories)
            {
                foreach (var textureFile in textureDirectory.Files)
                {
                    textureFilesByName[textureFile.Name.ToLower()] = textureFile;
                }
            }

            /*new MeshCsvWriter().WriteToFile(
             *  glo, new FinFile(Path.Join(outputDirectory.FullName, "mesh.csv")));
             * new FaceCsvWriter().WriteToFile(
             *  glo, new FinFile(Path.Join(outputDirectory.FullName, "face.csv")));
             * new VertexCsvWriter().WriteToFile(
             *  glo, new FinFile(Path.Join(outputDirectory.FullName, "vertex.csv")));*/

            var finModel = new ModelImpl();
            var finSkin  = finModel.Skin;

            var finRootBone = finModel.Skeleton.Root;

            var finTextureMap = new LazyDictionary <string, ITexture?>(
                textureFilename => {
                if (!textureFilesByName.TryGetValue(textureFilename.ToLower(),
                                                    out var textureFile))
                {
                    return(null);
                }

                using var rawTextureImage = FinImage.FromFile(textureFile.Impl);
                var textureImageWithAlpha =
                    GloModelLoader.AddTransparencyToGloImage_(rawTextureImage);

                var finTexture = finModel.MaterialManager.CreateTexture(
                    textureImageWithAlpha);
                finTexture.Name = textureFilename;

                if (this.mirrorTextures_.Contains(textureFilename))
                {
                    finTexture.WrapModeU = WrapMode.MIRROR_REPEAT;
                    finTexture.WrapModeV = WrapMode.MIRROR_REPEAT;
                }
                else
                {
                    finTexture.WrapModeU = WrapMode.REPEAT;
                    finTexture.WrapModeV = WrapMode.REPEAT;
                }

                return(finTexture);
            });
            var withCullingMap =
                new LazyDictionary <string, IMaterial>(textureFilename => {
                var finTexture = finTextureMap[textureFilename];
                if (finTexture == null)
                {
                    return(finModel.MaterialManager.AddStandardMaterial());
                }
                return(finModel.MaterialManager.AddTextureMaterial(finTexture));
            });
            var withoutCullingMap = new LazyDictionary <string, IMaterial>(
                textureFilename => {
                var finTexture        = finTextureMap[textureFilename];
                IMaterial finMaterial = finTexture == null
                                        ? finModel.MaterialManager
                                        .AddStandardMaterial()
                                        : finModel.MaterialManager
                                        .AddTextureMaterial(
                    finTexture);
                finMaterial.CullingMode = CullingMode.SHOW_BOTH;
                return(finMaterial);
            });

            var firstMeshMap = new Dictionary <string, GloMesh>();

            // TODO: Consider separating these out as separate models
            foreach (var gloObject in glo.Objects)
            {
                var finObjectRootBone = finRootBone.AddRoot(0, 0, 0);
                var meshQueue         = new Queue <(GloMesh, IBone)>();
                foreach (var topLevelGloMesh in gloObject.Meshes)
                {
                    meshQueue.Enqueue((topLevelGloMesh, finObjectRootBone));
                }

                List <(IAnimation, int, int)> finAndGloAnimations = new();
                foreach (var animSeg in gloObject.AnimSegs)
                {
                    var startFrame = (int)animSeg.StartFrame;
                    var endFrame   = (int)animSeg.EndFrame;

                    var finAnimation = finModel.AnimationManager.AddAnimation();
                    finAnimation.Name       = animSeg.Name;
                    finAnimation.FrameCount =
                        (int)(animSeg.EndFrame - animSeg.StartFrame + 1);

                    finAnimation.FrameRate = fps * animSeg.Speed;

                    finAndGloAnimations.Add((finAnimation, startFrame, endFrame));
                }

                while (meshQueue.Count > 0)
                {
                    var(gloMesh, parentFinBone) = meshQueue.Dequeue();

                    var name = gloMesh.Name;

                    GloMesh idealMesh;
                    if (!firstMeshMap.TryGetValue(name, out idealMesh))
                    {
                        firstMeshMap[name] = idealMesh = gloMesh;
                    }

                    var position = gloMesh.MoveKeys[0].Xyz;

                    var rotation   = gloMesh.RotateKeys[0];
                    var quaternion =
                        new Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W);
                    var xyzRadians = QuaternionUtil.ToEulerRadians(quaternion);

                    var scale = gloMesh.ScaleKeys[0].Scale;

                    var finBone = parentFinBone
                                  .AddChild(position.X, position.Y, position.Z)
                                  .SetLocalRotationRadians(
                        xyzRadians.X, xyzRadians.Y, xyzRadians.Z)
                                  .SetLocalScale(scale.X, scale.Y, scale.Z);
                    finBone.Name = name + "_bone";

                    var child = gloMesh.Pointers.Child;
                    if (child != null)
                    {
                        meshQueue.Enqueue((child, finBone));
                    }

                    var next = gloMesh.Pointers.Next;
                    if (next != null)
                    {
                        meshQueue.Enqueue((next, parentFinBone));
                    }

                    foreach (var(finAnimation, startFrame, endFrame) in
                             finAndGloAnimations)
                    {
                        var finBoneTracks = finAnimation.AddBoneTracks(finBone);

                        long prevTime = -1;
                        foreach (var moveKey in gloMesh.MoveKeys)
                        {
                            Asserts.True(moveKey.Time > prevTime);
                            prevTime = moveKey.Time;

                            if (!(moveKey.Time >= startFrame && moveKey.Time <= endFrame))
                            {
                                continue;
                            }

                            var time = (int)(moveKey.Time - startFrame);
                            Asserts.True(time >= 0 && time < finAnimation.FrameCount);

                            var moveValue = moveKey.Xyz;
                            finBoneTracks.Positions.Set(time, 0, moveValue.X);
                            finBoneTracks.Positions.Set(time, 1, moveValue.Y);
                            finBoneTracks.Positions.Set(time, 2, moveValue.Z);
                        }

                        prevTime = -1;
                        foreach (var rotateKey in gloMesh.RotateKeys)
                        {
                            Asserts.True(rotateKey.Time > prevTime);
                            prevTime = rotateKey.Time;

                            if (!(rotateKey.Time >= startFrame &&
                                  rotateKey.Time <= endFrame))
                            {
                                continue;
                            }

                            var time = (int)(rotateKey.Time - startFrame);
                            Asserts.True(time >= 0 && time < finAnimation.FrameCount);

                            var quaternionKey =
                                new Quaternion(rotateKey.X, rotateKey.Y, rotateKey.Z,
                                               rotateKey.W);
                            var xyzRadiansKey = QuaternionUtil.ToEulerRadians(quaternionKey);

                            finBoneTracks.Rotations.Set(time, 0,
                                                        xyzRadiansKey.X);
                            finBoneTracks.Rotations.Set(time, 1,
                                                        xyzRadiansKey.Y);
                            finBoneTracks.Rotations.Set(time, 2,
                                                        xyzRadiansKey.Z);
                        }

                        prevTime = -1;
                        foreach (var scaleKey in gloMesh.ScaleKeys)
                        {
                            Asserts.True(scaleKey.Time > prevTime);
                            prevTime = scaleKey.Time;

                            if (!(scaleKey.Time >= startFrame && scaleKey.Time <= endFrame))
                            {
                                continue;
                            }

                            var time = (int)(scaleKey.Time - startFrame);
                            Asserts.True(time >= 0 && time < finAnimation.FrameCount);

                            var scaleValue = scaleKey.Scale;
                            finBoneTracks.Scales.Set(time, 0, scaleValue.X);
                            finBoneTracks.Scales.Set(time, 1, scaleValue.Y);
                            finBoneTracks.Scales.Set(time, 2, scaleValue.Z);
                        }
                    }

                    // Anything with these names are debug objects and can be ignored.
                    if (this.hiddenNames_.Contains(name))
                    {
                        continue;
                    }

                    var finMesh = finSkin.AddMesh();
                    finMesh.Name = name;

                    var gloVertices = idealMesh.Vertices;

                    string    previousTextureName = null;
                    IMaterial?previousMaterial    = null;

                    foreach (var gloFace in idealMesh.Faces)
                    {
                        // TODO: What can we do if texture filename is empty?
                        var textureFilename = gloFace.TextureFilename;

                        var gloFaceColor = gloFace.Color;
                        var finFaceColor = ColorImpl.FromRgbaBytes(
                            gloFaceColor.R, gloFaceColor.G, gloFaceColor.B, gloFaceColor.A);

                        var enableBackfaceCulling = (gloFace.Flags & 1 << 2) == 0;

                        IMaterial?finMaterial;
                        if (textureFilename == previousTextureName)
                        {
                            finMaterial = previousMaterial;
                        }
                        else
                        {
                            previousTextureName = textureFilename;
                            finMaterial         = enableBackfaceCulling
                                ? withCullingMap[textureFilename]
                                : withoutCullingMap[textureFilename];
                            previousMaterial = finMaterial;
                        }

                        // Face flag:
                        // 0: potentially some kind of repeat mode??

                        var color = (gloFace.Flags & 1 << 6) != 0
                            ? ColorImpl.FromRgbaBytes(255, 0, 0, 255)
                            : ColorImpl.FromRgbaBytes(0, 255, 0, 255);

                        var finFaceVertices = new IVertex[3];
                        for (var v = 0; v < 3; ++v)
                        {
                            var gloVertexRef = gloFace.VertexRefs[v];
                            var gloVertex    = gloVertices[gloVertexRef.Index];

                            var finVertex = finSkin
                                            .AddVertex(gloVertex.X, gloVertex.Y, gloVertex.Z)
                                            .SetUv(gloVertexRef.U, gloVertexRef.V);
                            //.SetColor(color);
                            finVertex.SetBoneWeights(finSkin.GetOrCreateBoneWeights(
                                                         PreprojectMode.BONE, finBone));
                            finFaceVertices[v] = finVertex;
                        }

                        // TODO: Merge triangles together
                        var finTriangles = new (IVertex, IVertex, IVertex)[1];
Exemplo n.º 9
0
 public static IColor ParseRgb5A3(ushort color)
 {
     ColorUtil.SplitRgb5A3(color, out var r, out var g, out var b, out var a);
     return(ColorImpl.FromRgbaBytes(r, g, b, a));
 }
Exemplo n.º 10
0
 public static IColor ParseRgb565(ushort color)
 {
     ColorUtil.SplitRgb565(color, out var r, out var g, out var b);
     return(ColorImpl.FromRgbBytes(r, g, b));
 }
Exemplo n.º 11
0
 public static IColor Interpolate(IColor from, IColor to, double amt)
 => ColorImpl.FromRgbaBytes(
     (byte)Math.Round(from.Rb * (1 - amt) + to.Rb * amt),
     (byte)Math.Round(from.Gb * (1 - amt) + to.Gb * amt),
     (byte)Math.Round(from.Bb * (1 - amt) + to.Bb * amt),
     (byte)Math.Round(from.Ab * (1 - amt) + to.Ab * amt));
Exemplo n.º 12
0
        // TODO: Split these out into separate classes
        // TODO: Reading from the file here is gross
        public IModel LoadModel(CmbModelFileBundle modelFileBundle)
        {
            var cmbFile   = modelFileBundle.CmbFile;
            var csabFiles = modelFileBundle.CsabFiles;
            var ctxbFiles = modelFileBundle.CtxbFiles;
            var shpaFiles = modelFileBundle.ShpaFiles;

            var fps = 30;

            using var r =
                      new EndianBinaryReader(cmbFile.Impl.OpenRead(),
                                             Endianness.LittleEndian);

            var cmb = new Cmb(r);

            r.Position = 0;

            var filesAndCsabs =
                csabFiles?.Select(csabFile => {
                var csab =
                    csabFile.Impl.ReadNew <Csab>(Endianness.LittleEndian);
                return(csabFile, csab);
            })
                .ToList() ??
                new List <(IFileHierarchyFile shpaFile, Csab csab)>();

            var filesAndCtxbs =
                ctxbFiles?.Select(ctxbFile => {
                var ctxb =
                    ctxbFile.Impl.ReadNew <Ctxb>(Endianness.LittleEndian);
                return(ctxbFile, ctxb);
            })
                .ToList() ??
                new List <(IFileHierarchyFile shpaFile, Ctxb ctxb)>();

            var filesAndShpas =
                shpaFiles?.Select(shpaFile => {
                var shpa =
                    shpaFile.Impl.ReadNew <Shpa>(Endianness.LittleEndian);
                return(shpaFile, shpa);
            })
                .ToList() ??
                new List <(IFileHierarchyFile shpaFile, Shpa shpa)>();

            var finModel = new ModelImpl();
            var finSkin  = finModel.Skin;

            // Adds bones
            var finBones  = new IBone[cmb.skl.bones.Length];
            var boneQueue = new Queue <(Bone, IBone?)>();

            boneQueue.Enqueue((cmb.skl.bones[0], null));
            while (boneQueue.Count > 0)
            {
                var(cmbBone, finBoneParent) = boneQueue.Dequeue();

                var translation = cmbBone.translation;
                var radians     = cmbBone.rotation;
                var scale       = cmbBone.scale;

                var finBone =
                    (finBoneParent ?? finModel.Skeleton.Root)
                    .AddChild(translation.X, translation.Y, translation.Z)
                    .SetLocalRotationRadians(radians.X, radians.Y, radians.Z)
                    .SetLocalScale(scale.X, scale.Y, scale.Z);
                finBones[cmbBone.id] = finBone;

                foreach (var child in cmbBone.children)
                {
                    boneQueue.Enqueue((child, finBone));
                }
            }

            // Adds animations
            foreach (var(csabFile, csab) in filesAndCsabs)
            {
                var finAnimation = finModel.AnimationManager.AddAnimation();
                finAnimation.Name = csabFile.NameWithoutExtension;

                finAnimation.FrameCount = (int)csab.Duration;
                finAnimation.FrameRate  = fps;

                foreach (var(boneIndex, anod) in csab.BoneIndexToAnimationNode)
                {
                    var boneTracks = finAnimation.AddBoneTracks(finBones[boneIndex]);

                    // TODO: Add support for in/out tangents
                    foreach (var translationX in anod.TranslationX.Keyframes)
                    {
                        boneTracks.Positions.Set((int)translationX.Time,
                                                 0,
                                                 translationX.Value,
                                                 translationX.IncomingTangent,
                                                 translationX.OutgoingTangent);
                    }
                    foreach (var translationY in anod.TranslationY.Keyframes)
                    {
                        boneTracks.Positions.Set((int)translationY.Time,
                                                 1,
                                                 translationY.Value,
                                                 translationY.IncomingTangent,
                                                 translationY.OutgoingTangent);
                    }
                    foreach (var translationZ in anod.TranslationZ.Keyframes)
                    {
                        boneTracks.Positions.Set((int)translationZ.Time,
                                                 2,
                                                 translationZ.Value,
                                                 translationZ.IncomingTangent,
                                                 translationZ.OutgoingTangent);
                    }

                    foreach (var scaleX in anod.ScaleX.Keyframes)
                    {
                        boneTracks.Scales.Set((int)scaleX.Time,
                                              0,
                                              scaleX.Value,
                                              scaleX.IncomingTangent,
                                              scaleX.OutgoingTangent);
                    }
                    foreach (var scaleY in anod.ScaleY.Keyframes)
                    {
                        boneTracks.Scales.Set((int)scaleY.Time,
                                              1,
                                              scaleY.Value,
                                              scaleY.IncomingTangent,
                                              scaleY.OutgoingTangent);
                    }
                    foreach (var scaleZ in anod.ScaleZ.Keyframes)
                    {
                        boneTracks.Scales.Set((int)scaleZ.Time,
                                              2,
                                              scaleZ.Value,
                                              scaleZ.IncomingTangent,
                                              scaleZ.OutgoingTangent);
                    }

                    foreach (var rotationX in anod.RotationX.Keyframes)
                    {
                        boneTracks.Rotations.Set((int)rotationX.Time,
                                                 0,
                                                 rotationX.Value,
                                                 rotationX.IncomingTangent,
                                                 rotationX.OutgoingTangent);
                    }
                    foreach (var rotationY in anod.RotationY.Keyframes)
                    {
                        boneTracks.Rotations.Set((int)rotationY.Time,
                                                 1,
                                                 rotationY.Value,
                                                 rotationY.IncomingTangent,
                                                 rotationY.OutgoingTangent);
                    }
                    foreach (var rotationZ in anod.RotationZ.Keyframes)
                    {
                        boneTracks.Rotations.Set((int)rotationZ.Time,
                                                 2,
                                                 rotationZ.Value,
                                                 rotationZ.IncomingTangent,
                                                 rotationZ.OutgoingTangent);
                    }
                }
            }

            // TODO: Move these reads into the model reading logic
            var ctrTexture    = new CtrTexture();
            var textureImages =
                cmb.tex.textures.Select(cmbTexture => {
                var position = cmb.startOffset +
                               cmb.header.textureDataOffset +
                               cmbTexture.dataOffset;
                IImage image;
                if (position != 0)
                {
                    r.Position = position;
                    var data   =
                        r.ReadBytes((int)cmbTexture.dataLength);
                    image =
                        ctrTexture.DecodeImage(data, cmbTexture);
                }
                else
                {
                    var ctxb =
                        filesAndCtxbs
                        .Select(
                            fileAndCtxb => fileAndCtxb.Item2)
                        .Single(ctxb => ctxb.Chunk.Entry.name == cmbTexture.name);
                    image =
                        ctrTexture.DecodeImage(ctxb.Data,
                                               cmbTexture);
                }
                return(image);
            })
                .ToArray();

            // Creates meshes & textures
            // TODO: Emulate fixed-function materials
            var finMaterials = new List <IMaterial>();

            for (var i = 0; i < cmb.mat.materials.Length; ++i)
            {
                var cmbMaterial = cmb.mat.materials[i];

                // Get associated texture
                var texMapper = cmbMaterial.texMappers[0];
                var textureId = texMapper.textureId;

                ITexture?finTexture = null;
                if (textureId != -1)
                {
                    var cmbTexture   = cmb.tex.textures[textureId];
                    var textureImage = textureImages[textureId];

                    finTexture           = finModel.MaterialManager.CreateTexture(textureImage);
                    finTexture.Name      = cmbTexture.name;
                    finTexture.WrapModeU = this.CmbToFinWrapMode(texMapper.wrapS);
                    finTexture.WrapModeV = this.CmbToFinWrapMode(texMapper.wrapT);
                }

                // Create material
                IMaterial finMaterial = finTexture != null
                                    ? finModel.MaterialManager
                                        .AddTextureMaterial(
                    finTexture)
                                    : finModel.MaterialManager
                                        .AddLayerMaterial();

                finMaterial.Name        = $"material{i}";
                finMaterial.CullingMode = cmbMaterial.faceCulling switch {
                    CullMode.FrontAndBack => CullingMode.SHOW_BOTH,
                    CullMode.Front => CullingMode.SHOW_FRONT_ONLY,
                    CullMode.BackFace => CullingMode.SHOW_BACK_ONLY,
                    CullMode.Never => CullingMode.SHOW_NEITHER,
                    _ => throw new NotImplementedException(),
                };

                finMaterials.Add(finMaterial);
            }

            /*{
             * var nameToTextures = new Dictionary<string, ITexture>();
             * foreach (var finMaterial in finMaterials) {
             *  foreach (var finTexture in finMaterial.Textures) {
             *    nameToTextures[finTexture.Name] = finTexture;
             *  }
             * }
             *
             * foreach (var (_, finTexture) in nameToTextures) {
             *  finTexture.ImageData.Save(
             *      Path.Join(outputDirectory.FullName, finTexture.Name + ".png"));
             * }
             * }*/

            var verticesByIndex = new ListDictionary <int, IVertex>();

            // Adds meshes
            foreach (var cmbMesh in cmb.sklm.meshes.meshes)
            {
                var shape = cmb.sklm.shapes.shapes[cmbMesh.shapeIndex];

                uint vertexCount = 0;
                var  meshIndices = new List <uint>();
                foreach (var pset in shape.primitiveSets)
                {
                    foreach (var index in pset.primitive.indices)
                    {
                        meshIndices.Add(index);
                        vertexCount = Math.Max(vertexCount, index);
                    }
                }
                ++vertexCount;

                var preproject    = new bool?[vertexCount];
                var skinningModes = new SkinningMode?[vertexCount];
                foreach (var pset in shape.primitiveSets)
                {
                    foreach (var index in pset.primitive.indices)
                    {
                        skinningModes[index] = pset.skinningMode;
                        preproject[index]    = pset.skinningMode != SkinningMode.Smooth;
                    }
                }

                // Gets flags
                var inc    = 1;
                var hasNrm = BitLogic.GetFlag(shape.vertFlags, inc++);
                if (cmb.header.version > CmbVersion.OCARINA_OF_TIME_3D)
                {
                    // Skip "HasTangents" for now
                    inc++;
                }
                var hasClr = BitLogic.GetFlag(shape.vertFlags, inc++);
                var hasUv0 = BitLogic.GetFlag(shape.vertFlags, inc++);
                var hasUv1 = BitLogic.GetFlag(shape.vertFlags, inc++);
                var hasUv2 = BitLogic.GetFlag(shape.vertFlags, inc++);
                var hasBi  = BitLogic.GetFlag(shape.vertFlags, inc++);
                var hasBw  = BitLogic.GetFlag(shape.vertFlags, inc++);

                // Gets bone indices
                var boneCount = shape.boneDimensions;
                var bIndices  = new short[vertexCount * boneCount];
                foreach (var pset in shape.primitiveSets)
                {
                    foreach (var i in pset.primitive.indices)
                    {
                        if (hasBi && pset.skinningMode != SkinningMode.Single)
                        {
                            r.Position = cmb.startOffset +
                                         cmb.header.vatrOffset +
                                         cmb.vatr.bIndices.StartOffset +
                                         shape.bIndices.Start +
                                         i *
                                         DataTypeUtil.GetSize(shape.bIndices.DataType) *
                                         shape.boneDimensions;
                            for (var bi = 0; bi < shape.boneDimensions; ++bi)
                            {
                                var boneTableIndex = shape.bIndices.Scale *
                                                     DataTypeUtil.Read(
                                    r,
                                    shape.bIndices.DataType);
                                bIndices[i * boneCount + bi] =
                                    pset.boneTable[(int)boneTableIndex];
                            }
                        }
                        else
                        {
                            bIndices[i] = shape.primitiveSets[0].boneTable[0];
                        }
                    }
                }

                var finMesh = finSkin.AddMesh();

                // TODO: Encapsulate these reads somewhere else
                // Get vertices
                var finVertices = new IVertex[vertexCount];
                for (var i = 0; i < vertexCount; ++i)
                {
                    // Position
                    r.Position = cmb.startOffset +
                                 cmb.header.vatrOffset +
                                 cmb.vatr.position.StartOffset +
                                 shape.position.Start +
                                 3 * DataTypeUtil.GetSize(shape.position.DataType) * i;
                    var positionValues =
                        DataTypeUtil.Read(r, 3, shape.position.DataType)
                        .Select(value => value * shape.position.Scale)
                        .ToArray();

                    var finVertex = finSkin.AddVertex(positionValues[0],
                                                      positionValues[1],
                                                      positionValues[2]);
                    finVertices[i] = finVertex;

                    var index = (ushort)(shape.position.Start / 3 + i);
                    verticesByIndex.Add(index, finVertex);

                    if (hasNrm)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.normal.StartOffset +
                                     shape.normal.Start +
                                     3 * DataTypeUtil.GetSize(shape.normal.DataType) * i;
                        var normalValues =
                            DataTypeUtil.Read(r, 3, shape.normal.DataType)
                            .Select(value => value * shape.normal.Scale)
                            .ToArray();
                        finVertex.SetLocalNormal(normalValues[0],
                                                 normalValues[1],
                                                 normalValues[2]);
                    }

                    if (hasClr)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.color.StartOffset +
                                     shape.color.Start +
                                     4 * DataTypeUtil.GetSize(shape.color.DataType) * i;
                        var colorValues =
                            DataTypeUtil.Read(r, 4, shape.color.DataType)
                            .Select(value => value * shape.color.Scale)
                            .ToArray();

                        finVertex.SetColorBytes((byte)(colorValues[0] * 255),
                                                (byte)(colorValues[1] * 255),
                                                (byte)(colorValues[2] * 255),
                                                (byte)(colorValues[3] * 255));
                    }

                    if (hasUv0)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.uv0.StartOffset +
                                     shape.uv0.Start +
                                     2 * DataTypeUtil.GetSize(shape.uv0.DataType) * i;
                        var uv0Values =
                            DataTypeUtil.Read(r, 2, shape.uv0.DataType)
                            .Select(value => value * shape.uv0.Scale)
                            .ToArray();

                        finVertex.SetUv(0, uv0Values[0], 1 - uv0Values[1]);
                    }
                    if (hasUv1)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.uv1.StartOffset +
                                     shape.uv1.Start +
                                     2 * DataTypeUtil.GetSize(shape.uv1.DataType) * i;
                        var uv1Values =
                            DataTypeUtil.Read(r, 2, shape.uv1.DataType)
                            .Select(value => value * shape.uv1.Scale)
                            .ToArray();

                        finVertex.SetUv(1, uv1Values[0], 1 - uv1Values[1]);
                    }
                    if (hasUv2)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.uv2.StartOffset +
                                     shape.uv2.Start +
                                     2 * DataTypeUtil.GetSize(shape.uv2.DataType) * i;
                        var uv2Values =
                            DataTypeUtil.Read(r, 2, shape.uv2.DataType)
                            .Select(value => value * shape.uv2.Scale)
                            .ToArray();

                        finVertex.SetUv(2, uv2Values[0], 1 - uv2Values[1]);
                    }

                    var preprojectMode = preproject[i].Value
                                   ? PreprojectMode.BONE
                                   : PreprojectMode.NONE;

                    if (hasBw)
                    {
                        r.Position = cmb.startOffset +
                                     cmb.header.vatrOffset +
                                     cmb.vatr.bWeights.StartOffset +
                                     shape.bWeights.Start +
                                     i *
                                     DataTypeUtil.GetSize(shape.bWeights.DataType) *
                                     boneCount;

                        var totalWeight = 0f;
                        var boneWeights = new List <BoneWeight>();
                        for (var j = 0; j < boneCount; ++j)
                        {
                            // TODO: Looks like this is rounded to the nearest 2 in the original??
                            var weight = DataTypeUtil.Read(r, shape.bWeights.DataType) *
                                         shape.bWeights.Scale;
                            totalWeight += weight;

                            if (weight > 0)
                            {
                                var bone =
                                    finBones[bIndices[i * boneCount + j]];
                                var boneWeight = new BoneWeight(bone, null, weight);

                                boneWeights.Add(boneWeight);
                            }
                        }

                        Asserts.True(boneWeights.Count > 0);
                        Asserts.True(Math.Abs(1 - totalWeight) < .0001);
                        finVertex.SetBoneWeights(
                            finSkin.GetOrCreateBoneWeights(preprojectMode,
                                                           boneWeights.ToArray()));
                    }
                    else
                    {
                        var boneIndex = bIndices[i];
                        finVertex.SetBoneWeights(
                            finSkin.GetOrCreateBoneWeights(preprojectMode,
                                                           finBones[boneIndex]));
                    }

                    finVertex.SetColor(ColorImpl.FromSystemColor(Color.White));
                }

                // Adds faces. Thankfully, it's all just triangles!
                var triangleVertices = meshIndices
                                       .Select(meshIndex => finVertices[meshIndex])
                                       .ToArray();
                finMesh.AddTriangles(triangleVertices)
                .SetMaterial(finMaterials[cmbMesh.materialIndex])
                .SetVertexOrder(VertexOrder.NORMAL);
            }

            // Adds morph targets
            foreach (var(shpaFile, shpa) in filesAndShpas)
            {
                var shpaIndexToPosi =
                    shpa?.Posi.Values.Select((posi, i) => (shpa.Idxs.Indices[i], posi))
                    .ToDictionary(indexAndPosi => indexAndPosi.Item1,
                                  indexAndPosi => indexAndPosi.posi);

                var morphTarget = finModel.AnimationManager.AddMorphTarget();
                morphTarget.Name = shpaFile.NameWithoutExtension;

                foreach (var(index, position) in shpaIndexToPosi)
                {
                    if (!verticesByIndex.TryGetList(index, out var finVertices))
                    {
                        continue;
                    }

                    foreach (var finVertex in finVertices)
                    {
                        morphTarget.MoveTo(finVertex, position);
                    }
                }
            }

            return(finModel);
        }