public static void Load() { IO.Log.Write(" Loading CampaingProgresss..."); levelsCompleted.Clear(); System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Saves/progress.lpg", System.IO.FileMode.Open)); String s = ""; int l = 0; while (br.PeekChar() > -1) { s = br.ReadString(); l = br.ReadInt32(); byte[] d = new byte[l]; for (int j = 0; j < l; j++) { d[j] = br.ReadByte(); } levelsCompleted.Add(s, d); } br.Close(); IO.Log.Write(" Loading complete"); }
public static void split(string input_path, string dir_path, int nb) { System.IO.FileStream inf = new System.IO.FileStream(input_path, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(inf); System.IO.BinaryWriter[] writers = new System.IO.BinaryWriter[nb]; for (int x = 0; x < nb; x++) { writers[x] = new System.IO.BinaryWriter(new System.IO.FileStream(dir_path + "/part_" + (x + 1) + ".ACDC", System.IO.FileMode.Create, System.IO.FileAccess.Write)); } int i = 0; while (reader.PeekChar() != -1) { writers[i % nb].Write(reader.ReadChar()); i++; } for (int j=0; j<nb; j++) { writers[j].Close(); } }
private char readCharLiteral(System.IO.Stream stream, System.IO.BinaryReader reader) { char c = '\0'; SkipSpaces(stream); if ((char)reader.PeekChar() == '\'') { reader.ReadChar(); } c = reader.ReadChar(); if ((char)reader.PeekChar() == '\'') { reader.ReadChar(); } SkipSpaces(stream); return(c); }
public static string ReadAlignedString(System.IO.BinaryReader br) { string value = ""; // ignore any null padding in the front. while (br.PeekChar() == '\0') // loop over the embeded name. { br.ReadChar(); // discard the null } while (br.PeekChar() != '\0') // loop over the embeded name. { value += br.ReadChar(); } br.ReadChar();//discard the null terminating the end of the string. // if we are not alligned, then drop some bytes. while (br.BaseStream.Position % 4 != 0) { br.ReadChar(); // should be null padding for alignment } return(value); }
/// <summary> /// Interpretes the data as an String Value /// </summary> /// <returns>The Value interpreted as String</returns> protected string AsString() { System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(Value)); try { string ret = ""; while (br.PeekChar() != -1) { ret += br.ReadChar(); } return(ret); } catch (Exception) { return(""); } }
private void f17_ButtonReadKeyword_Click(object sender, EventArgs e) { Key = new byte[8][]; for (int i = 0; i < 8; i++) { Key[i] = new byte[4]; } int byteNumber = 0; int code; OpenFileDialog Load = new OpenFileDialog(); if (Load.ShowDialog() == DialogResult.OK) { System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default); int i = 0, j = 0; while ((code = reader.PeekChar()) > -1 && (byteNumber = i * 4 + j) < 32) { Key[i][j] = reader.ReadByte(); j++; if (j == 4) { j = 0; i++; } } reader.Close(); if (code == -1 && byteNumber == 31) { f17_fieldKeyword.Text = "Source: " + Load.FileName; } else { if (code == -1) { MessageBox.Show("Слишком короткий ключ в файле", "Ошибка"); } if (byteNumber == 31) { MessageBox.Show("Слишком длинный ключ в файле", "Ошибка"); } f17_fieldKeyword.Text = null; Key = new byte[0][]; } } }
protected virtual void InternalDeserialize(ref System.IO.BinaryReader reader) { if (reader.PeekChar() == 67) { reader.ReadChar(); this.m_id = reader.ReadInt16(); } else { this.m_targets = (SpellTargetType)reader.ReadInt32(); this.m_targetMask = reader.ReadString(); this.m_id = reader.ReadInt16(); this.m_duration = reader.ReadInt32(); this.m_delay = reader.ReadInt32(); this.m_random = reader.ReadInt32(); this.m_group = reader.ReadInt32(); this.m_modificator = reader.ReadInt32(); this.m_trigger = reader.ReadBoolean(); this.m_hidden = reader.ReadBoolean(); this.ParseRawZone(reader.ReadString()); } }
static int _m_PeekChar(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.BinaryReader gen_to_be_invoked = (System.IO.BinaryReader)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.PeekChar( ); LuaAPI.xlua_pushinteger(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
public static List <ScheduleTrain> loadFromFile(String fileName) { List <ScheduleTrain> trains = new List <ScheduleTrain>(); using (System.IO.BinaryReader binaryReader = new System.IO.BinaryReader( new System.IO.FileStream(fileName, System.IO.FileMode.Open))) { while (binaryReader.PeekChar() > -1) { ScheduleTrain train = new ScheduleTrain(); train.setDestinationStation(binaryReader.ReadString()); train.setNumberTrain(binaryReader.ReadString()); train.setDepartureTime(Convert.ToDateTime(binaryReader.ReadString())); train.setArrivalTime(Convert.ToDateTime(binaryReader.ReadString())); train.setTravelPrice(binaryReader.ReadDouble()); trains.Add(train); } } return(trains); }
private static string LoadPasswordFromFile(string fileName) { string value = ""; List <byte> byteList = new List <byte>(); System.IO.FileStream stream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); while (reader.PeekChar() != -1) { byteList.Add(reader.ReadByte()); } reader.Close(); reader.Dispose(); stream.Close(); stream.Dispose(); value = Encoding.UTF8.GetString(byteList.ToArray()); value = value.Replace(Environment.NewLine, ""); value = value.Replace(" ", ""); value = DESManager.Decrypt(value); value = DESManager.Decrypt(value); value = DESManager.Decrypt(value); return(value); }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { byte Magic1, Magic2, Magic3; openFileDialog1.ShowDialog(); System.IO.BinaryReader br; System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); Magic1 = br.ReadByte(); Magic2 = br.ReadByte(); Magic3 = br.ReadByte(); if (Magic1 != 'B' || Magic2 != '3' || Magic3 != '2') { MessageBox.Show("This is not a valid B32 file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StartAddr = br.ReadUInt16(); Console.WriteLine("Start Address: " + StartAddr); ExecAddr = br.ReadUInt16(); Console.WriteLine("Exec Address: " + ExecAddr); ushort Counter = 0; while (br.PeekChar() != -1) { B32Memory[StartAddr + Counter] = br.ReadByte(); Counter++; } br.Close(); fs.Close(); InstructionPointer = (ushort)(StartAddr + ExecAddr); Console.WriteLine("InstructionPointer: " + InstructionPointer); ExecuteProgram(ExecAddr, Counter); }
private bool skipComments(System.IO.BinaryReader reader) { string instruction = ""; while ((char)reader.PeekChar() == ';' || (char)reader.PeekChar() == '/' || (char)reader.PeekChar() == '*') { instruction += reader.ReadChar(); } if (instruction.StartsWith(";") || instruction.StartsWith("//")) { while ((char)reader.PeekChar() != '\n' && (char)reader.PeekChar() != '\r') { reader.ReadByte(); } return(true); } if (instruction.StartsWith("/*")) { back: while ((char)reader.PeekChar() != '*') { reader.ReadChar(); } string end = "*"; if ((char)reader.PeekChar() == '/') { end += reader.ReadChar(); return(true); } goto back; } return(false); }
private void f17_ButtonEncryptFile_Click(object sender, EventArgs e) { progressBar.Value = 0; LinkedList <byte> ResultFile = new LinkedList <byte>(); f17_labelPB.Text = "Выбор файла..."; f17_labelPB.Update(); OpenFileDialog Load = new OpenFileDialog(); if (Load.ShowDialog() == DialogResult.OK) { f17_labelPB.Text = "Считываем из файла..."; f17_labelPB.Update(); System.IO.FileInfo Inform = new System.IO.FileInfo(Load.FileName); progressBar.Maximum = Convert.ToInt32(Inform.Length / 8) + 1; System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default); f17_labelPB.Text = "Зашифровываем..."; f17_labelPB.Update(); byte[] SourceL = new byte[4]; byte[] SourceR = new byte[4]; byte[] Result = new byte[8]; for (long block = 0; block < (Inform.Length / 8); block++) //Блоки по 64 бит { SourceL = reader.ReadBytes(4); //4*8=32 SourceR = reader.ReadBytes(4); Result = FeistelNetwork(SourceL, SourceR); for (int i = 0; i < 8; i++) { ResultFile.AddLast(Result[i]); } progressBar.Value++; if (((progressBar.Maximum > 100 && progressBar.Value % (progressBar.Maximum / 100) == 0) || (progressBar.Value == progressBar.Maximum))) //Составляет ровно n% или 100% { f17_labelPB.Text = "Зашифровываем... Выполнено " + Convert.ToString(progressBar.Value) + " из " + Convert.ToString(progressBar.Maximum); } f17_labelPB.Update(); } LinkedList <byte> Tail = new LinkedList <byte>(); while (reader.PeekChar() > -1) { Tail.AddLast(reader.ReadByte()); } Tail.AddLast(0x80); while (Tail.Count != 8) { Tail.AddLast(0x00); } for (int i = 0; i < 4; i++) { SourceL[i] = Tail.ElementAt(i); } for (int i = 4; i < 8; i++) { SourceR[i - 4] = Tail.ElementAt(i); } Tail.Clear(); Result = FeistelNetwork(SourceL, SourceR); for (int i = 0; i < 8; i++) { ResultFile.AddLast(Result[i]); } progressBar.Value++; if (((progressBar.Maximum > 100 && progressBar.Value % (progressBar.Maximum / 100) == 0) || (progressBar.Value == progressBar.Maximum))) //Составляет ровно n% или 100% { f17_labelPB.Text = "Зашифровываем... Выполнено " + Convert.ToString(progressBar.Value) + " из " + Convert.ToString(progressBar.Maximum); } f17_labelPB.Update(); reader.Close(); } else { f17_labelPB.Text = "Готов к работе"; f17_labelPB.Update(); return; } SaveFileDialog Save = new SaveFileDialog(); if (Save.ShowDialog() == DialogResult.OK) { System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(Save.FileName, System.IO.FileMode.OpenOrCreate), Encoding.Default); f17_labelPB.Text = "Сохраняем результат в файл..."; f17_labelPB.Update(); foreach (var Byte in ResultFile) { writer.Write(Byte); } writer.Close(); } else { f17_labelPB.Text = "Готов к работе"; f17_labelPB.Update(); return; } f17_labelPB.Text = "Готово."; f17_labelPB.Update(); }
public bool parseOpcode() { bool firstBit; byte op; // Get opcode op = grvReader.ReadByte(); // Check if first bit set if ((op & 128) == 128) { op &= 127; firstBit = true; } else { firstBit = false; } try { opCount[op]++; } catch (Exception e) { Console.WriteLine("Bad opcode: " + op); } /* * if (something) * vars[0x103]++; * */ //if (VDXFlags.op400D == 2) //{ // // Play midi // music.playLoop(1); // VDXFlags.op400D = 0; //} /* if (.op1c05 > 0) ? * do things */ /* if (.op2042 & 0x80) * do stuff/jump * .op2402 = 0 */ //Console.WriteLine("Opcode 0x{0:X}", op); //if (scriptJumps switch (op) { #region NOP's case 0x28: case 0x4A: case 0x4F: case 0x50: // 2 byte NOP { ushort arg = grvReader.ReadUInt16(); genASM += ("\tNOP"); } break; case 0x1E: case 0x48: case 0x4B: // 1 Byte NOP { byte arg = grvReader.ReadByte(); genASM += ("\tNOP"); } break; case 0x01: case 0x46: case 0x49: case 0x47: // NOP genASM += ("\tNOP"); break; case 0x59: // Variable size NOP { ushort arg1, arg2; if (firstBit) { arg1 = grvReader.ReadByte(); } else { arg1 = grvReader.ReadUInt16(); } arg2 = grvReader.ReadByte(); //Console.WriteLine("NOP variable: 0x{0:X} with args 0x{1:X}, 0x{2:X}", op, arg1, arg2); genASM += ("\tOp59\t0x" + Convert.ToString(arg1, 16) + ", 0x" + Convert.ToString(arg2, 16)); } break; #endregion #region Bitflags (3, 5, 6, 7, A, 35, 57) case 0x03: // Enable bit 9 genASM += ("\tFADIN"); break; case 0x05: // Bit 8 (just still ?) genASM += ("\tBF8ON"); break; case 0x06: // Bit 6 genASM += ("\tBF6ON"); break; case 0x07: // Bit 7 - Just audio? genASM += ("\tBF7ON"); break; case 0x0A: // Bit 5 - skip stills? genASM += ("\tBF5ON"); break; case 0x35: // just audio genASM += ("\tBF7OFF"); break; case 0x57: // unimplemented Console.WriteLine("op57"); return(false); case 0x58: // unimplemented genASM += "\tOp58\t" + readAwk2() + "; unknown pvdx style"; Console.WriteLine("op58"); //return false; break; #endregion #region Mouse clicks - D, E, F, 10, 11, 12, 2C, 2D, 30, 44, 45, 53) case 0x0D: // Mark a rectangle clickable. On hover, show cursor arg6. Jump to arg5 on click { ushort left = grvReader.ReadUInt16(); ushort top = grvReader.ReadUInt16(); ushort right = grvReader.ReadUInt16(); ushort bottom = grvReader.ReadUInt16(); ushort jump = grvReader.ReadUInt16(); scriptJumps.Add(jump); byte cursor = grvReader.ReadByte(); genASM += ("\tHOTREC\tloc_" + jump + ", " + left + ", " + top + ", " + right + ", " + bottom + ", " + cursor); } break; case 0x0E: // Left 100px clickable { ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTL\tloc_" + offset); } break; case 0x0F: // Right 100px clickable { ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTR\tloc_" + offset); } break; case 0x10: case 0x11: // Middle 240px clickable { ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTC\tloc_" + offset); } break; case 0x12: // Current pos clickable { ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTFULL\tloc_" + offset); } break; case 0x30: // Bottom 80px clickable { ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTB\tloc_" + offset); } break; case 0x2C: { // Destination and cursor for top hotspot ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTTC\tloc_" + offset + ", " + grvReader.ReadByte()); } break; case 0x2D: { // Destination and cursor for bottom hotspot ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTBC\tloc_" + offset + ", " + grvReader.ReadByte()); } break; case 0x44: { // Destination for right hotspot //standardHotspot[1].jumpAddress = stream.ReadUInt16(); ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTRD\tloc_" + offset); } break; case 0x45: { // Destination for left hotspot //standardHotspot[3].jumpAddress = stream.ReadUInt16(); ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTLD\tloc_" + offset); //throw new Exception("Action for left hotspot"); } break; case 0x3B: // Savegame stuff, inc rendering sphinx.fnt { byte slot = grvReader.ReadByte(); ushort left = grvReader.ReadUInt16(), top = grvReader.ReadUInt16(), right = grvReader.ReadUInt16(), bottom = grvReader.ReadUInt16(); ushort offset = grvReader.ReadUInt16(); byte cursor = grvReader.ReadByte(); genASM += "\tHOTSAV\t" + slot + ", loc_" + offset + ", " + left + ", " + top + ", " + right + ", " + bottom + ", " + cursor; scriptJumps.Add(offset); } break; case 0x0B: // Start input loop //if (inputLoopPos == 0) // inputLoopPos = stream.BaseStream.Position - 1; //game.removeHotspot(); // Something midi related here // Play loop midi perhaps - if not midi playing already? //Console.WriteLine("Start input loop"); genASM += ("\tGOIN\t\t;Start input"); break; case 0x0C: // Keyboard related //game.addHotspot(stream.ReadByte(), stream.ReadUInt16()); { byte val = grvReader.ReadByte(); ushort offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += ("\tHOTKEY\tloc_" + offset + ", " + val + " ; " + ((char)val).ToString()); } break; case 0x13: // End input loop // Checks if mouse inputs have passed // Jump to input loop start //stream.BaseStream.Seek(inputLoopPos, SeekOrigin.Begin); genASM += ("\tSTIN\t\t;Stop input"); break; #endregion case 0x02: // Play "XMI". Unfortunately that's a little hard at the moment so play MIDI conversion { genASM += ("\tPMID\t" + ReadFileRef()); } break; case 0x04: // Fade out //game.removeVDX(); genASM += ("\tFADOUT"); break; case 0x08: // Loop XMI file? { genASM += ("\tMIDLOOP\t" + ReadFileRef()); } break; case 0x4E: { genASM += ("\tMIDDELAY\t" + grvReader.ReadUInt16()); } break; #region Display related case 0x22: // Copy bg to fg genASM += ("\tBG2FG\t"); //game.copyBuffer(); break; case 0x37: // Copy screen to game buffer { ushort left = grvReader.ReadUInt16(), top = grvReader.ReadUInt16(), right = grvReader.ReadUInt16(), bottom = grvReader.ReadUInt16(); genASM += ("\tREC2BG\t" + left + ", " + top + ", " + right + ", " + bottom); } break; case 0x09: // Play VDX { genASM += ("\tPVDX\t" + ReadFileRef()); } break; case 0x1C: { // Play VDX - 2nd type (simple) genASM += ("\tPVDX2\t" + ReadFileRef()); } break; case 0x26: //throw new Exception("Other awkward - library book tripped?"); //Console.WriteLine("Op26"); //return false; { genASM += "\tPVDXSTR\t" + readAwk2(); break; } //// Load a GJD here somewhere as well case 0x27: // Turns on bit 2 of bitflags (and bit 3 if firstbit is set). VDX file name (in a .gjd) follows: find it, then play it { //Console.WriteLine("Op27"); //return false; genASM += "\tPVDXSTR2\t" + readAwk2() + "\t;Same as PVDXSTR but set BF1 and optionally BF2"; } break; #endregion case 0x14: // Random number generation { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tRAND\t0x" + Convert.ToString(offset, 16) + ", " + grvReader.ReadByte()); } break; case 0x15: // Jump { ushort jump = grvReader.ReadUInt16(); scriptJumps.Add(jump); genASM += ("\tJMP\tloc_" + jump); } break; case 0x16: // Reads a string into the script variable specified in the first 2 (or 1) bytes { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tMOVS\tvar[0x" + Convert.ToString(offset, 16)) + "...] = "; string tmp = ""; do { tmp += readScriptChar(true, true, true) + ", "; grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current); } while ((grvReader.ReadByte() & 0x80) == 0); genASM += tmp.Substring(0, tmp.Length - 2); } break; case 0x17: // Return from CALL //vars[0x102] = stream.ReadByte(); genASM += ("\tRET\t" + grvReader.ReadByte()); //stream.BaseStream.Seek(callStack.Pop(), SeekOrigin.Begin); break; case 0x18: // CALL { //callStack.Push(stream.BaseStream.Position + 2); ushort offset = grvReader.ReadUInt16(); //stream.BaseStream.Seek(offset, SeekOrigin.Begin); scriptJumps.Add(offset); genASM += ("\tCALL\tloc_" + offset); } break; case 0x19: // Sleep //System.Console.WriteLine("Slept for a little bit"); //System.Threading.Thread.Sleep(stream.ReadUInt16() * 3); genASM += ("\tSLEEP\t" + grvReader.ReadUInt16()); break; #region String compare + jump (op 1A and 23) case 0x1A: case 0x23: { // Get var location ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } string l = ", 0x" + System.Convert.ToString(offset, 16); // JE or JNE? if (op == 0x1A) { genASM += ("\tJNE\tloc_"); } else { genASM += ("\tJE\tloc_"); } byte t; do { // Read byte l += ", " + readAwk1(); // Break when needed //offset++; grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current); t = grvReader.ReadByte(); //l += ", " + (t & 0x7f); } while ((t & 0x80) != 0x80); offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += (offset + l); } break; #endregion case 0x1B: // XOR { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tXOR\t0x" + Convert.ToString(offset, 16)); byte t; do { t = grvReader.ReadByte(); t &= 0x4F; genASM += (", " + t); grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current); t = grvReader.ReadByte(); } while ((t & 0x80) == 0); genASM += ("\t;XOR variables starting at offset, with each extra parameter"); } break; case 0x1D: // Swap to variables { ushort offa, offb; if (firstBit) { offa = grvReader.ReadByte(); } else { offa = grvReader.ReadUInt16(); } offb = grvReader.ReadUInt16(); genASM += ("\tSWAP\t0x" + Convert.ToString(offa, 16) + ", 0x" + Convert.ToString(offb, 16)); } break; case 0x1F: // INC if (firstBit) { genASM += ("\tINC\t0x" + Convert.ToString(grvReader.ReadByte(), 16)); } else { genASM += ("\tINC\t0x" + Convert.ToString(grvReader.ReadUInt16(), 16)); } break; case 0x20: // DEC if (firstBit) { genASM += ("\tDEC\t0x" + Convert.ToString(grvReader.ReadByte(), 16)); } else { genASM += ("\tDEC\t0x" + Convert.ToString(grvReader.ReadUInt16(), 16)); } break; case 0x21: { // call something if (firstBit) { genASM += "\tSTRCMPJNE\t" + grvReader.ReadByte(); } else { genASM += "\tSTRCMPJNE\t" + grvReader.ReadUInt16(); } genASM += ", " + readAwk2(); uint jmp = grvReader.ReadUInt16(); genASM += " loc_" + jmp; scriptJumps.Add(jmp); // ushort offset = 0; /* = (ushort)functionCall();*/ // if (offset > 0x09) // { // offset -= 7; // } // // loc_4031CF // offset = vars[offset + 0x19]; // byte match = 1, x, y, z; // // loc_4031F6 // do // { // x = vars[offset]; // y = awkward1(); // offset++; // if (x != y) // match = 0; // // loc_403237 // stream.BaseStream.Seek(-1, SeekOrigin.Current); // z = stream.ReadByte(); // } while ((z & 0x80) == 0); // offset = stream.ReadUInt16(); // if (match == 0) // stream.BaseStream.Seek(offset, SeekOrigin.Begin); //} //throw new Exception("Unknown param awk call"); } break; case 0x33: // Copy string into arg1 { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += "\tLOADSTR\t0x" + Convert.ToString(offset, 16); do { genASM += ", " + readAwk1(); grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current); } while ((grvReader.ReadByte() & 0x80) == 0); genASM += "\t\t;Load string into variable located by [\'var[param1]-0x31\'] "; break; //ushort offset; //if (firstBit) // offset = stream.ReadByte(); //else // offset = stream.ReadUInt16(); //offset = vars[offset]; //offset -= 0x31; //// loc_403678 //byte b; //do //{ // b = awkward1(); // vars[offset] = b;//??? // offset++; // vars[vars[offset++]] = (byte)(b & 0x7f); // stream.BaseStream.Seek(-1, SeekOrigin.Current); // b = stream.ReadByte(); //} while ((b & 0x80) == 0); } case 0x3A: // "Print" string? { genASM += "\tPRINT\t"; if (!t7g) { genASM += grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16() + ", "; genASM += grvReader.ReadByte() + ", " + grvReader.ReadByte() + ", " + grvReader.ReadByte() + ", "; } string l = ""; bool done = false; do { l += readAwk1() + ", "; if (t7g && (grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current) > 0 && (grvReader.ReadByte() & 0x80) != 0)) { done = true; } else if (!t7g && (grvReader.PeekChar() == 0)) { grvReader.ReadByte(); done = true; } } while (!done); genASM += l.Substring(0, l.Length - 2); break; } case 0x36: case 0x34: // Check stream of characters - var[off] < b or var[offset] > b { ushort offset; if (op == 0x34) { genASM += ("\tJG\tloc_"); } else { genASM += ("\tJL\tloc_"); } if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } string l = ", 0x" + Convert.ToString(offset, 16); do { l += ", " + readAwk1(); grvReader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current); } while ((grvReader.ReadByte() & 0x80) == 0); offset = grvReader.ReadUInt16(); scriptJumps.Add(offset); genASM += (offset + l); //Console.WriteLine("Unimplemented 36/34"); //return false; //ushort offset; //if (firstBit) // offset = stream.ReadByte(); //else // offset = stream.ReadUInt16(); //// Check stream to see if equal var[offset] //byte b; //byte match = 0; //if (op == 0x34) //{ // do // { // b = awkward1(); // if (vars[offset] > b) // match = 1; // //offset++; // stream.BaseStream.Seek(-1, SeekOrigin.Current); // b = stream.ReadByte(); // // Keep looping till end of string // } while ((b & 0x80) == 0); //} //else //{ // do // { // b = awkward1(); // if (vars[offset] < (b & 0x7F)) // match = 1; // offset++; // stream.BaseStream.Seek(-1, SeekOrigin.Current); // b = stream.ReadByte(); // // Keep looping till end of string // } while ((b & 0x80) == 0); //} //offset = stream.ReadUInt16(); //if (match == 1) //{ // stream.BaseStream.Seek(offset, SeekOrigin.Begin); //} } break; case 0x24: // MOV { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tMOV\t0x" + Convert.ToString(offset, 16) + ", " + grvReader.ReadUInt16()); } break; case 0x25: // ADD { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tADD\t0x" + Convert.ToString(offset, 16) + ", " + grvReader.ReadUInt16()); } break; case 0x29: // Stop MIDI genASM += ("\tSMID\t\t;Stop midi"); break; case 0x2A: // Close things // Close current GJD // Stop midi // Clear hotspots genASM += ("\tEXIT"); break; case 0x2E: { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tLOAD\t0x" + Convert.ToString(offset, 16)); //BinaryReader save = new BinaryReader(new FileStream(path + "t7g4win.00" + ((vars[offset]).ToString()), FileMode.Open, FileAccess.Read)); //vars = save.ReadBytes(vars.Length); //save.Close(); //Console.WriteLine("Loading game from slot " + (vars[offset].ToString()) + "?"); } break; case 0x2F: { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tSAVE\t0x" + Convert.ToString(offset, 16)); //BinaryWriter save = new BinaryWriter(new FileStream(path + "t7g4win.00" + (vars[offset].ToString()), FileMode.Create, FileAccess.Write)); //save.Write(vars, 0, vars.Length); //save.Close(); //Console.WriteLine("Save game to slot" + (vars[offset].ToString()) + "?"); } break; case 0x31: // Set MIDI volume. { ushort arg1 = grvReader.ReadUInt16(), arg2 = grvReader.ReadUInt16(); genASM += ("\tMIDVOL\t" + arg1 + ", " + arg2); } break; case 0x32: // JNE { ushort arg1; if (firstBit) { arg1 = grvReader.ReadByte(); } else { arg1 = grvReader.ReadUInt16(); } ushort arg2 = grvReader.ReadUInt16(); ushort offset = grvReader.ReadUInt16(); genASM += "\tJNE\tloc_" + offset + ", " + arg1 + ", " + arg2 + "; var[var[arg1] - 0x31] != var[arg2]"; scriptJumps.Add(offset); } break; case 0x38: // Reload stored stack pointer //Console.WriteLine("Reload stored stack pointer - TODO"); genASM += ("\tRLD"); break; case 0x39: // "Obscure" swap { //Console.WriteLine("Unimplemented 39"); //return false; genASM += "\tSWAP\t vars[10*" + readScriptChar(false, true, true) + " + " + readScriptChar(false, true, true) + " + 25]"; genASM += " <=> vars[10*" + readScriptChar(false, true, true) + " + " + readScriptChar(false, true, true) + " + 25] "; /* * * // .text:0040389B * ushort arg1, arg2, arg3; * * arg1 = grvReader.ReadByte(); * genASM += ", " + arg1; * arg1 &= 0x7F; * * if (arg1 == 0x23) * { * arg1 = grvReader.ReadByte(); * genASM += ", " + arg1; * } * // arg1 &= 0x7F; * // arg1 = vars[arg1 - 0x61]; * // arg1 *= 10; * //} * //else * //{ * // arg1 -= 0x30; * // arg1 *= 10; * //} * * arg2 = grvReader.ReadByte(); * arg2 &= 0x7F; * genASM += ", " + arg2; * * if (arg2 == 0x23) * { * arg2 = grvReader.ReadByte(); * genASM += ", " + arg2; * } * // arg2 &= 0x7F; * // arg1 += vars[arg2 - 0x61]; * //} * //else * //{ * // arg1 = vars[arg1 + arg2]; * //} * * //arg1 += 0x19; * * //// .text:0040394D (loc_40393E + 4lines) * * arg3 = grvReader.ReadByte(); * arg3 &= 0x7F; * genASM += ", " + arg3; * * if (arg3 == 0x23) * { * arg3 = grvReader.ReadByte(); * genASM += ", " + arg3; * } * // arg3 &= 0x7F; * // arg3 = vars[arg3 - 0x61]; * // arg3 *= 10; * //} * //else * //{ * // arg3 -= 0x30; * // arg3 *= 10; * //} * * arg2 = grvReader.ReadByte(); * arg2 &= 0x7F; * genASM += ", " + arg2; * * if (arg2 == 0x23) * { * arg2 = grvReader.ReadByte(); * genASM += ", " + arg2; * } * // arg2 &= 0x7F; * // arg3 += vars[arg2 - 0x61]; * //} * //else * //{ * // arg3 = vars[arg3 + arg2]; * //} * * //arg3 += 0x19; * * //// now got an arg1 (varOffset2) and arg3 (var13C) */ //byte tmp; //tmp = vars[arg1]; //vars[arg1] = vars[arg2]; //vars[arg2] = tmp; } break; case 0x3C: // Check valid savegames { genASM += ("\tCSAVE\t\t;Check saves"); } break; case 0x3D: // Reset 0x00 to 0xFF to zero genASM += ("\tCLRVARS"); break; case 0x3E: // MOD { Console.WriteLine("Needs work? to trace?"); ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tMOD\t0x" + Convert.ToString(offset, 16) + ", " + grvReader.ReadByte()); } break; case 0x3F: // Load subscript { genASM += "\tLOADSUB\t"; char t; string ret = ""; while ((t = grvReader.ReadChar()) != 0) { ret += t + ", "; } genASM += ret.Substring(0, ret.Length - 2); break; //Console.WriteLine("Unimplemented 3F"); //return false; //Console.WriteLine("Run a subscript"); //char c; //string f = ""; //do //{ // //t = stream.ReadByte(); // c = (char)stream.ReadByte(); // if (c != 0) // f += c;// t.ToString(); //} while (c != 0); //sub = new Groovie(f, game); //sub.passParams(ref vars, music, ref flags, vdx); } case 0x40: // Two params for VDX player { genASM += "\tSETCOORD\t" + grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16() + "\t;Set video start @ arg1,arg2"; //flags |= bitFlags.Bit7; //ushort arg1 = stream.ReadUInt16(); //if (arg1 > 0x7FFF) //{ // /* // * .text:00403E62 154 mov ecx, arg1 // .text:00403E68 154 sub ecx, 10000h ; Integer Subtraction // .text:00403E6E 154 mov arg1, ecx // */ //} //stream.ReadUInt16(); //// Same for arg2 //throw new Exception("Two VDX player params"); } break; case 0x41: // SUB { ushort offset; if (firstBit) { offset = grvReader.ReadByte(); } else { offset = grvReader.ReadUInt16(); } genASM += ("\tSUB\t0x" + Convert.ToString(offset, 16) + ", " + grvReader.ReadUInt16()); } break; case 0x42: //throw new Exception("Complicated"); //stream.ReadByte(); //Console.WriteLine("Unimplemented - Othello AI"); //return false; genASM += "\tOTHELLO\t" + grvReader.ReadByte(); break; case 0x43: // Return from subscript //vars[0x102] = stream.ReadByte(); //Console.WriteLine("Unimplemented - ret from script"); // Say we're done in this script :) //return false; genASM += ("\tRETFS\t" + grvReader.ReadByte()); break; case 0x4C: // Save current CD number. 1, 2, -1. { genASM += ("\tCCD"); } break; case 0x4D: // If arg1 == 2, play VIE logo, stop midi, play CD //if (stream.ReadByte() == 2) //{ // // do some other checks on 0x09 flags? // //VDX vdx = new VDX("vielogo", flags, game.GraphicsDevice); // //game.addVDX(vdx); // //vdx.play(); // //while (vdx.playing) // // System.Threading.Thread.Sleep(50); //} //if (music == null) // music = new GrvMusic(game); //music.CD(); genASM += ("\tPCD\t" + grvReader.ReadByte()); break; case 0x51: { UInt16 jmp = grvReader.ReadUInt16(); genASM += ("\tOp51\t" + jmp); scriptJumps.Add(jmp); } break; case 0x52: // Do heap to game area. Arg discarded? o2_copyfgtobg // .text:00403B22 genASM += ("\tCopyFgToBg\t" + grvReader.ReadByte()); break; case 0x53: // Load cursor stuff o_hotspot_outrect genASM += ("\toutrect\t" + grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16() + ", " + grvReader.ReadUInt16()); break; case 0x55: genASM += ("\tSetScriptEnd\t" + grvReader.ReadUInt16()); break; case 0x56: // o2_playsound genASM += ("\tSound\t" + grvReader.ReadUInt32() + ", " + grvReader.ReadByte() + ", " + grvReader.ReadByte()); break; case 0x5A: // o2_preview_loadgame genASM += ("\tPreviewLoadGame\t" + grvReader.ReadByte()); break; default: Console.WriteLine("Invalid opcode at location 0x" + Convert.ToString(grvReader.BaseStream.Position - 1, 16) + ": " + op); return(false); } genASM += ("\n"); return(true); }
private void PreProcess(System.IO.Stream stream) { System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); int address = 0; if (reader.PeekChar() == 65279) // UTF-8 identify char { reader.ReadChar(); } List <string> labelNames = PreProcessLabels(stream); reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); while (reader.BaseStream.Length != reader.BaseStream.Position) { #region Init, Process comments, labels, reserve if (reader.PeekChar() == 65279) // UTF-8 identify char { reader.ReadChar(); } string instruction = ""; SkipSpaces(stream); if (reader.BaseStream.Length == reader.BaseStream.Position) { break; } if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { while (char.IsLetterOrDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == ':' || (char)reader.PeekChar() == '_') { instruction += reader.ReadChar(); } } if (skipComments(reader)) { continue; } if (instruction.EndsWith(":")) { string label = instruction.Substring(0, instruction.Length - 1); if (!instructions.ContainsKey(label) && !constants.ContainsKey(label) && !registers.ContainsKey(label)) { labels.Add(label, address); } else { throw new Exception("This word is reserved!"); } continue; } #region Reserve if (instruction.ToLower() == "reserve") { SkipSpaces(stream); int size; if (!readIntValue(stream, reader, out size)) { throw new Exception("Expected size!"); } SkipSpaces(stream); if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } else { throw new Exception("Expected ','!"); } SkipSpaces(stream); int mult = 0; if (!readIntValue(stream, reader, out mult)) { throw new Exception("Expected multiplier!"); } address += size * mult; continue; } #endregion #region ConstToMemory if (instruction.ToLower() == "memory") { int size; do { size = 0; if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } SkipSpaces(stream); if ((char)reader.PeekChar() == '[') { reader.ReadChar(); readIntValue(stream, reader, out size); if ((char)reader.PeekChar() == ']') { reader.ReadChar(); } else { throw new Exception("Expected ']'"); } } SkipSpaces(stream); if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { string reg = readIdentifier(stream, reader); if (constants.ContainsKey(reg)) { address += 4; } else if (labels.ContainsKey(reg)) { address += 4; } else { throw new Exception("Identifier not found!"); } } if (char.IsDigit((char)reader.PeekChar())) { int val = readIntLiteral(stream, reader); if (((val < byte.MaxValue && val > sbyte.MinValue) && size == 0) || size == 1) { address += 1; } else if (((val < ushort.MaxValue && val > short.MinValue) && size == 0) || size == 2) { address += 2; } else if (((val < int.MaxValue && val > int.MinValue) && size == 0) || size == 4) { address += 4; } else { throw new Exception("Too big number!"); } } if ((char)reader.PeekChar() == '"') { string lit = readStringLiteral(stream, reader); byte[] bytes = Encoding.ASCII.GetBytes(lit); address += bytes.Length; } if ((char)reader.PeekChar() == '\'') { char lit = readCharLiteral(stream, reader); byte[] bytes = Encoding.ASCII.GetBytes("" + lit); address += bytes.Length; } SkipSpaces(stream); }while ((char)reader.PeekChar() == ','); continue; } #endregion #endregion #region Read parameters AssemblerOpcodeSet opcodes = instructions[instruction.ToLower()]; // get opcode from instruction List <int> args = new List <int>(); List <AssemblerParameters> _params = new List <AssemblerParameters>(); int parnum = 4; if (opcodes.Count == 1) { parnum = instructionSetProvider.InstructionSet[opcodes.Opcodes[0]].ParametersCount; } for (int i = 0; i < parnum; i++) { SkipSpaces(stream); bool pointer = false; if ((char)reader.PeekChar() == '[') { pointer = true; reader.ReadChar(); } if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { // parameter is register/const string reg = readIdentifier(stream, reader); PointerType?pointerType = pointer ? pointerType = PointerType.Bit8 : null; if (!pointer && reg.ToLower() == "byte" || reg.ToLower() == "word" || reg.ToLower() == "dword" || reg.ToLower() == "addr" || reg.ToLower() == "qword") { SkipSpaces(stream); if ((char)reader.PeekChar() == '[') { pointer = true; reader.ReadChar(); } if (pointer) { reg = readIdentifier(stream, reader); } } if (constants.ContainsKey(reg)) { args.Add(constants[reg]); _params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Value); } else if (labelNames.Contains(reg)) { args.Add(int.MaxValue); _params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Address); } else if (registers.ContainsKey(reg)) { args.Add(registers[reg.ToLower()].Item1); _params.Add(pointer ? AssemblerParameters.PointerInRegister : AssemblerParameters.Register); } else { throw new Exception("Undefined identifier: " + reg); } } else if (char.IsDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == '-') { // parameter is value/number args.Add(readIntLiteral(stream, reader)); _params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Value); } if (pointer) { if ((char)reader.PeekChar() == ']') { reader.ReadChar(); } else { throw new Exception("Expected ']'!"); } } SkipSpaces(stream); if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } else { break; } } #endregion #region Memory usage calculating byte opcode = opcodes.Find(_params.ToArray()); AssemblerInstruction asm = InstructionSetProvider.InstructionSet[opcode]; //byte paramstypes = 0; //writer.Write(opcode); address += 1; //writer.Write(paramstypes); address += 1; //for (int i = 0; i < args.Count; i++) //{ // if (_params[i] == AssemblerParameters.Register) // { // paramstypes |= (byte)(0x00 << (i * 2)); // } // else if ((_params[i] & AssemblerParameters.Value) != 0) // { // if ((_params[i] & AssemblerParameters.Pointer) != 0) // Address // { // paramstypes |= (byte)(0x02 << (i * 2)); // } // else // { // if (args[i] < byte.MaxValue) // paramstypes |= (byte)(0x00 << (i * 2)); // else if (args[i] < short.MaxValue) // paramstypes |= (byte)(0x01 << (i * 2)); // else // paramstypes |= (byte)(0x02 << (i * 2)); // } // } // else if ((_params[i] & AssemblerParameters.Pointer) != 0) // { // if ((_params[i] & AssemblerParameters.Register) != 0) // paramstypes |= (byte)(0x01 << (i * 2)); // else // paramstypes |= (byte)(0x00 << (i * 2)); // } //} for (int i = 0; i < args.Count; i++) { if (_params[i] == AssemblerParameters.Register) { address += 1; } else if ((_params[i] & AssemblerParameters.Value) != 0) { if ((_params[i] & AssemblerParameters.Pointer) != 0) // Address { address += 4; } else { if (args[i] < byte.MaxValue && args[i] > sbyte.MinValue) { address += 1; } else if (args[i] < ushort.MaxValue && args[i] > short.MinValue) { address += 2; } else { address += 4; } } } else if ((_params[i] & AssemblerParameters.Pointer) != 0) { if ((_params[i] & AssemblerParameters.Register) != 0) { address += 1; } else { address += 4; } } } #endregion } stream.Seek(0, System.IO.SeekOrigin.Begin); }
public byte[] Compile(System.IO.Stream stream) { System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); System.IO.MemoryStream buffer = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(buffer); line = 1; int address = 0; PreProcess(stream); while (reader.BaseStream.Length != reader.BaseStream.Position) { if (reader.PeekChar() == 65279) // UTF-8 identify char { reader.ReadChar(); } string instruction = ""; SkipSpaces(stream); if (reader.BaseStream.Length == reader.BaseStream.Position) { break; } if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { while (char.IsLetterOrDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == ':' || (char)reader.PeekChar() == '_') { instruction += reader.ReadChar(); } } if (skipComments(reader)) // skip comments { continue; } if (instruction.EndsWith(":")) // check if a label { continue; } #region Reserve if (instruction.ToLower() == "reserve") { SkipSpaces(stream); int size; if (!readIntValue(stream, reader, out size)) { throw new Exception("Expected size!"); } SkipSpaces(stream); if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } else { throw new Exception("Expected ','!"); } SkipSpaces(stream); int mult = 0; if (!readIntValue(stream, reader, out mult)) { throw new Exception("Expected multiplier!"); } writer.Write(new byte[size * mult], 0, size * mult); address += size * mult; continue; } #endregion #region ConstToMemory if (instruction.ToLower() == "memory") { int size = 0; do { size = 0; if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } SkipSpaces(stream); if ((char)reader.PeekChar() == '[') { reader.ReadChar(); readIntValue(stream, reader, out size); if ((char)reader.PeekChar() == ']') { reader.ReadChar(); } else { throw new Exception("Expected ']'"); } } SkipSpaces(stream); if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { string reg = readIdentifier(stream, reader); if (constants.ContainsKey(reg)) { writer.Write(constants[reg]); address += 4; } else if (labels.ContainsKey(reg)) { writer.Write(labels[reg]); address += 4; } else { throw new Exception("Identifier not found!"); } } if (char.IsDigit((char)reader.PeekChar())) { int val = readIntLiteral(stream, reader); if (((val < byte.MaxValue && val > sbyte.MinValue) && size == 0) || size == 1) { writer.Write((byte)val); address += 1; } else if (((val < ushort.MaxValue && val > short.MinValue) && size == 0) || size == 2) { writer.Write((short)val); address += 2; } else if (((val < int.MaxValue && val > int.MinValue) && size == 0) || size == 4) { writer.Write(val); address += 4; } else { throw new Exception("Too big number!"); } } if ((char)reader.PeekChar() == '"') { string lit = readStringLiteral(stream, reader); byte[] bytes = ASCIIEncoding.ASCII.GetBytes(lit); writer.Write(bytes, 0, bytes.Length); address += bytes.Length; } if ((char)reader.PeekChar() == '\'') { char lit = readCharLiteral(stream, reader); byte[] bytes = ASCIIEncoding.ASCII.GetBytes("" + lit); writer.Write(bytes, 0, bytes.Length); address += bytes.Length; } SkipSpaces(stream); }while ((char)reader.PeekChar() == ','); continue; } #endregion AssemblerOpcodeSet opcodes = instructions[instruction.ToLower()]; // get opcode from instruction List <AssemblerParameterValue> args = new List <AssemblerParameterValue>(); List <AssemblerParameters> @params = new List <AssemblerParameters>(); int parnum = 4; if (opcodes.Count == 1) { parnum = instructionSetProvider.InstructionSet[opcodes.Opcodes[0]].ParametersCount; } for (int i = 0; i < parnum; i++) { SkipSpaces(stream); bool pointer = false; if ((char)reader.PeekChar() == '[') { pointer = true; reader.ReadChar(); } if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_' || (char)reader.PeekChar() == '[') { // parameter is register/const string reg = readIdentifier(stream, reader); PointerType?pointerType = pointer ? pointerType = PointerType.Bit8 : null; if (!pointer && reg.ToLower() == "byte" || reg.ToLower() == "word" || reg.ToLower() == "dword" || reg.ToLower() == "addr" || reg.ToLower() == "qword") { SkipSpaces(stream); if ((char)reader.PeekChar() == '[') { pointer = true; reader.ReadChar(); } if (pointer) { if (reg.ToLower() == "byte") { pointerType = PointerType.Bit8; } else if (reg.ToLower() == "word") { pointerType = PointerType.Bit16; } else if (reg.ToLower() == "dword" || reg.ToLower() == "addr") { pointerType = PointerType.Bit32; } else if (reg.ToLower() == "qword") { pointerType = PointerType.Bit64; } reg = readIdentifier(stream, reader); } } if (constants.ContainsKey(reg)) { args.Add(new AssemblerParameterValue(constants[reg], pointerType, null)); @params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Value); } else if (labels.ContainsKey(reg)) { args.Add(new AssemblerParameterValue(labels[reg], pointerType, null)); @params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Address); } else if (registers.ContainsKey(reg)) { args.Add(new AssemblerParameterValue(registers[reg.ToLower()].Item1, pointerType, registers[reg.ToLower()].Item2)); @params.Add(pointer ? AssemblerParameters.PointerInRegister : AssemblerParameters.Register); } else { throw new Exception("Undefined identifier: " + reg); } } else if (char.IsDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == '-') { // parameter is value/number args.Add(readIntLiteral(stream, reader)); @params.Add(pointer ? AssemblerParameters.Pointer : AssemblerParameters.Value); } if (pointer) { if ((char)reader.PeekChar() == ']') { reader.ReadChar(); } else { throw new Exception("Expected ']'!"); } } SkipSpaces(stream); if ((char)reader.PeekChar() == ',') { reader.ReadChar(); } else { break; } } byte opcode = opcodes.Find(@params.ToArray()); AssemblerInstruction asm = instructionSetProvider.InstructionSet[opcode]; byte paramstypes = EncodeParamsTypes(args, @params); int startaddress = address; writer.Write(opcode); address += 1; writer.Write(paramstypes); address += 1; for (int i = 0; i < args.Count; i++) { if (@params[i] == AssemblerParameters.Register) { writer.Write((byte)args[i].Value); address += 1; } else if ((@params[i] & AssemblerParameters.Value) != 0) { int arg = args[i].Value; if ((@params[i] & AssemblerParameters.Pointer) != 0) // Address { address += 4; if (asm.ConvertLabelsToOffsets) { writer.Write(arg - address); } else { writer.Write(arg); } } else { if (arg < byte.MaxValue && arg > sbyte.MinValue) { writer.Write((byte)arg); address += 1; } else if (arg < ushort.MaxValue && arg > short.MinValue) { writer.Write((short)arg); address += 2; } else { writer.Write(arg); address += 4; } } } else if ((@params[i] & AssemblerParameters.Pointer) != 0) { if ((@params[i] & AssemblerParameters.Register) != 0) { writer.Write((byte)args[i].Value); address += 1; } else { writer.Write(args[i].Value); address += 4; } } } } byte[] zero = BitConverter.GetBytes(0); buffer.Write(zero, 0, zero.Length); //instructionSetProvider.Memory.Write(instructionSetProvider.ProgramMemory, buffer.ToArray()); return(buffer.ToArray()); }
private List <string> PreProcessLabels(System.IO.Stream stream) { System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); List <string> labels = new List <string>(); while (reader.BaseStream.Length != reader.BaseStream.Position) { string instruction = ""; SkipSpaces(stream); if (reader.BaseStream.Length == reader.BaseStream.Position) { break; } if (char.IsLetter((char)reader.PeekChar()) || (char)reader.PeekChar() == '_') { while (char.IsLetterOrDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == ':' || (char)reader.PeekChar() == '_') { instruction += reader.ReadChar(); } } while ((char)reader.PeekChar() == ',' || char.IsDigit((char)reader.PeekChar()) || (char)reader.PeekChar() == '[' || (char)reader.PeekChar() == ']' || (char)reader.PeekChar() == '-') { reader.ReadChar(); } if ((char)reader.PeekChar() == '"') { reader.ReadChar(); while (reader.ReadChar() != '"') { ; } } if ((char)reader.PeekChar() == '\'') { reader.ReadChar(); while (reader.ReadChar() != '\'') { ; } } if (skipComments(reader)) { continue; } if (instruction.EndsWith(":")) { string label = instruction.Substring(0, instruction.Length - 1); if (!instructions.ContainsKey(label) && !constants.ContainsKey(label) && !registers.ContainsKey(label)) { labels.Add(label); } else { throw new Exception("This word is reserved!"); } continue; } } return(labels); }
private static void Command(string command, string name, Model.Creature author) { string[] args = command.Split(" ".ToCharArray()); command = args.First(); args = args.Skip(1).ToArray(); var world = gsApi.World; var me = gsApi.World.Me; switch (command) { case "hello": Reply("Hello", name); break; /*case "login": * if (args.Length == 1) * if (Access.LogIn(name, args.First())) * Reply("Accept", name); * else * Reply("Reject", name); * break;*/ case "quit": gsApi.Logout(); break; case "to": case "moveto": { Library.Point?point = null; if (args.Length == 0) { var target = world[me.TargetId] as Model.Creature; if (target != null) { point = target.Position; } } if (args.Length == 1 && author != null) { if (args.First() == "me") { point = author.Position; } else if (args.First() == "my") { point = author.Destination; } } if (point.HasValue) { Manager.Free(MOVE_PROGRAM); gsApi.MoveTo(point.Value); } break; } case "get": case "target": if (args.Length == 1) { switch (args[0]) { case "self": gsApi.Target(me); break; case "me": if (author != null) { gsApi.Target(author); } else { Reply("Can't find", name); } break; case "my": if (author != null) { var target = world[author.TargetId] as Model.Creature; if (target != null) { gsApi.Target(target); break; } } Reply("Can't find", name); break; case "npc": //Живой, для мёртвого можно ввести команду target corpse { Model.Npc nearest = null; var min = double.MaxValue; lock (world) foreach (var obj in world) { var npc = obj as Model.Npc; if (npc != null && !npc.IsAlikeDead) { var distance = me.Distance(npc); if (distance < min) { min = distance; nearest = npc; } } } if (nearest != null) { gsApi.Target(nearest); } break; } default: Model.Character character = world.Find(args[0]); if (character != null) { gsApi.Target(character); } else { Reply("Can't find", name); } break; } } break; case "attack": gsApi.Interact(me.TargetId, null, true); break; case "cancel": gsApi.Cancel(); break; case "up": case "pickup": { /*int count = 0; * * if(args.Length == 1) * int.TryParse(args[0], out count); * * ... * * if (items.Count > 0) * gsApi.Interact(items.First());*/ /* Централизованный подбор предметов: * var items = world * .Where(obj => obj is Model.Item && !((Model.Item)obj).InInventory) * .OrderBy(obj => me.Distance((Model.Item)obj)).ToList();*/ /* Децентрализованный подбор предметов: * Сохраняем count и выполняем подбор ближайшего предмета с count-- пока count > 0 */ Model.Item nearest = null; var min = double.MaxValue; lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && !item.InInventory) { var distance = me.Distance(item); if (distance < min) { min = distance; nearest = item; } } } if (nearest != null) { gsApi.Interact(nearest); } break; } case "skill": case "useskill": int skillId = 0; if (args.Length == 1 && int.TryParse(args[0], out skillId)) { gsApi.UseSkill(skillId, true); } break; case "item": case "useitem": { int itemId = 0; if (args.Length == 1 && int.TryParse(args[0], out itemId)) { lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.ItemId == itemId && item.InInventory) { gsApi.UseItem(item); break; } } } break; } case "items": case "itemlist": lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.InInventory) { Reply(string.Format("[{0}] {1}", item.ItemId, item.Count), name); } } break; case "drop": case "dropitem": { int itemId = 0; int count = 0; if (args.Length > 0) { int.TryParse(args[0], out itemId); } if (args.Length > 1) { int.TryParse(args[1], out count); } if (itemId != 0) { lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.ItemId == itemId && item.InInventory) { gsApi.Drop(item, count); break; } } } break; } case "return": { var point = Lineage.ReturnPoint.Town; if (args.Length == 1) { Enum.TryParse <Lineage.ReturnPoint>(args[0], out point); } gsApi.Return(point); break; } case "info": new Command.Info(gsApi, args, name).Run(); break; case "travel": { if (args.Length == 0) { var program = Manager.Get(MOVE_PROGRAM) as Program.Move.Travel; var distance = program != null ? new Library.Interval(me.Position, program.Model.Waypoints.Last()).Length : 0; Reply(string.Format("{0}", (int)distance), name); } else if (args.Length == 3) { double x, y, z; if (double.TryParse(args[0], out x) && double.TryParse(args[1], out y) && double.TryParse(args[2], out z)) { var program = new Program.Move.Travel(gsApi); program.Start(new Library.Point(x, y, z)); Manager.Load(program, MOVE_PROGRAM); } } break; } case "follow": { var target = world[me.TargetId] as Model.Creature; if (args.Length >= 1 && target != null) { switch (args[0]) { case "fast": { var program = new Program.Move.FastFollow(gsApi); program.Bind(target); Manager.Load(program, MOVE_PROGRAM); break; } case "full": { var program = new Program.Move.FullFollow(gsApi); program.Bind(target); Manager.Load(program, MOVE_PROGRAM); break; } } } break; } case "cross": { int size = 0; if (args.Length == 1 && int.TryParse(args[0], out size)) { var center = me.Position; var program = new Program.Move.SimpleRoute(gsApi); program.Load(new Library.Point[] { new Library.Point(center.X + size, center.Y, center.Z), new Library.Point(center.X, center.Y + size, center.Z), new Library.Point(center.X - size, center.Y, center.Z), new Library.Point(center.X, center.Y - size, center.Z), new Library.Point(center.X + size, center.Y, center.Z), center }); Manager.Load(program, MOVE_PROGRAM); } break; } case "action": { if (args.Length > 0) { switch (args[0]) { case "sit": gsApi.UseUserCommand(Lineage.UserCommand.Sit); break; case "stand": gsApi.UseUserCommand(Lineage.UserCommand.Stand); break; } } break; } case "moving": { if (args.Length > 0 && System.IO.File.Exists(args[0])) { var parts = new List <List <Library.Point> >(); var reader = new System.IO.BinaryReader( System.IO.File.OpenRead(args[0])); while (reader.PeekChar() != -1) { var points = new List <Library.Point>(); int count = reader.ReadInt32(); for (int i = 0; i < count; i++) { points.Add(new Library.Point( reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32())); } parts.Add(points); } var graph = new Model.Graph(parts); var program = new Program.Move.OnGraph(gsApi); program.Play(graph); Manager.Load(program, MOVE_PROGRAM); } break; } case "autospoil": { throw new NotImplementedException(); break; } case "autosweep": // ToDo: Нуждается в тестировании и отладке { if (args.Length > 0) { var program = new Program.AutoSweep(gsApi); switch (args[0]) { case "my": program.Start(true); break; case "all": program.Start(false); break; } if (program.Enabled) { Manager.Load(program, typeof(Program.AutoSweep).Name); } } else { var program = Manager.Get(typeof(Program.AutoSweep).Name) as Program.AutoSweep; if (program != null) { Reply(string.Format("Enabled ({0})", program.OnlyMy ? "My" : "All"), name); } else { Reply("Disabled", name); } } break; } case "autopickup": { if (args.Length > 0) { var program = new Program.AutoPickup(gsApi); switch (args[0]) { case "my": program.Start(true); break; case "all": program.Start(false); break; } if (program.Enabled) { Manager.Load(program, typeof(Program.AutoPickup).Name); } } else { var program = Manager.Get(typeof(Program.AutoPickup).Name) as Program.AutoPickup; if (program != null) { Reply(string.Format("Enabled ({0})", program.OnlyMy ? "My" : "All"), name); } else { Reply("Disabled", name); } } break; } case "route": { if (args.Length > 0) { switch (args[0]) { case "record": if (args.Length > 1) { switch (args[1]) { case "add": if (RouteRecord != null && author != null) { RouteRecord.Add(author.Position); RouteRecord.Save(); } break; case "del": if (RouteRecord != null) { RouteRecord.Del(); RouteRecord.Save(); } break; case "auto": int period = 1; if (args.Length == 3) { int.TryParse(args[2], out period); } if (RecordTimer != null) { RecordTimer.Close(); } RecordTimer = new System.Timers.Timer(period * 1000); RecordTimer.Elapsed += (object timer, System.Timers.ElapsedEventArgs ea) => { if (RecordLastPos != author.Position) { RecordLastPos = author.Position; RouteRecord.Add(author.Position); RouteRecord.Save(); } }; RecordTimer.Enabled = true; break; case "stop": if (RecordTimer != null) { RecordTimer.Close(); } break; default: //ToDo ../ fix RouteRecord = new FileRoute(new System.IO.FileInfo(string.Format("{0}.route", args[1]))); break; } } break; default: if (args.Length == 1 && !string.IsNullOrEmpty(name = args[0])) //ToDo ../ fix { bool reverse = name.StartsWith("-"); name = (name[0] == '-' || name[0] == '+' ? name.Substring(1) : name); var route = new FileRoute(new System.IO.FileInfo(string.Format("{0}.route", name))); route.Load(); if (route.Count > 0) { var points = !reverse ? route.Points : route.Points.Reverse(); var program = new Program.Move.SimpleRoute(gsApi); program.Load(points); Manager.Load(program, MOVE_PROGRAM); } } break; } } else if (RouteRecord != null) { Reply(string.Format("Count: {0}, Length: {1}", RouteRecord.Count, RouteRecord.Length), name); } break; } default: Reply("Don’t understand", name); break; } }
public void RunProgram(string filename) { ClearRegisters(); byte Magic1; byte Magic2; byte Magic3; lock (b32Screen1) { b32Screen1.Reset(); } System.IO.BinaryReader br; System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); Magic1 = br.ReadByte(); Magic2 = br.ReadByte(); Magic3 = br.ReadByte(); if (Magic1 != 'B' && Magic2 != '3' && Magic3 != '2') { MessageBox.Show("This is not a valid B32 file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StartAddr = br.ReadUInt16(); ExecAddr = br.ReadUInt16(); ushort Counter = 0; while ((br.PeekChar() != -1)) { byte read = br.ReadByte(); B32Memory[(StartAddr + Counter)] = read; memory.ThreadPoke((ushort)(StartAddr + Counter), read); Counter++; } br.Close(); fs.Close(); InstructionPointer = ExecAddr; pauseProgramToolStripMenuItem.Enabled = true; resumeProgramToolStripMenuItem.Enabled = false; //ExecuteProgram(ExecAddr, Counter); //System.Threading.Thread prog = new System.Threading.Thread(delegate() { ExecuteProgram(ExecAddr, Counter); }); prog = new System.Threading.Thread(delegate() { ExecuteProgram(ExecAddr, Counter); }); PauseEvent = new System.Threading.ManualResetEvent(true); prog.Start(); }
private void openToolStripMenuItem_Click(object sender, System.EventArgs e) { byte Magic1; byte Magic2; byte Magic3; DialogResult dr; dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.Cancel) return; lock (reallySimpleScreen1) { reallySimpleScreen1.Reset(); } System.IO.BinaryReader br; System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); Magic1 = br.ReadByte(); Magic2 = br.ReadByte(); Magic3 = br.ReadByte(); if (Magic1 != 'B' && Magic2 != '3' && Magic3 != '2') { MessageBox.Show("This is not a valid B32 file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StartAddr = br.ReadUInt16(); ExecAddr = br.ReadUInt16(); ushort Counter = 0; while ((br.PeekChar() != -1)) { ReallySimpleMemory[(StartAddr + Counter)] = br.ReadByte(); Counter++; } br.Close(); fs.Close(); InstructionPointer = ExecAddr; //ExecuteProgram(ExecAddr, Counter); programThread = new Thread(delegate () { ExecuteProgram(ExecAddr, Counter); }); PauseEvent = new ManualResetEvent(true); programThread.Start(); }
private void readGameData() { textBox2.Text = path; if (roq != null) roq.stop(); roq = null; if (vdx != null) vdx.stop(); vdx = null; switch (game) { case GameID.T7G: lblGame.Text = "The 7th Guest"; System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(path); System.IO.FileInfo[] files = DI.GetFiles("*.rl"); this.gjdChooser.Items.Clear(); foreach (System.IO.FileInfo rl in files) { this.gjdChooser.Items.Add(rl.Name); } break; case GameID.T11H: lblGame.Text = "The 11th Hour"; //ROQ roq = new ROQ(new System.IO.BinaryReader(new System.IO.FileStream(path + "\\media\\final_hr.rol", System.IO.FileMode.Open))); this.gjdChooser.Items.Clear(); System.IO.BinaryReader idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\gjd.gjd", System.IO.FileMode.Open)); string name = ""; while (idx.BaseStream.Position < idx.BaseStream.Length) { if (idx.PeekChar() == 0x0A) { idx.ReadChar(); if (name.Length > 0) this.gjdChooser.Items.Add(name.Substring(0, name.IndexOf(" "))); name = ""; } else name += "" + idx.ReadChar(); } idx.Close(); V2_RL = new List<GJD.RLData>[this.gjdChooser.Items.Count]; for (int i = 0; i < V2_RL.Length; i++) V2_RL[i] = new List<GJD.RLData>(); this.gjdChooser.Items.Add("Icons"); idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\dir.rl", System.IO.FileMode.Open)); uint ctr = 0; while (idx.BaseStream.Position < idx.BaseStream.Length) { // Get RL content GJD.RLData rl = new GJD.RLData(); idx.ReadUInt32(); rl.offset = idx.ReadUInt32(); rl.length = idx.ReadUInt32(); rl.number = ctr; ctr++; ushort target = idx.ReadUInt16(); byte[] filename; filename = idx.ReadBytes(12); rl.filename = System.Text.Encoding.ASCII.GetString(filename).Trim(); idx.ReadBytes(6); V2_RL[target].Add(rl); } break; default: lblGame.Text = "None"; break; } }
/// <summary> /// Attempts to read the binary file header at the current position of the reader, the header is determined to be persent by 'peeking' and if present and thus determines if the file is Binary or Ascii in the process. /// If the file header has already been read then this function will not read anything /// </summary> void ReadBinaryFileIdentifier() { if (m_FileIdentifier != null) { return; } //If the next character in the stream is not '#' then this is not a binary format if (m_Reader.PeekChar() != RtpDumpExtensions.Hash) { m_Format = FileFormat.Text; return; } //Todo use the EncodingExtensions class //////Progress past the FileHeader should be #!rtpplay1.0 and IP/Port\n m_FileIdentifier = Common.Extensions.Stream.StreamExtensions.ReadDelimitedValue(m_Reader.BaseStream); //Get the length of the file header int length = m_FileIdentifier.Length; //strict /.. //Check for Hash, Bang? someone might have wrote something else... //Check for rtpplay //byte[] rtpPlay = Encoding.ASCII.GetBytes(RtpPlay.RtpPlayFormat); //after Hash and Bang int start = RtpPlay.RtpPlayBinaryIndex, count = RtpPlay.RtpPlayFormatLength; if (length < count) { goto Invalid; } //Look for rtpPlay at those precalculated index's //Utility.ContainsBytes(m_FileHeader, ref start, ref count, rtpPlay, 0, RtpPlay.RtpPlayFormatLength); //rtpplay is not present or if the format was unknown then if (!m_FileIdentifier.Skip(start).Take(count).SequenceEqual(Encoding.ASCII.GetBytes(RtpPlay.RtpPlayFormat)) || Array.IndexOf <byte>(m_FileIdentifier, 0x2f, start + count, m_FileIdentifier.Length - (start + count)) == -1) // start == -1 { goto Invalid; } //Version... // check for an address and port in ASCII delimited by `/`, 22 comes from //255.255.255.255/65535\n // ^ //if (Array.LastIndexOf<byte>(m_FileHeader, 0x2f, 22, 22) == -1) goto Invalid; //Binary type header, maybe header only if (m_Format == FileFormat.Unknown) { m_Format = FileFormat.Binary; } //No problems return; Invalid: Media.Common.TaggedExceptionExtensions.RaiseTaggedException(this, "Binary header is invalid."); }
private static void Command(string command, string name, Model.Creature author) { string[] args = command.Split(" ".ToCharArray()); command = args.First(); args = args.Skip(1).ToArray(); var world = gsApi.World; var me = gsApi.World.Me; switch (command) { case "hello": Reply("Hello", name); break; /*case "login": if (args.Length == 1) if (Access.LogIn(name, args.First())) Reply("Accept", name); else Reply("Reject", name); break;*/ case "quit": gsApi.Logout(); break; case "to": case "moveto": { Library.Point? point = null; if (args.Length == 0) { var target = world[me.TargetId] as Model.Creature; if (target != null) point = target.Position; } if (args.Length == 1 && author != null) if (args.First() == "me") point = author.Position; else if (args.First() == "my") point = author.Destination; if (point.HasValue) { Manager.Free(MOVE_PROGRAM); gsApi.MoveTo(point.Value); } break; } case "get": case "target": if (args.Length == 1) switch (args[0]) { case "self": gsApi.Target(me); break; case "me": if (author != null) gsApi.Target(author); else Reply("Can't find", name); break; case "my": if (author != null) { var target = world[author.TargetId] as Model.Creature; if (target != null) { gsApi.Target(target); break; } } Reply("Can't find", name); break; case "npc": //Живой, для мёртвого можно ввести команду target corpse { Model.Npc nearest = null; var min = double.MaxValue; lock(world) foreach (var obj in world) { var npc = obj as Model.Npc; if (npc != null && !npc.IsAlikeDead) { var distance = me.Distance(npc); if (distance < min) { min = distance; nearest = npc; } } } if (nearest != null) gsApi.Target(nearest); break; } default: Model.Character character = world.Find(args[0]); if (character != null) gsApi.Target(character); else Reply("Can't find", name); break; } break; case "attack": gsApi.Interact(me.TargetId, null, true); break; case "cancel": gsApi.Cancel(); break; case "up": case "pickup": { /*int count = 0; if(args.Length == 1) int.TryParse(args[0], out count); ... if (items.Count > 0) gsApi.Interact(items.First());*/ /* Централизованный подбор предметов: var items = world .Where(obj => obj is Model.Item && !((Model.Item)obj).InInventory) .OrderBy(obj => me.Distance((Model.Item)obj)).ToList();*/ /* Децентрализованный подбор предметов: * Сохраняем count и выполняем подбор ближайшего предмета с count-- пока count > 0 */ Model.Item nearest = null; var min = double.MaxValue; lock(world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && !item.InInventory) { var distance = me.Distance(item); if (distance < min) { min = distance; nearest = item; } } } if (nearest != null) gsApi.Interact(nearest); break; } case "skill": case "useskill": int skillId = 0; if (args.Length == 1 && int.TryParse(args[0], out skillId)) gsApi.UseSkill(skillId, true); break; case "item": case "useitem": { int itemId = 0; if (args.Length == 1 && int.TryParse(args[0], out itemId)) lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.ItemId == itemId && item.InInventory) { gsApi.UseItem(item); break; } } break; } case "items": case "itemlist": lock(world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.InInventory) Reply(string.Format("[{0}] {1}", item.ItemId, item.Count), name); } break; case "drop": case "dropitem": { int itemId = 0; int count = 0; if (args.Length > 0) int.TryParse(args[0], out itemId); if (args.Length > 1) int.TryParse(args[1], out count); if (itemId != 0) { lock (world) foreach (var obj in world) { var item = obj as Model.Item; if (item != null && item.ItemId == itemId && item.InInventory) { gsApi.Drop(item, count); break; } } } break; } case "return": { var point = Lineage.ReturnPoint.Town; if (args.Length == 1) Enum.TryParse<Lineage.ReturnPoint>(args[0], out point); gsApi.Return(point); break; } case "info": new Command.Info(gsApi, args, name).Run(); break; case "travel": { if (args.Length == 0) { var program = Manager.Get(MOVE_PROGRAM) as Program.Move.Travel; var distance = program != null ? new Library.Interval(me.Position, program.Model.Waypoints.Last()).Length : 0; Reply(string.Format("{0}", (int)distance), name); } else if (args.Length == 3) { double x, y, z; if (double.TryParse(args[0], out x) && double.TryParse(args[1], out y) && double.TryParse(args[2], out z)) { var program = new Program.Move.Travel(gsApi); program.Start(new Library.Point(x, y, z)); Manager.Load(program, MOVE_PROGRAM); } } break; } case "follow": { var target = world[me.TargetId] as Model.Creature; if (args.Length >= 1 && target != null) switch (args[0]) { case "fast": { var program = new Program.Move.FastFollow(gsApi); program.Bind(target); Manager.Load(program, MOVE_PROGRAM); break; } case "full": { var program = new Program.Move.FullFollow(gsApi); program.Bind(target); Manager.Load(program, MOVE_PROGRAM); break; } } break; } case "cross": { int size = 0; if (args.Length == 1 && int.TryParse(args[0], out size)) { var center = me.Position; var program = new Program.Move.SimpleRoute(gsApi); program.Load(new Library.Point[] { new Library.Point(center.X + size, center.Y, center.Z), new Library.Point(center.X, center.Y + size, center.Z), new Library.Point(center.X - size, center.Y, center.Z), new Library.Point(center.X, center.Y - size, center.Z), new Library.Point(center.X + size, center.Y, center.Z), center }); Manager.Load(program, MOVE_PROGRAM); } break; } case "action": { if (args.Length > 0) switch (args[0]) { case "sit": gsApi.UseUserCommand(Lineage.UserCommand.Sit); break; case "stand": gsApi.UseUserCommand(Lineage.UserCommand.Stand); break; } break; } case "moving": { if(args.Length > 0 && System.IO.File.Exists(args[0])) { var parts = new List<List<Library.Point>>(); var reader = new System.IO.BinaryReader( System.IO.File.OpenRead(args[0])); while (reader.PeekChar() != -1) { var points = new List<Library.Point>(); int count = reader.ReadInt32(); for (int i = 0; i < count; i++) points.Add(new Library.Point( reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32())); parts.Add(points); } var graph = new Model.Graph(parts); var program = new Program.Move.OnGraph(gsApi); program.Play(graph); Manager.Load(program, MOVE_PROGRAM); } break; } case "autospoil": { throw new NotImplementedException(); break; } case "autosweep": // ToDo: Нуждается в тестировании и отладке { if (args.Length > 0) { var program = new Program.AutoSweep(gsApi); switch (args[0]) { case "my": program.Start(true); break; case "all": program.Start(false); break; } if (program.Enabled) Manager.Load(program, typeof(Program.AutoSweep).Name); } else { var program = Manager.Get(typeof(Program.AutoSweep).Name) as Program.AutoSweep; if (program != null) Reply(string.Format("Enabled ({0})", program.OnlyMy ? "My" : "All"), name); else Reply("Disabled", name); } break; } case "autopickup": { if (args.Length > 0) { var program = new Program.AutoPickup(gsApi); switch (args[0]) { case "my": program.Start(true); break; case "all": program.Start(false); break; } if (program.Enabled) Manager.Load(program, typeof(Program.AutoPickup).Name); } else { var program = Manager.Get(typeof(Program.AutoPickup).Name) as Program.AutoPickup; if (program != null) Reply(string.Format("Enabled ({0})", program.OnlyMy ? "My" : "All"), name); else Reply("Disabled", name); } break; } case "route": { if (args.Length > 0) switch(args[0]) { case "record": if(args.Length > 1) switch (args[1]) { case "add": if (RouteRecord != null && author != null) { RouteRecord.Add(author.Position); RouteRecord.Save(); } break; case "del": if (RouteRecord != null) { RouteRecord.Del(); RouteRecord.Save(); } break; case "auto": int period = 1; if (args.Length == 3) int.TryParse(args[2], out period); if (RecordTimer != null) RecordTimer.Close(); RecordTimer = new System.Timers.Timer(period * 1000); RecordTimer.Elapsed += (object timer, System.Timers.ElapsedEventArgs ea) => { if (RecordLastPos != author.Position) { RecordLastPos = author.Position; RouteRecord.Add(author.Position); RouteRecord.Save(); } }; RecordTimer.Enabled = true; break; case "stop": if (RecordTimer != null) RecordTimer.Close(); break; default: //ToDo ../ fix RouteRecord = new FileRoute(new System.IO.FileInfo(string.Format("{0}.route", args[1]))); break; } break; default: if (args.Length == 1 && !string.IsNullOrEmpty(name = args[0])) //ToDo ../ fix { bool reverse = name.StartsWith("-"); name = (name[0] == '-' || name[0] == '+' ? name.Substring(1) : name); var route = new FileRoute(new System.IO.FileInfo(string.Format("{0}.route", name))); route.Load(); if (route.Count > 0) { var points = !reverse ? route.Points : route.Points.Reverse(); var program = new Program.Move.SimpleRoute(gsApi); program.Load(points); Manager.Load(program, MOVE_PROGRAM); } } break; } else if (RouteRecord != null) Reply(string.Format("Count: {0}, Length: {1}", RouteRecord.Count, RouteRecord.Length), name); break; } default: Reply("Don’t understand", name); break; } }