/// <summary>
    /// Reads from the provided file name all parameters and data for a
    /// heightmap.  If the data for the heightmap does not exist, then
    /// no data is written to the provided texture.
    /// </summary>
    /// <param name='fileName'>
    /// The file name.  This can be relative or fully-qualified.
    /// </param>
    /// <param name='no'>
    /// The <see cref="NormalOptions" /> that will store read-in parameters.
    /// </param>
    /// <param name='co'>
    /// The <see cref="CloudOptions" /> that will store read-in parameters for
    /// <see cref="CloudFractal" />.
    /// </param>
    /// <param name='wo'>
    /// The <see cref="WorleyOptions" />  that will store read-in parameters for
    /// <see cref="WorleyNoise" />.
    /// </param>
    /// <param name='tex'>
    /// The <code>Texture2D</code> containing the heightmap data.
    /// </param>
    public static void Read(string fileName, ref NormalOptions no,
	                        ref CloudOptions co, ref VoronoiOptions vo,
							ref Texture2D tex)
    {
        using(BinaryReader r = new BinaryReader(File.OpenRead(fileName)))
        {
            no.size = r.ReadInt32();
            no.seed = r.ReadInt32();
            no.cloudInf = r.ReadSingle();
            no.voronoiInf = r.ReadSingle();
            no.useThermalErosion = r.ReadBoolean();
            no.useHydroErosion = r.ReadBoolean();
            no.showSeams = r.ReadBoolean();

            co.upperLeftStart = r.ReadSingle();
            co.lowerLeftStart = r.ReadSingle();
            co.lowerRightStart = r.ReadSingle();
            co.upperRightStart = r.ReadSingle();

            vo.metric = (DistanceFunctions.DistanceMetric)r.ReadInt32();
            vo.combiner = (CombinerFunctions.CombineFunction)r.ReadInt32();
            vo.numberOfFeaturePoints = r.ReadInt32();
            vo.numberOfSubregions = r.ReadInt32();
            vo.multiplier = r.ReadSingle();

            tex.Resize(no.size, no.size);
            int bLeft = (int)(r.BaseStream.Length - r.BaseStream.Position);
            if(bLeft > 0)
                tex.LoadImage(r.ReadBytes(bLeft));
        }
    }
Beispiel #2
1
	public static bool SendFileToPrinter( string szPrinterName, string szFileName )
	{
		// Open the file.
		FileStream fs = new FileStream(szFileName, FileMode.Open);
		// Create a BinaryReader on the file.
		BinaryReader br = new BinaryReader(fs);
		// Dim an array of bytes big enough to hold the file's contents.
		Byte []bytes = new Byte[fs.Length];
		bool bSuccess = false;
		// Your unmanaged pointer.
		IntPtr pUnmanagedBytes = new IntPtr(0);
		int nLength;

		nLength = Convert.ToInt32(fs.Length);
		// Read the contents of the file into the array.
		bytes = br.ReadBytes( nLength );
		// Allocate some unmanaged memory for those bytes.
		pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
		// Copy the managed byte array into the unmanaged array.
		Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
		// Send the unmanaged bytes to the printer.
		bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
		// Free the unmanaged memory that you allocated earlier.
		Marshal.FreeCoTaskMem(pUnmanagedBytes);
		return bSuccess;
	}
 public void HandleGyroSettings(BinaryReader reader)
 {
     Input.gyro.enabled = (reader.ReadInt32() != 0);
     float updateInterval = reader.ReadSingle();
     if (updateInterval != 0.0f && updateInterval != Input.gyro.updateInterval)
         Input.gyro.updateInterval = updateInterval;
 }
    public static ActionPayload Decode(byte[] payload)
    {
        MemoryStream stream = new MemoryStream(payload);
        BinaryReader reader = new BinaryReader(stream);

        byte op = reader.ReadByte ();

        ActionPayload action = new ActionPayload();

        switch (op) {

            case ActionPayload.OP_MOVEMENT:

                action.op = op;
                action.time = reader.ReadSingle ();

                action.position = new Vector3();
                action.position.x = reader.ReadSingle ();
                action.position.y = reader.ReadSingle ();
                action.position.z = reader.ReadSingle ();

                action.rot = reader.ReadSingle ();
                action.state = (int)reader.ReadSingle ();

            break;
        }

        return action;
    }
    protected void btnGuardarNotificacion_Click(object sender, EventArgs e)
    {
        String textoValidacion = validarNotificacion(false);
        if (textoValidacion.Equals(""))
        {
            Stream fs = upFileNotificacion.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            ARCHIVO archivo = new ARCHIVO();
            archivo = archivo.addArchivo(Path.GetFileName(upFileNotificacion.PostedFile.FileName),
                                         Path.GetExtension(upFileNotificacion.PostedFile.FileName).Substring(1), bytes);

            if (archivo.ARCHIVOID != 0)
            {
                NOTIFICACION notificacion = new NOTIFICACION();
                notificacion.addNotificacion(txtNombreNotificacion.Text, txtDescripcionNotificacion.Text, archivo.ARCHIVOID,
                                             Convert.ToInt32(lblInstitucionId.Text));
                cargarNotificaciones();
                lblSucess.Text = "Se creo Correctamente la Notificacion";
                pnlSucess.Visible = true;
            }
            else
            {
                lblError.Text = "El archivo es demasiado pesado";
                pnlError.Visible = true;
            }

        }
        else
        {
            lblError.Text = textoValidacion;
            pnlError.Visible = true;
        }
    }
    public static void Main() {
        byte[] bytes;

        var values = new long[] {
            0, 1, 0xFFFF, 0xFF00FF00FF00L, 12345678901234L, -0xFFFF, -0xFF00FF00FF00L
        };

        long length;

        using (var ms = new MemoryStream())
        using (var bw = new BinaryWriter(ms)) {
            foreach (var value in values) {
                bw.Write(value);
                Console.WriteLine(value);
            }

            bw.Flush();
            length = ms.Position;

            bytes = ms.GetBuffer();
        }

        Util.PrintByteArray(bytes, (int)length);

        using (var ms = new MemoryStream(bytes, false))
        using (var br = new BinaryReader(ms)) {
            for (int i = 0; i < values.Length; i++) {
                var value = br.ReadInt64();
                Console.WriteLine(value);
            }
        }
    }
Beispiel #7
0
    public void ReadBinary(BinaryReader reader)
    {
        maxHealth = reader.ReadInt32();
        maxMana = reader.ReadInt32();

        str = reader.ReadInt32();
        mag = reader.ReadInt32();
        dex = reader.ReadInt32();
        agi = reader.ReadInt32();
        def = reader.ReadInt32();

        weight = reader.ReadInt32();

        moveRange = reader.ReadInt32();
        moveSpeed = reader.ReadSingle();
        lobRange = reader.ReadInt32();

        string affStr = reader.ReadString();
        affinity = (AFFINITY) Enum.Parse(typeof(AFFINITY), affStr, true);

        soul = reader.ReadInt32();
        float cr = reader.ReadSingle();
        float cg = reader.ReadSingle();
        float cb = reader.ReadSingle();
        float ca = reader.ReadSingle();
        soulColor = new Color(cr, cg, cb, ca);
    }
	public override void LoadTable(string _path)
	{		
		if ((null != AssetbundleManager.Instance && true == AssetbundleManager.Instance.useAssetbundle) || true == AsTableManager.Instance.useReadBinary) 
		{
			// Ready Binary
			TextAsset textAsset = ResourceLoad.LoadTextAsset (_path);
			MemoryStream stream = new MemoryStream (textAsset.bytes);
			BinaryReader br = new BinaryReader (stream);

			int nCount = br.ReadInt32 ();

			for (int i = 0; i < nCount; i++) {
				Tbl_SynDisassemble_Record record = new Tbl_SynDisassemble_Record (br);
					m_recordList.Add (record);		
			}

			br.Close ();
			stream.Close ();				
		} 
		else 
		{
			XmlElement root = GetXmlRootElement(_path);
			XmlNodeList nodes = root.ChildNodes;
			
			foreach(XmlNode node in nodes)
			{
				Tbl_SynDisassemble_Record record = new Tbl_SynDisassemble_Record((XmlElement)node);			
				m_recordList.Add( record );
			}		
		}
	}		 
Beispiel #9
0
    //caller will use this to determine the right class and then
    //construct it himself
    public static Type GetBagType(string path)
    {
        BagType type;
        Type bagClass = null;
        FileStream idx;

        string idxPath = path.Replace(".bag",".idx");
        if (File.Exists(idxPath))
            idx = File.Open(idxPath, FileMode.OpenOrCreate);
        else
            idx = File.Open(path, FileMode.OpenOrCreate);

        BinaryReader rdr = new BinaryReader(idx);

        type = (BagType) rdr.ReadInt32();
        if (type == BagType.GABA)
            type = (BagType) rdr.ReadInt32();

        rdr.Close();

        //only support GABA2 and VIDEO for now
        switch (type)
        {
                //HACK: these can break if namespace or class names change, FIXME
            case BagType.VIDEO:
                bagClass = Type.GetType("NoxBagTool.VideoBag");
                break;
            case BagType.GABA2:
                bagClass = Type.GetType("NoxBagTool.Gaba2Bag");
                break;
        }

        return bagClass;
    }
    public static Recording Read1(BinaryReader reader)
    {
        // Create a recording
        Recording rec = new Recording();

        // Read the flagged value
        rec.flagged = reader.ReadBoolean();

        // Read the fps
        rec.fps = reader.ReadInt32();

        // Read the score.
        rec.score.Read(reader);

        // Read the level name
        rec.levelName = reader.ReadString();

        // Read all the states.
        int stateCount = reader.ReadInt32();
        for (int i = 0; i < stateCount; ++i)
        {
            State state = new State();
            state.Read(reader);
            rec.states.Add(state);
        }

        return rec;
    }
    public static NetworkResponse Parse(MemoryStream dataStream)
    {
        ResponseConvergePriorAttempt response = new ResponseConvergePriorAttempt();

        using (BinaryReader br = new BinaryReader(dataStream, Encoding.UTF8)) {
            int playerId = br.ReadInt32 ();
            int ecosystemId = br.ReadInt32 ();
            int attemptId = br.ReadInt32 ();
            bool allowHints = br.ReadBoolean ();
            int hintId = br.ReadInt32 ();
            short fldSize = br.ReadInt16 ();
            String config = System.Text.Encoding.UTF8.GetString (br.ReadBytes (fldSize));
            fldSize = br.ReadInt16 ();
            String csv = System.Text.Encoding.UTF8.GetString (br.ReadBytes (fldSize));

            ConvergeAttempt attempt = new ConvergeAttempt (playerId,
                                                           ecosystemId,
                                                           attemptId,
                                                           allowHints,
                                                           hintId,
                                                           config,
                                                           csv
                                                           //null
                                                           );

            response.attempt = attempt;
        }

        return response;
    }
Beispiel #12
0
    public override void ApplyChanges(Stream stream)
    {
        using (var reader = new BinaryReader(stream))
        {
            var stamp = reader.ReadInt64();
            var x = reader.ReadSingle();
            var y = reader.ReadSingle();
            var z = reader.ReadSingle();

            var vx = reader.ReadSingle();
            var vy = reader.ReadSingle();
            var vz = reader.ReadSingle();

            var rx = reader.ReadSingle();
            var ry = reader.ReadSingle();
            var rz = reader.ReadSingle();
            var rw = reader.ReadSingle();

            if (LastChanged < stamp)
            {
                LastChanged = stamp;
                Stormancer.MainThread.Post(() =>
                {
                    this.transform.position = new Vector3(x, y, z);
                    PlayerRigidbody.velocity = new Vector3(vx, vy, vz);
                    this.transform.rotation = new Quaternion(rx, ry, rz, rw);
                });
            }
        }
    }
	private static void SkipExeSection(FileStream fs, BinaryReader br)
	{
		//skips over the exe section of an exe
		//skip dos stub
		fs.Seek(60, SeekOrigin.Begin);
		int e_lfanew = br.ReadInt32();
		//MessageBox.Show(e_lfanew.ToString());
		fs.Seek(e_lfanew + 4, SeekOrigin.Begin);
		//IMAGE_FILE_HEADER
		fs.Seek(2, SeekOrigin.Current);
		int NumberOfSections = br.ReadInt16();
		fs.Seek(16, SeekOrigin.Current);
		//end of IMAGE_FILE_HEADER
		//IMAGE_OPTIONAL_HEADER
		fs.Seek(224, SeekOrigin.Current);
		//end of IMAGE_OPTIONAL_HEADER
		//section directories
		int Size = 0; // size of section
		int Pos = 0;  // position of section
		for (int i=0; i<NumberOfSections; i++)
		{
			fs.Seek(16, SeekOrigin.Current);
			Size = br.ReadInt32();
			Pos = br.ReadInt32();
			fs.Seek(16, SeekOrigin.Current);
		}
		//end of section directories
		fs.Seek(Pos+Size, SeekOrigin.Begin);
	}
Beispiel #14
0
 static void Main(string[] args)
 {
     InitComplements();
       var seq = new List<byte[]>();
       var b = new Block { Count = -1 };
       Index line = Index.None, start = Index.None, end = Index.None;
       using (var r = new BinaryReader(Console.OpenStandardInput())) {
      using (var w = Console.OpenStandardOutput()) {
         while (b.Read(r) > 0) {
            seq.Add(b.Data);
            if (line.Pos < 0) line = b.IndexOf(Gt, 0);
            while (line.Pos >= 0) {
               if (start.Pos < 0) {
                  var off = line.InBlock(b) ? line.Pos : 0;
                  start = b.IndexOf(Lf, off);
                  if (start.Pos < 0) {
                      w.Write(b.Data, off, b.Data.Length - off);
                      seq.Clear(); break;
                  }
                  w.Write(b.Data, off, start.Pos + 1 - off);
               }
               if (end.Pos < 0) {
                  end = b.IndexOf(Gt, start.InBlock(b) ? start.Pos : 0);
                  if (end.Pos < 0) break;
               }
               w.Reverse(start.Pos, end.Pos, seq);
               if (seq.Count > 1) seq.RemoveRange(0, seq.Count - 1);
               line = end; end = Index.None; start = Index.None;
            }
         }
         if (start.Pos >= 0 && end.Pos < 0)
            w.Reverse(start.Pos, seq[seq.Count -1].Length, seq);
      }
       }
 }
Beispiel #15
0
    public static Save Read(string filename)
    {
        #if UNITY_WEBPLAYER
        string savefile = PlayerPrefs.GetString("savefile", "");

        if (savefile == "")
            return null;

        byte[] binary = System.Convert.FromBase64String(savefile);
        MemoryStream ms = new MemoryStream(binary);
        BinaryReader reader = new BinaryReader(ms);
        #else
        string fullfilename = Application.persistentDataPath + dir + "/" + filename;

        if (!File.Exists(fullfilename))
            return null;

        // Open the file.
        FileStream file = new FileStream(fullfilename, FileMode.Open, FileAccess.Read);
        BinaryReader reader = new BinaryReader(file);
        #endif

        // Read the version number
        int version = reader.ReadInt32();

        // Use the function that corresponds
        Save read;
        switch (version)
        {
        case 1:
            read = Read1(reader);
            break;
        case 2:
            read = Read2(reader);
            break;
        case 3:
            read = Read3(reader);
            break;
        case 4:
            read = Read4(reader);
            break;
        case 5:
            read = Read5(reader);
            break;
        default:
            throw new NotImplementedException();
        }
        read.filename = filename;

        // Close the file
        reader.Close();

        #if UNITY_WEBPLAYER
        ms.Close();
        #else
        file.Close();
        #endif

        return read;
    }
Beispiel #16
0
    public static System.Text.Encoding GetType( FileStream fs )
    {
        byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
        byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
        byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //with BOM

        Encoding reVal;
        byte[] ss;
        int i;

        using (BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default)) {
            int.TryParse(fs.Length.ToString(), out i);
            ss = r.ReadBytes(i);

            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)) {
                reVal = Encoding.UTF8;
            } else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00) {
                reVal = Encoding.BigEndianUnicode;
            } else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41) {
                reVal = Encoding.Unicode;
            } else {
                reVal = Encoding.Default;
            }

            r.Close();
        }

        return reVal;
    }
Beispiel #17
0
    public static Texture3D LoadVolumeFromFile(string fileName, TextureFormat format, int elementSize ,int width, int height, int depth)
    {
        BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read));
        Texture3D noiseTex = new Texture3D(width, height, depth, TextureFormat.RGBA32, false);
        noiseTex.filterMode = FilterMode.Bilinear;
        noiseTex.wrapMode = TextureWrapMode.Repeat;

        int numElements = width * height * depth;
        List<Color> colors = new List<Color>(numElements);


        // Get pixels from 2d texture for each slize in z direction
        for (int z = 0; z < depth; z++)
        {
            Texture2D tex2d = LoadTexture2DRaw(br, width, height, format, elementSize);
            colors.AddRange(tex2d.GetPixels());
        }
        //colors should now be filled with all pixels
        noiseTex.SetPixels(colors.ToArray());
        noiseTex.Apply(false);

        br.Close();
        return noiseTex;
   
    }
Beispiel #18
0
    public static ZipDirHeader[] GetFiles(BinaryReader br, Func<ZipDirHeader, bool> f)
    {
        var list = new List<ZipDirHeader>();

        var fs = br.BaseStream;
        if (fs.Length < 22)
            throw new Exception("ファイルが小さ過ぎます。");

        fs.Position = fs.Length - 22;
        if (br.ReadInt32() != 0x06054b50)
            throw new Exception("ヘッダが見付かりません。");

        fs.Position += 6;
        int count = br.ReadUInt16();
        var dir_len = br.ReadUInt32();
        var dir_start = br.ReadUInt32();

        fs.Position = dir_start;
        for (int i = 0; i < count; i++)
        {
            if (br.ReadInt32() != 0x02014b50)
                throw new Exception("ファイルが壊れています。");
            var zipdh = new ZipDirHeader(br);
            if (f(zipdh)) list.Add(zipdh);
        }

        return list.ToArray();
    }
Beispiel #19
0
 public static int LoadTheScore()
 {
     #if UNITY_STANDALONE || UNITY_EDITOR
     string fullpath = Path.Combine(Application.dataPath, HighScoreFilename);
     #elif UNITY_IPHONE
     string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
     path = path.Substring(0, path.LastIndexOf('/'));
     string fullpath = path + "/Documents/"+HighScoreFilename;
     #elif UNITY_ANDROID
     string fullpath = Path.Combine(Application.persistentDataPath , HighScoreFilename);
     #endif
     using (FileStream fs = new FileStream(fullpath, FileMode.OpenOrCreate, FileAccess.Read))
     {
         using (BinaryReader br = new BinaryReader(fs))
         {
             try
             {
                 highscore = br.ReadInt32();
                 //Debug.Log("Highscore " + highscore);
             }
             catch(EndOfStreamException e)
             {
                     Debug.Log("{0} caught and ignored. " + "Using default values."+ e.Message+" "+e.StackTrace);
             }
             finally
             {
                 br.Close();
             }
         }
         fs.Dispose();
     }
     return (highscore);
 }
	public static GroupIconResource FromIco(string FileName)
	{
		using(FileStream Stream = new FileStream(FileName, FileMode.Open, FileAccess.Read))
		{
			BinaryReader Reader = new BinaryReader(Stream);

			Reader.ReadUInt16(); // Reserved
			Reader.ReadUInt16(); // Type
			ushort Count = Reader.ReadUInt16();

			IconResource[] Icons = new IconResource[Count];
			uint[] Offsets = new uint[Count];

			for(int Idx = 0; Idx < Count; Idx++)
			{
				Icons[Idx] = ReadIconHeader(Reader);
				Offsets[Idx] = Reader.ReadUInt32();
			}

			for(int Idx = 0; Idx < Icons.Length; Idx++)
			{
				Stream.Seek(Offsets[Idx], SeekOrigin.Begin);
				Stream.Read(Icons[Idx].Data, 0, Icons[Idx].Data.Length);
			}

			return new GroupIconResource(Icons);
		}
	}
    protected void Button1_Click(object sender, EventArgs e)
    {
        var sponsors = CodeCampSV.SponsorListManager.I.GetAllCurrentYear7();
         int good = 0;
            int bad = 0;
        foreach (var sponsor in sponsors)
        {
            string fileName = Context.Server.MapPath(sponsor.ImageURL);

            if (sponsor.SponsorName == "Intuit")
            {

            }

            try
            {
                Byte[] bytes;
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    var r = new BinaryReader(fs);
                    bytes = r.ReadBytes((int) fs.Length);
                }
                Utils.UpdateSponsorImage(sponsor.Id, bytes,fileName);
                good++;
            }
            catch (Exception)
            {

                bad++;
            }

        }

        Label1.Text = "good: " + good.ToString() + "  bad: " + bad.ToString();
    }
 public void Read(BinaryReader r)
 {
     //if (r == null) throw new ArgumentNullException("r");
     FResult     = new StringBuilder(r.ReadString());
     FSeparator  = r.ReadString();
     FEmpty      = r.ReadBoolean();
 }
	void AnimatedMeshCallback(string classname, BinaryReader br)
	{
		switch ( classname )
		{
			case "AnimMesh": LoadAnimMesh(br); break;
		}
	}
Beispiel #24
0
    public void makeBuilding(float interval,float tmpWidth,int regionWidth,float tmpDepth,float tmpHeight,float[] height)
    {
        int afterX,afterY,galo,selo,building_height;
        FileStream building_fs = new FileStream ("building_data_bin", FileMode.Open);
        BinaryReader reader = new BinaryReader (building_fs);

        int ncols_building = reader.ReadInt32();
        int nrows_building = reader.ReadInt32();

        //Debug.Log ("ncols_building :" + ncols_building);
        //Debug.Log ("nrows_building : " + nrows_building);

        while (reader.PeekChar () != -1) {

            afterX = reader.ReadInt32 ()/(int)interval;		//To adjust the resolution, divid with interval
            afterY = reader.ReadInt32 ()/(int)interval;
            galo = reader.ReadInt32 ();
            selo = reader.ReadInt32 ();

            building_height = reader.ReadInt32();

            /*Debug.Log ("afterX : " + afterX);
            Debug.Log ("afterY : " + afterY);
            Debug.Log ("galo : " + galo);
            Debug.Log ("selo : " + selo);
            Debug.Log ("height : " + building_height);*/

            GameObject building = GameObject.CreatePrimitive(PrimitiveType.Cube);
            building.transform.localScale = new Vector3(galo,selo,building_height);
            building.transform.position = new Vector3(afterX*interval - tmpWidth,((height [regionWidth * afterY + afterX] - tmpDepth)*5f)+(building.transform.localScale.y/2),(afterY* interval - tmpHeight));
            //building.AddComponent<BoxCollider>();
            //building.AddComponent<Rigidbody>().useGravity=false;
            building.AddComponent<clicked_building>();
        }
    }
Beispiel #25
0
    //上传用户导入XML
    protected void BtnPutin_Click(object sender, EventArgs e)
    {
        errMsg = "";
        int count = 0;
        string info = "";
        string flPath = FileUpload1.PostedFile.FileName.ToString();
        string treeID = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
        FileStream fs = new FileStream(flPath, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
        BinaryReader br = new BinaryReader(fs);

        byte[] imgBytesIn = br.ReadBytes((int)fs.Length);  //将流读入到字节数组中

        bool flag = bl.RetBoolUpFile(treeID, this.treeName.Value, imgBytesIn, out errMsg);

        if (errMsg == "")
        {
            if (flag == true)
            {
                info = "菜单文件导入成功!";
                count = 1;
            }
            else
            {
                info = "菜单文件导入失败!";
            }
        }
        else
            info = errMsg;
        Response.Redirect(webpath);
    }
Beispiel #26
0
    public static GameDataContainer LoadGameSave()
    {
        GameDataContainer data = new GameDataContainer ();

        // Ensure that the file exists, else returns
        if (!File.Exists ("Data/SaveGame.dat"))
            return data;

        using (BinaryReader br = new BinaryReader(File.OpenRead("Data/SaveGame.dat")))
        {
            br.ReadBytes(10); // Header

            int moneyBytes = br.ReadInt32(); // sizeof (money)
            data.Money = new BigInteger(Encoding.ASCII.GetString(br.ReadBytes(moneyBytes))); // money

            // Loop for product data
            for (int i = 0; i < (int)Products.Max; i++)
            {
                int level;
                level = br.ReadInt32();

                data.ProdList[i] = level;
            }

            int upgradeCount = br.ReadInt32();
            for (int i = 0; i < upgradeCount; i++) {
                int upId = br.ReadInt32();
                data.AcquiredUpgrades.Add(upId);
            }
        }

        return data;
    }
    //Generalized file loading function (basically a copy paste of the titan portion of the code)
    //Loads the file "bodyNameEphem_saturn.dat"
    public Boolean LoadFile(string bodyName, List<DateTime> times)
    {
        string filename = "Assets/Data/"+bodyName+"Ephem_saturn.dat";
        if(File.Exists(filename)) {
            List<Vector3> posList = new List<Vector3>();
            Debug.Log("Loading Titan ephemera");
            BinaryReader binReader = new BinaryReader(File.Open(filename, FileMode.Open));
            bool finished = false;

            while(! finished) {
                try{
                    double x = binReader.ReadDouble();
                    double z = binReader.ReadDouble();
                    double y = binReader.ReadDouble();
                    posList.Add(new Vector3((float) x, (float)y, (float)z));
                } catch (Exception e) {
                    finished = true;
                }
            }

            //Match up the positions and times
            SortedList<DateTime, EphemerisData> titanData = new SortedList<DateTime, EphemerisData>();
            for(int i = 0; i < posList.Count && i < times.Count; i++) {
                titanData.Add(times[i], new EphemerisData(posList[i], times[i]));
            }

            bodies[bodyName] = titanData;
            return true;
        } else return false;
    }
	static public MegaBezVector3KeyControl LoadBezVector3KeyControl(BinaryReader br)
	{
		con = new MegaBezVector3KeyControl();

		MegaParse.Parse(br, Parse);
		return con;
	}
Beispiel #29
0
 public static string ReadString(BinaryReader b)
 {
     int strLen = b.ReadInt32();
       char[] chars = b.ReadChars(strLen);
       string str = new string(chars);
       return str;
 }
Beispiel #30
0
        public static (MsbMetadata, IEnumerable <MaplePacket>) ReadMsbFile(string fileName)
        {
            var metadata = new MsbMetadata();
            List <MaplePacket> packets = new List <MaplePacket>();

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
                var    reader  = new BinaryReader(stream);
                ushort version = reader.ReadUInt16();
                if (version < 0x2000)
                {
                    metadata.Build     = version;
                    metadata.LocalPort = reader.ReadUInt16();
                    metadata.Locale    = MapleLocale.UNKNOWN;
                }
                else
                {
                    byte v1 = (byte)((version >> 12) & 0xF),
                         v2 = (byte)((version >> 8) & 0xF),
                         v3 = (byte)((version >> 4) & 0xF),
                         v4 = (byte)((version >> 0) & 0xF);
                    logger.Info($"Loading MSB file, saved by MapleShark V{v1}.{v2}.{v3}.{v4}");

                    if (version == 0x2012)
                    {
                        metadata.Locale    = (byte)reader.ReadUInt16();
                        metadata.Build     = reader.ReadUInt16();
                        metadata.LocalPort = reader.ReadUInt16();
                    }
                    else if (version == 0x2014)
                    {
                        metadata.LocalEndpoint  = reader.ReadString();
                        metadata.LocalPort      = reader.ReadUInt16();
                        metadata.RemoteEndpoint = reader.ReadString();
                        metadata.RemotePort     = reader.ReadUInt16();

                        metadata.Locale = (byte)reader.ReadUInt16();
                        metadata.Build  = reader.ReadUInt16();
                    }
                    else if (version == 0x2015 || version >= 0x2020)
                    {
                        metadata.LocalEndpoint  = reader.ReadString();
                        metadata.LocalPort      = reader.ReadUInt16();
                        metadata.RemoteEndpoint = reader.ReadString();
                        metadata.RemotePort     = reader.ReadUInt16();

                        metadata.Locale = reader.ReadByte();
                        metadata.Build  = reader.ReadUInt32();
                    }
                    else
                    {
                        string message = $"Invalid msb file, version: {v1}.{v2}.{v3}.{v4}";
                        MessageBox.Show(message, "MapleShark2", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return(metadata, new List <MaplePacket>());
                    }
                }


                while (stream.Position < stream.Length)
                {
                    long   timestamp = reader.ReadInt64();
                    int    size      = version < 0x2027 ? reader.ReadUInt16() : reader.ReadInt32();
                    ushort opcode    = reader.ReadUInt16();
                    bool   outbound;

                    if (version >= 0x2020)
                    {
                        outbound = reader.ReadBoolean();
                    }
                    else
                    {
                        outbound = (size & 0x8000) != 0;
                        size     = (ushort)(size & 0x7FFF);
                    }

                    byte[] buffer = reader.ReadBytes(size);
                    if (version >= 0x2025 && version < 0x2030)
                    {
                        reader.ReadUInt32(); // preDecodeIV
                        reader.ReadUInt32(); // postDecodeIV
                    }

                    var packet = new MaplePacket(new DateTime(timestamp), outbound, metadata.Build, opcode, new ArraySegment <byte>(buffer));
                    packets.Add(packet);
                }

                return(metadata, packets);
            }
        }
 public override void DeserializeBody(BinaryReader br)
 {
     Id = ObjectUtils.DeserializeVector <TLAbsInputUser>(br);
 }
Beispiel #32
0
        public static void DnaExperiment()
        {
            Util.NormalizationHandler = new Util.Normalize(Util.MeanZero_Normalization);
            // in-memory data, referenced by the index
            const string DATAFOLDER = @"K:\Datasets\DNA\Dna2Ts\Monkey_Binary";

            // load index
            Index <Meta2DataFormat> si = Index <Meta2DataFormat> .Load(Globals.IndexRootDir);

            // populate in-memory data
            DnaDataLoader.LoadDnaToMetaBuffer(DATAFOLDER);

            // generate queries
            DateTime queryStart = DateTime.Now;
            int      numQueries = 0;

            string[] humanChrs = Directory.GetFiles(@"K:\Datasets\DNA\Dna2Ts\Human_Binary", "*.dat");
            Array.Sort(humanChrs, new NaturalStringComparer());
            Dictionary <string, DnaChrResult> queryResult = new Dictionary <string, DnaChrResult>(humanChrs.Length);

            for (int chrNo = 0; chrNo < humanChrs.Length; ++chrNo)
            {
                string chrFile = humanChrs[chrNo];
                GC.Collect();
                using (BinaryReader br = new BinaryReader(new FileStream(chrFile, FileMode.Open, FileAccess.Read)))
                {
                    List <DnaSearchResult> qResults = new List <DnaSearchResult>();
                    // List<Meta2DataFormat> _queryApproxRes = new List<Meta2DataFormat>();
                    // List<double> _dists = new List<double>();
                    // List<int> _queryPos = new List<int>();

                    long fileLength = br.BaseStream.Length / sizeof(int);
                    int  posShift   = Globals.TimeSeriesLength / 4; // shift by quarters

                    double[] dnaChr = new double[(int)Math.Floor((fileLength / sizeof(int)) / (double)DnaDataLoader.SAMPLERATE)];
                    Console.WriteLine("F:{0} OrigLen:{1} newLen:{2} Shift:{3}", chrFile, fileLength, dnaChr.Length, posShift);

                    // downsample
                    int    count = 0;
                    double sum   = 0;
                    for (int i = 0; i < dnaChr.Length; ++i)
                    {
                        sum   = 0;
                        count = 0;
                        while (count < DnaDataLoader.SAMPLERATE)
                        {
                            sum += br.ReadInt32();
                            count++;
                        }
                        dnaChr[i] = sum / DnaDataLoader.SAMPLERATE;
                    }

                    double[] ts = new double[Globals.TimeSeriesLength];
                    for (int pos = 0; pos < dnaChr.Length - Globals.TimeSeriesLength; pos += posShift)
                    {
                        numQueries += 2;
                        Array.Copy(dnaChr, pos, ts, 0, Globals.TimeSeriesLength);
                        double mean = Util.Mean(ts, 0, ts.Length - 1);
                        for (int k = 0; k < ts.Length; ++k)
                        {
                            ts[k] = ts[k] - mean;
                        }

                        TermEntry tEntry = si.ApproximateSearch(ts);
                        List <Meta2DataFormat> termNodeEntries = si.ReturnDataFormatFromTermEntry(tEntry);

                        double          bsfDist = Double.MaxValue;
                        Meta2DataFormat bsfMeta = new Meta2DataFormat();
                        foreach (Meta2DataFormat m in termNodeEntries)
                        {
                            double dist = Util.EuclideanDistance(Util.NormalizationHandler(m.GetTimeSeries()), ts);
                            if (dist < bsfDist)
                            {
                                bsfDist = dist;
                                bsfMeta = m;
                            }
                        }

                        qResults.Add(new DnaSearchResult()
                        {
                            dist        = bsfDist,
                            matchingChr = bsfMeta._chrNo,
                            matchingPos = bsfMeta._pos,
                            queryChr    = chrNo,
                            queryPos    = pos,
                        });


                        // reverse
                        ts              = ts.Reverse().ToArray();
                        tEntry          = si.ApproximateSearch(ts);
                        termNodeEntries = si.ReturnDataFormatFromTermEntry(tEntry);
                        bsfDist         = Double.MaxValue;
                        bsfMeta         = new Meta2DataFormat();
                        foreach (Meta2DataFormat m in termNodeEntries)
                        {
                            double dist = Util.EuclideanDistance(Util.NormalizationHandler(m.GetTimeSeries()), ts);
                            if (dist < bsfDist)
                            {
                                bsfDist = dist;
                                bsfMeta = m;
                            }
                        }

                        qResults.Add(new DnaSearchResult()
                        {
                            dist        = bsfDist,
                            matchingChr = bsfMeta._chrNo,
                            matchingPos = bsfMeta._pos,
                            queryChr    = chrNo,
                            queryPos    = pos,
                        });
                    }
                    queryResult.Add(chrFile, new DnaChrResult()
                    {
                        results = qResults
                    });
                }
            }
            DateTime queryStop = DateTime.Now;

            Console.WriteLine("{0} Queries, {1} TimeElapsed.", numQueries, queryStop - queryStart);
            //// print results
            using (StreamWriter sw = new StreamWriter(Path.Combine(Globals.IndexRootDir, "queryOutput.txt")))
            {
                foreach (KeyValuePair <string, DnaChrResult> kvp in queryResult)
                {
                    //    Console.WriteLine("HumanChromosome:{0}", kvp.Key);
                    //    Console.WriteLine("AverageDistance:{0}", kvp.Value.AverageDistance);
                    //    Console.WriteLine();
                    foreach (DnaSearchResult sr in kvp.Value.results)
                    {
                        sw.WriteLine(sr.ToString());
                    }
                }
            }

            //using (StreamWriter sw = new StreamWriter(Path.Combine(Globals.IndexRootDir, "queryOutputTop.txt")))
            //{
            //    foreach (KeyValuePair<string, DnaChrResult> kvp in queryResult)
            //    {
            //        //    Console.WriteLine("HumanChromosome:{0}", kvp.Key);
            //        //    Console.WriteLine("AverageDistance:{0}", kvp.Value.AverageDistance);
            //        //    Console.WriteLine();
            //        List<DnaSearchResult>sr  = kvp.Value.results;
            //        sr.Sort();
            //        sr = sr.GetRange(0, 10);

            //        Console.WriteLine("For Human Chr:{0}", kvp.Key);
            //        var counts = from q in sr
            //                     group q by q.matchingChr into g
            //                     select new { Chr = g.Key, NumHits = g.Count() };
            //        foreach (var v in counts)
            //            Console.WriteLine("{0} : {1}", v.Chr, v.NumHits);

            //    }
            //    //    //{
            //    //    //    for (int i = 0; i < kvp.Value.queryTs.Count; ++i)
            //    //    //    {
            //    //    //        sw.WriteLine(Util.ArrayToString(kvp.Value.queryTs[i]));
            //    //    //        sw.WriteLine(Util.ArrayToString(Util.NormalizationHandler(kvp.Value.queryApproxRes[i].GetTimeSeries())));
            //    //    //    }
            //    //    //    //foreach (double[] d in kvp.Value.queryTs)
            //    //    //    //    sw.WriteLine(Util.ArrayToString(d));
            //}
        }
 public override void Read(BinaryReader file, uint size) => base.Read(file, size);
Beispiel #34
0
    public ItemInfo(BinaryReader reader, int version = int.MaxValue, int Customversion = int.MaxValue)
    {
        Index          = reader.ReadInt32();
        Name           = reader.ReadString();
        Type           = (ItemType)reader.ReadByte();
        Grade          = (ItemGrade)reader.ReadByte();
        RequiredType   = (RequiredType)reader.ReadByte();
        RequiredClass  = (RequiredClass)reader.ReadByte();
        RequiredGender = (RequiredGender)reader.ReadByte();
        Set            = (ItemSet)reader.ReadByte();

        Shape          = reader.ReadInt16();
        Weight         = reader.ReadByte();
        Light          = reader.ReadByte();
        RequiredAmount = reader.ReadByte();

        Image      = reader.ReadUInt16();
        Durability = reader.ReadUInt16();

        StackSize = reader.ReadUInt32();
        Price     = reader.ReadUInt32();

        MinAC    = reader.ReadByte();
        MaxAC    = reader.ReadByte();
        MinMAC   = reader.ReadByte();
        MaxMAC   = reader.ReadByte();
        MinDC    = reader.ReadByte();
        MaxDC    = reader.ReadByte();
        MinMC    = reader.ReadByte();
        MaxMC    = reader.ReadByte();
        MinSC    = reader.ReadByte();
        MaxSC    = reader.ReadByte();
        HP       = reader.ReadUInt16();
        MP       = reader.ReadUInt16();
        Accuracy = reader.ReadByte();
        Agility  = reader.ReadByte();

        Luck        = reader.ReadSByte();
        AttackSpeed = reader.ReadSByte();

        StartItem = reader.ReadBoolean();

        BagWeight  = reader.ReadByte();
        HandWeight = reader.ReadByte();
        WearWeight = reader.ReadByte();

        Effect         = reader.ReadByte();
        Strong         = reader.ReadByte();
        MagicResist    = reader.ReadByte();
        PoisonResist   = reader.ReadByte();
        HealthRecovery = reader.ReadByte();
        SpellRecovery  = reader.ReadByte();
        PoisonRecovery = reader.ReadByte();
        HPrate         = reader.ReadByte();
        MPrate         = reader.ReadByte();
        CriticalRate   = reader.ReadByte();
        CriticalDamage = reader.ReadByte();
        byte bools = reader.ReadByte();

        NeedIdentify    = (bools & 0x01) == 0x01;
        ShowGroupPickup = (bools & 0x02) == 0x02;
        ClassBased      = (bools & 0x04) == 0x04;
        LevelBased      = (bools & 0x08) == 0x08;
        CanMine         = (bools & 0x10) == 0x10;

        if (version >= 77)
        {
            GlobalDropNotify = (bools & 0x20) == 0x20;
        }

        MaxAcRate     = reader.ReadByte();
        MaxMacRate    = reader.ReadByte();
        Holy          = reader.ReadByte();
        Freezing      = reader.ReadByte();
        PoisonAttack  = reader.ReadByte();
        Bind          = (BindMode)reader.ReadInt16();
        Reflect       = reader.ReadByte();
        HpDrainRate   = reader.ReadByte();
        Unique        = (SpecialItemMode)reader.ReadInt16();
        RandomStatsId = reader.ReadByte();

        CanFastRun = reader.ReadBoolean();

        CanAwakening = reader.ReadBoolean();
        bool isTooltip = reader.ReadBoolean();

        if (isTooltip)
        {
            ToolTip = reader.ReadString();
        }

        if (version < 70) //before db version 70 all specialitems had wedding rings disabled, after that it became a server option
        {
            if ((Type == ItemType.Ring) && (Unique != SpecialItemMode.None))
            {
                Bind |= BindMode.NoWeddingRing;
            }
        }
    }
Beispiel #35
0
    public UserItem(BinaryReader reader, int version = int.MaxValue, int Customversion = int.MaxValue)
    {
        UniqueID  = reader.ReadUInt64();
        ItemIndex = reader.ReadInt32();

        CurrentDura = reader.ReadUInt16();
        MaxDura     = reader.ReadUInt16();

        Count = reader.ReadUInt32();

        AC  = reader.ReadByte();
        MAC = reader.ReadByte();
        DC  = reader.ReadByte();
        MC  = reader.ReadByte();
        SC  = reader.ReadByte();

        Accuracy = reader.ReadByte();
        Agility  = reader.ReadByte();
        HP       = reader.ReadByte();
        MP       = reader.ReadByte();

        AttackSpeed = reader.ReadSByte();
        Luck        = reader.ReadSByte();

        SoulBoundId = reader.ReadInt32();
        byte Bools = reader.ReadByte();

        Identified     = (Bools & 0x01) == 0x01;
        Cursed         = (Bools & 0x02) == 0x02;
        Strong         = reader.ReadByte();
        MagicResist    = reader.ReadByte();
        PoisonResist   = reader.ReadByte();
        HealthRecovery = reader.ReadByte();
        ManaRecovery   = reader.ReadByte();
        PoisonRecovery = reader.ReadByte();
        CriticalRate   = reader.ReadByte();
        CriticalDamage = reader.ReadByte();
        Freezing       = reader.ReadByte();
        PoisonAttack   = reader.ReadByte();


        int count = reader.ReadInt32();

        for (int i = 0; i < count; i++)
        {
            if (reader.ReadBoolean())
            {
                continue;
            }
            UserItem item = new UserItem(reader, version, Customversion);
            Slots[i] = item;
        }

        GemCount = reader.ReadUInt32();

        Awake = new Awake(reader);

        RefinedValue = (RefinedValue)reader.ReadByte();
        RefineAdded  = reader.ReadByte();
        WeddingRing  = reader.ReadInt32();

        if (version < 65)
        {
            return;
        }

        if (reader.ReadBoolean())
        {
            ExpireInfo = new ExpireInfo(reader, version, Customversion);
        }

        if (version < 76)
        {
            return;
        }

        if (reader.ReadBoolean())
        {
            RentalInformation = new RentalInformation(reader, version, Customversion);
        }
    }
Beispiel #36
0
 public ChatItem(BinaryReader reader)
 {
     UniqueID = reader.ReadUInt64();
     Title    = reader.ReadString();
     Grid     = (MirGridType)reader.ReadByte();
 }
Beispiel #37
0
 public ExpireInfo(BinaryReader reader, int version = int.MaxValue, int Customversion = int.MaxValue)
 {
     ExpiryDate = DateTime.FromBinary(reader.ReadInt64());
 }
Beispiel #38
0
        /// <summary>
        /// Function returns when object is downloaded or download fails
        /// </summary>
        /// <returns></returns>
        protected static object retriveURL(string url)
        {
            WebRequest  req = WebRequest.Create(url);
            WebResponse res = null;

            object data = null;

            bool   downloadPossible = false;
            bool   isText           = false;
            string statusDescription;     // HTTP status description, or exception message

            try
            {
                // Issue a response against the request.
                // will fail for many reasons
                res = req.GetResponse();
                //res.Headers.

                if (res is HttpWebResponse)
                {
                    HttpStatusCode statusCode = ((HttpWebResponse)res).StatusCode;
                    if (statusCode == HttpStatusCode.OK)
                    {
                        downloadPossible = true;
                        //use the http content type metadata to determine of the object is text
                        string contentType = ((HttpWebResponse)res).ContentType;

                        if (contentType == null)
                        {
                            isText = doesURLHintText(res.ResponseUri.AbsoluteUri);
                        }
                        else if (contentType.Trim() == "")
                        {
                            isText = doesURLHintText(res.ResponseUri.AbsoluteUri);
                        }
                        if (contentType.Trim().StartsWith("text"))
                        {
                            isText = true;
                        }
                    }
                    else
                    {
                        WDAppLog.logError(ErrorLevel.Error,
                                          String.Format("Could not retive url {0}", url),
                                          statusCode.ToString());
                    }
                    statusDescription = ((HttpWebResponse)res).StatusDescription;
                }

                if (res is FileWebResponse)
                {
                    //anything > 64mb has to be written to file
                    if (((FileWebResponse)res).ContentLength > (64 * 1024 * 1024))
                    {
                    }
                    else
                    {
                        downloadPossible = true;
                        isText           = doesURLHintText(res.ResponseUri.AbsoluteUri);
                    }
                }

                if (downloadPossible)
                {
                    // Read the contents into our state
                    // object and fire the content handlers
                    if (isText)
                    {
                        //download text
                        StreamReader sr = null;
                        try
                        {
                            sr   = new StreamReader(res.GetResponseStream());
                            data = sr.ReadToEnd();
                        }
                        catch
                        {
                            data = null;
                        }
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                    else
                    {
                        //download file
                        Stream sr = null;
                        try
                        {
                            sr = res.GetResponseStream();
                            try
                            {
                                //try sr.Length for accelerated download
                                byte[] rawData = new byte[sr.Length];
                                sr.Read(rawData, 0, rawData.Length);
                                data = rawData;
                            }
                            catch
                            {
                                //try sr.Length was not available?

                                BinaryReader bs         = new BinaryReader(sr);
                                int          bufferSize = 1024 * 1024 * 5;
                                byte[]       rawData    = new byte[bufferSize];
                                ArrayList    al         = new ArrayList();
                                try{
                                    while (rawData.Length == bufferSize)
                                    {
                                        rawData = bs.ReadBytes(bufferSize);
                                        al.AddRange(rawData);
                                    }

                                    data = new byte[al.Count];
                                    al.CopyTo((byte[])data);
                                    //data = rawData;
                                }
                                catch (Exception ex2)
                                {
                                    data = null;
                                    WDAppLog.logError(ErrorLevel.Error, "Could not load downloaded object", ex2.Message);
                                }
                            }
                        }
                        catch
                        {
                            data = null;
                        }
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return(data);
        }
Beispiel #39
0
        /// <summary>
        /// Reads the ARZ file.
        /// </summary>
        /// <returns>true on success</returns>
        public bool Read()
        {
            StreamWriter outStream = null;

            if (TQDebug.DatabaseDebugLevel > 2)
            {
                outStream = new StreamWriter("arzOut.txt", false);
            }

            try
            {
                // ARZ header file format
                //
                // 0x000000 int32
                // 0x000004 int32 start of dbRecord table
                // 0x000008 int32 size in bytes of dbRecord table
                // 0x00000c int32 numEntries in dbRecord table
                // 0x000010 int32 start of string table
                // 0x000014 int32 size in bytes of string table
                FileStream   instream = new FileStream(this.fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader reader   = new BinaryReader(instream);
                try
                {
                    int[] header = new int[6];

                    for (int i = 0; i < 6; ++i)
                    {
                        header[i] = reader.ReadInt32();
                        if (outStream != null)
                        {
                            outStream.WriteLine("Header[{0}] = {1:n0} (0x{1:X})", i, header[i]);
                        }
                    }

                    int firstTableStart  = header[1];
                    int firstTableCount  = header[3];
                    int secondTableStart = header[4];

                    this.ReadStringTable(secondTableStart, reader, outStream);
                    this.ReadRecordTable(firstTableStart, firstTableCount, reader, outStream);

                    // 4 final int32's from file
                    // first int32 is numstrings in the stringtable
                    // second int32 is something ;)
                    // 3rd and 4th are crap (timestamps maybe?)
                    for (int i = 0; i < 4; ++i)
                    {
                        int val = reader.ReadInt32();
                        if (outStream != null)
                        {
                            outStream.WriteLine("{0:n0} 0x{0:X}", val);
                        }
                    }
                }
                catch (IOException)
                {
                    throw;
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (IOException exception)
            {
                if (!TQDebug.DebugEnabled)
                {
                    TQDebug.DebugEnabled = true;
                }

                // Write the exception to the debug log.
                TQDebug.DebugWriteLine(exception.ToString());
                return(false);
            }
            finally
            {
                if (outStream != null)
                {
                    outStream.Close();
                }
            }

            return(true);
        }
Beispiel #40
0
        public bool LoadMapTile(uint tileX, uint tileY, VMapManager vm)
        {
            if (iTreeValues == null)
            {
                Log.outError(LogFilter.Server, "StaticMapTree.LoadMapTile() : tree has not been initialized [{0}, {1}]", tileX, tileY);
                return(false);
            }
            bool result = true;

            FileStream stream = OpenMapTileFile(VMapManager.VMapPath, iMapID, tileX, tileY, vm);

            if (stream == null)
            {
                iLoadedTiles[PackTileID(tileX, tileY)] = false;
            }
            else
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
                    {
                        return(false);
                    }

                    uint numSpawns = reader.ReadUInt32();

                    for (uint i = 0; i < numSpawns && result; ++i)
                    {
                        // read model spawns
                        ModelSpawn spawn;
                        result = ModelSpawn.ReadFromFile(reader, out spawn);
                        if (result)
                        {
                            // acquire model instance
                            WorldModel model = vm.AcquireModelInstance(spawn.name, spawn.flags);
                            if (model == null)
                            {
                                Log.outError(LogFilter.Server, "StaticMapTree.LoadMapTile() : could not acquire WorldModel [{0}, {1}]", tileX, tileY);
                            }

                            // update tree
                            if (iSpawnIndices.ContainsKey(spawn.Id))
                            {
                                uint referencedVal = iSpawnIndices[spawn.Id];
                                if (!iLoadedSpawns.ContainsKey(referencedVal))
                                {
                                    if (referencedVal >= iNTreeValues)
                                    {
                                        Log.outError(LogFilter.Maps, "StaticMapTree.LoadMapTile() : invalid tree element ({0}/{1}) referenced in tile {2}", referencedVal, iNTreeValues, stream.Name);
                                        continue;
                                    }

                                    iTreeValues[referencedVal]   = new ModelInstance(spawn, model);
                                    iLoadedSpawns[referencedVal] = 1;
                                }
                                else
                                {
                                    ++iLoadedSpawns[referencedVal];
                                }
                            }
                            else
                            {
                                result = false;
                            }
                        }
                    }
                }
                iLoadedTiles[PackTileID(tileX, tileY)] = true;
            }
            return(result);
        }
        public VniAnimation(BinaryReader reader, int fileVersion) : base(reader.BaseStream.Position)
        {
            // animations name
            var nameLength = reader.ReadInt16BE();

            Name = nameLength > 0 ? Encoding.UTF8.GetString(reader.ReadBytes(nameLength)) : "<undefined>";

            // other data
            Cycles       = reader.ReadInt16BE();
            Hold         = reader.ReadInt16BE();
            ClockFrom    = reader.ReadInt16BE();
            ClockSmall   = reader.ReadByte() != 0;
            ClockInFront = reader.ReadByte() != 0;
            ClockOffsetX = reader.ReadInt16BE();
            ClockOffsetY = reader.ReadInt16BE();
            RefreshDelay = reader.ReadInt16BE();
            Type         = reader.ReadByte();
            Fsk          = reader.ReadByte();

            int numFrames = reader.ReadInt16BE();

            if (numFrames < 0)
            {
                numFrames += 65536;
            }

            if (fileVersion >= 2)
            {
                ReadPalettesAndColors(reader);
            }
            if (fileVersion >= 3)
            {
                EditMode = (AnimationEditMode)reader.ReadByte();
            }
            if (fileVersion >= 4)
            {
                Width  = reader.ReadInt16BE();
                Height = reader.ReadInt16BE();
            }
            if (fileVersion >= 5)
            {
                int numMasks = reader.ReadInt16BE();
                Masks = new byte[numMasks][];
                for (var i = 0; i < numMasks; i++)
                {
                    int locked = reader.ReadByte();
                    int size   = reader.ReadInt16BE();
                    Masks[i] = reader.ReadBytesRequired(size).Select(VniAnimationPlane.Reverse).ToArray();
                }
            }

            if (fileVersion >= 6)
            {
                int    LinkedAnimation = reader.ReadByte();
                int    size            = reader.ReadInt16BE();
                string AnimName        = size > 0 ? Encoding.UTF8.GetString(reader.ReadBytes(nameLength)) : "<undefined>";
                uint   startFrame      = reader.ReadUInt32BE();
            }

            Logger.Debug("VNI[{3}] Reading {0} frame{1} for animation \"{2}\"...", numFrames, numFrames == 1 ? "" : "s", Name, reader.BaseStream.Position);
            Frames            = new AnimationFrame[numFrames];
            AnimationDuration = 0;
            for (var i = 0; i < numFrames; i++)
            {
                Frames[i] = new VniAnimationFrame(reader, fileVersion, AnimationDuration);
                if (Frames[i].Mask != null && TransitionFrom == 0)
                {
                    TransitionFrom = i;
                }
                AnimationDuration += Frames[i].Delay;
            }
        }
Beispiel #42
0
            void ReadEscapeSequence(ref BinaryReader br)
            {
                var sb = new StringBuilder();

                char curChar = (char)br.ReadByte();

                while (!char.IsLetter(curChar))
                {
                    sb.Append(curChar);
                    curChar = (char)br.ReadByte();
                }

                string[] args = (sb.Length > 0) ? sb.ToString().Split(';') : new string[0];
                int      i;

                switch (curChar)
                {
                case 'A':                          // move cursor up
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.Y -= i;
                    if (ptCur.Y < rClip.Top)
                    {
                        ptCur.Y = rClip.Top;
                    }
                    break;

                case 'B':                          // move cursor down
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.Y += i;
                    if (ptCur.Y > rClip.InnerBottom)
                    {
                        ptCur.Y = rClip.InnerBottom;
                    }
                    break;

                case 'C':                          // move cursor right
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.X += i;
                    if (ptCur.X > rClip.InnerRight)
                    {
                        ptCur.X = rClip.InnerRight;
                    }
                    break;

                case 'D':                          // move cursor left
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.X -= i;
                    if (ptCur.X < rClip.Left)
                    {
                        ptCur.X = rClip.Left;
                    }
                    break;

                case 'E':
                    ptCur.X = rClip.Left;
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.Y += i;
                    while (ptCur.Y > rClip.InnerBottom)
                    {
                        if (AnimateView)
                        {
                            canvas.ShiftUp();
                            ptCur.Y--;
                        }
                        else
                        {
                            throw new CanvasOverflowException();
                        }
                    }
                    break;

                case 'F':
                    ptCur.X = rClip.Left;
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.Y -= i;
                    if (ptCur.Y < rClip.Top)
                    {
                        ptCur.Y = rClip.Top;
                    }
                    break;

                case 'G':
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }
                    ptCur.X = rClip.Left + i - 1;
                    if (ptCur.X < rClip.Left)
                    {
                        ptCur.X = rClip.Left;
                    }
                    if (ptCur.X > rClip.InnerRight)
                    {
                        ptCur.X = rClip.InnerRight;
                    }
                    break;

                case 'H':
                case 'f':
                    if (args.Length > 0 && args[0] != string.Empty)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i > 0)
                            {
                                ptCur.Y = i - 1 + rClip.Top;
                            }
                            else
                            {
                                ptCur.Y = rClip.Top;
                            }
                        }
                    }
                    else
                    {
                        ptCur.Y = rClip.Top;
                    }

                    if (args.Length > 1 && args[1] != string.Empty)
                    {
                        if (ConvertToInt(args[1], out i))
                        {
                            if (i > 0)
                            {
                                ptCur.X = i - 1 + rClip.Left;
                            }
                            else
                            {
                                ptCur.X = rClip.Left;
                            }
                        }
                    }
                    else
                    {
                        ptCur.X = rClip.Left;
                    }

                    ptCur.Restrict(rClip);
                    break;

                case 'J':
                    if (args.Length > 0)
                    {
                        ConvertToInt(args[0], out i);
                    }
                    else
                    {
                        i = 0;
                    }

                    switch (i)
                    {
                    case 0:
                        canvas.Fill(new Rectangle(new Point(rClip.Left, ptCur.Y), rClip.InnerBottomRight), new CanvasElement(' ', 7));
                        break;

                    case 1:
                        canvas.Fill(new Rectangle(rClip.TopLeft, new Point(rClip.InnerRight, ptCur.Y)), new CanvasElement(' ', 7));
                        break;

                    case 2:
                        attribute = rgbAttribute = new Attribute(7, 0);
                        canvas.Fill(rClip, new CanvasElement(' ', attribute));
                        ptCur.X = rClip.Left;
                        ptCur.Y = rClip.Top;
                        break;
                    }
                    break;

                case 'K':
                    if (args.Length > 0)
                    {
                        ConvertToInt(args[0], out i);
                    }
                    else
                    {
                        i = 0;
                    }

                    switch (i)
                    {
                    case 0:
                        canvas.Fill(new Rectangle(ptCur, new Point(rClip.InnerRight, ptCur.Y)), new CanvasElement(' ', 7));
                        break;

                    case 1:
                        canvas.Fill(new Rectangle(ptCur, new Point(0, ptCur.Y)), new CanvasElement(' ', 7));
                        break;

                    case 2:
                        canvas.Fill(new Rectangle(new Point(0, ptCur.Y), new Point(rClip.InnerRight, ptCur.Y)), new CanvasElement(' ', 7));
                        break;
                    }
                    break;

                case 't':
                    if (args.Length == 4)
                    {
                        var r   = ConvertToInt(args[1]) ?? 0;
                        var g   = ConvertToInt(args[2]) ?? 0;
                        var b   = ConvertToInt(args[3]) ?? 0;
                        var col = palette.FindAddColour(Color.FromArgb(r, g, b));
                        switch (args[0])
                        {
                        case "0":
                            rgbAttribute.Background = col;
                            break;

                        case "1":
                            rgbAttribute.Foreground = col;
                            break;
                        }
                    }
                    break;

                case 'h':
                    foreach (string flag in args)
                    {
                        switch (flag.Trim())
                        {
                        case "?33":                                         // ice colour on
                            iceColours = true;
                            break;

                        case "?7":
                            ansiLineWrap = true;
                            break;
                        }
                    }
                    break;

                case 'l':
                    foreach (var flag in args)
                    {
                        switch (flag.Trim())
                        {
                        case "?33":                                         // ice colour off
                            iceColours = false;
                            break;

                        case "?7":
                            ansiLineWrap = false;
                            break;
                        }
                    }
                    break;

                case 'm':
                    if (args.Length == 0)
                    {
                        attribute = rgbAttribute = new Attribute(7, 0);
                    }
                    else
                    {
                        for (int count = 0; count < args.Length; count++)
                        {
                            int j;
                            if (ConvertToInt(args[count], out i))
                            {
                                switch (i)
                                {
                                case 0:
                                    attribute = rgbAttribute = new Attribute(7, 0);
                                    break;

                                case 1:
                                    attribute.Bold          = true;
                                    rgbAttribute.Foreground = attribute.Foreground;
                                    break;

                                case 2:
                                case 22:
                                    attribute.Bold          = false;
                                    rgbAttribute.Foreground = attribute.Foreground;
                                    break;

                                case 5:
                                    attribute.Blink         = true;
                                    rgbAttribute.Background = attribute.Background;
                                    break;

                                case 25:
                                    attribute.Blink         = false;
                                    rgbAttribute.Background = attribute.Background;
                                    break;

                                case 7:
                                case 27:
                                    j = attribute.ForegroundOnly;
                                    attribute.ForegroundOnly = attribute.BackgroundOnly;
                                    attribute.BackgroundOnly = j;
                                    j = rgbAttribute.ForegroundOnly;
                                    rgbAttribute.ForegroundOnly = rgbAttribute.BackgroundOnly;
                                    rgbAttribute.BackgroundOnly = j;
                                    break;

                                case 30:
                                case 31:
                                case 32:
                                case 33:
                                case 34:
                                case 35:
                                case 36:
                                case 37:
                                    attribute.ForegroundOnly = ColourMap[i - 30];
                                    rgbAttribute.Foreground  = attribute.Foreground;
                                    break;

                                case 40:
                                case 41:
                                case 42:
                                case 43:
                                case 44:
                                case 45:
                                case 46:
                                case 47:
                                    attribute.BackgroundOnly = ColourMap[i - 40];
                                    rgbAttribute.Background  = attribute.Background;
                                    break;
                                }
                            }
                        }
                    }
                    break;

                case 'S':
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }

                    if (AnimateView)
                    {
                        while (i > 1)
                        {
                            canvas.ShiftUp();
                            i--;
                        }
                    }
                    break;

                case 'T':
                    if (args.Length > 0)
                    {
                        if (ConvertToInt(args[0], out i))
                        {
                            if (i == 0)
                            {
                                i = 1;
                            }
                        }
                    }
                    else
                    {
                        i = 1;
                    }

                    if (AnimateView)
                    {
                        while (i > 1)
                        {
                            canvas.ShiftDown();
                            i--;
                        }
                    }
                    break;

                case 's':
                    if (args.Length == 0)
                    {
                        ptSave = ptCur;
                    }
                    break;

                case 'u':
                    if (args.Length == 0)
                    {
                        ptCur = ptSave;
                    }
                    break;
                }
            }
Beispiel #43
0
        static string[] GetModels(int displayid, int slot)
        {
            int records;
            int fields;
            int id;
            int left    = 0;
            int right   = 0;
            int geoset1 = -1;
            int geoset2 = -1;
            int geoset3 = -1;

            string[] models = Enumerable.Repeat("", 10).ToArray();
            using (BinaryReader reader = new BinaryReader(File.Open("ItemDisplayInfo.dbc", FileMode.Open)))
            {
                Skip(1, reader);
                records = reader.ReadInt32();
                fields  = reader.ReadInt32();
                Skip(2, reader);
                for (int i = 0; i < records; i++)
                {
                    id = reader.ReadInt32();
                    if (id == displayid)
                    {
                        left  = reader.ReadInt32();
                        right = reader.ReadInt32();
                        Skip(3, reader);
                        geoset1 = reader.ReadInt32();
                        geoset2 = reader.ReadInt32();
                        geoset3 = reader.ReadInt32();
                        Skip(fields - 9, reader);
                        continue;
                    }
                    Skip(fields - 1, reader);
                }
                models[0] = FindString(left, reader);
                models[1] = FindString(right, reader);
            }
            switch (slot)
            {
            case 4:
                models[3] = SleeveGeoset(geoset1);
                models[5] = DoubletGeoset(geoset2);
                break;

            case 5:
            case 20:
                models[3] = SleeveGeoset(geoset1);
                models[5] = DoubletGeoset(geoset2);
                models[7] = RobeGeoset(geoset3);
                break;

            case 7:
                models[6] = SkirtGeoset(geoset1);
                models[8] = KneesGeoset(geoset2);
                models[7] = RobeGeoset(geoset3);
                break;

            case 8:
                models[9] = BootsGeoset(geoset1);
                break;

            case 10:
                models[4] = WristGeoset(geoset1);
                break;

            case 16:
                models[2] = CapeGeoset(geoset1);
                break;
            }
            return(models);
        }
Beispiel #44
0
            /// <summary>
            /// Decompresses an individual record.
            /// </summary>
            /// <param name="arzFile">ARZ file which we are decompressing.</param>
            /// <returns>decompressed DBRecord.</returns>
            public DBRecordCollection Decompress(ArzFile arzFile)
            {
                // record variables have this format:
                // 0x00 int16 specifies data type:
                //      0x0000 = int - data will be an int32
                //      0x0001 = float - data will be a Single
                //      0x0002 = string - data will be an int32 that is index into string table
                //      0x0003 = bool - data will be an int32
                // 0x02 int16 specifies number of values (usually 1, but sometimes more (for arrays)
                // 0x04 int32 key string ID (the id into the string table for this variable name
                // 0x08 data value
                byte[] data = this.DecompressBytes(arzFile);

                int numberOfDWords = data.Length / 4;

                if (data.Length % 4 != 0)
                {
                    // Turn on debugging so we can log the exception.
                    if (!TQDebug.DebugEnabled)
                    {
                        TQDebug.DebugEnabled = true;
                    }

                    TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName));
                    TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, data Length = {1} which is not a multiple of 4", this.ID, (int)data.Length));
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, data Length = {1} which is not a multiple of 4", this.ID, (int)data.Length));
                }

                DBRecordCollection record = new DBRecordCollection(this.ID, this.RecordType);

                // Create a memory stream to read the binary data
                using (BinaryReader inReader = new BinaryReader(new MemoryStream(data, false)))
                {
                    int i = 0;
                    while (i < numberOfDWords)
                    {
                        short  dataType     = inReader.ReadInt16();
                        short  valCount     = inReader.ReadInt16();
                        int    variableID   = inReader.ReadInt32();
                        string variableName = arzFile.Getstring(variableID);

                        if (variableName == null)
                        {
                            // Turn on debugging so we can log the exception.
                            if (!TQDebug.DebugEnabled)
                            {
                                TQDebug.DebugEnabled = true;
                            }

                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName));
                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable is NULL", this.ID));
                            throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable is NULL", this.ID));
                        }

                        if (dataType < 0 || dataType > 3)
                        {
                            // Turn on debugging so we can log the exception.
                            if (!TQDebug.DebugEnabled)
                            {
                                TQDebug.DebugEnabled = true;
                            }

                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName));
                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {2}, bad dataType {3}", this.ID, variableName, dataType));
                            throw new ArgumentOutOfRangeException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {2}, bad dataType {3}", this.ID, variableName, dataType));
                        }

                        Variable v = new Variable(variableName, (VariableDataType)dataType, valCount);

                        if (valCount < 1)
                        {
                            // Turn on debugging so we can log the exception.
                            if (!TQDebug.DebugEnabled)
                            {
                                TQDebug.DebugEnabled = true;
                            }

                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName));
                            TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {1}, bad valCount {2}", this.ID, variableName, valCount));
                            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {1}, bad valCount {2}", this.ID, variableName, valCount));
                        }

                        // increment our dword count
                        i += 2 + valCount;

                        for (int j = 0; j < valCount; ++j)
                        {
                            switch (v.DataType)
                            {
                            case VariableDataType.Integer:
                            case VariableDataType.Boolean:
                            {
                                int val = inReader.ReadInt32();
                                v[j] = val;
                                break;
                            }

                            case VariableDataType.Float:
                            {
                                float val = inReader.ReadSingle();
                                v[j] = val;
                                break;
                            }

                            case VariableDataType.StringVar:
                            {
                                int    id  = inReader.ReadInt32();
                                string val = arzFile.Getstring(id);
                                if (val == null)
                                {
                                    val = string.Empty;
                                }
                                else
                                {
                                    val = val.Trim();
                                }

                                v[j] = val;
                                break;
                            }

                            default:
                            {
                                int val = inReader.ReadInt32();
                                v[j] = val;
                                break;
                            }
                            }
                        }

                        record.Set(v);
                    }
                }

                return(record);
            }
Beispiel #45
0
 public void SetupBlock(BinaryReader file)
 {
     Data = file.ReadBytes((int)CompressedSize);
 }
 private static Dependency ReadDependency(this BinaryReader br) => new(br.ReadUInt64());
Beispiel #47
0
        public override bool load()
        {
            if (File.Exists(myFilename) == false)
            {
                Warn.print("Cannot find file {0}", myFilename);
                myState = SourceState.FAILED;
                return(false);
            }

            using (FileStream waveFileStream = File.Open(myFilename, System.IO.FileMode.Open))
            {
                BinaryReader reader = new BinaryReader(waveFileStream);

                int chunkID = reader.ReadInt32();
                if (chunkID != 0x46464952)
                {
                    Warn.print("{0} is not a RIFF formated file", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }
                int fileSize = reader.ReadInt32();
                int riffType = reader.ReadInt32();
                if (riffType != 0x45564157) //"WAVE" in bytes
                {
                    Warn.print("{0} is not a WAV", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }
                int fmtID = reader.ReadInt32();
                if (fmtID != 0x20746d66) //"fmt " in bytes
                {
                    Warn.print("Cannot find valid fmt chunk in {0}", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }

                int fmtSize = reader.ReadInt32();
                if (fmtSize != 16)
                {
                    Warn.print("{0} is not in 16 bit format", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }
                int fmtCode = reader.ReadInt16();
                if (fmtCode != 1) //PCM data
                {
                    Warn.print("{0} is not in PCM format", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }
                myNumChannels = reader.ReadInt16();
                if (myIs3d == true && myNumChannels != 1)
                {
                    Error.print("Unable to load stereo files for 3D capability");
                    myState = SourceState.FAILED;
                    return(false);
                }

                mySampleRate = reader.ReadInt32();
                int fmtAvgBPS     = reader.ReadInt32();
                int fmtBlockAlign = reader.ReadInt16();
                int bitDepth      = reader.ReadInt16();

                if (fmtSize == 18)
                {
                    // Read any extra values
                    int fmtExtraSize = reader.ReadInt16();
                    reader.ReadBytes(fmtExtraSize);
                }

                int dataID = reader.ReadInt32();
                if (dataID != 0x61746164) //"data" in bytes
                {
                    Warn.print("Cannot find valid data chunk in file {0}", myFilename);
                    myState = SourceState.FAILED;
                    return(false);
                }
                int dataSize = reader.ReadInt32();

                if (bitDepth != 16)
                {
                    Warn.print("WAV files must be 16-bit PCM format");
                    myState = SourceState.FAILED;
                    return(false);
                }

                //read the data
                byte[] data;
                data = reader.ReadBytes(dataSize);

                //convert to shorts
                short[] audioData = new short[dataSize / 2];
                for (int i = 0; i < dataSize / 2; i++)
                {
                    audioData[i] = BitConverter.ToInt16(data, i * 2);
                }

                AudioBuffer buffer = new AudioBuffer(myNumChannels == 1 ? AudioBuffer.AudioFormat.MONO16 : AudioBuffer.AudioFormat.STEREO16, mySampleRate);
                buffer.setData(audioData);

                //put it in the audio system
                buffer.buffer();
                myBuffers.Add(buffer);
            }

            myState = Source.SourceState.LOADED;
            Info.print("Loaded audio file: {0}", myFilename);

            return(true);
        }
Beispiel #48
0
 static void Skip(int count, BinaryReader reader)
 {
     reader.BaseStream.Position += count * 4;
 }
Beispiel #49
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            HttpPostedFile postedFile = FileUpload1.PostedFile;
            string filename = Path.GetFileName(postedFile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int fileSize = postedFile.ContentLength;

            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".gif"
                || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".bmp")
            {
                Stream stream = postedFile.InputStream;
                BinaryReader binaryReader = new BinaryReader(stream);
                Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);


                using (SqlConnection con = new SqlConnection(connstring))
                {
                    SqlCommand cmd = new SqlCommand("spUploadImage", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter paramName = new SqlParameter()
                    {
                        ParameterName = @"Name",
                        Value = filename
                    };
                    cmd.Parameters.Add(paramName);

                    SqlParameter paramSize = new SqlParameter()
                    {
                        ParameterName = "@Size",
                        Value = fileSize
                    };
                    cmd.Parameters.Add(paramSize);

                    SqlParameter paramImageData = new SqlParameter()
                    {
                        ParameterName = "@ImageData",
                        Value = bytes
                    };
                    cmd.Parameters.Add(paramImageData);

                    SqlParameter paramNewId = new SqlParameter()
                    {
                        ParameterName = "@NewId",
                        Value = -1,
                        Direction = ParameterDirection.Output
                    };
                    cmd.Parameters.Add(paramNewId);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                    lblMessage.Visible = true;
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Text = "Upload Successful";
                    hyperlink.Visible = true;
                    hyperlink.NavigateUrl = "~/WebForm2.aspx?Id=" + cmd.Parameters["@NewId"].Value.ToString();
                    LoadImages();
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Only images (.jpg, .png, .gif and .bmp) can be uploaded";
                hyperlink.Visible = false;
            }

        }
Beispiel #50
0
 public Block(BinaryReader file)
 {
     CompressedSize   = file.ReadUInt32();
     DecompressedSize = file.ReadUInt32();
 }
Beispiel #51
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("You have to enter file name");
        }
        else
        {
            string pcxFile = args[0];
            if (!File.Exists(pcxFile))
            {
                Console.WriteLine("File doesn't exist");
            }
            else
            {
                try
                {
                    BinaryReader pcxReader = new BinaryReader(
                        File.Open(pcxFile, FileMode.Open));

                    byte head = pcxReader.ReadByte();
                    if (head != 10)
                    {
                        Console.WriteLine("Not a PCX file...");
                        return;
                    }

                    pcxReader.ReadByte();
                    byte zip      = pcxReader.ReadByte();
                    bool checkZip = false;
                    if (zip == 1)
                    {
                        checkZip = true;
                    }
                    else if (zip == 0)
                    {
                        checkZip = false;
                    }

                    byte bitPerPixel = pcxReader.ReadByte();
                    if (bitPerPixel != 8)
                    {
                        Console.WriteLine("Bit per pixels is not 8");
                        return;
                    }


                    pcxReader.BaseStream.Seek(4, SeekOrigin.Begin);
                    short xMin   = pcxReader.ReadInt16();
                    short yMin   = pcxReader.ReadInt16();
                    short xMax   = pcxReader.ReadInt16();
                    short yMax   = pcxReader.ReadInt16();
                    int   width  = xMax - xMin + 1;
                    int   height = yMax - yMin + 1;

                    pcxReader.BaseStream.Seek(66, SeekOrigin.Begin);
                    byte checkWidth = pcxReader.ReadByte();
                    if (checkWidth != width)
                    {
                        Console.WriteLine("Width incorrect");
                        return;
                    }

                    string imageData = "";
                    pcxReader.BaseStream.Seek(128, SeekOrigin.Begin);
                    while (pcxReader.BaseStream.Position <
                           pcxReader.BaseStream.Length - 1)
                    {
                        byte data = pcxReader.ReadByte();
                        if (data < 192)
                        {
                            imageData += pixelToDraw(data);
                        }
                        else
                        {
                            byte repeats = (byte)(data - 192);
                            data = pcxReader.ReadByte();
                            string drawingLine =
                                new string(pixelToDraw(data), repeats);
                            imageData += drawingLine;
                        }
                    }
                    pcxReader.Close();

                    Console.WriteLine("Bits per pixel: " + bitPerPixel);
                    Console.WriteLine("Width: " + width);
                    Console.WriteLine("Height: " + height);
                    Console.WriteLine("Bytes per Line: " + checkWidth);
                    Console.WriteLine("Zip: " + checkZip);

                    int actualPosition = 0;
                    for (int row = 0; row < height; row++)
                    {
                        for (int column = 0; column < width; column++)
                        {
                            Console.Write(imageData[actualPosition]);
                            actualPosition++;
                        }
                        Console.WriteLine();
                    }
                }
                catch (PathTooLongException)
                {
                    Console.WriteLine("ERROR: Path too long");
                }
                catch (IOException)
                {
                    Console.WriteLine("ERROR: IO Exception");
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: " + e);
                }
            }
        }
    }
Beispiel #52
0
 protected VpkReaderBase(string filename)
 {
     Reader      = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
     _strBuilder = new StringBuilder(256);
 }
Beispiel #53
0
 public abstract Variable Parse(BinaryReader reader, ref int size);
Beispiel #54
0
        /// <summary>
        /// Gets the contract icon for the given id and seed (color).
        /// </summary>
        /// <param name="url">URL of the icon</param>
        /// <param name="seed">Seed to use for generating the color</param>
        /// <returns>The texture</returns>
        public static Texture2D GetContractIcon(string url, int seed)
        {
            // Check cache for texture
            Texture2D texture;
            Color     color = SystemUtilities.RandomColor(seed, 1.0f, 1.0f, 1.0f);

            if (!contractIcons.ContainsKey(url))
            {
                contractIcons[url] = new Dictionary <Color, Texture2D>();
            }
            if (!contractIcons[url].ContainsKey(color))
            {
                Texture2D baseTexture = ContractDefs.textures[url];

                try
                {
                    Texture2D loadedTexture = null;
                    string    path          = (url.Contains('/') ? "GameData/" : "GameData/Squad/Contracts/Icons/") + url;
                    // PNG loading
                    if (File.Exists(path + ".png"))
                    {
                        path         += ".png";
                        loadedTexture = new Texture2D(baseTexture.width, baseTexture.height, TextureFormat.RGBA32, false);
                        loadedTexture.LoadImage(File.ReadAllBytes(path.Replace('/', Path.DirectorySeparatorChar)));
                    }
                    // DDS loading
                    else if (File.Exists(path + ".dds"))
                    {
                        path += ".dds";
                        BinaryReader br = new BinaryReader(new MemoryStream(File.ReadAllBytes(path)));

                        if (br.ReadUInt32() != DDSValues.uintMagic)
                        {
                            throw new Exception("Format issue with DDS texture '" + path + "'!");
                        }
                        DDSHeader ddsHeader = new DDSHeader(br);
                        if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDX10)
                        {
                            DDSHeaderDX10 ddsHeaderDx10 = new DDSHeaderDX10(br);
                        }

                        TextureFormat texFormat;
                        if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT1)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT1;
                        }
                        else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT3)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT1 | UnityEngine.TextureFormat.Alpha8;
                        }
                        else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT5)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT5;
                        }
                        else
                        {
                            throw new Exception("Unhandled DDS format!");
                        }

                        loadedTexture = new Texture2D((int)ddsHeader.dwWidth, (int)ddsHeader.dwHeight, texFormat, false);
                        loadedTexture.LoadRawTextureData(br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)));
                    }
                    else
                    {
                        throw new Exception("Couldn't find file for icon  '" + url + "'");
                    }

                    Color[] pixels = loadedTexture.GetPixels();
                    for (int i = 0; i < pixels.Length; i++)
                    {
                        pixels[i] *= color;
                    }
                    texture = new Texture2D(baseTexture.width, baseTexture.height, TextureFormat.RGBA32, false);
                    texture.SetPixels(pixels);
                    texture.Apply(false, false);
                    contractIcons[url][color] = texture;
                    UnityEngine.Object.Destroy(loadedTexture);
                }
                catch (Exception e)
                {
                    Debug.LogError("WaypointManager: Couldn't create texture for '" + url + "'!");
                    Debug.LogException(e);
                    texture = contractIcons[url][color] = baseTexture;
                }
            }
            else
            {
                texture = contractIcons[url][color];
            }

            return(texture);
        }
        private static object ReadValue(List <TypeTreeNode> members, BinaryReader reader, ref int i)
        {
            var    member     = members[i];
            var    varTypeStr = member.m_Type;
            object value;
            var    align = (member.m_MetaFlag & 0x4000) != 0;

            switch (varTypeStr)
            {
            case "SInt8":
                value = reader.ReadSByte();
                break;

            case "UInt8":
            case "char":
                value = reader.ReadByte();
                break;

            case "short":
            case "SInt16":
                value = reader.ReadInt16();
                break;

            case "UInt16":
            case "unsigned short":
                value = reader.ReadUInt16();
                break;

            case "int":
            case "SInt32":
                value = reader.ReadInt32();
                break;

            case "UInt32":
            case "unsigned int":
            case "Type*":
                value = reader.ReadUInt32();
                break;

            case "long long":
            case "SInt64":
                value = reader.ReadInt64();
                break;

            case "UInt64":
            case "unsigned long long":
            case "FileSize":
                value = reader.ReadUInt64();
                break;

            case "float":
                value = reader.ReadSingle();
                break;

            case "double":
                value = reader.ReadDouble();
                break;

            case "bool":
                value = reader.ReadBoolean();
                break;

            case "string":
                value = reader.ReadAlignedString();
                i    += 3;
                break;

            case "map":
            {
                if ((members[i + 1].m_MetaFlag & 0x4000) != 0)
                {
                    align = true;
                }
                var map = GetMembers(members, i);
                i += map.Count - 1;
                var first  = GetMembers(map, 4);
                var next   = 4 + first.Count;
                var second = GetMembers(map, next);
                var size   = reader.ReadInt32();
                var dic    = new List <KeyValuePair <object, object> >(size);
                for (int j = 0; j < size; j++)
                {
                    int tmp1 = 0;
                    int tmp2 = 0;
                    dic.Add(new KeyValuePair <object, object>(ReadValue(first, reader, ref tmp1), ReadValue(second, reader, ref tmp2)));
                }
                value = dic;
                break;
            }

            case "TypelessData":
            {
                var size = reader.ReadInt32();
                value = reader.ReadBytes(size);
                i    += 2;
                break;
            }

            default:
            {
                if (i < members.Count - 1 && members[i + 1].m_Type == "Array")         //Array
                {
                    if ((members[i + 1].m_MetaFlag & 0x4000) != 0)
                    {
                        align = true;
                    }
                    var vector = GetMembers(members, i);
                    i += vector.Count - 1;
                    var size = reader.ReadInt32();
                    var list = new List <object>(size);
                    for (int j = 0; j < size; j++)
                    {
                        int tmp = 3;
                        list.Add(ReadValue(vector, reader, ref tmp));
                    }
                    value = list;
                    break;
                }
                else         //Class
                {
                    var @class = GetMembers(members, i);
                    i += @class.Count - 1;
                    var obj = new OrderedDictionary();
                    for (int j = 1; j < @class.Count; j++)
                    {
                        var classmember = @class[j];
                        var name        = classmember.m_Name;
                        obj[name] = ReadValue(@class, reader, ref j);
                    }
                    value = obj;
                    break;
                }
            }
            }
            if (align)
            {
                reader.AlignStream();
            }
            return(value);
        }
 public override void DeserializeResponse(BinaryReader br)
 {
     Response = BoolUtil.Deserialize(br);
 }
Beispiel #57
0
 public static Matrix ReadMatrix(this BinaryReader br)
 {
   return new Matrix(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(),
     br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(),
     br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle());
 }
Beispiel #58
0
 public abstract void Verify(BinaryReader reader, ref int size);
 public Flipper(BinaryReader reader, string itemName) : this(new FlipperData(reader, itemName))
 {
 }
Beispiel #60
-5
    // 바이너리 로드
    public void Load(TextAsset kTa_)
    {
        //FileStream fs = new FileStream("Assets\\Resources\\StageDB.bytes", FileMode.Open);
        //BinaryReader br = new BinaryReader(fs);
        Stream kStream = new MemoryStream (kTa_.bytes);
        BinaryReader br = new BinaryReader(kStream);

        // *주의
        // 바이너리 세이브 순서와 로드 순서가 같아야된다. [5/13/2012 JK]
        // 바이너리 리드
        int iCount = br.ReadInt32();        // 갯수 읽기
        for (int i = 0; i < iCount; ++i)
        {
            StStateInfo kInfo = new StStateInfo();

            kInfo.m_nStageIndex = br.ReadInt32();          // 캐릭터 코드
            // 스테이지 별로 나오는 캐릭터
            kInfo.m_anCharCode = new int[(int)EStageDetail.Count];
            for (int k = 0; k < (int)EStageDetail.Count; ++k)
            {
                kInfo.m_anCharCode[k] = br.ReadInt32();
            }
            kInfo.m_fTermTime = br.ReadSingle();

            m_tmStage.Add(kInfo.m_nStageIndex, kInfo);
        }

        //fs.Close();
        br.Close();
        kStream.Close();
    }