Exemple #1
0
        public Form1()
        {
            InitializeComponent();

            using ( System.IO.FileStream S = new System.IO.FileInfo( "../TestAreaLight/BRDF0_64x64.table" ).OpenRead() )
                using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) )
                    for ( int i=0; i < 64; i++ ) {
                        m_IntegralSpecularReflection[i,0] = R.ReadSingle();
                        m_IntegralSpecularReflection[i,1] = R.ReadSingle();
                    }
            outputPanelDiffuseFresnelReflectance.m_Table = m_IntegralSpecularReflection;
        }
 public static Single ReadMemorySingle(IntPtr handle, IntPtr addr)
 {
     byte[] Buffer = new Byte[4];
     Single i = 0;
     Buffer = ReadProcessMemory(handle, (int)addr, 4);
     try
     {
         System.IO.MemoryStream ms = new System.IO.MemoryStream(Buffer);
         System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
         i = br.ReadSingle();
     }
     finally
     {
     }
     return i;
 }
Exemple #3
0
 public AlchemyRecordData(System.IO.BinaryReader reader)
 {
     weight   = reader.ReadSingle();
     value    = reader.ReadInt32();
     autoCalc = reader.ReadInt32();
 }
Exemple #4
0
 public SkinWeight(System.IO.BinaryReader reader)
 {
     Index  = reader.ReadInt16();
     Weight = reader.ReadSingle();
 }
Exemple #5
0
 public Vec2f ReadStream(System.IO.BinaryReader reader)
 {
     return(new Vec2f(reader.ReadSingle(), reader.ReadSingle()));
 }
Exemple #6
0
        private void bEdit_Click(object sender, EventArgs e)
        {
            if(dataGridView1.SelectedRows.Count!=1) return;
            int i=dataGridView1.SelectedRows[0].Index;
            switch(mode) {
            case Mode.Arrays: {
                    DataType[] types=new DataType[connection.ArrayLengths[i]];
                    string[] strings=new string[connection.ArrayLengths[i]];
                    connection.WriteDataType(DataTypeSend.GetArray);
                    connection.WriteInt(i);
                    for(int j=0;j<strings.Length;j++) types[j]=(DataType)connection.ReadInt();
                    byte[] buf=connection.ReadBytes(connection.ArrayLengths[i]*connection.ArrayDataSizes[i]);
                    MemoryStream ms=new MemoryStream(buf);
                    BinaryReader br=new BinaryReader(ms);
                    for(int j=0;j<strings.Length;j++) {
                        ms.Position=j*connection.ArrayDataSizes[i];
                        switch(types[j]) {
                        case DataType.Int:
                            strings[j]=br.ReadInt32().ToString();
                            break;
                        case DataType.Float:
                            strings[j]=br.ReadSingle().ToString();
                            break;
                        case DataType.String:
                            byte[] bytes=br.ReadBytes(connection.ArrayDataSizes[i]);
                            strings[j]=System.Text.Encoding.ASCII.GetString(bytes, 0, Array.IndexOf<byte>(bytes, 0));
                            break;
                        }
                    }
                    br.Close();
                    strings=EditorWindow.ShowEditor(null, types, strings);
                    if(strings!=null) {
                        connection.WriteDataType(DataTypeSend.SetArray);
                        connection.WriteInt(i);
                        ms=new MemoryStream(connection.ArrayLengths[i]*connection.ArrayDataSizes[i]);
                        BinaryWriter bw=new BinaryWriter(ms);
                        for(int j=0;j<strings.Length;j++) {
                            ms.Position=j*connection.ArrayDataSizes[i];
                            switch(types[j]) {
                            case DataType.Int:
                                bw.Write(int.Parse(strings[j]));
                                break;
                            case DataType.Float:
                                bw.Write(float.Parse(strings[j]));
                                break;
                            case DataType.String:
                                byte[] bytes=System.Text.Encoding.ASCII.GetBytes(strings[j]);
                                if(bytes.Length<connection.ArrayDataSizes[i]) bw.Write(bytes);
                                else bw.Write(bytes, 0, connection.ArrayDataSizes[i]-1);
                                bw.Write(0);
                                break;
                            }
                        }
                        connection.WriteBytes(ms.GetBuffer(), 0, connection.ArrayLengths[i]*connection.ArrayDataSizes[i]);
                        bw.Close();
                    }
                }
                break;
            case Mode.Critters: {
                    DataType[] types=new DataType[29];
                    string[] strings=new string[29];
                    string[] names=new string[29];
                    connection.WriteDataType(DataTypeSend.RetrieveCritter);
                    connection.WriteInt(i);
                    BinaryReader br=new BinaryReader(new System.IO.MemoryStream(connection.ReadBytes(29*4)));
                    for(int j=0;j<29;j++) {
                        types[j]=DataType.Int;
                        strings[j]=br.ReadInt32().ToString();
                        names[j]="0x"+(j*4).ToString("x");
                    }
                    br.Close();
                    names[1]="Tile";
                    names[10]="Elevation";
                    names[11]="Inventory count";
                    names[13]="Inventory pointer";
                    names[16]="Current AP";
                    names[17]="Crippled limbs";
                    names[22]="HP";
                    names[23]="Rads";
                    names[24]="Poison";
                    names[25]="Proto ID";
                    strings=EditorWindow.ShowEditor(names, types, strings);
                    if(strings!=null) {
                        MemoryStream ms=new MemoryStream(29*4);
                        BinaryWriter bw=new BinaryWriter(ms);
                        for(int j=0;j<29;j++) bw.Write(int.Parse(strings[j]));
                        connection.WriteDataType(DataTypeSend.SetCritter);
                        connection.WriteInt(i);
                        connection.WriteBytes(ms.GetBuffer(), 0, 29*4);
                        bw.Close();
                    }

                }
                break;
            }
        }
Exemple #7
0
        private void readMeshFrame(System.IO.BinaryReader reader, uint frameNum, uint meshIndex, uint sectionLength)
        {
            long end        = reader.BaseStream.Position + sectionLength;
            uint frameIndex = frameNum * _numMeshes + meshIndex;

            while (reader.BaseStream.Position < end)
            {
                ActSubsectionHeader subsection;
                subsection.Type     = reader.ReadByte();
                subsection.DataSize = reader.ReadUInt32();

                if (subsection.Type == (byte)ActSubsectionType.Group)
                {
                    ushort groupIndex  = reader.ReadUInt16();
                    ushort numVertices = reader.ReadUInt16();

                    float[] vertices = new float[numVertices * 3];
                    for (ushort j = 0; j < numVertices; j++)
                    {
                        vertices[j * 3 + 0] = reader.ReadSingle();
                        vertices[j * 3 + 1] = reader.ReadSingle();
                        vertices[j * 3 + 2] = reader.ReadSingle();
                    }

                    _frames[frameIndex].Active = true;
                    if (_frames[frameIndex].Vertices == null)
                    {
                        _frames[frameIndex].Vertices = new List <FrameSectionVertices>();
                    }

                    FrameSectionVertices sectionVertices;
                    sectionVertices.SectionIndex = groupIndex;
                    sectionVertices.Vertices     = vertices;
                    _frames[frameIndex].Vertices.Add(sectionVertices);
                }
                else if (subsection.Type == (byte)ActSubsectionType.DeltaGroup)
                {
                    ushort groupIndex  = reader.ReadUInt16();
                    ushort numVertices = reader.ReadUInt16();

                    byte[] bitfield = reader.ReadBytes(numVertices / 4 + 1);

                    float[] vertices = new float[numVertices * 3];
                    for (ushort j = 0; j < numVertices; j++)
                    {
                        int type = getDeltaType(j, bitfield);
                        if (type == (int)VertexChangeType.None)
                        {
                            // nothing
                        }
                        else if (type == (int)VertexChangeType.Short)
                        {
                            vertices[j * 3 + 0] = uncompress(reader.ReadByte());
                            vertices[j * 3 + 1] = uncompress(reader.ReadByte());
                            vertices[j * 3 + 2] = uncompress(reader.ReadByte());
                        }
                        else if (type == (int)VertexChangeType.Long)
                        {
                            vertices[j * 3 + 0] = uncompress(reader.ReadUInt16());
                            vertices[j * 3 + 1] = uncompress(reader.ReadUInt16());
                            vertices[j * 3 + 2] = uncompress(reader.ReadUInt16());
                        }
                        else if (type == (int)VertexChangeType.Absolute)
                        {
                            vertices[j * 3 + 0] = reader.ReadSingle();
                            vertices[j * 3 + 1] = reader.ReadSingle();
                            vertices[j * 3 + 2] = reader.ReadSingle();
                        }
                    }

                    convertDeltaVerticesToAbsolute(vertices, (int)meshIndex, groupIndex, (int)frameNum);

                    _frames[frameIndex].Active = true;
                    if (_frames[frameIndex].Vertices == null)
                    {
                        _frames[frameIndex].Vertices = new List <FrameSectionVertices>();
                    }

                    FrameSectionVertices sectionVertices;
                    sectionVertices.SectionIndex = groupIndex;
                    sectionVertices.Vertices     = vertices;
                    _frames[frameIndex].Vertices.Add(sectionVertices);
                }
                else if (subsection.Type == (byte)ActSubsectionType.Transform)
                {
                    // read the 4x3 transform matrix
                    float[] transform = new float[4 * 3];
                    transform[0] = reader.ReadSingle();
                    transform[1] = reader.ReadSingle();
                    transform[2] = reader.ReadSingle();

                    transform[3] = reader.ReadSingle();
                    transform[4] = reader.ReadSingle();
                    transform[5] = reader.ReadSingle();

                    transform[6] = reader.ReadSingle();
                    transform[7] = reader.ReadSingle();
                    transform[8] = reader.ReadSingle();

                    transform[9]  = reader.ReadSingle();
                    transform[10] = reader.ReadSingle();
                    transform[11] = reader.ReadSingle();

                    _frames[frameIndex].Active    = true;
                    _frames[frameIndex].Transform = new FrameTransformation(transform);
                }
                else if (subsection.Type == (byte)ActSubsectionType.BoundingBox)
                {
                    _frames[frameIndex].Active      = true;
                    _frames[frameIndex].BoundingBox = new float[6];

                    // read the bounding box
                    _frames[frameIndex].BoundingBox[0] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[1] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[2] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[3] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[4] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[5] = reader.ReadSingle();
                }
                else
                {
                    throw new Exception("Invalid subsection type found");
                }
            }
        }
Exemple #8
0
        public override void PrepareProcessing()
        {
            _reader?.Dispose();
            try {
                _reader = new System.IO.BinaryReader(System.IO.File.OpenRead(_attrFilePath.TypedGet()));
            } catch (Exception ex) {
                Parent.Context.Notify(new GraphNotification(GraphNotification.NotificationType.Error, ex.ToString()));
                throw;
            }

            if (_reader != null)
            {
                _reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                _portOut.PrepareProcessing();
                _portTrigger.PrepareProcessing();
                _buffer      = new TimeLocatedBuffer1D <double>(_portOut.Buffer.Capacity, _portOut.Samplerate);
                _endOfStream = false;

                if (_portTrigger.Connection == null)
                {
                    _startTime = new TimeStamp(0);
                }
            }
            else
            {
                throw new Exception("File node: did not specify input");
            }

            _lastStatePosition = 0;

            _sampleSize = _dataTypeSizes[_attrDataType.TypedGet()];

            _sampleGetterFunc = () => {
                throw new System.IO.EndOfStreamException();
            };

            switch (_attrDataType.TypedGet())
            {
            case DataType.Float32:
                _sampleGetterFunc = () => _reader.ReadSingle();
                break;

            case DataType.Float64:
                _sampleGetterFunc = () => _reader.ReadDouble();
                break;

            case DataType.Int16:
                _sampleGetterFunc = () => _reader.ReadInt16();
                break;

            case DataType.Int32:
                _sampleGetterFunc = () => _reader.ReadInt32();
                break;

            case DataType.Int64:
                _sampleGetterFunc = () => _reader.ReadInt64();
                break;

            default:
                throw new NotImplementedException();
            }
        }
Exemple #9
0
        public RecievePacket handleData(System.IO.BinaryReader br, System.IO.BinaryWriter bw, System.Net.Sockets.TcpClient client)
        {
            //online bool, name,realname,,avatar,playcount,totalscore,mode,currentsong,currentchart, accuracy, level
            bool online = br.ReadBoolean();

            if (online)
            {
                //Console.WriteLine("name:" + br.ReadString());
                //Console.WriteLine("pc:" + br.ReadInt32());
                string   user       = br.ReadString();
                string   rn         = br.ReadString();
                string   avatar     = br.ReadString();
                int      pc         = br.ReadInt32();
                int      totalscore = br.ReadInt32();
                PlayMode pm         = (PlayMode)br.ReadInt32();
                string   cs         = br.ReadString();
                string   cc         = br.ReadString();
                float    acc        = br.ReadSingle();//float
                int      lvl        = br.ReadInt32();
                lock (User.users)
                {
                    if (User.users.ContainsKey(user))
                    {
                        User.users[user].Name           = user;
                        User.users[user].RealName       = rn;
                        User.users[user].Avatar         = avatar;
                        User.users[user].Playcount      = pc;
                        User.users[user].TotalScore     = totalscore;
                        User.users[user].Mode           = pm;
                        User.users[user].CurrentSong    = cs;
                        User.users[user].CurrentChart   = cs;
                        User.users[user].Accuracy       = acc;
                        User.users[user].Level          = lvl;
                        User.users[user].UpdateGraphics = true;
                    }
                    else
                    {
                        User u = new User()
                        {
                            Name         = user,
                            RealName     = rn,
                            Avatar       = avatar,
                            Playcount    = pc,
                            TotalScore   = totalscore,
                            Mode         = pm,
                            CurrentSong  = cs,
                            CurrentChart = cc,
                            Accuracy     = acc,
                            Level        = lvl
                        };


                        User.users.Add(user, u);
                        u.UpdateGraphics = true;
                    }
                    Console.WriteLine("added/modified {0} score is {1}", user, totalscore);
                }
            }
            else
            {
                string removeuser = br.ReadString();
                lock (User.users)
                {
                    if (User.users.ContainsKey(removeuser))
                    {
                        Console.WriteLine("removed {0}", removeuser);
                        Console.WriteLine(User.users.Remove(removeuser) + " at removing " + removeuser);
                    }
                    else
                    {
                        Console.WriteLine("no key userhandler.cs");
                    }
                }
            }
            return(null);
        }
Exemple #10
0
        public override void LoadData(System.IO.FileStream __fsFileStream)
        {
            System.IO.BinaryReader _brdrReader = new System.IO.BinaryReader(__fsFileStream);

            // only read necessary params from file header
            __fsFileStream.Seek(42, System.IO.SeekOrigin.Begin);
            int _iXDimension = (int)_brdrReader.ReadInt16();
            __fsFileStream.Seek(108, System.IO.SeekOrigin.Begin);
            DataType _dtDataType = (DataType)_brdrReader.ReadInt16();
            __fsFileStream.Seek(656, System.IO.SeekOrigin.Begin);
            int _iYDimension = (int)_brdrReader.ReadInt16();
            __fsFileStream.Seek(1446, System.IO.SeekOrigin.Begin);
            UInt32 numframes = (UInt32)_brdrReader.ReadInt32();

            // Start reading the XCalibStruct.
            SpeCalib XCalib = new SpeCalib(0, 0);
            __fsFileStream.Seek(3000, System.IO.SeekOrigin.Begin);
            XCalib.Offset = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3008, System.IO.SeekOrigin.Begin);
            XCalib.Factor = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3016, System.IO.SeekOrigin.Begin);
            XCalib.current_unit = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3098, System.IO.SeekOrigin.Begin);
            XCalib.CalibValid = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3101, System.IO.SeekOrigin.Begin);
            XCalib.PolynomOrder = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3263, System.IO.SeekOrigin.Begin);

            XCalib.PolynomCoeff[0] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[1] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[2] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[3] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[4] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[5] = _brdrReader.ReadDouble();

            __fsFileStream.Seek(3311, System.IO.SeekOrigin.Begin);
            XCalib.LaserPosition = (double)_brdrReader.ReadDouble();

            // Start reading the YCalibStruct.
            SpeCalib YCalib = new SpeCalib(0, 0);
            __fsFileStream.Seek(3489, System.IO.SeekOrigin.Begin);   // move ptr to x_calib start
            YCalib.Offset = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3497, System.IO.SeekOrigin.Begin);
            YCalib.Factor = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3505, System.IO.SeekOrigin.Begin);
            YCalib.current_unit = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3587, System.IO.SeekOrigin.Begin);
            YCalib.CalibValid = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3590, System.IO.SeekOrigin.Begin);
            YCalib.PolynomOrder = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3752, System.IO.SeekOrigin.Begin);

            YCalib.PolynomCoeff[0] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[1] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[2] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[3] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[4] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[5] = _brdrReader.ReadDouble();

            __fsFileStream.Seek(3800, System.IO.SeekOrigin.Begin);
            YCalib.LaserPosition = (double)_brdrReader.ReadDouble();

            int _iDimension;
            SpeCalib _calCurrCalib;
            if (_iYDimension == 1)
            {
                _iDimension = _iXDimension;
                _calCurrCalib = XCalib;
            }
            else if (_iXDimension == 1)
            {
                _iDimension = _iYDimension;
                _calCurrCalib = YCalib;
            }
            else
            {
                throw new UnexpectedFormatException("xylib does not support 2-D images");
            }

            __fsFileStream.Seek(4100, System.IO.SeekOrigin.Begin);      // move ptr to frames-start
            for (int frm = 0; frm < (int)numframes; frm++)
            {
                Block _blkBlock = new Block();

                Column _colXCol = this.GetCalibColumn(_calCurrCalib, _iDimension);
                _blkBlock.AddColumn(_colXCol, "", true);

                ListColumn _colYCol = new ListColumn();

                for (int i = 0; i < _iDimension; ++i)
                {
                    double _dYVal = 0;
                    switch (_dtDataType)
                    {
                        case DataType.SPE_DATA_FLOAT:
                            _dYVal = (double)_brdrReader.ReadSingle();
                            break;
                        case DataType.SPE_DATA_LONG:
                            _dYVal = (double)_brdrReader.ReadInt32();
                            break;
                        case DataType.SPE_DATA_INT:
                            _dYVal = (double)_brdrReader.ReadInt16();
                            break;
                        case DataType.SPE_DATA_UINT:
                            _dYVal = (double)_brdrReader.ReadUInt16();
                            break;
                        default:
                            break;
                    }
                    _colYCol.AddValue(_dYVal);
                }
                _blkBlock.AddColumn(_colYCol, "", true);
                this.m_blcklstBlocks.Add(_blkBlock);
            }
        }
Exemple #11
0
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            try {
                // Initialize the device
                m_device = new Device();
                m_device.Init( graphPanel.Handle, false, true );

                // Create the render shaders
                try {
                    Shader.WarningAsError = false;

                    m_shader_RenderSphere = new Shader( m_device, new System.IO.FileInfo( @"./Shaders/RenderSphere.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                    m_shader_RenderScene = new Shader( m_device, new System.IO.FileInfo( @"./Shaders/RenderScene.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                    m_shader_RenderLDR = new Shader( m_device, new System.IO.FileInfo( @"./Shaders/RenderLDR.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                } catch ( Exception _e ) {
                    throw new Exception( "Failed to compile shader! " + _e.Message );
                }

                // Create CB
                m_CB_Render = new ConstantBuffer< CB_Main >( m_device, 0 );

                // Create textures
                LoadHDRImage();

                m_Tex_HDRBuffer = new Texture2D( m_device, (uint) graphPanel.Width, (uint) graphPanel.Height, 2, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null );

                {	// Build noise texture
                    SimpleRNG.SetSeed( 1U );
                    PixelsBuffer	content = new PixelsBuffer( 256*256*16 );
                    using ( System.IO.BinaryWriter W = content.OpenStreamWrite() )
                        for ( int i=0; i < 256*256; i++ ) {
                            W.Write( (float) SimpleRNG.GetUniform() );
                            W.Write( (float) SimpleRNG.GetUniform() );
                            W.Write( (float) SimpleRNG.GetUniform() );
                            W.Write( (float) SimpleRNG.GetUniform() );
                        }
                    m_Tex_Noise = new Texture2D( m_device, 256, 256, 1, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, new PixelsBuffer[] { content } );
                }

                // Build SH coeffs
                const int	ORDERS = 20;
                {
                    const int	TABLE_SIZE = 64;

                    // Load A coeffs into a texture array
                    float[,,]	A = new float[TABLE_SIZE,TABLE_SIZE,ORDERS];
            //					using ( System.IO.FileStream S = new System.IO.FileInfo( @"ConeTable_cosAO_order20.float" ).OpenRead() )
                    using ( System.IO.FileStream S = new System.IO.FileInfo( @"ConeTable_cosTheta_order20.float" ).OpenRead() )
                        using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {
                            for ( int thetaIndex=0; thetaIndex < TABLE_SIZE; thetaIndex++ )
                                for ( int AOIndex=0; AOIndex < TABLE_SIZE; AOIndex++ ) {
                                    for ( int order=0; order < ORDERS; order++ )
                                        A[thetaIndex,AOIndex,order] = R.ReadSingle();
                                }
                        }

                    PixelsBuffer[]	coeffSlices = new PixelsBuffer[5];	// 5 slices of 4 coeffs each to get our 20 orders
                    for ( int sliceIndex=0; sliceIndex < coeffSlices.Length; sliceIndex++ ) {
                        PixelsBuffer	coeffSlice = new PixelsBuffer( TABLE_SIZE*TABLE_SIZE*16 );
                        coeffSlices[sliceIndex] = coeffSlice;

                        using ( System.IO.BinaryWriter W = coeffSlice.OpenStreamWrite() ) {
                            for ( int thetaIndex=0; thetaIndex < TABLE_SIZE; thetaIndex++ )
                                for ( int AOIndex=0; AOIndex < TABLE_SIZE; AOIndex++ ) {
                                    W.Write( A[thetaIndex,AOIndex,4*sliceIndex+0] );
                                    W.Write( A[thetaIndex,AOIndex,4*sliceIndex+1] );
                                    W.Write( A[thetaIndex,AOIndex,4*sliceIndex+2] );
                                    W.Write( A[thetaIndex,AOIndex,4*sliceIndex+3] );
                                }
                        }
                    }

                    m_Tex_ACoeffs = new Texture2D( m_device, 64, 64, coeffSlices.Length, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, coeffSlices );
                }

                {
                    // Load environment coeffs into a constant buffer
                    float3[]	coeffs = new float3[ORDERS*ORDERS];
                    using ( System.IO.FileStream S = new System.IO.FileInfo( @"Ennis_order20.float3" ).OpenRead() )
                        using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) )
                            for ( int coeffIndex=0; coeffIndex < ORDERS*ORDERS; coeffIndex++ )
                                coeffs[coeffIndex].Set( R.ReadSingle(), R.ReadSingle(), R.ReadSingle() );

                    // Write into a raw byte[]
                    byte[]	rawContent = new byte[400 * 4 * 4];
                    using ( System.IO.MemoryStream	MS = new System.IO.MemoryStream( rawContent ) )
                        using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( MS ) ) {
                            for ( int coeffIndex=0; coeffIndex < ORDERS*ORDERS; coeffIndex++ ) {
                                W.Write( coeffs[coeffIndex].x );
                                W.Write( coeffs[coeffIndex].y );
                                W.Write( coeffs[coeffIndex].z );
                                W.Write( 0.0f );
                            }
                        }
             					m_CB_Coeffs = new RawConstantBuffer( m_device, 1, rawContent.Length );
                    m_CB_Coeffs.UpdateData( rawContent );
                }

                // Create camera + manipulator
                m_camera.CreatePerspectiveCamera( 0.5f * (float) Math.PI, (float) graphPanel.Width / graphPanel.Height, 0.01f, 100.0f );
                m_camera.CameraTransformChanged += m_camera_CameraTransformChanged;
                m_cameraManipulator.Attach( graphPanel, m_camera );
                m_cameraManipulator.InitializeCamera( -2.0f * float3.UnitZ, float3.Zero, float3.UnitY );
                m_camera_CameraTransformChanged( null, EventArgs.Empty );

                // Start rendering
                Application.Idle += Application_Idle;

            } catch ( Exception _e ) {
                MessageBox.Show( "Failed to initialize D3D renderer!\r\nReason: " + _e.Message );
            }
        }
Exemple #12
0
		public Texture2D	PipoImage2Texture( System.IO.FileInfo _FileName ) {
			using ( System.IO.FileStream S = _FileName.OpenRead() )
				using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {

					int	W, H;
					W = R.ReadInt32();
					H = R.ReadInt32();

					PixelsBuffer	Buff = new PixelsBuffer( (uint) (4 * W * H * 4) );
					using ( System.IO.BinaryWriter Wr = Buff.OpenStreamWrite() )
					{
						float4	C = new float4();
						for ( int Y=0; Y < H; Y++ ) {
							for ( int X=0; X < W; X++ ) {
								C.x = R.ReadSingle();
								C.y = R.ReadSingle();
								C.z = R.ReadSingle();
								C.w = R.ReadSingle();

								Wr.Write( C.x );
								Wr.Write( C.y );
								Wr.Write( C.z );
								Wr.Write( C.w );
							}
						}
					}

					return Image2Texture( (uint) W, (uint) H, PIXEL_FORMAT.RGBA32_FLOAT, Buff );
				}
		}
Exemple #13
0
        public VoxelModel LoadVoxelModel(System.IO.Stream stream, out Vector3 pivot, IProgressListener progress)
        {
            var reader = new System.IO.BinaryReader(stream);

            {
                var buf = new byte[4];
                if (stream.Read(buf, 0, 4) < 4)
                {
                    throw new System.IO.IOException("Magic not read");
                }
                if (buf[0] != 'K' ||
                   buf[1] != 'v' ||
                   buf[2] != 'x' ||
                   buf[3] != 'l')
                {
                    throw new System.IO.IOException("Invalid magic");
                }
            }

            int xsiz = reader.ReadInt32();
            int ysiz = reader.ReadInt32();
            int zsiz = reader.ReadInt32();
            float xpivot = reader.ReadSingle();
            float ypivot = reader.ReadSingle();
            float zpivot = reader.ReadSingle();
            int numblocks = reader.ReadInt32();
            var blocks = new Kv6Block[numblocks];

            progress?.Report("Reading voxels");

            for (int i = 0; i < blocks.Length; ++i)
            {
                blocks[i].color = reader.ReadUInt32();
                blocks[i].zpos = (int) reader.ReadUInt16();
                reader.ReadUInt16(); // skip visFaces & lighting
                if (((i & 8191) == 0))
                {
                    progress?.Report((double)i / blocks.Length * 0.5);
                }
            }

            var xyoffset = new int[xsiz * ysiz];

            // skip xoffset
            for (int i = 0; i < xsiz; ++i)
            {
                reader.ReadInt32();
            }
            for (int i = 0; i < xyoffset.Length; ++i)
            {
                xyoffset[i] = (int) reader.ReadUInt16();
            }

            progress?.Report("Placing voxels");

            int pos = 0;
            var model = new VoxelModel(xsiz, ysiz, zsiz);
            for (int x = 0; x < xsiz; ++x) {
                for (int y = 0; y < ysiz; ++y) {
                    int sb = xyoffset[x * ysiz + y];
                    for (int i = 0; i < sb; ++i) {
                        var b = blocks[pos];
                        model[x, y, b.zpos] = b.color;
                        pos += 1;
                    }
                }

                progress?.Report((double)pos / blocks.Length * 0.5 + 0.5);
            }

            pivot = new Vector3(xpivot, ypivot, zpivot);

            return model;
        }
Exemple #14
0
		public Texture3D	Pipu2Texture( System.IO.FileInfo _FileName ) {
			using ( System.IO.FileStream S = _FileName.OpenRead() )
				using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {

					int		SlicesCount = R.ReadInt32();
					int		W = R.ReadInt32();
					int		H = R.ReadInt32();

					PixelsBuffer	Slices = new PixelsBuffer( (uint) (4 * W * H * SlicesCount * 4) );
					using ( System.IO.BinaryWriter Wr = Slices.OpenStreamWrite() ) {
						for ( int SliceIndex=0; SliceIndex < SlicesCount; SliceIndex++ ) {
							float4	C = new float4();
							for ( int Y=0; Y < H; Y++ ) {
								for ( int X=0; X < W; X++ ) {
									C.x = R.ReadSingle();
									C.y = R.ReadSingle();
									C.z = R.ReadSingle();
									C.w = R.ReadSingle();

									Wr.Write( C.x );
									Wr.Write( C.y );
									Wr.Write( C.z );
									Wr.Write( C.w );
								}
							}
						}
					}

					return Image2Texture3D( (uint) W, (uint) H, (uint) SlicesCount, PIXEL_FORMAT.RGBA32_FLOAT, new PixelsBuffer[] { Slices } );
				}
		}
Exemple #15
0
		public Texture2D	Pipi2Texture( System.IO.FileInfo _FileName ) {
			using ( System.IO.FileStream S = _FileName.OpenRead() )
				using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {

					int				MipLevels = R.ReadInt32();
					PixelsBuffer[]	Mips = new PixelsBuffer[MipLevels];
					int				ImageWidth = 0, ImageHeight = 0;
					for ( int MipLevel=0; MipLevel < MipLevels; MipLevel++ ) {
						int	W, H;
						W = R.ReadInt32();
						H = R.ReadInt32();
						if ( MipLevel == 0 ) {
							ImageWidth = W;
							ImageHeight = H;
						}

						PixelsBuffer	Buff = new PixelsBuffer( (uint) (4 * W * H * 4) );
						Mips[MipLevel] = Buff;
						using ( System.IO.BinaryWriter Wr = Buff.OpenStreamWrite() )
						{
							float4	C = new float4();
							for ( int Y=0; Y < H; Y++ ) {
								for ( int X=0; X < W; X++ ) {
									C.x = R.ReadSingle();
									C.y = R.ReadSingle();
									C.z = R.ReadSingle();
									C.w = R.ReadSingle();

									Wr.Write( C.x );
									Wr.Write( C.y );
									Wr.Write( C.z );
									Wr.Write( C.w );
								}
							}
						}
					}

					return Image2Texture( (uint) ImageWidth, (uint) ImageHeight, PIXEL_FORMAT.RGBA32_FLOAT, Mips );
				}
		}
Exemple #16
0
/*	https://knarkowicz.wordpress.com/2014/12/27/analytical-dfg-term-for-ibl/
uint32_t ReverseBits( uint32_t v )
{
    v = ( ( v >> 1 ) & 0x55555555 ) | ( ( v & 0x55555555 ) << 1 );
    v = ( ( v >> 2 ) & 0x33333333 ) | ( ( v & 0x33333333 ) << 2 );
    v = ( ( v >> 4 ) & 0x0F0F0F0F ) | ( ( v & 0x0F0F0F0F ) << 4 );
    v = ( ( v >> 8 ) & 0x00FF00FF ) | ( ( v & 0x00FF00FF ) << 8 );
    v = (   v >> 16               ) | (   v                << 16 );
    return v;
}

float GSmith( float roughness, float ndotv, float ndotl )
{
    float const m2   = roughness * roughness;
    float const visV = ndotv + sqrt( ndotv * ( ndotv - ndotv * m2 ) + m2 );
    float const visL = ndotl + sqrt( ndotl * ( ndotl - ndotl * m2 ) + m2 );

    return 1.0f / ( visV * visL );
}

int main()
{
    float const MATH_PI         = 3.14159f;
    unsigned const LUT_WIDTH    = 128;
    unsigned const LUT_HEIGHT   = 128;
    unsigned const sampleNum    = 128;

    float lutData[ LUT_WIDTH * LUT_HEIGHT * 4 ];

    for ( unsigned y = 0; y < LUT_HEIGHT; ++y )
    {
        float const ndotv = ( y + 0.5f ) / LUT_WIDTH;

        for ( unsigned x = 0; x < LUT_WIDTH; ++x )
        {
            float const gloss       = ( x + 0.5f ) / LUT_HEIGHT;
            float const roughness   = powf( 1.0f - gloss, 4.0f );

            float const vx = sqrtf( 1.0f - ndotv * ndotv );
            float const vy = 0.0f;
            float const vz = ndotv;

            float scale = 0.0f;
            float bias  = 0.0f;

            
            for ( unsigned i = 0; i < sampleNum; ++i )
            {
                float const e1 = (float) i / sampleNum;
                float const e2 = (float) ( (double) ReverseBits( i ) / (double) 0x100000000LL );

                float const phi         = 2.0f * MATH_PI * e1;
                float const cosPhi      = cosf( phi );
                float const sinPhi      = sinf( phi );
                float const cosTheta    = sqrtf( ( 1.0f - e2 ) / ( 1.0f + ( roughness * roughness - 1.0f ) * e2 ) );
                float const sinTheta    = sqrtf( 1.0f - cosTheta * cosTheta );

                float const hx  = sinTheta * cosf( phi );
                float const hy  = sinTheta * sinf( phi );
                float const hz  = cosTheta;

                float const vdh = vx * hx + vy * hy + vz * hz;
                float const lx  = 2.0f * vdh * hx - vx;
                float const ly  = 2.0f * vdh * hy - vy;
                float const lz  = 2.0f * vdh * hz - vz;

                float const ndotl = std::max( lz,   0.0f );
                float const ndoth = std::max( hz,   0.0f );
                float const vdoth = std::max( vdh,  0.0f );

                if ( ndotl > 0.0f )
                {
                    float const gsmith      = GSmith( roughness, ndotv, ndotl );
                    float const ndotlVisPDF = ndotl * gsmith * ( 4.0f * vdoth / ndoth );
                    float const fc          = powf( 1.0f - vdoth, 5.0f );

                    scale   += ndotlVisPDF * ( 1.0f - fc );
                    bias    += ndotlVisPDF * fc;
                }
            }
            scale /= sampleNum;
            bias  /= sampleNum;

            lutData[ x * 4 + y * LUT_WIDTH * 4 + 0 ] = scale;
            lutData[ x * 4 + y * LUT_WIDTH * 4 + 1 ] = bias;
            lutData[ x * 4 + y * LUT_WIDTH * 4 + 2 ] = 0.0f;
            lutData[ x * 4 + y * LUT_WIDTH * 4 + 3 ] = 0.0f;
        }
    }   

} */

#endif

		Texture2D	BuildBRDFTexture( System.IO.FileInfo _TableFileName, uint _TableSize ) {

			float2[,]	Table = new float2[_TableSize,_TableSize];

			float	MinA = 1, MaxA = 0;
			float	MinB = 1, MaxB = 0;
			using ( System.IO.FileStream S = _TableFileName.OpenRead() )
				using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) )
					for ( int Y=0; Y < _TableSize; Y++ )
						for ( int X=0; X < _TableSize; X++ ) {
							float	A = R.ReadSingle();
							float	B = R.ReadSingle();
							Table[X,Y].x = A;
							Table[X,Y].y = B;
							MinA = Math.Min( MinA, A );
							MaxA = Math.Max( MaxA, A );
							MinB = Math.Min( MinB, B );
							MaxB = Math.Max( MaxB, B );
						}

			// MaxA = 1
			// MaxB = 0.00014996325546887346

// MaxA = 1.0;
// MaxB = 1.0;

			// Create the texture
//			PixelsBuffer	Content = new PixelsBuffer( _TableSize*_TableSize*4 );
			PixelsBuffer	Content = new PixelsBuffer( (uint) (_TableSize*_TableSize*2*4) );
			using ( System.IO.BinaryWriter W = Content.OpenStreamWrite() )
			for ( int Y=0; Y < _TableSize; Y++ )
				for ( int X=0; X < _TableSize; X++ ) {
// 					W.Write( (ushort) (65535.0 * Table[X,Y].x / MaxA) );
// 					W.Write( (ushort) (65535.0 * Table[X,Y].y / MaxB) );
					W.Write( Table[X,Y].x );
					W.Write( Table[X,Y].y );
				}


//			Texture2D	Result = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG16_UNORM, false, false, new PixelsBuffer[] { Content } );
			Texture2D	Result = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG32_FLOAT, false, false, new PixelsBuffer[] { Content } );
			return Result;
		}
Exemple #17
0
        public BspResource(string name, System.IO.Stream stream, Resource.ResourceManager content)
            : base(name, true)
        {
            System.IO.BinaryReader reader =
                new System.IO.BinaryReader(stream);

            // read the header
            BspHeader header = new BspHeader();

            header.heading          = reader.ReadBytes(4);
            header.minorVersion     = reader.ReadUInt16();
            header.majorVersion     = reader.ReadUInt16();
            header.dataSectionSize  = reader.ReadUInt32();
            header.rootIndex        = reader.ReadUInt32();
            header.numModels        = reader.ReadUInt32();
            header.numVertices      = reader.ReadUInt32();
            header.numTexCoords     = reader.ReadUInt32();
            header.numVertexIndices = reader.ReadUInt32();
            header.numTexIndices    = reader.ReadUInt32();
            header.numSurfaces      = reader.ReadUInt32();
            header.numPlanes        = reader.ReadUInt32();
            header.numNodes         = reader.ReadUInt32();
            header.numPolygons      = reader.ReadUInt32();

            // read the model names
            byte[]     buffer32 = new byte[32];
            BspModel[] models   = new BspModel[header.numModels];
            _modelsNames = new string[header.numModels];
            for (uint i = 0; i < header.numModels; i++)
            {
                models[i] = new BspModel();

                models[i].name  = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32));
                _modelsNames[i] = models[i].name;
            }

            // read the surfaces
            Random randomGenerator = new Random();

            _surfaces = new BspSurface[header.numSurfaces];
            for (uint i = 0; i < header.numSurfaces; i++)
            {
                if (i == 134)
                {
                    i = i;
                }

                _surfaces[i] = new BspSurface();

                _surfaces[i].modelIndex = reader.ReadUInt32();
                _surfaces[i].texture    = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32));
                _surfaces[i].uCoord     = reader.ReadSingle();
                _surfaces[i].vCoord     = reader.ReadSingle();
                _surfaces[i].uScale     = reader.ReadSingle();
                _surfaces[i].vScale     = reader.ReadSingle();
                _surfaces[i].size1      = reader.ReadUInt16();
                _surfaces[i].size2      = reader.ReadUInt16();
                _surfaces[i].flags      = (BspSurfaceFlags)reader.ReadUInt32();

                _surfaces[i].r     = (float)randomGenerator.NextDouble();
                _surfaces[i].g     = (float)randomGenerator.NextDouble();
                _surfaces[i].b     = (float)randomGenerator.NextDouble();
                _surfaces[i].index = i;
            }

            // read the BSP nodes (for now throw them away)
            _nodes = new BspNode[header.numNodes];
            for (uint i = 0; i < header.numNodes; i++)
            {
                _nodes[i].Left              = reader.ReadInt16();
                _nodes[i].Right             = reader.ReadInt16();
                _nodes[i].PlaneIndex        = reader.ReadInt16();
                _nodes[i].PolygonStartIndex = reader.ReadInt16();
                reader.ReadInt16();
                _nodes[i].NumPolygons = reader.ReadInt16();

                uint i3 = reader.ReadUInt16();
                uint i4 = reader.ReadUInt16();
            }

            // TEMP: validate the BSP
            foreach (BspNode node in _nodes)
            {
                if (node.Left >= _nodes.Length ||
                    node.Right >= _nodes.Length)
                {
                    throw new Exception("OH NO!");
                }
            }

            int parent = findParent(_nodes, 0);

            // read all the polygons
            _polygons = new BspPolygon[header.numPolygons];
            for (uint i = 0; i < header.numPolygons; i++)
            {
                _polygons[i] = new BspPolygon();

                _polygons[i].vertexIndex  = reader.ReadUInt16();
                _polygons[i].flags        = reader.ReadUInt16();
                _polygons[i].numVertices  = reader.ReadUInt16();
                _polygons[i].surfaceIndex = reader.ReadUInt16();

                if (_polygons[i].surfaceIndex == 134)
                {
                    i = i;
                }
            }

            // read all the planes (thow them away)
            for (uint i = 0; i < header.numPlanes; i++)
            {
                reader.ReadBytes(16);
            }

            // read the vertices
            _vertices = new float[header.numVertices * 3];
            for (uint i = 0; i < header.numVertices; i++)
            {
                _vertices[i * 3 + 0] = reader.ReadSingle();
                _vertices[i * 3 + 1] = reader.ReadSingle();
                _vertices[i * 3 + 2] = reader.ReadSingle();
            }

            // read the texture vertices
            _texcoords = new float[header.numTexCoords * 2];
            for (uint i = 0; i < header.numTexCoords; i++)
            {
                _texcoords[i * 2 + 0] = reader.ReadSingle();
                _texcoords[i * 2 + 1] = reader.ReadSingle();
            }

            // read all the vertex indices
            ushort[] indices = new ushort[header.numVertexIndices];
            for (uint i = 0; i < header.numVertexIndices; i++)
            {
                indices[i] = reader.ReadUInt16();
            }

            // read all the texcoord indices
            ushort[] texindices = new ushort[header.numTexIndices];
            for (uint i = 0; i < header.numTexIndices; i++)
            {
                texindices[i] = reader.ReadUInt16();
            }

            // read the bounding spheres
            _boundingSpheres = new Math.Vector4[header.numNodes];
            for (uint i = 0; i < header.numNodes; i++)
            {
                _boundingSpheres[i].Z = reader.ReadSingle();
                _boundingSpheres[i].Y = reader.ReadSingle();
                _boundingSpheres[i].X = reader.ReadSingle();
                _boundingSpheres[i].W = reader.ReadSingle();
            }

            // load the "thingies", whatever that means
            _bspVertices = new List <BspVertex>();
            for (int i = 0; i < header.numSurfaces; i++)
            {
                // throw junk away
                _surfaces[i].boundingSphere.X = reader.ReadSingle();
                _surfaces[i].boundingSphere.Y = reader.ReadSingle();
                _surfaces[i].boundingSphere.Z = reader.ReadSingle();
                _surfaces[i].boundingSphere.W = reader.ReadSingle();

                reader.ReadBytes(12);

                uint numIndices = reader.ReadUInt32();
                _surfaces[i].numTriangles = reader.ReadUInt32();

                UInt16[] myindices = new UInt16[numIndices];
                for (uint j = 0; j < numIndices; j++)
                {
                    myindices[j] = reader.ReadUInt16();
                }

                _surfaces[i].VertexIndex = _bspVertices.Count;
                _surfaces[i].indices     = new ushort[_surfaces[i].numTriangles * 3];
                for (uint j = 0; j < _surfaces[i].numTriangles; j++)
                {
                    ushort x = reader.ReadUInt16();
                    ushort y = reader.ReadUInt16();
                    ushort z = reader.ReadUInt16();

                    _surfaces[i].indices[j * 3 + 0] = myindices[x];
                    _surfaces[i].indices[j * 3 + 1] = myindices[y];
                    _surfaces[i].indices[j * 3 + 2] = myindices[z];

                    // TODO: since we aren't using indices the hardware can't cache vertices,
                    // so there's some performance loss. Figure out a good way to still use indices.

                    // vertex 1
                    BspVertex vertex = new BspVertex();
                    vertex.X = _vertices[myindices[x] * 3 + 0];
                    vertex.Y = _vertices[myindices[x] * 3 + 1];
                    vertex.Z = _vertices[myindices[x] * 3 + 2];
                    vertex.U = _texcoords[myindices[x] * 2 + 0];
                    vertex.V = _texcoords[myindices[x] * 2 + 1];
                    _bspVertices.Add(vertex);

                    // vertex 2
                    vertex.X = _vertices[myindices[y] * 3 + 0];
                    vertex.Y = _vertices[myindices[y] * 3 + 1];
                    vertex.Z = _vertices[myindices[y] * 3 + 2];
                    vertex.U = _texcoords[myindices[y] * 2 + 0];
                    vertex.V = _texcoords[myindices[y] * 2 + 1];
                    _bspVertices.Add(vertex);

                    // vertex 3
                    vertex.X = _vertices[myindices[z] * 3 + 0];
                    vertex.Y = _vertices[myindices[z] * 3 + 1];
                    vertex.Z = _vertices[myindices[z] * 3 + 2];
                    vertex.U = _texcoords[myindices[z] * 2 + 0];
                    vertex.V = _texcoords[myindices[z] * 2 + 1];
                    _bspVertices.Add(vertex);
                }
                _surfaces[i].VertexCount = _bspVertices.Count - _surfaces[i].VertexIndex;
            }

            reader.Close();

            loadTextures(content);
        }
Exemple #18
0
        void TestSHRGBEEncoding()
        {
            float3[]	coeffs = null;

            System.IO.FileInfo	coeffsFileName = new System.IO.FileInfo( "SHCoeffs.sh3" );
            using ( System.IO.FileStream S = coeffsFileName.OpenRead() )
                using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {
                    uint	coeffsCount = R.ReadUInt32();
                    coeffs = new float3[coeffsCount * 9];
                    for ( int i=0; i < 9*coeffsCount; i++ ) {
                        coeffs[i] = new float3( R.ReadSingle(), R.ReadSingle(), R.ReadSingle() );

            // The exponent bias allows us to support up to 512 in luminance!
            //coeffs[i] *= 5.0f;

                    }
                }

            uint	test1_packed = EncodeRGBE( new float3( 1, 0, 1.5f ) );
            float3	test1_unpacked = DecodeRGBE( test1_packed );

            //			float3	coeffMin = new float3( float.MaxValue, float.MaxValue, float.MaxValue );
            float3	coeffMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            float3	coeffMinAbs = new float3( float.MaxValue, float.MaxValue, float.MaxValue );
            int		coeffsWithDifferentSignsInRGBCount = 0;
            for ( int i=0; i < coeffs.Length; i++ ) {
                float3	coeff = coeffs[i];
                float3	absCoeff = new float3( Math.Abs( coeff.x ), Math.Abs( coeff.y ), Math.Abs( coeff.z ) );

                if ( coeff.x * coeff.y < 0.0f || coeff.x * coeff.z < 0.0f || coeff.y * coeff.z < 0.0f )
                    coeffsWithDifferentSignsInRGBCount++;

            //				coeffMin.Min( coeff );
                coeffMax.Max( absCoeff );
                if ( absCoeff.x > 0.0f ) coeffMinAbs.x = Math.Min( coeffMinAbs.x, absCoeff.x );
                if ( absCoeff.y > 0.0f ) coeffMinAbs.y = Math.Min( coeffMinAbs.y, absCoeff.y );
                if ( absCoeff.z > 0.0f ) coeffMinAbs.z = Math.Min( coeffMinAbs.z, absCoeff.z );
            }

            double	expMin = Math.Min( Math.Min( Math.Log( coeffMinAbs.x ) / Math.Log(2), Math.Log( coeffMinAbs.y ) / Math.Log(2) ), Math.Log( coeffMinAbs.z ) / Math.Log(2) );
            double	expMax = Math.Max( Math.Max( Math.Log( coeffMax.x ) / Math.Log(2), Math.Log( coeffMax.y ) / Math.Log(2) ), Math.Log( coeffMax.z ) / Math.Log(2) );

            // Measure discrepancies after RGBE encoding
            // 			float3	errorAbsMin = new float3( +float.MaxValue, +float.MaxValue, +float.MaxValue );
            // 			float3	errorAbsMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            float3	errorRelMin = new float3( +float.MaxValue, +float.MaxValue, +float.MaxValue );
            float3	errorRelMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            int		minExponent = +int.MaxValue, maxExponent = -int.MaxValue;
            int		largeRelativeErrorsCount = 0;
            for ( int i=0; i < coeffs.Length; i++ ) {
                float3	originalRGB = coeffs[i];
                uint	RGBE = EncodeRGBE( originalRGB );
                float3	decodedRGB = DecodeRGBE( RGBE );

                // Compute absolute error
            // 				float3	delta = decodedRGB - originalRGB;
            // 				float3	distanceFromOriginal = new float3( Math.Abs( delta.x ), Math.Abs( delta.y ), Math.Abs( delta.z ) );
            // 				errorAbsMin.Min( distanceFromOriginal );
            // 				errorAbsMax.Max( distanceFromOriginal );

                // Compute relative error
                float3	errorRel = new float3( Math.Abs( originalRGB.x ) > 0.0f ? Math.Abs( decodedRGB.x / originalRGB.x - 1.0f ) : 0.0f, Math.Abs( originalRGB.y ) > 0.0f ? Math.Abs( decodedRGB.y / originalRGB.y - 1.0f ) : 0.0f, Math.Abs( originalRGB.z ) > 0.0f ? Math.Abs( decodedRGB.z / originalRGB.z - 1.0f ) : 0.0f );

                // Scale the relative error by the magnitude of each component as compared to the maximum component
                // This way, if we happen to have a "large" relative error on a component that is super small compared to the component with maximum amplitude then we can safely drop that small component (it's insignificant compared to the largest contribution)
                float	maxComponent = Math.Max( Math.Max( Math.Abs( originalRGB.x ), Math.Abs( originalRGB.y ) ), Math.Abs( originalRGB.z ) );
                float3	magnitudeScale = maxComponent > 0.0f ? new float3( Math.Abs( originalRGB.x ) / maxComponent, Math.Abs( originalRGB.y ) / maxComponent, Math.Abs( originalRGB.z ) / maxComponent ) : float3.Zero;
                errorRel *= magnitudeScale;

                // Don't account for dernomalization
            // 				if ( decodedRGB.x == 0.0 && originalRGB.x != 0.0f ) errorRel.x = 0.0f;
            // 				if ( decodedRGB.y == 0.0 && originalRGB.y != 0.0f ) errorRel.y = 0.0f;
            // 				if ( decodedRGB.z == 0.0 && originalRGB.z != 0.0f ) errorRel.z = 0.0f;

                const float	errorThreshold = 0.2f;
                if ( Math.Abs( errorRel.x ) > errorThreshold || Math.Abs( errorRel.y ) > errorThreshold || Math.Abs( errorRel.z ) > errorThreshold )
                    largeRelativeErrorsCount++;
                errorRelMin.Min( errorRel );
                errorRelMax.Max( errorRel );

                int		exp = (int) ((RGBE >> 24) & 31) - EXPONENT_BIAS;
                minExponent = Math.Min( minExponent, exp );
                maxExponent = Math.Max( maxExponent, exp );
            }
        }
Exemple #19
0
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.ControlSystemStateMessage message = new MavLink4Net.Messages.Common.ControlSystemStateMessage();
     message.TimeUsec       = reader.ReadUInt64();
     message.XAcc           = reader.ReadSingle();
     message.YAcc           = reader.ReadSingle();
     message.ZAcc           = reader.ReadSingle();
     message.XVel           = reader.ReadSingle();
     message.YVel           = reader.ReadSingle();
     message.ZVel           = reader.ReadSingle();
     message.XPos           = reader.ReadSingle();
     message.YPos           = reader.ReadSingle();
     message.ZPos           = reader.ReadSingle();
     message.Airspeed       = reader.ReadSingle();
     message.VelVariance[0] = reader.ReadSingle();
     message.VelVariance[1] = reader.ReadSingle();
     message.VelVariance[2] = reader.ReadSingle();
     message.PosVariance[0] = reader.ReadSingle();
     message.PosVariance[1] = reader.ReadSingle();
     message.PosVariance[2] = reader.ReadSingle();
     message.Q[0]           = reader.ReadSingle();
     message.Q[1]           = reader.ReadSingle();
     message.Q[2]           = reader.ReadSingle();
     message.Q[3]           = reader.ReadSingle();
     message.RollRate       = reader.ReadSingle();
     message.PitchRate      = reader.ReadSingle();
     message.YawRate        = reader.ReadSingle();
     return(message);
 }
        /// <summary>
        /// Loads a file consisting of 256x256 floats and imports it as an array into the map.
        /// </summary>
        /// <remarks>TODO: Move this to libTerrain itself</remarks>
        /// <param name="filename">The filename of the float array to import</param>
        public void loadFromFileF32(string filename)
        {
            System.IO.FileInfo file = new System.IO.FileInfo(filename);
            System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
            int x, y;
            for (x = 0; x < w; x++)
            {
                for (y = 0; y < h; y++)
                {
                    heightmap.map[x, y] = (double)bs.ReadSingle();
                }
            }

            bs.Close();
            s.Close();

            tainted++;
        }
Exemple #21
0
        private void read(System.IO.Stream stream)
        {
            _intermediateOutput = new IntermediateOutput();

            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);

            SheepHeader header;

            header.Magic1 = reader.ReadUInt32();
            header.Magic2 = reader.ReadUInt32();

            if (header.Magic1 != SheepHeader.Magic1Value ||
                header.Magic2 != SheepHeader.Magic2Value)
            {
                throw new Exception("Input file is not a valid sheep file");
            }

            header.Unknown     = reader.ReadUInt32();
            header.ExtraOffset = reader.ReadUInt32();
            header.DataOffset  = reader.ReadUInt32();
            header.DataSize    = reader.ReadUInt32();
            header.DataCount   = reader.ReadUInt32();

            header.OffsetArray = new uint[header.DataCount];

            for (uint i = 0; i < header.DataCount; i++)
            {
                header.OffsetArray[i] = reader.ReadUInt32();
            }

            for (uint i = 0; i < header.DataCount; i++)
            {
                if (header.OffsetArray[i] >= stream.Length)
                {
                    throw new Exception("Input file is not a valid Sheep file");
                }

                stream.Seek(header.DataOffset + header.OffsetArray[i], System.IO.SeekOrigin.Begin);

                SectionHeader sectionHeader = readSectionHeader(reader);
                long          currentOffset = stream.Position;

                if (sectionHeader.Label == "SysImports")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        SheepImport import;

                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        short lengthOfName = reader.ReadInt16();
                        import.Name     = readString(reader, lengthOfName);
                        import.Callback = null;

                        // skip padding
                        reader.ReadByte();

                        byte numReturns    = reader.ReadByte();
                        byte numParameters = reader.ReadByte();

                        import.ReturnType = (SheepSymbolType)numReturns;
                        import.Parameters = new SheepSymbolType[numParameters];

                        for (byte k = 0; k < numParameters; k++)
                        {
                            SheepSymbolType paramterType = (SheepSymbolType)reader.ReadByte();

                            if (paramterType == SheepSymbolType.Int ||
                                paramterType == SheepSymbolType.Float ||
                                paramterType == SheepSymbolType.String)
                            {
                                import.Parameters[k] = paramterType;
                            }
                        }

                        _intermediateOutput.Imports.Add(import);
                    }
                }
                else if (sectionHeader.Label == "StringConsts")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        SheepStringConstant constant;
                        constant.Offset = sectionHeader.OffsetArray[j];
                        constant.Value  = readString(reader);

                        _intermediateOutput.Constants.Add(constant);
                    }
                }
                else if (sectionHeader.Label == "Variables")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        SheepSymbol symbol = new SheepSymbol();
                        short       len    = reader.ReadInt16();
                        symbol.Name = readString(reader, len);

                        // skip padding
                        reader.ReadByte();

                        symbol.Type = (SheepSymbolType)reader.ReadUInt32();

                        if (symbol.Type == SheepSymbolType.Int)
                        {
                            symbol.InitialIntValue = reader.ReadInt32();
                        }
                        else if (symbol.Type == SheepSymbolType.Float)
                        {
                            symbol.InitialFloatValue = reader.ReadSingle();
                        }
                        else if (symbol.Type == SheepSymbolType.String)
                        {
                            symbol.InitialStringValue = reader.ReadInt32();
                        }
                        else
                        {
                            throw new Exception("???");
                        }

                        _intermediateOutput.Symbols.Add(symbol);
                    }
                }
                else if (sectionHeader.Label == "Functions")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        SheepFunction func = new SheepFunction();
                        short         len  = reader.ReadInt16();
                        func.Name = readString(reader, len);

                        reader.ReadByte();
                        reader.ReadByte();
                        func.CodeOffset = reader.ReadUInt32();

                        _intermediateOutput.Functions.Add(func);
                    }
                }
                else if (sectionHeader.Label == "Code")
                {
                    if (sectionHeader.Datacount > 1)
                    {
                        throw new Exception("Extra code sections found");
                    }

                    for (int j = 0; j < _intermediateOutput.Functions.Count; j++)
                    {
                        stream.Seek(currentOffset + _intermediateOutput.Functions[j].CodeOffset, System.IO.SeekOrigin.Begin);

                        uint size;
                        if (j == _intermediateOutput.Functions.Count - 1)
                        {
                            size = sectionHeader.DataSize - _intermediateOutput.Functions[j].CodeOffset;
                        }
                        else
                        {
                            size = _intermediateOutput.Functions[j + 1].CodeOffset - _intermediateOutput.Functions[j].CodeOffset;
                        }

                        SheepFunction f = _intermediateOutput.Functions[j];
                        f.Code = reader.ReadBytes((int)size);
                        _intermediateOutput.Functions[j] = f;
                    }
                }
            }
        }
Exemple #22
0
    private static TclObject ScanNumber( byte[] src, int pos, int type )
    // Format character from "binary scan"
    {
      switch ( type )
      {

        case 'c':
          {
            return TclInteger.newInstance( (sbyte)src[pos] );
          }

        case 's':
          {
            short value = (short)( ( src[pos] & 0xff ) + ( ( src[pos + 1] & 0xff ) << 8 ) );
            return TclInteger.newInstance( (int)value );
          }

        case 'S':
          {
            short value = (short)( ( src[pos + 1] & 0xff ) + ( ( src[pos] & 0xff ) << 8 ) );
            return TclInteger.newInstance( (int)value );
          }

        case 'i':
          {
            int value = ( src[pos] & 0xff ) + ( ( src[pos + 1] & 0xff ) << 8 ) + ( ( src[pos + 2] & 0xff ) << 16 ) + ( ( src[pos + 3] & 0xff ) << 24 );
            return TclInteger.newInstance( value );
          }
        case 'I':
          {
            int value = ( src[pos + 3] & 0xff ) + ( ( src[pos + 2] & 0xff ) << 8 ) + ( ( src[pos + 1] & 0xff ) << 16 ) + ( ( src[pos] & 0xff ) << 24 );
            return TclInteger.newInstance( value );
          }
        case 'f':
          {
            System.IO.MemoryStream ms = new System.IO.MemoryStream( src, pos, 4, false );
            System.IO.BinaryReader reader = new System.IO.BinaryReader( ms );
            double fvalue = reader.ReadSingle();
            reader.Close();
            ms.Close();
            return TclDouble.newInstance( fvalue );
          }
        case 'd':
          {
            System.IO.MemoryStream ms = new System.IO.MemoryStream( src, pos, 8, false );
            System.IO.BinaryReader reader = new System.IO.BinaryReader( ms );
            double dvalue = reader.ReadDouble();
            reader.Close();
            ms.Close();
            return TclDouble.newInstance( dvalue );
          }
      }
      return null;
    }
Exemple #23
0
        /// <summary>Loads the black-box logs from the previous simulation run</summary>
        internal static void LoadLogs()
        {
            string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");

            try
            {
                using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
                    {
                        byte[]      Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
                        const short Version    = 1;
                        byte[]      Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        short Number = Reader.ReadInt16();
                        if (Version != Number)
                        {
                            throw new System.IO.InvalidDataException();
                        }
                        Game.LogRouteName = Reader.ReadString();
                        Game.LogTrainName = Reader.ReadString();
                        Game.LogDateTime  = DateTime.FromBinary(Reader.ReadInt64());
                        Interface.CurrentOptions.GameMode = (GameMode)Reader.ReadInt16();
                        Game.BlackBoxEntryCount           = Reader.ReadInt32();
                        Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
                        for (int i = 0; i < Game.BlackBoxEntryCount; i++)
                        {
                            Game.BlackBoxEntries[i].Time           = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Position       = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Speed          = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].Acceleration   = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerDriver    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerSafety    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeDriver    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeSafety    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].EventToken     = (Game.BlackBoxEventToken)Reader.ReadInt16();
                        }
                        Game.ScoreLogCount             = Reader.ReadInt32();
                        Game.ScoreLogs                 = new Game.ScoreLog[Game.ScoreLogCount];
                        Game.CurrentScore.CurrentValue = 0;
                        for (int i = 0; i < Game.ScoreLogCount; i++)
                        {
                            Game.ScoreLogs[i].Time          = Reader.ReadDouble();
                            Game.ScoreLogs[i].Position      = Reader.ReadDouble();
                            Game.ScoreLogs[i].Value         = Reader.ReadInt32();
                            Game.ScoreLogs[i].TextToken     = (Game.ScoreTextToken)Reader.ReadInt16();
                            Game.CurrentScore.CurrentValue += Game.ScoreLogs[i].Value;
                        }
                        Game.CurrentScore.Maximum = Reader.ReadInt32();
                        Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
                        Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        Reader.Close();
                    } Stream.Close();
                }
            }
            catch
            {
                Game.LogRouteName       = "";
                Game.LogTrainName       = "";
                Game.LogDateTime        = DateTime.Now;
                Game.BlackBoxEntries    = new Game.BlackBoxEntry[256];
                Game.BlackBoxEntryCount = 0;
                Game.ScoreLogs          = new Game.ScoreLog[64];
                Game.ScoreLogCount      = 0;
            }
        }
Exemple #24
0
 public void Populate(int iOffset, bool useMemoryStream)
 {
     this.isNulledOutReflexive = false;
     System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
     //set offsets
     BR.BaseStream.Position = iOffset + this.chunkOffset;
     this.offsetInMap = iOffset + this.chunkOffset;
     // If we need to read / save tag info directly to file...
     if (!useMemoryStream)
     {
         map.OpenMap(MapTypes.Internal);
         BR = map.BR;
         BR.BaseStream.Position = this.offsetInMap;
     }
     else
         this.offsetInMap += meta.offset;
     switch (ValueType)
     {
         case IFPIO.ObjectEnum.Short:
             {
                 this.Value = BR.ReadInt16();
                 break;
             }
         case IFPIO.ObjectEnum.Int:
             {
                 this.Value = BR.ReadInt32();
                 break;
             }
         case IFPIO.ObjectEnum.UShort:
             {
                 this.Value = BR.ReadUInt16();
                 break;
             }
         case IFPIO.ObjectEnum.UInt:
             {
                 this.Value = BR.ReadUInt32();
                 break;
             }
         case IFPIO.ObjectEnum.Float:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Unknown:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Byte:
             {
                 this.Value = BR.ReadByte();
                 break;
             }
     }
     // ...and then close the file once we are done!
     if (!useMemoryStream)
         map.CloseMap();
     if (this.ValueType != IFPIO.ObjectEnum.Unused)
         this.Controls[1].Text = this.Value.ToString();
 }
Exemple #25
0
        // Per spot:
        // uint32 magic
        // uint32 reserved;
        // uint32 flags;
        // float x;
        // float y;
        // float z;
        // uint32 no_paths
        //   for each path
        //     float x;
        //     float y;
        //     float z;
        public bool Load(string baseDir)
        {
            string fileName = FileName();
            string filenamebin = baseDir + fileName;

            System.IO.Stream stream = null;
            System.IO.BinaryReader file = null;
            int n_spots = 0;
            int n_steps = 0;
            try
            {
                stream = System.IO.File.OpenRead(filenamebin);
                if (stream != null)
                {
                    file = new System.IO.BinaryReader(stream);
                    if (file != null)
                    {
                        uint magic = file.ReadUInt32();
                        if (magic == FILE_MAGIC)
                        {

                            uint type;
                            while ((type = file.ReadUInt32()) != FILE_ENDMAGIC)
                            {
                                n_spots++;
                                uint reserved = file.ReadUInt32();
                                uint flags = file.ReadUInt32();
                                float x = file.ReadSingle();
                                float y = file.ReadSingle();
                                float z = file.ReadSingle();
                                uint n_paths = file.ReadUInt32();
                                if (x != 0 && y != 0)
                                {
                                    Spot s = new Spot(x, y, z);
                                    s.flags = flags;

                                    for (uint i = 0; i < n_paths; i++)
                                    {
                                        n_steps++;
                                        float sx = file.ReadSingle();
                                        float sy = file.ReadSingle();
                                        float sz = file.ReadSingle();
                                        s.AddPathTo(sx, sy, sz);
                                    }
                                    AddSpot(s);
                                }
                            }
                        }
                    }
                }
            }
            catch (System.IO.FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            if (file != null)
            {
                file.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }

            Log("Loaded " + fileName + " " + n_spots + " spots " + n_steps + " steps");

            modified = false;
            return false;
        }
Exemple #26
0
		private void	BuildPhaseQuantileBuffer( System.IO.FileInfo _PhaseQuantileFileName )
		{
			const int	QUANTILES_COUNT = 65536;

			Reg( m_SB_PhaseQuantile = new StructuredBuffer<float>( m_Device, 2*QUANTILES_COUNT, true ) );
			using ( System.IO.FileStream S = _PhaseQuantileFileName.OpenRead() )
				using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) )
				{
					for ( int i=0; i < m_SB_PhaseQuantile.m.Length; i++ )
						m_SB_PhaseQuantile.m[i] = R.ReadSingle();
				}
			m_SB_PhaseQuantile.Write();
		}
Exemple #27
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try {
                // Initialize the device
                m_device = new Device();
                m_device.Init(graphPanel.Handle, false, true);

                // Create the render shaders
                try {
                    Shader.WarningAsError = false;

                    m_shader_RenderSphere = new Shader(m_device, new System.IO.FileInfo(@"./Shaders/RenderSphere.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS");
                    m_shader_RenderScene  = new Shader(m_device, new System.IO.FileInfo(@"./Shaders/RenderScene.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS");
                    m_shader_RenderLDR    = new Shader(m_device, new System.IO.FileInfo(@"./Shaders/RenderLDR.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS");
                } catch (Exception _e) {
                    throw new Exception("Failed to compile shader! " + _e.Message);
                }

                // Create CB
                m_CB_Render = new ConstantBuffer <CB_Main>(m_device, 0);

                // Create textures
                LoadHDRImage();

                m_Tex_HDRBuffer = new Texture2D(m_device, (uint)graphPanel.Width, (uint)graphPanel.Height, 2, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, null);

                {                       // Build noise texture
                    SimpleRNG.SetSeed(1U);
                    PixelsBuffer content = new PixelsBuffer(256 * 256 * 16);
                    using (System.IO.BinaryWriter W = content.OpenStreamWrite())
                        for (int i = 0; i < 256 * 256; i++)
                        {
                            W.Write((float)SimpleRNG.GetUniform());
                            W.Write((float)SimpleRNG.GetUniform());
                            W.Write((float)SimpleRNG.GetUniform());
                            W.Write((float)SimpleRNG.GetUniform());
                        }
                    m_Tex_Noise = new Texture2D(m_device, 256, 256, 1, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, new PixelsBuffer[] { content });
                }

                // Build SH coeffs
                const int ORDERS = 20;
                {
                    const int TABLE_SIZE = 64;

                    // Load A coeffs into a texture array
                    float[,,]       A = new float[TABLE_SIZE, TABLE_SIZE, ORDERS];
//					using ( System.IO.FileStream S = new System.IO.FileInfo( @"ConeTable_cosAO_order20.float" ).OpenRead() )
                    using (System.IO.FileStream S = new System.IO.FileInfo(@"ConeTable_cosTheta_order20.float").OpenRead())
                        using (System.IO.BinaryReader R = new System.IO.BinaryReader(S)) {
                            for (int thetaIndex = 0; thetaIndex < TABLE_SIZE; thetaIndex++)
                            {
                                for (int AOIndex = 0; AOIndex < TABLE_SIZE; AOIndex++)
                                {
                                    for (int order = 0; order < ORDERS; order++)
                                    {
                                        A[thetaIndex, AOIndex, order] = R.ReadSingle();
                                    }
                                }
                            }
                        }

                    PixelsBuffer[] coeffSlices = new PixelsBuffer[5];                           // 5 slices of 4 coeffs each to get our 20 orders
                    for (int sliceIndex = 0; sliceIndex < coeffSlices.Length; sliceIndex++)
                    {
                        PixelsBuffer coeffSlice = new PixelsBuffer(TABLE_SIZE * TABLE_SIZE * 16);
                        coeffSlices[sliceIndex] = coeffSlice;

                        using (System.IO.BinaryWriter W = coeffSlice.OpenStreamWrite()) {
                            for (int thetaIndex = 0; thetaIndex < TABLE_SIZE; thetaIndex++)
                            {
                                for (int AOIndex = 0; AOIndex < TABLE_SIZE; AOIndex++)
                                {
                                    W.Write(A[thetaIndex, AOIndex, 4 * sliceIndex + 0]);
                                    W.Write(A[thetaIndex, AOIndex, 4 * sliceIndex + 1]);
                                    W.Write(A[thetaIndex, AOIndex, 4 * sliceIndex + 2]);
                                    W.Write(A[thetaIndex, AOIndex, 4 * sliceIndex + 3]);
                                }
                            }
                        }
                    }

                    m_Tex_ACoeffs = new Texture2D(m_device, 64, 64, coeffSlices.Length, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, coeffSlices);
                }

                {
                    // Load environment coeffs into a constant buffer
                    float3[] coeffs = new float3[ORDERS * ORDERS];
                    using (System.IO.FileStream S = new System.IO.FileInfo(@"Ennis_order20.float3").OpenRead())
                        using (System.IO.BinaryReader R = new System.IO.BinaryReader(S))
                            for (int coeffIndex = 0; coeffIndex < ORDERS * ORDERS; coeffIndex++)
                            {
                                coeffs[coeffIndex].Set(R.ReadSingle(), R.ReadSingle(), R.ReadSingle());
                            }

                    // Write into a raw byte[]
                    byte[] rawContent = new byte[400 * 4 * 4];
                    using (System.IO.MemoryStream MS = new System.IO.MemoryStream(rawContent))
                        using (System.IO.BinaryWriter W = new System.IO.BinaryWriter(MS)) {
                            for (int coeffIndex = 0; coeffIndex < ORDERS * ORDERS; coeffIndex++)
                            {
                                W.Write(coeffs[coeffIndex].x);
                                W.Write(coeffs[coeffIndex].y);
                                W.Write(coeffs[coeffIndex].z);
                                W.Write(0.0f);
                            }
                        }
                    m_CB_Coeffs = new RawConstantBuffer(m_device, 1, rawContent.Length);
                    m_CB_Coeffs.UpdateData(rawContent);
                }

                // Create camera + manipulator
                m_camera.CreatePerspectiveCamera(0.5f * (float)Math.PI, (float)graphPanel.Width / graphPanel.Height, 0.01f, 100.0f);
                m_camera.CameraTransformChanged += m_camera_CameraTransformChanged;
                m_cameraManipulator.Attach(graphPanel, m_camera);
                m_cameraManipulator.InitializeCamera(-2.0f * float3.UnitZ, float3.Zero, float3.UnitY);
                m_camera_CameraTransformChanged(null, EventArgs.Empty);

                // Start rendering
                Application.Idle += Application_Idle;
            } catch (Exception _e) {
                MessageBox.Show("Failed to initialize D3D renderer!\r\nReason: " + _e.Message);
            }
        }
    /// <summary>
    /// Imports a Galactic SPC file into a x and an y array. The file must not be a multi spectrum file (an exception is thrown in this case).
    /// </summary>
    /// <param name="xvalues">The x values of the spectrum.</param>
    /// <param name="yvalues">The y values of the spectrum.</param>
    /// <param name="filename">The filename where to import from.</param>
    /// <returns>Null if successful, otherwise an error description.</returns>
    public static string ToArrays(string filename, out double [] xvalues, out double [] yvalues)
    {
      System.IO.Stream stream=null;

      SPCHDR hdr = new SPCHDR();
      SUBHDR subhdr = new SUBHDR();

      try
      {
        stream = new System.IO.FileStream(filename,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
        System.IO.BinaryReader binreader = new System.IO.BinaryReader(stream);


        hdr.ftflgs = binreader.ReadByte(); // ftflgs : not-evenly spaced data
        hdr.fversn = binreader.ReadByte(); // fversn : new version
        hdr.fexper = binreader.ReadByte(); // fexper : general experimental technique
        hdr.fexp   = binreader.ReadByte(); // fexp   : fractional scaling exponent (0x80 for floating point)

        hdr.fnpts  = binreader.ReadInt32(); // fnpts  : number of points

        hdr.ffirst = binreader.ReadDouble(); // ffirst : first x-value
        hdr.flast  = binreader.ReadDouble(); // flast : last x-value
        hdr.fnsub  = binreader.ReadInt32(); // fnsub : 1 (one) subfile only
      
        binreader.ReadByte(); //  Type of X axis units (see definitions below) 
        binreader.ReadByte(); //  Type of Y axis units (see definitions below) 
        binreader.ReadByte(); // Type of Z axis units (see definitions below)
        binreader.ReadByte(); // Posting disposition (see GRAMSDDE.H)

        binreader.Read(new byte[0x1E0],0,0x1E0); // rest of SPC header


        // ---------------------------------------------------------------------
        //   following the x-values array
        // ---------------------------------------------------------------------

        if(hdr.fversn!=0x4B)
        {
          if(hdr.fversn==0x4D)
            throw new System.FormatException(string.Format("This SPC file has the old format version of {0}, the only version supported here is the new version {1}",hdr.fversn,0x4B));
          else
            throw new System.FormatException(string.Format("This SPC file has a version of {0}, the only version recognized here is {1}",hdr.fversn,0x4B));
        }

        if(0!=(hdr.ftflgs & 0x80))
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = binreader.ReadSingle();
        }
        else if(0==hdr.ftflgs) // evenly spaced data
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = hdr.ffirst + i*(hdr.flast-hdr.ffirst)/(hdr.fnpts-1);
        }
        else
        {
          throw new System.FormatException("The SPC file must not be a multifile; only single file format is accepted!");
        }



        // ---------------------------------------------------------------------
        //   following the y SUBHEADER
        // ---------------------------------------------------------------------

        subhdr.subflgs = binreader.ReadByte(); // subflgs : always 0
        subhdr.subexp  = binreader.ReadByte(); // subexp : y-values scaling exponent (set to 0x80 means floating point representation)
        subhdr.subindx = binreader.ReadInt16(); // subindx :  Integer index number of trace subfile (0=first)

        subhdr.subtime = binreader.ReadSingle(); // subtime;   Floating time for trace (Z axis corrdinate) 
        subhdr.subnext = binreader.ReadSingle(); // subnext;   Floating time for next trace (May be same as beg) 
        subhdr.subnois = binreader.ReadSingle(); // subnois;   Floating peak pick noise level if high byte nonzero 

        subhdr.subnpts = binreader.ReadInt32(); // subnpts;  Integer number of subfile points for TXYXYS type 
        subhdr.subscan = binreader.ReadInt32(); // subscan; Integer number of co-added scans or 0 (for collect) 
        subhdr.subwlevel = binreader.ReadSingle();        // subwlevel;  Floating W axis value (if fwplanes non-zero) 
        subhdr.subresv   = binreader.ReadInt32(); // subresv[4];   Reserved area (must be set to zero) 


        // ---------------------------------------------------------------------
        //   following the y-values array
        // ---------------------------------------------------------------------
        yvalues = new double[hdr.fnpts];
        
        if(hdr.fexp==0x80) //floating point format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadSingle();
        }
        else // fixed exponent format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadInt32()*Math.Pow(2,hdr.fexp-32);
        }
      }
      catch(Exception e)
      {
        xvalues = null;
        yvalues = null;
        return e.ToString();
      }
      finally
      {
        if(null!=stream)
          stream.Close();
      }
      
      return null;
    }
Exemple #29
0
 public override void Deserialize(System.IO.BinaryReader readFrom)
 {
     location.x = readFrom.ReadSingle();
     location.y = readFrom.ReadSingle();
     location.z = readFrom.ReadSingle();
 }
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.FollowTargetMessage message = new MavLink4Net.Messages.Common.FollowTargetMessage();
     message.Timestamp       = reader.ReadUInt64();
     message.CustomState     = reader.ReadUInt64();
     message.Lat             = reader.ReadInt32();
     message.Lon             = reader.ReadInt32();
     message.Alt             = reader.ReadSingle();
     message.Vel[0]          = reader.ReadSingle();
     message.Vel[1]          = reader.ReadSingle();
     message.Vel[2]          = reader.ReadSingle();
     message.Acc[0]          = reader.ReadSingle();
     message.Acc[1]          = reader.ReadSingle();
     message.Acc[2]          = reader.ReadSingle();
     message.AttitudeQ[0]    = reader.ReadSingle();
     message.AttitudeQ[1]    = reader.ReadSingle();
     message.AttitudeQ[2]    = reader.ReadSingle();
     message.AttitudeQ[3]    = reader.ReadSingle();
     message.Rates[0]        = reader.ReadSingle();
     message.Rates[1]        = reader.ReadSingle();
     message.Rates[2]        = reader.ReadSingle();
     message.PositionCov[0]  = reader.ReadSingle();
     message.PositionCov[1]  = reader.ReadSingle();
     message.PositionCov[2]  = reader.ReadSingle();
     message.EstCapabilities = reader.ReadByte();
     return(message);
 }
Exemple #31
0
        public static Assembly FromAIN(string path)
        {
            Assembly asm = new Assembly();
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
            fs.Position = 8;
            uint size = br.ReadUInt32();
            uint compressedSize = br.ReadUInt32();
            byte[] buf;
            byte[] dst = new byte[size];
            buf = br.ReadBytes((int)compressedSize);
            fixed (byte* ptr = buf)
            {
                fixed (byte* ptr2 = dst)
                {
                    uncompress(ptr2, &size, ptr, compressedSize);
                }
            }
            fs.Close();

            System.IO.MemoryStream ms = new System.IO.MemoryStream(dst);
            br = new System.IO.BinaryReader(ms);
            while (ms.Position < ms.Length)
            {
                string trunk = Encoding.ASCII.GetString(br.ReadBytes(4));
                switch (trunk)
                {
                    case "VERS":
                        asm.Version = br.ReadInt32();
                        if (asm.Version != 6)
                        {
                            throw new NotSupportedException("本SDK仅支持版本为:6的反编译");
                        }
                        break;
                    case "KEYC":
                        asm.Keyc = br.ReadInt32();
                        break;
                    case "CODE":
                        asm.CodeBuffer = br.ReadBytes(br.ReadInt32());
                        break;
                    case "FUNC":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Function func = new Function();
                                func.Address = br.ReadInt32();
                                func.Assembly = asm;
                                func.Name = ReadString(br);
                                func.U1 = br.ReadInt32();
                                func.ReturnType = (VarTypes)br.ReadInt32();
                                func.StructID = br.ReadInt32();
                                func.ArgCount = br.ReadInt32();
                                func.TotalLocalCount = br.ReadInt32();
                                func.U4 = br.ReadInt32();
                                for (int j = 0; j < func.TotalLocalCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.Assembly = asm;
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    if (j < func.ArgCount)
                                        func.Arguments.Add(arg);
                                    func.LocalVariables.Add(arg);
                                }
                                asm.Functions.Add(func);
                            }
                        }
                        break;
                    case "GLOB":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Variable var = new Variable();
                                var.Name = ReadString(br);
                                var.Assembly = asm;
                                var.VarType = (VarTypes)br.ReadInt32();
                                var.StructID = br.ReadInt32();
                                var.Dimension = br.ReadInt32();
                                var.U3 = br.ReadInt32();
                                asm.global.Add(var);
                            }
                        }
                        break;
                    case "GSET":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Variable var = asm.global[br.ReadInt32()];
                                VarTypes type = (VarTypes)br.ReadInt32();
                                switch (type)
                                {
                                    case VarTypes.Float:
                                        var.FloatVal = br.ReadSingle();
                                        break;
                                    case VarTypes.String:
                                        var.StringVal = ReadString(br);
                                        break;
                                    case VarTypes.Bool:
                                        var.BoolVal = br.ReadInt32() == 1;
                                        break;
                                    default:
                                        var.IntVal = br.ReadInt32();
                                        break;
                                }
                            }
                        }
                        break;
                    case "STRT":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Struct str = new Struct();
                                str.Name = ReadString(br);
                                int func = br.ReadInt32();
                                if (func != -1)
                                    str.Constructor = asm.func[func];
                                func = br.ReadInt32();
                                if (func != -1)
                                    str.Destructor = asm.func[func];
                                str.VarCount = br.ReadInt32();
                                for (int j = 0; j < str.VarCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.Assembly = asm;
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    str.Variables.Add(arg);
                                }
                                asm.structs.Add(str);
                            }
                        }
                        break;
                    case "MSG0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                asm.msgs.Add(ReadString(br));
                            }
                        }
                        break;
                    case "MAIN":
                        asm.EntryPoint = asm.func[br.ReadInt32()];
                        break;
                    case "MSGF":
                        asm.MessageFunction = asm.func[br.ReadInt32()];
                        break;
                    case "HLL0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string name = ReadString(br);
                                Hll hll = new Hll();
                                hll.Name = name;
                                int count2 = br.ReadInt32();
                                for (int j = 0; j < count2; j++)
                                {
                                    Function func = new Function();
                                    func.Name = ReadString(br);
                                    func.ReturnType = (VarTypes)br.ReadInt32();
                                    func.TotalLocalCount = br.ReadInt32();
                                    func.ArgCount = func.TotalLocalCount;
                                    for (int k = 0; k < func.TotalLocalCount; k++)
                                    {
                                        Variable arg = new Variable();
                                        arg.Assembly = asm;
                                        arg.Name = ReadString(br);
                                        arg.VarType = (VarTypes)br.ReadInt32();
                                        func.Arguments.Add(arg);
                                    }
                                    hll.Functions.Add(func);
                                }
                                asm.hlls.Add(hll);
                            }
                        }
                        break;
                    case "SWI0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Switch swi = new Switch();
                                swi.SwitchType = (SwitchTypes)br.ReadInt32();
                                swi.DefaultCase = br.ReadInt32();
                                int count2 = br.ReadInt32();
                                for (int j = 0; j < count2; j++)
                                {
                                    swi.SwitchTable.Add(br.ReadInt32(), br.ReadInt32());
                                }
                                asm.switches.Add(swi);
                            }
                        }
                        break;
                    case "GVER":
                        asm.GVersion = br.ReadInt32();
                        break;
                    case "STR0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.strings.Add(str);
                            }
                        }
                        break;
                    case "FNAM":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.fname.Add(str);
                            }
                        }
                        break;
                    case "OJMP":
                        {
                            int funcID = br.ReadInt32();
                            if (funcID >= 0)
                                asm.JumpFunction = asm.func[funcID];
                        }
                        break;
                    case "FNCT":
                        {
                            int len = br.ReadInt32();
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Function func = new Function();
                                func.Name = ReadString(br);
                                func.ReturnType = (VarTypes)br.ReadInt32();
                                func.StructID = br.ReadInt32();
                                func.ArgCount = br.ReadInt32();
                                func.TotalLocalCount = br.ReadInt32();
                                for (int j = 0; j < func.TotalLocalCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    func.Arguments.Add(arg);
                                }
                                asm.fnct.Add(func);
                            }
                        }
                        break;
                    case "OBJG":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.objg.Add(str);
                            }
                        }
                        break;
                    default:
                        throw new ArgumentException(string.Format("{0}文件中包含未知的Trunk:{1}", path, trunk));
                }
            }
            return asm;
        }
Exemple #32
0
        private bool _LeeSLTBinario(String FicheroSLT)
        {
            /*****Binary STL
             *
             * Because ASCII STL files can become very large, a binary version of STL exists. A binary STL file has an 80-character header (which is generally ignored, but should never begin with
             * "solid" because that will lead most software to assume that this is an ASCII STL file). Following the header is a 4-byte unsigned integer indicating the number of triangular facets
             * in the file. Following that is data describing each triangle in turn. The file simply ends after the last triangle.
             *
             * Each triangle is described by twelve 32-bit doubleing-point numbers: three for the normal and then three for the X/Y/Z coordinate of each vertex – just as with the ASCII version of STL.
             * After these follows a 2-byte ("short") unsigned integer that is the "attribute byte count" – in the standard format, this should be zero because most software does not understand anything else.
             *
             * doubleing-point numbers are represented as IEEE doubleing-point numbers and are assumed to be little-endian, although this is not stated in documentation.
             *
             *  UINT8[80] – Header
             *  UINT32 – Number of triangles
             *
             *  foreach triangle
             *  REAL32[3] – Normal vector
             *  REAL32[3] – Vertex 1
             *  REAL32[3] – Vertex 2
             *  REAL32[3] – Vertex 3
             *  UINT16 – Attribute byte count
             *  end
             */

            bool Res = true;

            System.IO.StreamReader SR = new System.IO.StreamReader(FicheroSLT, Encoding.ASCII);
            //Evalua si es binario o ASCII
            string LineaSLT = SR.ReadLine();

            LineaSLT = LineaSLT.TrimStart(new char[2] {
                ' ', '\t'
            });
            SR.Close();
            SR.Dispose();

            if (!LineaSLT.StartsWith("solid "))
            {
                System.IO.FileStream   FS = new System.IO.FileStream(FicheroSLT, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader BR = new System.IO.BinaryReader(FS);

                //Cabecera UINT8[80] – Header
                for (int i = 0; i < 80; i++)
                {
                    char TempChar = BR.ReadChar();
                    if (TempChar != '\0')
                    {
                        Nombre += TempChar;
                    }
                }

                //Número de triángulos UINT32 – Number of triangles
                UInt32 NumTriangulos = BR.ReadUInt32();

                if (NumTriangulos > 0)
                {
                    LoopSLT  TempLoop  = new LoopSLT();
                    FacetSLT TempFacet = new FacetSLT();

                    for (UInt32 Ui = 0; Ui < NumTriangulos; Ui++)
                    {
                        //Vector Normal REAL32[3] – Normal vector

                        TempFacet._Normal = new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle()));

                        //REAL32[3] – Vertex 1
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));
                        //REAL32[3] – Vertex 2
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));
                        //REAL32[3] – Vertex 3
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));

                        TempLoop.ActualizaBoundingZ();
                        TempFacet._Loops.Add(TempLoop);

                        //Attribute byte count
                        TempFacet._Attribute = BR.ReadUInt16();

                        if (TempFacet.EsValido())
                        {
                            _Facets.Add(TempFacet);
                        }
                        else
                        {
                            Res = false;
                            Fallos.Add("Lectura SLT Binario: Faceta no válida");
                        }

                        TempLoop  = new LoopSLT();
                        TempFacet = new FacetSLT();
                    }
                }
                else
                {
                    Res = false;
                    Fallos.Add("Lectura SLT Binario: Número de triángulos nulo o igual a 0");
                }

                BR.Close();
                FS.Close();
                BR.Dispose();
                FS.Dispose();
            }
            else
            {
                Res = false;
                Fallos.Add("Lectura SLT Binario: El Fichero comienza por 'solid '");
            }

            return(Res);
        }
Exemple #33
0
 public void loadState(System.IO.BinaryReader reader)
 {
     _life   = reader.ReadSingle();
     maxlife = reader.ReadSingle();
     isGod   = reader.ReadBoolean();
 }
Exemple #34
0
        public void read(System.IO.BinaryReader reader)
        {
            if (count <= 0)
            {
                return;
            }
            switch (type)
            {
            case TIFFdataType.Byte:
                content = new byte[count];
                for (int i = 0; i < count; i++)
                {
                    ((byte[])content)[i] = reader.ReadByte();
                }
                break;

            case TIFFdataType.Ascii:
                content = new char[count];
                for (int i = 0; i < count; i++)
                {
                    ((char[])content)[i] = (char)reader.ReadByte();
                }
                break;

            case TIFFdataType.Short:
                content = new ushort[count];
                for (int i = 0; i < count; i++)
                {
                    ((ushort[])content)[i] = reader.ReadUInt16();
                }
                break;

            case TIFFdataType.Long:
                content = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    ((uint[])content)[i] = reader.ReadUInt32();
                }
                break;

            case TIFFdataType.Rational:
                content = new uint[count * 2];
                for (int i = 0; i < 2 * count; i++)
                {
                    ((uint[])content)[i] = reader.ReadUInt32();
                }
                break;

            case TIFFdataType.SignedByte:
                content = new sbyte[count];
                for (int i = 0; i < count; i++)
                {
                    ((sbyte[])content)[i] = reader.ReadSByte();
                }
                break;

            case TIFFdataType.SignedShort:
                content = new short[count];
                for (int i = 0; i < count; i++)
                {
                    ((short[])content)[i] = reader.ReadInt16();
                }
                break;

            case TIFFdataType.SignedLong:
                content = new int[count];
                for (int i = 0; i < count; i++)
                {
                    ((int[])content)[i] = reader.ReadInt32();
                }
                break;

            case TIFFdataType.SignedRational:
                content = new int[count * 2];
                for (int i = 0; i < 2 * count; i++)
                {
                    ((int[])content)[i] = reader.ReadInt32();
                }
                break;

            case TIFFdataType.Float:
                content = new float[count];
                for (int i = 0; i < count; i++)
                {
                    ((float[])content)[i] = reader.ReadSingle();
                }
                break;

            case TIFFdataType.Double:
                content = new double[count];
                for (int i = 0; i < count; i++)
                {
                    ((double[])content)[i] = reader.ReadDouble();
                }
                break;

            default:
                content = new Object[0];
                break;
            }
        }
            /// <summary>
            /// reads a file and populates the map receiver instance.
            /// </summary>
            /// <returns></returns>
            public static bool Read_pachm(out Mapping.PachMapReceiver[] Map)
            {
                System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
                of.DefaultExt = ".pachm";
                of.AddExtension = true;
                of.Filter = "Pachyderm Mapping Data File (*.pachm)|*.pachm|" + "All Files|";
                if (of.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    Map = null;
                    return false;
                }
                System.IO.BinaryReader sr = new System.IO.BinaryReader(System.IO.File.Open(of.FileName, System.IO.FileMode.Open));
                //1. Write calculation type. (string)
                string CalcType = sr.ReadString();
                if (CalcType != "Type;Map_Data" && CalcType != "Type;Map_Data_NoDir") throw new Exception("Map Data File Expected");
                bool Directional = (CalcType == "Type;Map_Data");

                //2. Write the number of samples in each histogram. (int)
                int SampleCT = (int)sr.ReadUInt32();
                //3. Write the sample rate. (int)
                int SampleRate = (int)sr.ReadUInt32();
                //4. Write the number of Receivers (int)
                int Rec_CT = (int)sr.ReadUInt32();
                //4.5 Write the version number
                double version = 1.1;
                double rev = 0;
                //5. Announce that the following data pertains to the form of the analysis mesh. (string)
                int s_ct=1;
                Rhino.Geometry.Mesh Map_Mesh = new Rhino.Geometry.Mesh();
                Map = new Mapping.PachMapReceiver[1];
                //Map[0] = new Pach_Map_Receiver();
                //double[] Rho_C = null;
                double[] delay;

                do
                {
                    switch (sr.ReadString())
                    {
                        case "Version":
                            //Pach1.7 = Versioning functionality added.
                            string v = sr.ReadString();
                            version = double.Parse(v.Substring(0, 3));
                            rev = int.Parse(v.Split(new char[1] { '.' })[3]);
                            break;
                        case "Mesh Information":
                            //6. Announce Mesh Vertices (string)
                            //Write the number of vertices & faces (int) (int)
                            if (sr.ReadString() != "Mesh Vertices") throw new Exception("Mesh Vertices Expected");

                            int VC = (int)sr.ReadUInt32();
                            int FC = (int)sr.ReadUInt32();
                            for (int i = 0; i < VC; i++)
                            {
                                //Write Vertex: (double) (double) (double)
                                Map_Mesh.Vertices.Add(new Rhino.Geometry.Point3d(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()));
                            }

                            //7. Announce Mesh Faces (string)
                            if (sr.ReadString() != "Mesh Faces") throw new Exception("Mesh Faces Expected");

                            for (int i = 0; i < FC; i++)
                            {
                                // Write mesh vertex indices: (int) (int) (int) (int)
                                Map_Mesh.Faces.AddFace((int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32());
                            }
                            break;
                        case "Sources":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "SourceswLoc":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate * 1000;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].Src = new Rhino.Geometry.Point3d(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "Receiver Hit Data":
                            if (Map[0] == null)
                            {
                                Map = new Mapping.PachMapReceiver[1];
                                Map[0] = new Mapping.PachMapReceiver();
                                Map[0].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[0].SampleRate = SampleRate;
                                Map[0].SampleCT = SampleCT;
                                Map[0].Map_Mesh = Map_Mesh;
                                Map[0].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[0].SrcType = "Geodesic";
                            }

                            //8. Announce that the following data pertains to the receiver histograms (string)
                            //8a. Announce whether or not data is linked to vertices rather than faces (bool)
                            bool vert_Receiver = sr.ReadBoolean();
                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s].Rec_Vertex = vert_Receiver;
                                for (int i = 0; i < Map[s].Rec_List.Length; i++)
                                {
                                    //for version 1.7 and up, write direct sound arrival time.
                                    //Write Receiver Index (int)
                                    int j = (int)sr.ReadUInt32();
                                    //Write Direct Sound Arrival Time.
                                    double Direct_Time;
                                    if (version >= 1.7) Direct_Time = sr.ReadDouble(); else Direct_Time = (Utilities.PachTools.RPttoHPt(Map[s].Src) - Map[s].Rec_List[i].H_Origin).Length() / 343f;
                                    //Write Impedance of Air
                                    double Rho_C = version >= 2.0 ? sr.ReadDouble() : 400;

                                    if (vert_Receiver)
                                    {
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(Map_Mesh.Vertices[i], new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }
                                    else
                                    {
                                        Rhino.Geometry.Point3d RecLoc = Map_Mesh.Faces.GetFaceCenter(i);
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(new Rhino.Geometry.Point3f((float)RecLoc.X, (float)RecLoc.Y, (float)RecLoc.Z), new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }

                                    for (int Octave = 0; Octave < 8; Octave++)
                                    {
                                        //Write Octave (int)
                                        int Oct_out = (int)sr.ReadUInt32();
                                        if (Oct_out != Octave) throw new Exception(string.Format("Octave {0} Expected", Octave));
                                        double[] Hist = Map[s].Rec_List[i].GetEnergyHistogram(Octave);
                                        if (Directional)
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                        }
                                        else
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0, 0, 0), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0,0,0), Octave);
                                            }
                                        }
                                    }
                                    if (sr.ReadString() != "End_Receiver_Hits") throw new Exception("End of Receiver Hits Expected");
                                }
                            }
                            break;
                        case "End_of_File":
                            sr.Close();
                            return true;
                    }
                } while (true);
                throw new Exception("Unsuccessful Read");
            }
Exemple #36
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        protected override void Unserialize(System.IO.BinaryReader reader)
        {
            ver       = reader.ReadUInt16();
            subver    = reader.ReadUInt16();
            sz.Width  = reader.ReadInt32();
            sz.Height = reader.ReadInt32();
            type      = (LotType)reader.ReadByte();

            roads     = reader.ReadByte();
            rotation  = (Rotation)reader.ReadByte();
            unknown_0 = reader.ReadUInt32();

            lotname     = StreamHelper.ReadString(reader);
            description = StreamHelper.ReadString(reader);

            unknown_1 = new List <float>();
            int len = reader.ReadInt32();

            for (int i = 0; i < len; i++)
            {
                this.unknown_1.Add(reader.ReadSingle());
            }

            if (subver >= (UInt16)LtxtSubVersion.Voyage)
            {
                unknown_3 = reader.ReadSingle();
            }
            else
            {
                unknown_3 = 0;
            }
            if (subver >= (UInt16)LtxtSubVersion.Freetime)
            {
                unknown_4 = reader.ReadUInt32();
            }
            else
            {
                unknown_4 = 0;
            }

            if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment)
            {
                unknown_5 = reader.ReadBytes(14);
            }
            else
            {
                unknown_5 = new byte[0];
            }

            int y = reader.ReadInt32();
            int x = reader.ReadInt32();

            loc = new Point(x, y);

            elevation   = reader.ReadSingle();
            lotInstance = reader.ReadUInt32();
            orient      = (LotOrientation)reader.ReadByte();

            texture = StreamHelper.ReadString(reader);

            unknown_2 = reader.ReadByte();

            if (ver >= (int)LtxtVersion.Business)
            {
                owner = reader.ReadUInt32();
            }
            else
            {
                owner = 0;
            }

            if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment)
            {
                int count;

                apartmentBase = reader.ReadUInt32();
                unknown_6     = reader.ReadBytes(9);

                subLots = new List <SubLot>();
                count   = reader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    subLots.Add(new SubLot(reader));
                }

                unknown_7 = new List <uint>();
                count     = reader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    unknown_7.Add(reader.ReadUInt32());
                }
            }
            else
            {
                apartmentBase = 0;
                unknown_6     = new byte[0];
                subLots       = new List <SubLot>();
                unknown_7     = new List <uint>();
            }

            followup = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
        }
Exemple #37
0
 public float getFloat()
 {
     return(reader.ReadSingle());
 }
 /// <summary>
 ///Deserializes DiagramState
 ///</summary>
 ///<param name="reader">the reader from which to deserialize</param>
 ///<returns>deserialized DiagramState</returns>
 public virtual object Deserialize(System.IO.BinaryReader reader)
 {
     this._LeftSpeed = reader.ReadSingle();
     this._RighSpeed = reader.ReadSingle();
     return(this);
 }
Exemple #39
0
        public void UnserializeData(System.IO.BinaryReader reader)
        {
            unknown1 = reader.ReadInt16();
            short ct1 = reader.ReadInt16();
            short ct2 = reader.ReadInt16();

            headerb = reader.ReadBytes(headerb.Length);
            for (int i = 0; i < headeri.Length; i++)
            {
                headeri[i] = reader.ReadUInt32();
            }
            for (int i = 0; i < headerf.Length; i++)
            {
                headerf[i] = reader.ReadSingle();
            }

            objname = Helper.ToString(reader.ReadBytes(headerb[5]));
            reader.ReadByte();             //read the terminating 0
            objmod = Helper.ToString(reader.ReadBytes(headerb[0]));
            reader.ReadByte();             //read the terminating 0

            int ct = headerb[0] + headerb[5];

            Align(reader, ct + 2);

            //--- part1 ---
            ab1 = new AnimBlock1[ct1];
            int len = 0;

            for (int i = 0; i < ab1.Length; i++)
            {
                ab1[i] = new AnimBlock1(this.Parent);
                ab1[i].UnserializeData(reader);
            }
            for (int i = 0; i < ab1.Length; i++)
            {
                len += ab1[i].UnserializeName(reader);
            }
            Align(reader, len);

            //--- part2 ---
            len = 0;
            for (int i = 0; i < ab1.Length; i++)
            {
                ab1[i].UnserializePart2Data(reader);
            }
            for (int i = 0; i < ab1.Length; i++)
            {
                len += ab1[i].UnserializePart2Name(reader);
            }
            Align(reader, len);

            try
            {
                //--- part3 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart3Data(reader);
                }
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart3AddonData(reader);
                }

                //--- part4 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart4Data(reader);
                }

                //--- part5 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart5Data(reader);
                }

                //--- part6 ---
                ab6 = new AnimBlock6[ct2];
                len = 0;
                for (int i = 0; i < ab6.Length; i++)
                {
                    ab6[i] = new AnimBlock6();
                    ab6[i].UnserializeData(reader);
                }
                for (int i = 0; i < ab6.Length; i++)
                {
                    len += ab6[i].UnserializeName(reader);
                }
            }
            catch {}

            unknowndata = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
        }
Exemple #40
0
        // Per spot:
        // uint32 magic
        // uint32 reserved;
        // uint32 flags;
        // float x;
        // float y;
        // float z;
        // uint32 no_paths
        //   for each path
        //     float x;
        //     float y;
        //     float z;

        public bool Load(string baseDir)
        {
            string fileName    = FileName();
            string filenamebin = baseDir + fileName;

            System.IO.Stream       stream = null;
            System.IO.BinaryReader file   = null;
            int n_spots = 0;
            int n_steps = 0;

            try
            {
                stream = System.IO.File.OpenRead(filenamebin);
                if (stream != null)
                {
                    file = new System.IO.BinaryReader(stream);
                    if (file != null)
                    {
                        uint magic = file.ReadUInt32();
                        if (magic == FILE_MAGIC)
                        {
                            uint type;
                            while ((type = file.ReadUInt32()) != FILE_ENDMAGIC)
                            {
                                n_spots++;
                                uint  reserved = file.ReadUInt32();
                                uint  flags    = file.ReadUInt32();
                                float x        = file.ReadSingle();
                                float y        = file.ReadSingle();
                                float z        = file.ReadSingle();
                                uint  n_paths  = file.ReadUInt32();
                                if (x != 0 && y != 0)
                                {
                                    Spot s = new Spot(x, y, z);
                                    s.flags = flags;

                                    for (uint i = 0; i < n_paths; i++)
                                    {
                                        n_steps++;
                                        float sx = file.ReadSingle();
                                        float sy = file.ReadSingle();
                                        float sz = file.ReadSingle();
                                        s.AddPathTo(sx, sy, sz);
                                    }
                                    AddSpot(s);
                                }
                            }
                        }
                    }
                }
            }
            catch (System.IO.FileNotFoundException e)
            {
                logger.Debug(e.Message);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                logger.Debug(e.Message);
            }
            catch (Exception e)
            {
                logger.Debug(e.Message);
            }

            if (file != null)
            {
                file.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }

            Log("Loaded " + fileName + " " + n_spots + " spots " + n_steps + " steps");

            modified = false;
            return(false);
        }
Exemple #41
0
        public bool LoadMap(string fileName)
        {
            bool result = false;

            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(fileName, System.IO.FileMode.Open)))
                {
                    int readFileVersion = reader.ReadInt32();
                    if (readFileVersion != FileVersionNum)
                    {
                        FileLoadResult = "File has no valid format";
                        return(false);
                    }

                    this.mapNumCellsPerRow   = reader.ReadInt32();
                    this.mapNumCellPerColumn = reader.ReadInt32();

                    int heightMapLength = reader.ReadInt32();
                    this.heightMap = new int[heightMapLength];
                    for (int i = 0; i < this.heightMap.Length; i++)
                    {
                        this.heightMap[i] = reader.ReadInt32();
                    }

                    int sectorLength = reader.ReadInt32();
                    this.sector = new int[sectorLength];
                    for (int i = 0; i < this.sector.Length; i++)
                    {
                        this.sector[i] = reader.ReadInt32();
                    }

                    int pointXLength = reader.ReadInt32();
                    this.pointX = new int[pointXLength];
                    for (int i = 0; i < this.pointX.Length; i++)
                    {
                        pointX[i] = reader.ReadInt32();
                    }

                    int pointYLength = reader.ReadInt32();
                    this.pointY = new int[pointYLength];
                    for (int i = 0; i < this.pointY.Length; i++)
                    {
                        pointY[i] = reader.ReadInt32();
                    }

                    int pointAltitudeLength = reader.ReadInt32();
                    this.pointAltitude = new int[pointAltitudeLength];
                    for (int i = 0; i < this.pointAltitude.Length; i++)
                    {
                        pointAltitude[i] = reader.ReadInt32();
                    }


                    // this.textureMap			vector4[]
                    int texturMapLength = reader.ReadInt32();
                    this.textureMap = new Vector4[texturMapLength];
                    float x, y, z, w;
                    for (int i = 0; i < this.textureMap.Length; i++)
                    {
                        x = reader.ReadSingle();
                        y = reader.ReadSingle();
                        z = reader.ReadSingle();
                        w = reader.ReadSingle();

                        textureMap[i] = new Vector4(x, y, z, w);
                    }



                    // this.resources			ResourceCell[]
                    int resourceCellLength = reader.ReadInt32();
                    this.resources = new ResourceCell[resourceCellLength];

                    for (int i = 0; i < this.resources.Length; i++)
                    {
                        this.resources[i] = new ResourceCell();

                        this.resources[i].Aluminium = reader.ReadSingle();


                        this.resources[i].Copper   = reader.ReadSingle();
                        this.resources[i].Gold     = reader.ReadSingle();
                        this.resources[i].Iron     = reader.ReadSingle();
                        this.resources[i].Lead     = reader.ReadSingle();
                        this.resources[i].Lithium  = reader.ReadSingle();
                        this.resources[i].Nickel   = reader.ReadSingle();
                        this.resources[i].Platinum = reader.ReadSingle();
                        this.resources[i].Silver   = reader.ReadSingle();
                        this.resources[i].Titanium = reader.ReadSingle();
                        this.resources[i].Tungsten = reader.ReadSingle();
                        this.resources[i].Uranium  = reader.ReadSingle();
                    }



                    // entities			List<Entity>



                    PrecalculateVertices();
                    GenerateMovementMap();
                    GenerateSearchTree();

                    entities = new List <Entity>();
                    result   = true;
                }
            }



            return(result);
        }
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.PositionTargetLocalNedMessage message = new MavLink4Net.Messages.Common.PositionTargetLocalNedMessage();
     message.TimeBootMs      = reader.ReadUInt32();
     message.X               = reader.ReadSingle();
     message.Y               = reader.ReadSingle();
     message.Z               = reader.ReadSingle();
     message.Vx              = reader.ReadSingle();
     message.Vy              = reader.ReadSingle();
     message.Vz              = reader.ReadSingle();
     message.Afx             = reader.ReadSingle();
     message.Afy             = reader.ReadSingle();
     message.Afz             = reader.ReadSingle();
     message.Yaw             = reader.ReadSingle();
     message.YawRate         = reader.ReadSingle();
     message.TypeMask        = reader.ReadUInt16();
     message.CoordinateFrame = ((MavLink4Net.Messages.Common.Frame)(reader.ReadByte()));
     return(message);
 }
Exemple #43
0
 protected override void DataUpdate()
 {
     System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
     ByteStream.Position = 0;
     X        = BSReader.ReadSingle();
     Y        = BSReader.ReadSingle();
     Z        = BSReader.ReadSingle();
     W        = BSReader.ReadSingle();
     RX       = BSReader.ReadUInt16();
     COMRX    = BSReader.ReadUInt16();
     RY       = BSReader.ReadUInt16();
     COMRY    = BSReader.ReadUInt16();
     RZ       = BSReader.ReadUInt16();
     COMRZ    = BSReader.ReadUInt16();
     Size1    = BSReader.ReadInt32();
     Size1    = BSReader.ReadInt32();
     SomeNum1 = BSReader.ReadInt32();
     Array.Resize(ref Something1, Size1);
     for (int i = 0; i <= Size1 - 1; i++)
     {
         Something1[i] = BSReader.ReadUInt16();
     }
     Size2    = BSReader.ReadInt32();
     Size2    = BSReader.ReadInt32();
     SomeNum2 = BSReader.ReadInt32();
     Array.Resize(ref Something2, Size2);
     for (int i = 0; i <= Size2 - 1; i++)
     {
         Something2[i] = BSReader.ReadUInt16();
     }
     Size3    = BSReader.ReadInt32();
     Size3    = BSReader.ReadInt32();
     SomeNum3 = BSReader.ReadInt32();
     Array.Resize(ref Something3, Size3);
     for (int i = 0; i <= Size3 - 1; i++)
     {
         Something3[i] = BSReader.ReadUInt16();
     }
     ObjectID         = BSReader.ReadUInt16();
     AfterOID         = BSReader.ReadUInt32();
     ParametersHeader = BSReader.ReadUInt32();
     UnkI32           = BSReader.ReadUInt32();
     UnkI321Number    = BSReader.ReadInt32();
     Array.Resize(ref UnkI321, UnkI321Number);
     for (int i = 0; i <= UnkI321Number - 1; i++)
     {
         UnkI321[i] = BSReader.ReadUInt32();
     }
     UnkI322Number = BSReader.ReadInt32();
     Array.Resize(ref UnkI322, UnkI322Number);
     for (int i = 0; i <= UnkI322Number - 1; i++)
     {
         UnkI322[i] = BSReader.ReadSingle();
     }
     UnkI323Number = BSReader.ReadInt32();
     Array.Resize(ref UnkI323, UnkI323Number);
     for (int i = 0; i <= UnkI323Number - 1; i++)
     {
         UnkI323[i] = BSReader.ReadUInt32();
     }
 }
Exemple #44
0
        private void bEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                return;
            }
            int i = (int)dataGridView1.SelectedRows[0].Tag;

            switch (mode)
            {
            case Mode.Arrays: {
                DataType[] types   = new DataType[connection.ArrayLengths[i]];
                int[]      lenType = new int[connection.ArrayLengths[i]];
                string[]   strings = new string[connection.ArrayLengths[i]];
                connection.WriteDataType(DataTypeSend.GetArray); // code
                connection.WriteInt(i);                          // index
                int lenData = 0;
                for (int j = 0; j < strings.Length; j++)
                {
                    types[j]   = (DataType)connection.ReadInt();
                    lenType[j] = connection.ReadInt();     // len data of type
                    lenData   += lenType[j];
                }
                byte[]       buf = connection.ReadBytes(lenData); // read data
                BinaryReader br  = new BinaryReader(new MemoryStream(buf));
                for (int j = 0; j < strings.Length; j++)
                {
                    switch (types[j])
                    {
                    case DataType.None:
                        br.BaseStream.Position += 4;
                        break;

                    case DataType.Int:
                        strings[j] = br.ReadInt32().ToString();
                        break;

                    case DataType.Float:
                        strings[j] = br.ReadSingle().ToString();
                        break;

                    case DataType.String:
                        byte[] bytes = br.ReadBytes(lenType[j]);
                        strings[j] = System.Text.Encoding.ASCII.GetString(bytes, 0, Array.IndexOf <byte>(bytes, 0));
                        break;
                    }
                }
                br.Close();
                strings = EditorWindow.ShowEditor(this, null, types, strings, connection.ArrayIsMap[i]);
                if (strings != null)       // save
                {
                    MemoryStream ms = new MemoryStream(lenData);
                    BinaryWriter bw = new BinaryWriter(ms);
                    for (int j = 0; j < strings.Length; j++)
                    {
                        switch (types[j])
                        {
                        case DataType.None:
                            bw.BaseStream.Position += 4;
                            break;

                        case DataType.Int:
                            bw.Write(int.Parse(strings[j]));
                            break;

                        case DataType.Float:
                            bw.Write(float.Parse(strings[j]));
                            break;

                        case DataType.String:
                            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strings[j]);
                            if (bytes.Length < lenType[j])
                            {
                                bw.Write(bytes);
                            }
                            else
                            {
                                bw.Write(bytes, 0, lenType[j] - 1);
                            }
                            bw.Write((byte)0);
                            break;
                        }
                    }
                    // send data to sfall
                    connection.WriteDataType(DataTypeSend.SetArray);
                    connection.WriteInt(i);     // index
                    connection.WriteInt(lenData);
                    connection.WriteBytes(ms.GetBuffer(), 0, lenData);
                    bw.Close();
                }
            }
            break;

            case Mode.Critters: {
                DataType[] types   = new DataType[33];
                string[]   strings = new string[33];
                string[]   names   = new string[33];
                connection.WriteDataType(DataTypeSend.RetrieveCritter);
                connection.WriteInt(i);
                BinaryReader br = new BinaryReader(new System.IO.MemoryStream(connection.ReadBytes(33 * 4)));
                for (int j = 0; j < 33; j++)
                {
                    types[j]   = DataType.Int;
                    strings[j] = br.ReadInt32().ToString();
                }
                br.Close();
                names[0]  = " ID";
                names[1]  = " Tile";
                names[6]  = " Current frame";
                names[7]  = " Rotation";
                names[8]  = " FID";
                names[9]  = " Flags";
                names[10] = " Elevation";
                names[11] = " Inventory count";
                names[13] = " Inventory pointer";
                names[14] = " Reaction";
                names[15] = " Combat state";
                names[16] = " Current AP";
                names[17] = " Combat flags";
                names[18] = " Last Turn Damage";
                names[19] = " AI Packet";
                names[20] = " Team";
                names[21] = " Who hit me";
                names[22] = " HP";
                names[23] = " Rads";
                names[24] = " Poison";
                names[25] = " Proto ID";
                names[26] = " Combat ID";
                names[29] = " Outline flags";
                names[30] = " Script ID";
                names[32] = " Script index";
                strings   = EditorWindow.ShowEditor(this, names, types, strings);
                if (strings != null)
                {
                    MemoryStream ms = new MemoryStream(33 * 4);
                    BinaryWriter bw = new BinaryWriter(ms);
                    for (int j = 0; j < 33; j++)
                    {
                        bw.Write(int.Parse(strings[j]));
                    }
                    connection.WriteDataType(DataTypeSend.SetCritter);
                    connection.WriteInt(i);
                    connection.WriteBytes(ms.GetBuffer(), 0, 33 * 4);
                    bw.Close();
                }
            }
            break;
            }
        }
Exemple #45
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
        public static System.Numerics.Matrix4x4 ReadMatrix(this System.IO.BinaryReader instream)
        {
            System.Numerics.Matrix4x4 m;

            // Yes, the matricies appear to be written top-down in colums, this isn't the field names being wrong
            // This is how a multidimensional array is layed out in memory.

            // First column
            m.M11 = instream.ReadSingle();
            m.M12 = instream.ReadSingle();
            m.M13 = instream.ReadSingle();
            m.M14 = instream.ReadSingle();

            // Second column
            m.M21 = instream.ReadSingle();
            m.M22 = instream.ReadSingle();
            m.M23 = instream.ReadSingle();
            m.M24 = instream.ReadSingle();

            // Third column
            m.M31 = instream.ReadSingle();
            m.M32 = instream.ReadSingle();
            m.M33 = instream.ReadSingle();
            m.M34 = instream.ReadSingle();

            // Fourth column
            m.M41 = instream.ReadSingle();
            m.M42 = instream.ReadSingle();
            m.M43 = instream.ReadSingle();
            m.M44 = instream.ReadSingle();

            return(m);
        }
Exemple #47
0
 /// <summary>
 /// Deserializes all following Frames of this State.
 /// </summary>
 /// <param name="stream">Input Stream</param>
 /// <param name="version">Protocol Version</param>
 public override void DeserializeUpdate(System.IO.BinaryReader stream, byte version)
 {
     CarrierStrength = stream.ReadSingle();
 }
 static public System.Numerics.Vector3 ReadVector3(this System.IO.BinaryReader self)
 => new System.Numerics.Vector3(self.ReadSingle(), self.ReadSingle(), self.ReadSingle());
Exemple #49
0
		/// <summary>Loads the black-box logs from the previous simulation run</summary>
		internal static void LoadLogs()
		{
			string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");
			try
			{
				using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
					{
						byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
						const short Version = 1;
						byte[] Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						short Number = Reader.ReadInt16();
						if (Version != Number) throw new System.IO.InvalidDataException();
						Game.LogRouteName = Reader.ReadString();
						Game.LogTrainName = Reader.ReadString();
						Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64());
						Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
						Game.BlackBoxEntryCount = Reader.ReadInt32();
						Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
						for (int i = 0; i < Game.BlackBoxEntryCount; i++)
						{
							Game.BlackBoxEntries[i].Time = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Position = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Speed = Reader.ReadSingle();
							Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle();
							Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
							Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16();
						}
						Game.ScoreLogCount = Reader.ReadInt32();
						Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount];
						Game.CurrentScore.Value = 0;
						for (int i = 0; i < Game.ScoreLogCount; i++)
						{
							Game.ScoreLogs[i].Time = Reader.ReadDouble();
							Game.ScoreLogs[i].Position = Reader.ReadDouble();
							Game.ScoreLogs[i].Value = Reader.ReadInt32();
							Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16();
							Game.CurrentScore.Value += Game.ScoreLogs[i].Value;
						}
						Game.CurrentScore.Maximum = Reader.ReadInt32();
						Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
						Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						Reader.Close();
					} Stream.Close();
				}
			}
			catch
			{
				Game.LogRouteName = "";
				Game.LogTrainName = "";
				Game.LogDateTime = DateTime.Now;
				Game.BlackBoxEntries = new Game.BlackBoxEntry[256];
				Game.BlackBoxEntryCount = 0;
				Game.ScoreLogs = new Game.ScoreLog[64];
				Game.ScoreLogCount = 0;
			}
		}
 static public System.Numerics.Quaternion ReadQuaternion(this System.IO.BinaryReader self)
 => new System.Numerics.Quaternion(self.ReadSingle(), self.ReadSingle(), self.ReadSingle(), self.ReadSingle());
Exemple #51
0
        void FastFit()
        {
            // Load response curve
            //			string	text = "";
            List<float>	responseCurve = new List<float>();
            using ( System.IO.FileStream S = new System.IO.FileInfo( "../../responseCurve9.float" ).OpenRead() )
                using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {
                    for ( int i=0; i < 256; i++ ) {
                        responseCurve.Add( R.ReadSingle() );
            //						text += ", " + responseCurve[responseCurve.Count-1];
                    }
                }

            // Perform fitting
            float	a = 0.0f, b = 1.0f, c = 0.0f, d = 0.0f;		// sumSqDiff = 21.664576085822642
            //			float	a = -6.55077f, b = 0.1263f, c = -0.000435788f, d = 7.52068e-7f;
            //			FindFit( responseCurve.ToArray(), ref a, ref b, ref c, ref d );
            FindFitBFGS( responseCurve.ToArray(), ref a, ref b, ref c, ref d );

            // Render
            m_imageFile.Init( 1024, 768, ImageFile.PIXEL_FORMAT.RGBA8, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
            m_imageFile.Clear( new float4( 1, 1, 1, 1 ) );

            float2	rangeX = new float2( 0, 255 );
            float2	rangeY = new float2( -2, 2 );
            /*
            m_imageFile.PlotGraphAutoRangeY( black, rangeX, ref rangeY, ( float x ) => {
                int		i0 = (int) Math.Min( 255, Math.Floor( x ) );
                int		i1 = (int) Math.Min( 255, i0+1 );
                float	g0 = responseCurve[i0];
                float	g1 = responseCurve[i1];
                float	t = x - i0;
                return TentFilter( x ) * (g0 + (g1-g0) * t);
            //				return (float) Math.Pow( 2.0f, g0 + (g1-g0) * t );
            } );
            m_imageFile.PlotGraph( red, rangeX, rangeY, ( float x ) => {
                return TentFilter( x ) * (a + b * x + c * x*x + d * x*x*x);
            } );
            m_imageFile.PlotLogAxes( black, rangeX, rangeY, -16.0f, 2.0f );
            */

            //			m_imageFile.PlotGraphAutoRangeY( black, rangeX, ref rangeY, ( float x ) => {
            rangeY = new float2( 0, 400 );
            m_imageFile.PlotGraph( black, rangeX, rangeY, ( float x ) => {
                int		i0 = (int) Math.Min( 255, Math.Floor( x ) );
                int		i1 = (int) Math.Min( 255, i0+1 );
                float	g0 = responseCurve[i0];
                float	g1 = responseCurve[i1];
                float	t = x - i0;
            //				return (float) (Math.Log( (g0 + (g1-g0) * t) ) / Math.Log( 2 ));
                return (float) Math.Pow( 2.0, (g0 + (g1-g0) * t) );
            } );
            m_imageFile.PlotGraph( red, rangeX, rangeY, ( float x ) => {
            //				return (float) (Math.Log( (a + b * x + c * x*x + d * x*x*x) ) / Math.Log( 2 ));
                return (float) Math.Pow( 2.0, (a + b * x + c * x*x + d * x*x*x) );
            } );

            panelLoad.Bitmap = m_imageFile.AsBitmap;
        }
Exemple #52
0
Fichier : Row.cs Projet : vebin/BD2
 public static Row Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             byte[] columnSet = BR.ReadBytes (32);
             int FieldCount = BR.ReadInt32 ();
             object[] fields = new object[FieldCount];
             ColumnSet cs = css [columnSet];
             if (cs.Columns.Length != fields.Length)
                 throw new Exception ();
             for (int n = 0; n != fields.Length; n++) {
                 bool Null = BR.ReadBoolean ();
                 if (Null) {
                     fields [n] = null;
                     continue;
                 }
                 switch (cs.Columns [n].TFQN) {
                 case "System.Byte[]":
                     fields [n] = BR.ReadBytes (BR.ReadInt32 ());
                     break;
                 case "System.Byte":
                     fields [n] = BR.ReadByte ();
                     break;
                 case "System.SByte":
                     fields [n] = BR.ReadSByte ();
                     break;
                 case "System.Int16":
                     fields [n] = BR.ReadInt16 ();
                     break;
                 case "System.UInt16":
                     fields [n] = BR.ReadUInt16 ();
                     break;
                 case "System.Int32":
                     fields [n] = BR.ReadInt32 ();
                     break;
                 case "System.UInt32":
                     fields [n] = BR.ReadUInt32 ();
                     break;
                 case "System.Int64":
                     fields [n] = BR.ReadInt64 ();
                     break;
                 case "System.UInt64":
                     fields [n] = BR.ReadUInt64 ();
                     break;
                 case "System.Single":
                     fields [n] = BR.ReadSingle ();
                     break;
                 case "System.Double":
                     fields [n] = BR.ReadDouble ();
                     break;
                 case "System.String":
                     fields [n] = BR.ReadString ();
                     break;
                 case "System.Char":
                     fields [n] = BR.ReadChar ();
                     break;
                 case "System.Boolean":
                     fields [n] = BR.ReadBoolean ();
                     break;
                 case "System.DateTime":
                     fields [n] = new DateTime (BR.ReadInt64 ());
                     break;
                 case "System.Guid":
                     fields [n] = new Guid (BR.ReadBytes (16));
                     break;
                 }
             }
             return new Row (cs, fields);
         }
     }
 }