Example #1
0
        private static MDLObject LoadMDLMesh(System.IO.BinaryReader br)
        {
            MDLMesh mesh = new MDLMesh();

            mesh.nvertex  = br.ReadInt32();
            mesh.nfaces   = br.ReadInt32();
            mesh.vertices = new MDLVertice[mesh.nvertex];
            for (int n = 0; n < mesh.nvertex; n++)
            {
                // read vertice
                MDLVertice vert = new MDLVertice();
                vert.x           = br.ReadSingle();
                vert.y           = br.ReadSingle();;
                vert.z           = br.ReadSingle();;
                vert.mx          = br.ReadSingle();;
                vert.my          = br.ReadSingle();;
                vert.nx          = br.ReadSingle();;
                vert.ny          = br.ReadSingle();;
                vert.nz          = br.ReadSingle();;
                mesh.vertices[n] = vert;
            }
            mesh.faces = new ushort[mesh.nfaces];
            for (int n = 0; n < mesh.nfaces; n++)
            {
                mesh.faces[n] = br.ReadUInt16();
            }
            MDLObject mdlo = MDLFile.NewMDLObject();

            mdlo.mesh = mesh;
            mdlo.type = MDLType.mdl_mesh;
            return(mdlo);
        }
Example #2
0
        public void Setup()
        {
            if (!TestRuntime.CheckXcodeVersion(7, 0))
            {
                Assert.Ignore("Requires iOS 9.0+ or macOS 10.11+");
            }

            if (
#if !MONOMAC
                Runtime.Arch == Arch.SIMULATOR &&
#endif
                IntPtr.Size == 4)
            {
                // There's a bug in the i386 version of objc_msgSend where it doesn't preserve SIMD arguments
                // when resizing the cache of method selectors for a type. So here we call all selectors we can
                // find, so that the subsequent tests don't end up producing any cache resize (radar #21630410).
                using (var obj = new MDLObject()) {
                    object dummy;
                    obj.SetComponent(new MDLTransform(), new Protocol("MDLComponent"));
                    obj.IsComponentConforming(new Protocol("MDLComponent"));
                    dummy = obj.Parent;
                    dummy = obj.Transform;
                    obj.AddChild(new MDLObject());
                    obj.GetBoundingBox(0);
                }
            }
        }
Example #3
0
 public void ProtocolTest()
 {
     using (var obj = new MDLObject()) {
         var p = new Protocol(typeof(IMDLComponent));
         obj.SetComponent(new MDLTransform(), p);
         Assert.NotNull(obj.IsComponentConforming(p));
     }
 }
        public void CreateGlobalTransformTest()
        {
            Matrix4        m4;
            MatrixFloat4x4 m4x4;

            using (var obj = new MDLObject()) {
                m4 = MDLTransform.CreateGlobalTransform(obj, 0);
                Asserts.AreEqual((Matrix4)MatrixFloat4x4.Transpose(CFunctions.MDLTransform_CreateGlobalTransform(obj, 0)), m4, "CreateGlobalTransform");

                m4x4 = MDLTransform.CreateGlobalTransform4x4(obj, 0);
                Asserts.AreEqual(CFunctions.MDLTransform_CreateGlobalTransform(obj, 0), m4, "CreateGlobalTransform4x4");
            }
        }
Example #5
0
        protected ArrayList FlattenChildren(MDLObject obj)
        {
            ArrayList ares = new ArrayList(0);

            if (obj.type == MDLType.mdl_group)
            {
                MDLMesh[] childmeshes = new MDLMesh[obj.nchildren];
                for (int i = 0; i < obj.nchildren; i++)
                {
                    ares.AddRange(FlattenChildren(obj.childrens[i]));
                }
            }
            if (obj.type == MDLType.mdl_mesh)
            {
                ares.Add(obj);
            }
            return(ares);
        }
Example #6
0
 public BinaryMDL(MDL.MDLFile mdlf)
 {
     this.binaryHeader._1_MDLMagic           = 0xDEBADF00;
     binaryHeader._2_MDLVersion              = mdlf.header.MDLVersion;
     binaryHeader._3_ImportedNameSpacesCount = mdlf.header.ImportedNameSpacesCount;
     binaryHeader._4_ImportedSymbolCount     = mdlf.header.ImportedSymoblCount;
     binaryHeader._5_ExportedSymbolCount     = mdlf.header.ExportedSymbolCount;
     binaryHeader._6_OtherObjectCount        = mdlf.header.OtherObjectsCount;
     if (mdlf.Lights != null)
     {
         lights = new List <MDLLight>(mdlf.Lights);
     }
     if (mdlf.FrameDatas != null)
     {
         frames = new List <MDLFrameData>(mdlf.FrameDatas);
     }
     if (mdlf.Textures != null)
     {
         textures = new List <string>(mdlf.Textures);
     }
     mainObject = mdlf.RootObject;
     FrameVal   = mdlf.FrameVal;
 }
Example #7
0
 public void GetBoundingBox()
 {
     using (var obj = MDLObject.FromNode(SCNNode.FromGeometry(SCNBox.Create(1, 1, 1, 0)))) {
         var bb = obj.GetBoundingBox(0);
     }
 }
Example #8
0
 public static MatrixFloat4x4 CreateGlobalTransform4x4(MDLObject obj, double atTime)
 {
     return(MatrixFloat4x4.Transpose((MatrixFloat4x4)CreateGlobalTransform(obj, atTime)));
 }
Example #9
0
        /// <summary>
        /// The device has been created.  Resources that are not lost on
        /// Reset() can be created here -- resources in Pool.Managed,
        /// Pool.Scratch, or Pool.SystemMemory.  Image surfaces created via
        /// CreateImageSurface are never lost and can be created here.  Vertex
        /// shaders and pixel shaders can also be created here as they are not
        /// lost on Reset().
        /// </summary>
        protected override void InitializeDeviceObjects()
        {
            // Initialize the drawingFont's internal textures
            drawingFont.InitializeDeviceObjects(device);

            //ExtendedMaterial[] mtrl = null;
            mdlfile = new MDLFile();
            string path = DXUtil.FindMediaFile(initialDirectory, meshFilename);

            try
            {
                //systemMemoryMesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out adjacency, out mtrl);
                if (!mdlfile.ReadFromFile(initialDirectory + "\\" + meshFilename))
                {
                    throw new FileLoadException("not a valide MDL file.", meshFilename);
                }
                MDLObject obj = mdlfile.RootObject;
                rootmdl = obj;

                CBLOD.Items.Clear();
                if (obj.type == MDLType.mdl_lod)
                {
                    CBLOD.Enabled = true;
                    for (int i = 0; i < obj.nchildren; i++)
                    {
                        CBLOD.Items.Add(obj.childrens[i].lodval);
                    }
                    obj = obj.childrens[0];
                    CBLOD.SelectedIndex = 0;
                }
                else
                {
                    CBLOD.Enabled = false;
                }

                //				while (obj.type != MDLType.mdl_mesh)
                //				{
                //					if (obj.childrens[0].type == MDLType.mdl_empty)
                //						obj = obj.childrens[1];
                //					else
                //						obj = obj.childrens[0];
                //
                //				}
                // process textures
                if (mdlfile.NumTextures > 0)
                {
                    meshMaterials = new Material[mdlfile.NumTextures];
                    meshTextures  = new Texture[mdlfile.NumTextures];
                    for (int i = 0; i < mdlfile.NumTextures; i++)
                    {
                        meshMaterials[i]         = new Direct3D.Material();
                        meshMaterials[i].Ambient = Color.White;
                        meshMaterials[i].Diffuse = Color.White;

                        MDLFile mdlbmp = new MDLFile();
                        if (mdlbmp.ReadFromFile(initialDirectory + "\\" + mdlfile.Textures[i] + ".mdl"))
                        {
                            if (mdlbmp.RootObject.type == MDLType.mdl_image)
                            {
                                MDLImage     mdlimg    = mdlbmp.RootObject.image;
                                MemoryStream memstream = new MemoryStream(mdlimg.bitmap);
                                try
                                {
                                    //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.bitmap.Length,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.Managed,Filter.Linear,Filter.Linear,0);
                                    //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.SystemMemory,Filter.Linear,Filter.Linear,1);
                                    Bitmap     bitmap = new Bitmap(mdlimg.w, mdlimg.h, PixelFormat.Format16bppRgb565);
                                    Rectangle  rect   = new Rectangle(0, 0, mdlimg.w, mdlimg.h);
                                    BitmapData bmdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format16bppRgb565);
                                    IntPtr     pixels = bmdata.Scan0;
                                    unsafe
                                    {
                                        byte *pBits = (byte *)pixels.ToPointer();
                                        for (int p = 0; p < mdlimg.bitmap.Length; p++)
                                        {
                                            pBits[p] = mdlimg.bitmap[p];
                                        }
                                    }
                                    bitmap.UnlockBits(bmdata);
                                    //bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
                                    meshTextures[i] = Texture.FromBitmap(device, bitmap, Usage.AutoGenerateMipMap, Pool.Managed);
                                }
                                catch (Exception e)
                                {
                                    string mess = e.Message;
                                    MessageBox.Show("error loading texture '" + mdlfile.Textures[i] + ".mdl'. " + e.Message);
                                }
                            }
                        }
                    }
                }

                ArrayList objs = FlattenChildren(obj);

                Meshes       = new Mesh[objs.Count];
                MeshesEnable = new bool[objs.Count];
                MeshesTex    = new int[objs.Count];
                objectRadius = 0;
                tvObj.Nodes.Clear();

                for (int oi = 0; oi < objs.Count; oi++)
                {
                    obj = (MDLObject)objs[oi];


                    TreeNode tn = new TreeNode("part " + oi.ToString());
                    tn.Tag     = oi;
                    tn.Checked = true;
                    tn.Nodes.Add("# vertices = " + obj.mesh.nvertex.ToString());
                    tn.Nodes.Add("# faces = " + (obj.mesh.nfaces / 3).ToString());
                    if (obj.textidx == -1)
                    {
                        tn.Nodes.Add("no texture");
                    }
                    else
                    {
                        tn.Nodes.Add("texture = " + mdlfile.Textures[obj.textidx]);
                    }
                    tvObj.Nodes.Add(tn);

                    // process mesh
                    systemMemoryMesh = new Mesh(obj.mesh.nfaces / 3, obj.mesh.nvertex, MeshFlags.SystemMemory, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture1, device);

                    //systemMemoryMesh = Mesh.Box(device,12,15,2);
                    VertexBuffer pVB           = systemMemoryMesh.VertexBuffer;
                    int          dwNumVertices = systemMemoryMesh.NumberVertices;

                    CustomVertex.PositionNormalTextured [] dest =
                        (CustomVertex.PositionNormalTextured [])pVB.Lock(0,
                                                                         typeof(CustomVertex.PositionNormalTextured), 0, dwNumVertices);

                    for (int i = 0; i < dest.Length; i++)
                    {
                        dest[i].X = obj.mesh.vertices[i].x;
                        dest[i].Y = obj.mesh.vertices[i].y;
                        dest[i].Z = obj.mesh.vertices[i].z;

                        dest[i].Nx = obj.mesh.vertices[i].nx;
                        dest[i].Ny = obj.mesh.vertices[i].ny;
                        dest[i].Nz = obj.mesh.vertices[i].nz;

                        dest[i].Tu = obj.mesh.vertices[i].mx;
                        dest[i].Tv = obj.mesh.vertices[i].my;
                    }

                    pVB.Unlock();

                    int      dwNumFaces = systemMemoryMesh.NumberFaces * 3;
                    ushort[] idxs       = (ushort[])systemMemoryMesh.LockIndexBuffer(typeof(ushort), 0, dwNumFaces);

                    for (int i = 0; i < dwNumFaces; i += 3)
                    {
                        idxs[i]     = obj.mesh.faces[i];
                        idxs[i + 1] = obj.mesh.faces[i + 2];
                        idxs[i + 2] = obj.mesh.faces[i + 1];
                    }
                    systemMemoryMesh.UnlockIndexBuffer();
                    //systemMemoryMesh.SetIndexBufferData(obj.mesh.faces,LockFlags.None);
                    // Lock the vertex buffer, to generate a simple bounding sphere
                    VertexBuffer vb = null;
                    try
                    {
                        vb = systemMemoryMesh.VertexBuffer;
                        GraphicsStream vbStream = vb.Lock(0, 0, 0);
                        objectRadius = Math.Max(objectRadius, Geometry.ComputeBoundingSphere(vbStream, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out objectCenter));
                    }
                    finally
                    {
                        // Make sure we unlock the buffer if we fail
                        if (vb != null)
                        {
                            vb.Unlock();
                        }
                    }
                    // Make sure there are normals, which are required for the tesselation
                    // enhancement
                    if ((systemMemoryMesh.VertexFormat & VertexFormats.Normal) != VertexFormats.Normal)
                    {
                        Mesh tempMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value, systemMemoryMesh.VertexFormat | VertexFormats.Normal, device);

                        tempMesh.ComputeNormals();
                        systemMemoryMesh.Dispose();
                        systemMemoryMesh = tempMesh;
                    }
                    Meshes[oi]       = systemMemoryMesh;
                    MeshesEnable[oi] = true;
                    MeshesTex[oi]    = obj.textidx;
                }                 // oi loop
                tvObj.ExpandAll();
                objectCenter = new Vector3(0, 0, 0);
            }             // try
            catch
            {
                // Hide the error so we display a blue screen
                return;
            }
        }
Example #10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("mesh_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("mesh_fragment");

            // Generate meshes
            MTKMeshBufferAllocator mtkBufferAllocator = new MTKMeshBufferAllocator(device);
            NSUrl     url       = NSBundle.MainBundle.GetUrlForResource("Fighter", "obj");
            MDLAsset  mdlAsset  = new MDLAsset(url, new MDLVertexDescriptor(), mtkBufferAllocator);
            MDLObject mdlObject = mdlAsset.GetObject(0);
            MDLMesh   mdlMesh   = mdlObject as MDLMesh;

            NSError error;

            objMesh = new MTKMesh(mdlMesh, device, out error);

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = MTLVertexDescriptor.FromModelIO(objMesh.VertexDescriptor);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 1, 2), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            this.proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);

            this.constantBuffer = device.CreateBuffer((uint)Marshal.SizeOf(this.param), MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat
            };

            pipelineStateDescriptor.ColorAttachments[0].PixelFormat = mtkView.ColorPixelFormat;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            NSImage          image            = NSImage.ImageNamed("Fighter_Diffuse.jpg");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.texture = mTKTextureLoader.FromCGImage(image.CGImage, new MTKTextureLoaderOptions(), out error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.ClampToEdge,
                TAddressMode = MTLSamplerAddressMode.ClampToEdge,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);
        }
Example #11
0
        private void WriteBinaryFileInfo(string varname)
        {
            // DISPLAY BINARY MDL INFO
            if (currentBinaryMDL != null && lstInternalImages.Visible == false)
            {
                CultureInfo   ci = new CultureInfo("en-us");
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("---Binary MDL---");
                sb.AppendLine("--Header--");
                sb.AppendLine("MDLMagic: " + currentBinaryMDL.header.MDLMAGIC.ToString("X", ci));
                sb.AppendLine("MDLVersion: " + currentBinaryMDL.header.MDLVersion.ToString("X", ci));
                sb.AppendLine("Imported Libs: " + currentBinaryMDL.header.ImportedNameSpacesCount.ToString());
                sb.AppendLine("Imported Symbols: " + currentBinaryMDL.header.ImportedSymoblCount.ToString());
                sb.AppendLine("Exported Symbols: " + currentBinaryMDL.header.ExportedSymbolCount.ToString());
                sb.AppendLine("Others Objs: " + currentBinaryMDL.header.OtherObjectsCount.ToString());

                sb.AppendLine("");
                sb.AppendLine("--Imported Libraries:" + currentBinaryMDL.header.NameSpaces.Count);
                foreach (string item in currentBinaryMDL.header.NameSpaces)
                {
                    sb.AppendLine("\t NameSpace:" + item);
                }
                sb.AppendLine("--Imported Symbols:" + currentBinaryMDL.header.ImportedSymbols.Count);
                foreach (SymbolPair item in currentBinaryMDL.header.ImportedSymbols)
                {
                    sb.AppendFormat("\t Sym:[{0},{1}] {2}", item.Name, item.Value, Environment.NewLine);
                }
                sb.AppendLine("--Exported Symbols:" + currentBinaryMDL.header.ExportedSymbols.Count);
                foreach (string item in currentBinaryMDL.header.ExportedSymbols)
                {
                    sb.AppendLine("\t Sym: " + item);
                }
                sb.AppendLine("--Exported Symbol Data:" + currentBinaryMDL.Textures.Count);
                foreach (var item in currentBinaryMDL.RootObject.Where(x => x.type == MDLType.mdl_image).Select(x => x.image))
                {
                    sb.AppendFormat("Data:[MDLImage]: {0}", Environment.NewLine);

                    sb.AppendLine("\t Width: " + item.ImageHeader.width.ToString());
                    sb.AppendLine("\t Height: " + item.ImageHeader.height.ToString());
                    sb.AppendLine("\t Pitch: " + item.ImageHeader.pitch.ToString());
                    sb.AppendLine("\t Bpp: " + item.ImageHeader.bitCount.ToString());
                    sb.AppendLine("\t RedMask: " + item.ImageHeader.redMask.ToString());
                    sb.AppendLine("\t GreenMask: " + item.ImageHeader.greenMask.ToString());
                    sb.AppendLine("\t BlueMask: " + item.ImageHeader.blueMask.ToString());
                    sb.AppendLine("\t AlphaMask: " + item.ImageHeader.alphaMask.ToString());
                    sb.AppendLine("\t ColorKey: " + item.ImageHeader.UseColorKey.ToString());
                }
                if (currentBinaryMDL.Lights != null)
                {
                    sb.AppendFormat("Data:[MDLLights]: {0}", Environment.NewLine);
                    foreach (var item in currentBinaryMDL.Lights)
                    {
                        sb.AppendLine(string.Format("\t Light: speed({0}) color({1},{2},{3}) pos({4},{5},{6})", Convert.ToInt32(item.red * 255), Convert.ToInt32(item.green * 255), Convert.ToInt32(item.blue * 255), item.speed.ToString(), item.posx, item.posy, item.posz));
                    }
                }
                if (currentBinaryMDL.FrameDatas != null)
                {
                    sb.AppendFormat("Data:[MDLFrames]: {0}", Environment.NewLine);
                    foreach (var item in currentBinaryMDL.FrameDatas)
                    {
                        sb.AppendLine(string.Format("\t Frame: {0} pos({1},{2},{3}) n({4},{5},{6}) p({7},{8},{9})", item.name, item.posx, item.posy, item.posz, item.nx, item.ny, item.nz, item.px, item.py, item.pz));
                    }
                }
                if (currentBinaryMDL.Textures.Count > 0)
                {
                    sb.AppendFormat("Data:[MDLTexture]: {0}", Environment.NewLine);
                    foreach (var item in currentBinaryMDL.Textures)
                    {
                        sb.AppendLine(string.Format("\t Texture: {0} ref: {1}", item.Key, item.Value));
                    }
                }

                for (int i = 0; i < currentBinaryMDL.RootObject.Count; i++)
                {
                    MDLObject obj = currentBinaryMDL.RootObject[i];
                    if (obj.type == MDLType.mdl_mesh)
                    {
                        sb.AppendFormat("Data:[MDLMesh]: {0}", Environment.NewLine);
                        sb.AppendLine("\t Faces: " + obj.mesh.faces.Count());
                        sb.AppendLine("\t NFaces: " + obj.mesh.nfaces.ToString());
                        sb.AppendLine("\t NVertex: " + obj.mesh.nvertex.ToString());
                        sb.AppendLine("\t VerticiesLoaded: " + obj.mesh.vertices.Count());
                        sb.AppendLine("\t TextureIndex: " + obj.textidx.ToString());
                        if (obj.textidx > -1 && currentBinaryMDL.Textures.Count > obj.textidx)
                        {
                            sb.AppendLine(string.Format("\t\t Maps to Texture({0})", currentBinaryMDL.Textures.ElementAt(obj.textidx)));
                        }
                        else
                        {
                            sb.AppendLine(string.Format("\t\t Maps to Texture( Error! - BAD Index - No Texture at Index {0})", obj.textidx.ToString()));
                        }
                        sb.AppendLine("\t LOD: " + obj.lodval.ToString());
                    }
                }

                txtBinaryHeader.Text       = sb.ToString();
                txtBinaryHeader.ScrollBars = ScrollBars.Both;
            }
        }