code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
using System; using System.Collections.Generic; using System.Text; using Cores; using System.Data; using System.Data.SqlClient; namespace DAOLayer { public class VeDao { private Connection _conn; public Connection Conn { get { return _conn; } set { _conn = value; } } public VeDao() { Conn = new Connection(); if (Conn.Connect().State == ConnectionState.Closed) { Conn.ConnObj.Open(); } } ~VeDao() { return; } //Phần của Ngọc public DataTable DanhSachVe(int MaKH) { SqlCommand cmd = new SqlCommand("spDanhSachVe", Conn.ConnObj); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MaKH", MaKH); DataTable result = new DataTable("spDanhSachVe"); result.Columns.Add("MaVe", typeof(int)); result.Columns.Add("TenPhim", typeof(string)); result.Columns.Add("NgayChieu", typeof(DateTime)); result.Columns.Add("ThoiGianBD", typeof(string)); result.Columns.Add("TenRap", typeof(string)); result.Columns.Add("TenDay", typeof(string)); result.Columns.Add("ViTri", typeof(int)); SqlDataReader rd = cmd.ExecuteReader(); DataRow rows; while (rd.Read()) { rows = result.NewRow(); rows["MaVe"] = rd.GetInt32(0); rows["TenPhim"] = rd.GetString(1); rows["NgayChieu"] = rd.GetDateTime(2); rows["ThoiGianBD"] = rd.GetString(3); rows["TenRap"] = rd.GetString(4); rows["TenDay"] = rd.GetString(5); rows["ViTri"] = rd.GetInt32(6); result.Rows.Add(rows); } rd.Close(); Conn.Disconnect(); return result; } } }
07hc114
trunk/RapPhimRollRoyce/DAOLayer/VeDao.cs
C#
gpl2
2,082
using System; using System.Collections.Generic; using System.Text; using Cores; using System.Data; using System.Data.SqlClient; namespace DAOLayer { public class DienVienDao { private Connection _conn; public Connection Conn { get { return _conn; } set { _conn = value; } } public DienVienDao() { Conn = new Connection(); if (Conn.Connect().State == ConnectionState.Closed) { Conn.ConnObj.Open(); } } ~DienVienDao() { return; } public DataTable DanhSachDienVien() { SqlCommand cmd = new SqlCommand("SpDanhSachDienVien", Conn.ConnObj); cmd.CommandType = CommandType.StoredProcedure; DataTable result = new DataTable("DanhSachDienVien"); result.Columns.Add("Ma", typeof(int)); result.Columns.Add("HoTen", typeof(string)); result.Columns.Add("LiLich", typeof(string)); result.Columns.Add("HinhMH", typeof(string)); SqlDataReader rd = cmd.ExecuteReader(); DataRow rows; while (rd.Read()) { rows = result.NewRow(); rows["Ma"] = rd.GetInt32(0); rows["HoTen"] = rd.GetString(1); rows["LiLich"] = rd.GetString(2); rows["HinhMH"] = rd.GetString(3); result.Rows.Add(rows); } rd.Close(); Conn.Disconnect(); return result; } public DataTable DanhSachDienVienTheoTen(string TenDV) { SqlCommand cmd = new SqlCommand("spDanhSachDienVienTheoTen", Conn.ConnObj); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@TenDV", TenDV); DataTable result = new DataTable("DanhSachDienVien"); result.Columns.Add("Ma", typeof(int)); result.Columns.Add("HoTen", typeof(string)); result.Columns.Add("LiLich", typeof(string)); result.Columns.Add("HinhMH", typeof(string)); SqlDataReader rd = cmd.ExecuteReader(); DataRow rows; while (rd.Read()) { rows = result.NewRow(); rows["Ma"] = rd.GetInt32(0); rows["HoTen"] = rd.GetString(1); rows["LiLich"] = rd.GetString(2); rows["HinhMH"] = rd.GetString(3); result.Rows.Add(rows); } rd.Close(); Conn.Disconnect(); return result; } } }
07hc114
trunk/RapPhimRollRoyce/DAOLayer/DienVienDao.cs
C#
gpl2
2,762
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DAOLayer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DAOLayer")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("19fd8b9a-9f11-47a0-b1d2-63ce106a42e2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
07hc114
trunk/RapPhimRollRoyce/DAOLayer/Properties/AssemblyInfo.cs
C#
gpl2
1,387
using System; using System.Collections.Generic; using System.Text; using Cores; using System.Data; using System.Data.SqlClient; namespace DAOLayer { public class LichChieuDao { private Connection _conn; public Connection Conn { get { return _conn; } set { _conn = value; } } public LichChieuDao() { Conn = new Connection(); if (Conn.Connect().State == ConnectionState.Closed) { Conn.ConnObj.Open(); } } ~LichChieuDao() { return; } public DataTable LayLichChieu(int maphim, DateTime ngaybd, DateTime ngaykt) { SqlCommand cmd = new SqlCommand("SpLayLichChieu", Conn.ConnObj); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MaPhim", maphim); cmd.Parameters.AddWithValue("@NgayBD", ngaybd); cmd.Parameters.AddWithValue("@NgayKT", ngaykt); DataTable result = new DataTable("LichChieu"); result.Columns.Add("TenPhim", typeof(string)); result.Columns.Add("TenRap", typeof(string)); result.Columns.Add("NgayChieu", typeof(string)); result.Columns.Add("ThoiGianBD", typeof(string)); SqlDataReader rd = cmd.ExecuteReader(); DataRow rows; while (rd.Read()) { rows = result.NewRow(); rows["TenPhim"] = rd.GetString(0); rows["TenRap"] = rd.GetString(1); DateTime dt = rd.GetDateTime(2); rows["NgayChieu"] = dt.ToShortDateString(); rows["ThoiGianBD"] = rd.GetString(3); result.Rows.Add(rows); } rd.Close(); Conn.Disconnect(); return result; } } }
07hc114
trunk/RapPhimRollRoyce/DAOLayer/LichChieuDao.cs
C#
gpl2
1,973
using System; using System.Collections.Generic; using System.Text; using Cores; using System.Security.Cryptography; using System.Data; using System.Data.SqlClient; namespace DAOLayer { public class KhachHangDao { private Connection _conn; public Connection Conn { get { return _conn; } set { _conn = value; } } public KhachHangDao() { Conn = new Connection(); if (Conn.Connect().State == ConnectionState.Closed) { Conn.ConnObj.Open(); } } ~KhachHangDao() { return; } public int LayMaKhachHang(int MaTK) { SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn.ConnObj; cmd.CommandType = CommandType.Text; cmd.CommandText = "Select dbo.fTimKiemMaKH(@MaTK)"; cmd.Parameters.AddWithValue("@MaTK", MaTK); SqlDataReader rd = cmd.ExecuteReader(); int result = 0; if (rd.Read()) result = rd.GetInt32(0); rd.Close(); Conn.Disconnect(); return result; } } }
07hc114
trunk/RapPhimRollRoyce/DAOLayer/KhachHangDao.cs
C#
gpl2
1,268
using System; using System.Collections.Generic; using System.Text; using Cores; using System.Data; using System.Data.SqlClient; namespace DAOLayer { public class DatVeDao { private Connection _conn; public Connection Conn { get { return _conn; } set { _conn = value; } } public DatVeDao() { Conn = new Connection(); if (Conn.Connect().State == ConnectionState.Closed) { Conn.ConnObj.Open(); } } ~DatVeDao() { return; } public void Xoa(int MaVe, int MaKH) { SqlCommand cmd = new SqlCommand("spXoaVe", Conn.ConnObj); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MaVe", MaVe); cmd.Parameters.AddWithValue("@MaKH", MaKH); cmd.ExecuteNonQuery(); } } }
07hc114
trunk/RapPhimRollRoyce/DAOLayer/DatVeDao.cs
C#
gpl2
997
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Windows.Forms; namespace Cores { public class Connection { private String _connString; private SqlConnection _connObj; public String ConnString { get { return _connString; } set { _connString = value; } } public SqlConnection ConnObj { get { return _connObj; } set { _connObj = value; } } public Connection() { ConnString = "Data Source=.;Initial Catalog=DatVeOnline;Integrated Security=SSPI;"; } public Connection(String connStr) { ConnString = connStr; } public SqlConnection Connect() { try { ConnObj = new SqlConnection(ConnString); ConnObj.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error from sever", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } return ConnObj; } public SqlConnection Disconnect() { ConnObj.Close(); return ConnObj; } } }
07hc114
trunk/RapPhimRollRoyce/Cores/Connection.cs
C#
gpl2
1,374
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class LichChieu { private int _MaPhim; private DateTime _NgayChieu; private string _ThoiGianBD; private int _MaRap; public int MaPhim { get { return _MaPhim; } set { _MaPhim = value; } } public DateTime NgayChieu { get { return _NgayChieu; } set { _NgayChieu = value; } } public string ThoiGianBD { get { return _ThoiGianBD; } set { _ThoiGianBD = value; } } public int MaRap { get { return _MaRap; } set { _MaRap = value; } } public LichChieu() { _MaPhim = 1; _NgayChieu = DateTime.Now; _ThoiGianBD = ""; _MaRap = 1; } ~LichChieu() { } } }
07hc114
trunk/RapPhimRollRoyce/Cores/LichChieu.cs
C#
gpl2
1,040
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class DatVe { private int _MaKH; private int _MaVe; public int MaKH { get { return _MaKH; } set { _MaKH = value; } } public int MaVe { get { return _MaVe; } set { _MaVe = value; } } public DatVe() { _MaKH = 1; _MaVe = 1; } } }
07hc114
trunk/RapPhimRollRoyce/Cores/DatVe.cs
C#
gpl2
535
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class TaiKhoan { private string _UserName; private string _Password; private int _MaQuyen; public string UserName { get { return _UserName; } set { _UserName = value; } } public string Password { get { return _Password; } set { _Password = value; } } public int MaQuyen { get { return _MaQuyen; } set { _MaQuyen = value; } } public TaiKhoan() { _UserName = ""; _Password = ""; _MaQuyen = 0; } public TaiKhoan(int ma, string user, string pass, int maq) { _UserName = user; _Password = pass; _MaQuyen = maq; } ~TaiKhoan() { } } }
07hc114
trunk/RapPhimRollRoyce/Cores/TaiKhoan.cs
C#
gpl2
991
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class Phim { private string _Ten; private int _ThoiGian; private string _NuocSX; private int _MaTheLoai; private string _GioiThieu; private string _NSX; private int _NamSX; private string _Poster; private string _Trailer; public string Trailer { get { return _Trailer; } set { _Trailer = value; } } public string Ten { get { return _Ten; } set { _Ten = value; } } public int ThoiGian { get { return _ThoiGian; } set { _ThoiGian = value; } } public string NuocSX { get { return _NuocSX; } set { _NuocSX = value; } } public int MaTheLoai { get { return _MaTheLoai; } set { _MaTheLoai = value; } } public string GioiThieu { get { return _GioiThieu; } set { _GioiThieu = value; } } public string NSX { get { return _NSX; } set { _NSX = value; } } public int NamSX { get { return _NamSX; } set { _NamSX = value; } } public string Poster { get { return _Poster; } set { _Poster = value; } } public Phim() { _Ten = ""; _ThoiGian = 0; _NuocSX = ""; _MaTheLoai = 1; _GioiThieu = ""; _NSX = ""; _NamSX = DateTime.Now.Year; _Poster = ""; _Trailer = ""; } ~Phim() { } } }
07hc114
trunk/RapPhimRollRoyce/Cores/Phim.cs
C#
gpl2
2,002
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Cores")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Cores")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9f78d0d9-7f8a-42fa-b266-fd3679ab0448")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
07hc114
trunk/RapPhimRollRoyce/Cores/Properties/AssemblyInfo.cs
C#
gpl2
1,381
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class Ve { private int _MaLich; private int _MaDay; private int _ViTri; public int MaLich { get { return _MaLich; } set { _MaLich = value; } } public int MaDay { get { return _MaDay; } set { _MaDay = value; } } public int ViTri { get { return _ViTri; } set { _ViTri = value; } } public Ve() { _MaLich = 1; _MaDay = 1; _ViTri = 0; } } }
07hc114
trunk/RapPhimRollRoyce/Cores/Ve.cs
C#
gpl2
728
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class DienVien { private string _HoTen; private string _LiLich; private string _HinhMH; public string HoTen { get { return _HoTen; } set { _HoTen = value; } } public string LiLich { get { return _LiLich; } set { _LiLich = value; } } public string HinhMH { get { return _HinhMH; } set { _HinhMH = value; } } public DienVien() { _HoTen = ""; _LiLich = ""; _HinhMH = ""; } ~DienVien() { } } }
07hc114
trunk/RapPhimRollRoyce/Cores/DienVien.cs
C#
gpl2
803
using System; using System.Collections.Generic; using System.Text; namespace Cores { public class KhachHang { private int _Ma; public int Ma { get { return _Ma; } set { _Ma = value; } } private string _Ten; public string Ten { get { return _Ten; } set { _Ten = value; } } private string _CMND; public string CMND { get { return _CMND; } set { _CMND = value; } } private string _DiaChi; public string DiaChi { get { return _DiaChi; } set { _DiaChi = value; } } private string _DienThoai; public string DienThoai { get { return _DienThoai; } set { _DienThoai = value; } } private int _MaTK; public int MaTK { get { return _MaTK; } set { _MaTK = value; } } ~KhachHang() { } } }
07hc114
trunk/RapPhimRollRoyce/Cores/KhachHang.cs
C#
gpl2
1,112
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using BUSLayer; using Cores; using DAOLayer; public partial class XemThongTinDienVien : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { TenTextBox.Focus(); } } DienVienBus DVbus = new DienVienBus(); PhimBus PBus = new PhimBus(); public void LoadThongTinDienVien() { string TenDV = TenTextBox.Text; DataTable tblDV = DVbus.DSDienVienTheoTen(TenDV); DienVienGridView.DataSource = tblDV; DienVienGridView.DataBind(); } public void LoadThongTinPhimCuaDienVien() { string TenDV = TenTextBox.Text; DataTable tblP = PBus.DSPhimTheoDV(TenDV); PhimGridView.DataSource = tblP; PhimGridView.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { LoadThongTinDienVien(); LoadThongTinPhimCuaDienVien(); } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/XemThongTinDienVien.aspx.cs
C#
gpl2
1,268
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="XemThongTinDienVien.aspx.cs" Inherits="XemThongTinDienVien" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <table> <tr> <td class="header" colspan="3"> Xem thông tin diễn viên</td> </tr> <tr> <td class="content1"> Nhập tên diễn viên</td> <td> <asp:TextBox ID="TenTextBox" runat="server" Height="23px" BackColor="#E0E0E0" BorderColor="#404040" BorderStyle="None"></asp:TextBox></td> <td> <asp:Button ID="Button1" runat="server" CssClass="button" Text="Xem" OnClick="Button1_Click" /></td> </tr> <tr> <td class="content1" colspan="3"> <asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/DanhSachDienVien.aspx">Click vào đây để xem danh sách diễn viên</asp:LinkButton> </td> </tr> <tr> <td class="content1" colspan="3"> Thông tin chi tiết diễn viên :</td> </tr> <tr> <td colspan="3"> <asp:GridView ID="DienVienGridView" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Ma" HeaderText="M&#227;" Visible="False" /> <asp:BoundField DataField="HoTen" HeaderText="Họ t&#234;n" /> <asp:BoundField DataField="LiLich" HeaderText="L&#253; lịch" /> <asp:ImageField HeaderText="H&#236;nh ảnh minh họa"> </asp:ImageField> </Columns> </asp:GridView> </td> </tr> <tr> <td class="content1" colspan="3"> Thông tin phim diễn viễn đã tham gia :</td> </tr> <tr> <td colspan="3"> <asp:GridView ID="PhimGridView" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Ma" HeaderText="M&#227;" Visible="False" /> <asp:BoundField DataField="Ten" HeaderText="T&#234;n" /> <asp:BoundField DataField="ThoiGian" HeaderText="Thời gian" /> <asp:BoundField DataField="NuocSX" HeaderText="Nước SX" /> <asp:BoundField DataField="MaTheLoai" HeaderText="M&#227; thể loại" Visible="False" /> </Columns> </asp:GridView> </td> </tr> </table> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/XemThongTinDienVien.aspx
ASP.NET
gpl2
2,810
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using BUSLayer; public partial class FormXemLichChieu : System.Web.UI.Page { PhimBus Phimbus= new PhimBus(); LichChieuBus LCbus = new LichChieuBus(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { DataTable dt = Phimbus.LayDSPhim(); GridViewDSPhim.DataSource = dt; GridViewDSPhim.DataBind(); } } protected void CheckBoxCheckAll_CheckedChanged(object sender, EventArgs e) { for (int i = 0; i < GridViewDSPhim.Rows.Count; i++) { CheckBox c = (CheckBox)GridViewDSPhim.Rows[i].FindControl("CheckBox1"); c.Checked = CheckBoxCheckAll.Checked; } } protected void ButtonXemLich_Click(object sender, EventArgs e) { } private DataTable XuatLichChieu() { DataTable tbLichChieu = new DataTable(); tbLichChieu.Columns.Add("TenPhim", typeof(string)); tbLichChieu.Columns.Add("TenRap", typeof(string)); tbLichChieu.Columns.Add("NgayChieu", typeof(string)); tbLichChieu.Columns.Add("ThoiGianBD", typeof(string)); for (int i = 0; i < GridViewDSPhim.Rows.Count; i++) { CheckBox c = (CheckBox)GridViewDSPhim.Rows[i].FindControl("CheckBox1"); if (c.Checked == true) { int MaPhim = int.Parse(GridViewDSPhim.Rows[i].Cells[2].Text); DataTable tbPhim = LCbus.LayLichChieu(MaPhim); for(int j=0;j< tbPhim.Rows.Count;j++) { DataRow Row = tbLichChieu.NewRow(); Row[0] = tbPhim.Rows[j]["TenPhim"].ToString(); Row[1] = tbPhim.Rows[j]["TenRap"].ToString(); Row[2] = tbPhim.Rows[j]["NgayChieu"].ToString(); Row[3] = tbPhim.Rows[j]["ThoiGianBD"].ToString(); tbLichChieu.Rows.Add(Row); } } } return tbLichChieu; } protected void Button1_Click(object sender, EventArgs e) { DataTable dt = LCbus.LayLichChieu(1); //DataListLichChieu.DataSource = dt; //DataListLichChieu.DataBind(); GridView1.DataSource = XuatLichChieu(); GridView1.DataBind(); //Label3.Text = dt.Rows.Count.ToString();*/ } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/FormXemLichChieu.aspx.cs
C#
gpl2
2,754
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Session["IsLogin"] = 0; Session["UserName"] = null; Session["Password"] = null; Session["MaKH"] = 0; Session.Timeout = 30; } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Session["login"] = 1; Session["MaKH"] = 1; } </script>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/Global.asax
ASP.NET
gpl2
1,173
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ThongTinFilm.aspx.cs" Inherits="ThongTinFilm" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <table style="width: 476px; height: 147px"> <tr> <td style="width: 171px"> <asp:Label ID="Label9" runat="server" Text="THÔNG TIN PHIM" Font-Bold="True"></asp:Label></td> <td style="width: 87px"> </td> <td style="width: 170px"> </td> </tr> <tr> <td style="height: 18px; width: 171px;"> </td> <td style="width: 87px; height: 18px"> <asp:Label ID="Label1" runat="server" Text="Tên phim:"></asp:Label></td> <td style="width: 170px; height: 18px"> <asp:Label ID="tenLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td rowspan="8" style="width: 171px"> <asp:Image ID="posterImage" runat="server" Height="180px" ImageAlign="Baseline" Width="180px" /></td> <td style="width: 87px; height: 46px"> <asp:Label ID="Label2" runat="server" Text="Giới thiệu:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="gThieuLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label3" runat="server" Text="Nhà sản xuất:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="nsxLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label8" runat="server" Text="Quốc gia:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="qGiaLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label7" runat="server" Text="Đạo diễn:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="dDienLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label11" runat="server" Text="Diễn viên:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="dvLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label4" runat="server" Text="Độ dài:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="dDaiLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label5" runat="server" Text="Thể loại:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="thLoaiLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 87px; height: 46px"> <asp:Label ID="Label6" runat="server" Text="Năm sản xuất:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="namLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="height: 46px; width: 171px;"> </td> <td style="width: 87px; height: 46px"> <asp:Label ID="Label10" runat="server" Text="Trailer:"></asp:Label></td> <td style="width: 170px; height: 46px"> <asp:Label ID="trailerLabel" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td colspan="2" rowspan="3"> </td> <td style="width: 170px; height: 46px"> </td> </tr> <tr> <td style="width: 170px; height: 46px"> </td> </tr> <tr> <td style="width: 170px; height: 46px"> </td> </tr> <tr> <td style="height: 46px; width: 171px;"> </td> <td style="width: 87px; height: 46px"> <asp:Button ID="xLichChieuButton" runat="server" Text="Xem lịch chiếu" BackColor="Violet" /></td> <td style="width: 170px; height: 46px"> <asp:Button ID="datVeButton" runat="server" Text="Đặt vé" BackColor="Violet" /></td> </tr> </table> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/ThongTinFilm.aspx
ASP.NET
gpl2
4,920
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="FormHuyVe.aspx.cs" Inherits="FormHuyVe" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <table width="100%"> <tr> <td style="width: 160px; height: 18px;"> </td> <td style="width: 358px; height: 18px"> HỦY VÉ MÀ KHÁCH HÀNG ĐÃ ĐẶT</td> <td style="height: 18px"> </td> </tr> <tr> <td style="width: 160px; height: 16px;"> Danh sách vé đã đặt: </td> <td style="width: 358px; height: 16px;"> </td> <td style="height: 16px"> </td> </tr> <tr> <td colspan="3"> <asp:GridView ID="DSVeGridView" runat="server" AutoGenerateColumns="False" Width="494px"> <Columns> <asp:TemplateField HeaderText="Chọn"> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </EditItemTemplate> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="MaVe" HeaderText="M&#227; v&#233;" /> <asp:BoundField DataField="TenPhim" HeaderText="T&#234;n phim" /> <asp:BoundField DataField="NgayChieu" HeaderText="Ng&#224;y chiếu" /> <asp:BoundField DataField="ThoiGianBD" HeaderText="Thời gian BĐ" /> <asp:BoundField DataField="TenRap" HeaderText="T&#234;n rạp" /> <asp:BoundField DataField="TenDay" HeaderText="T&#234;n d&#227;y" /> <asp:BoundField DataField="ViTri" HeaderText="Vị tr&#237;" /> </Columns> </asp:GridView> </td> </tr> <tr> <td style="width: 160px"> </td> <td style="width: 358px"> </td> <td> <asp:Button ID="XoaButton" runat="server" Text="Xóa" Width="75px" OnClick="XoaButton_Click" CssClass="button" /></td> </tr> <tr> <td style="width: 160px"> </td> <td style="width: 358px"> </td> <td> </td> </tr> <tr> <td style="width: 160px"> </td> <td style="width: 358px"> </td> <td> </td> </tr> </table> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/FormHuyVe.aspx
ASP.NET
gpl2
2,908
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/Default.aspx.cs
C#
gpl2
406
a:link { color: #C4940F; } a:hover { text-decoration: underline; color: #FF0000; } a:visited { color: #C4940F; } * { border: 0; margin: 0; } body { background: #000000 url(images/back_all.gif) repeat-x top; font: 13px Tahoma, Arial, Helvetica, sans-serif; color: #666666; } #main { margin: 0 auto; width: 787px; background: #ffffff; } #logo { width: 787px; height: 51px; background: url(images/header.jpg) no-repeat; text-align: center; padding-top: 220px; } #logo a { text-decoration: none; font-style: italic; font-size: 18px; color: #FFFFFF; font-weight: bold; } #logo H2 a { font-size: 12px; } #buttons { height: 37px; width: 700px; border-left: 4px solid #FFFFFF; background: url(images/buttons.jpg) repeat-x; padding-left: 80px; } #buttons li { display: inline; } #buttons a { display: block; float: left; width: 100px; height: 27px; background: #FFFFFF url(images/buttons.jpg) repeat-x; text-align: center; text-decoration: none; color: #ffffff; font-weight: bold; font-size: 14px; padding-top: 10px; } #buttons a:hover { width: 100px; height: 27px; background: #FFFFFF url(images/buttons_r.jpg) repeat-x; } #content { width: 775px; padding: 5px; background: #ffffff; min-height: 400px; height:900px; } #left { width: 500px; padding: 10px; height:100%; } #left H1 { color: #CE0B09; margin: 0; padding: 0; font-size: 24px; } #left H2 { color: #CE0B09; margin: 0; padding: 0; font-size: 18px; } #right { float: right; } #sidebar { width: 230px; } #sidebar ul { margin: 0; padding: 0; list-style: none; } #sidebar li { margin-bottom: 15px; } #sidebar li ul { padding: 10px; border-top: none; } #sidebar li li { margin: 0; padding: 3px 0; } #sidebar li h2 { height: 35px; margin: 0; padding: 5px 0 0 10px; background: url(images/title.jpg) no-repeat; font-size: 18px; color: #ffffff; } #sidebar a:link { text-decoration: none; } #sidebar a:hover { text-decoration: underline; } #sidebar a:visited { text-decoration: none; } #sidebar li a { padding-left: 10px; } #footer { background: url(images/footer.gif) repeat-x; height: 15%; font-size: 10px; color: #000000; padding-top: 10px; text-align: center; border-top: 5px solid #977004 } #footer a { color: #000000; font-size: 10px; text-decoration: none; } .padding { padding: 10px; color:#FF0000; font-weight: bold; } .item { background: url(images/img09.gif) no-repeat left center; } .button { width: 100px; height: 20px; text-align:center; color:Blue; font-weight:bold; background: url(images/button.png) repeat-x; background-position:center; } .header { font-size: x-large; text-align:center; text-transform:uppercase; font-weight:bold; color:Blue; font-family:Times New Roman; } .content1 { font-size: 13px; text-align:left; color:Maroon; }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/styles.css
CSS
gpl2
3,040
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/Default.aspx
ASP.NET
gpl2
261
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using BUSLayer; using Cores; using DAOLayer; public partial class DanhSachDienVien : System.Web.UI.Page { public void LoadDSDienVien() { DienVienBus DVBus=new DienVienBus(); DataTable tblDV = DVBus.DanhSachDV(); DSDienVienGridView.DataSource = tblDV; DSDienVienGridView.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { LoadDSDienVien(); } } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/DanhSachDienVien.aspx.cs
C#
gpl2
776
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Cores; using BUSLayer; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } protected void LoginButton_Click(object sender, EventArgs e) { TaiKhoanBus tk = new TaiKhoanBus(); string un = Login1.UserName.ToString(); string pw = TaiKhoanBus.Encrypte(Login1.Password.ToString()); int kq = tk.KTUser(un, pw); if (kq != 0) { Session["UserName"] = un; Session["IsLogin"] = 1; Session["MaKH"] = kq; Response.Redirect("~/FormHuyVe.aspx"); } else Login1.FailureText = "Tài Khoản Không Hợp Lệ !"; } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/MasterPage.master.cs
C#
gpl2
1,046
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="DanhSachDienVien.aspx.cs" Inherits="DanhSachDienVien" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <table> <tr> <td class="header" colspan="2"> danh sách diễn viên</td> </tr> <tr> <td colspan="2"> <asp:GridView ID="DSDienVienGridView" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Ma" HeaderText="M&#227;" Visible="False" /> <asp:BoundField DataField="HoTen" HeaderText="Họ t&#234;n" /> <asp:BoundField DataField="LiLich" HeaderText="L&#253; lịch" /> <asp:ImageField HeaderText="Ảnh minh họa"> </asp:ImageField> </Columns> </asp:GridView> </td> </tr> </table> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/DanhSachDienVien.aspx
ASP.NET
gpl2
1,126
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="FormXemLichChieu.aspx.cs" Inherits="FormXemLichChieu" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <script language="javascript" type="text/javascript"> // <!CDATA[ // ]]> </script> <table style="width: 100%"> <tr> <td style="width: 24px"> </td> <td class="header" colspan="2"> Lịch Chiếu Phim</td> </tr> <tr> <td style="width: 24px; height: 146px"> </td> <td style="height: 146px;" colspan="2"> <asp:GridView ID="GridViewDSPhim" runat="server" AutoGenerateColumns="False" Width="234px"> <Columns> <asp:TemplateField HeaderText="Chon"> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </EditItemTemplate> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" /> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" /> </asp:TemplateField> <asp:BoundField DataField="Ten" HeaderText="T&#234;n Phim"> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" CssClass="content" /> <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" /> </asp:BoundField> <asp:BoundField DataField="Ma" HeaderText="MaPhim" /> </Columns> </asp:GridView> </td> </tr> <tr> <td style="height: 17px; width: 24px;"> </td> <td style="height: 17px; width: 1px;"> <asp:CheckBox ID="CheckBoxCheckAll" runat="server" Width="157px" CssClass="content" OnCheckedChanged="CheckBoxCheckAll_CheckedChanged" Text="Chọn Tất Cả" AutoPostBack="True" /></td> <td style="width: 20px; height: 17px"> <asp:Button ID="Button1" runat="server" Text="Xem Lịch" CssClass="button" OnClick="Button1_Click" /></td> </tr> <tr> <td style="width: 24px; height: 17px"> </td> <td style="width: 1px; height: 17px"> </td> <td style="width: 20px; height: 17px"> </td> </tr> <tr> <td style="width: 24px; height: 17px"> </td> <td style="height: 17px" colspan="2"> &nbsp;<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="456px"> <Columns> <asp:BoundField DataField="TenPhim" HeaderText="TenPhim" > <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" /> </asp:BoundField> <asp:BoundField DataField="TenRap" HeaderText="Rap" > <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" /> </asp:BoundField> <asp:BoundField DataField="NgayChieu" HeaderText="Ng&#224;y Chiếu"> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="70px" /> </asp:BoundField> <asp:BoundField DataField="ThoiGianBD" HeaderText="Xuất Chiếu"> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="70px" /> </asp:BoundField> </Columns> </asp:GridView> &nbsp; </td> </tr> <tr> <td style="width: 24px; height: 17px"> </td> <td style="width: 1px; height: 17px"> </td> <td style="width: 20px; height: 17px"> </td> </tr> </table> <br /> </asp:Content>
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/FormXemLichChieu.aspx
ASP.NET
gpl2
4,419
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using BUSLayer; using DAOLayer; public partial class ThongTinFilm : System.Web.UI.Page { public PhimBus film = new PhimBus(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int maso; object temp = (Request.QueryString.Get("MaPhim")); if (temp != null) { maso = Convert.ToInt32(temp); } else maso = 1;//lấy tạm 1 giá trị để demo LayThongTinPhim(maso); LayThongTinDaoDien(maso); LayDsDienVien(maso); } } private void LayThongTinPhim(int maso) { DataTable resFilm = film.LayThongTinPhim(maso); if (resFilm.Rows.Count > 0) { DataRow fRow = resFilm.Rows[0]; tenLabel.Text = fRow["Ten"].ToString(); gThieuLabel.Text = fRow["GioiThieu"].ToString(); nsxLabel.Text = fRow["NSX"].ToString(); qGiaLabel.Text = fRow["NuocSX"].ToString(); dDaiLabel.Text = fRow["ThoiGian"].ToString(); thLoaiLabel.Text = fRow["TheLoai"].ToString(); namLabel.Text = fRow["NamSX"].ToString(); trailerLabel.Text = fRow["Trailer"].ToString(); string poster = @"images\Poster\"; poster += fRow["Poster"].ToString(); posterImage.ImageUrl = poster; } } private void LayThongTinDaoDien(int maso) { DataTable resDir = film.LayDsDaoDienTrongPhim(maso); if (resDir.Rows.Count > 0) { if (resDir.Rows.Count == 1) { DataRow directors = resDir.Rows[0]; dDienLabel.Text = directors["HoTen"].ToString(); } else { string dirs = ""; DataRow directors; for (int j = 0; j < resDir.Rows.Count - 1; j++) { directors = resDir.Rows[j]; dirs += directors["HoTen"].ToString() + ", "; } DataRow lastDir = resDir.Rows[resDir.Rows.Count - 1]; dirs += lastDir["HoTen"].ToString(); dDienLabel.Text = dirs; } } } private void LayDsDienVien(int maso) { DataTable resAct = film.LayDsDienVienTrongPhim(maso); if (resAct.Rows.Count > 0) { string dv = ""; for (int i = 0; i < resAct.Rows.Count - 1; i++) { DataRow iAct = resAct.Rows[i]; dv += iAct["HoTen"].ToString() + ", "; } DataRow lastAct = resAct.Rows[resAct.Rows.Count - 1]; dv += lastAct["HoTen"].ToString(); dvLabel.Text = dv; } } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/ThongTinFilm.aspx.cs
C#
gpl2
3,175
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using DAOLayer; using BUSLayer; public partial class FormHuyVe : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int loginStatus = Convert.ToInt32(Session["IsLogin"].ToString()); if (loginStatus == 0) { Response.Redirect("Default.aspx"); } else { if(IsPostBack==false) XuatDSVe(); } } public void XuatDSVe() { /*TaiKhoanBus TKbus = new TaiKhoanBus(); KhachHangBus KHBus = new KhachHangBus(); int MaTK = TKbus.LayMaTK(un, pw); int MaKH = KHBus.LayMaKH(MaTK);*/ int MaKH = int.Parse(Session["MaKH"].ToString()); VeBus veControl = new VeBus(); DataTable tbVe = new DataTable(); tbVe = veControl.DanhSachVe(MaKH); DSVeGridView.DataSource = tbVe; DSVeGridView.DataBind(); } protected void XoaButton_Click(object sender, EventArgs e) { /*string un, pw; un = Session["UserName"].ToString(); pw = Session["Password"].ToString();*/ TaiKhoanBus TKbus = new TaiKhoanBus(); KhachHangBus KHBus = new KhachHangBus(); //int MaTK = TKbus.LayMaTK(un, pw); int MaKH = int.Parse(Session["MaKH"].ToString());//.ToString();//KHBus.LayMaKH(MaTK); DatVeBus dvControl = new DatVeBus(); //int MaKH = Convert.ToInt32(Session["MaKH"]); for (int i = 0; i < DSVeGridView.Rows.Count; i++) { CheckBox c = (CheckBox)DSVeGridView.Rows[i].FindControl("CheckBox1"); if (c.Checked == true) { int MaVe = int.Parse(DSVeGridView.Rows[i].Cells[1].Text); dvControl.Xoa(MaVe, MaKH); } } XuatDSVe(); } }
07hc114
trunk/RapPhimRollRoyce/RapPhimRollRoyce/FormHuyVe.aspx.cs
C#
gpl2
2,135
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("QuanLyNhaSach")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Viettel Corporation")] [assembly: AssemblyProduct("QuanLyNhaSach")] [assembly: AssemblyCopyright("Copyright © Viettel Corporation 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("468ba153-1437-4008-b1fa-5c1212f6a392")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1042037-project
trunk/Source/QuanLyNhaSach/QuanLyNhaSach/Properties/AssemblyInfo.cs
C#
asf20
1,476
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace QuanLyNhaSach { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //DevExpress.XtraNavBar.NavBarItem item = navBarControl1.Items.Add(); //item.LargeImageIndex = item.SmallImageIndex = imageComboBoxEdit1.SelectedIndex; //item.Caption = "Item " + (i++).ToString(); //navBarControl1.ActiveGroup.ItemLinks.Add(item); //ExistSelectedItemLink(); for (int i = 0; i < 2; i++) { DevExpress.XtraNavBar.NavBarGroup group = nbmenu.Groups.Add(); group.Caption = "Nhap lieu"+i.ToString(); for (int j = 0; j < 2; j++) { DevExpress.XtraNavBar.NavBarItem item = nbmenu.Items.Add(); item.Caption = "item" + j.ToString(); nbmenu.Groups[i].ItemLinks.Add(item); } } } } }
1042037-project
trunk/Source/QuanLyNhaSach/QuanLyNhaSach/Form1.cs
C#
asf20
1,315
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace QuanLyNhaSach { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
1042037-project
trunk/Source/QuanLyNhaSach/QuanLyNhaSach/Program.cs
C#
asf20
505
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" class Line { private: Texture * m_tex; V2DF m_start; V2DF m_end; float m_length; float m_angle; int m_numSprites; RECT m_lastSprite; int m_spriteHeight; int m_spriteWidth; void calculate(); public: Line(); ~Line(); void release(); void initialize(Texture * a_tex, V2DF start, V2DF end); void render(); void update(float dT); void setStart(V2DF start); void setEnd(V2DF end); V2DF getStart() { return m_start; } V2DF getEnd() { return m_end; } Texture* getTextureReference() { return m_tex; } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Line.h
C++
bsd
609
#include "Enemy.h" Enemy::Enemy() { State = Wander; } void Enemy::update() { switch(State) { case Wander: break; case Chase: break; case Attack: break; case Advanced_Attack: break; case Flank: break; default: break; } }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Enemy.cpp
C++
bsd
270
#pragma once #include "HelpfulData.h" #include "Animation.h" class Skills { private: ClDwn cldwn; int lvlReq; int str; Animation playerAnimation; public: void use(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Skills.h
C++
bsd
187
#include "Floor.h" // default constructor Floor::Floor() {} // default deconstructor, make sure release is called Floor::~Floor() { release(); } // release all data safetly void Floor::release() { } // setup floor void Floor::intialize(char * fileName) { // setup a default test room for(int y = 0; y < FLOORSIZE; y++) { for(int x = 0; x < FLOORSIZE; x++) { // used later for graph int id = x + y * FLOORSIZE; // set all tiles to floor except edges if(x == 0 || x == FLOORSIZE-1 || y == 0 || y == FLOORSIZE-1) m_layout[y][x].initialize(V2DF(x*32,y*32),0); else m_layout[y][x].initialize(V2DF(x*32,y*32),1); } } // set flags to defaults m_visited = m_cleared = false; } // update all tiles void Floor::update(float dT) {} // render this floor void Floor::render() { // render each tile for(int y = 0; y < FLOORSIZE; y++) { for(int x = 0; x < FLOORSIZE; x++) { m_layout[y][x].render(); } } } // check if this entity is colliding with any walls bool Floor::WallCollision(Entity * entity) { return false; } // get graphnode based on position GraphNode * Floor::getNode(V2DF position) { return 0; } // get graphnode based on id GraphNode * Floor::getNode(int id) { return 0; }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Floor.cpp
C++
bsd
1,290
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" class Tile { private: SpriteSheet m_tex; FRect m_bounds; int m_tileType; public: V2DF m_position; Tile(); ~Tile(); void initialize(V2DF pos, int tileType); void release(); void render(); void update(float dT); FRect getBounds(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Tile.h
C++
bsd
326
#include "Input.h" // Return a reference to the input device Input::Input() { // set devices to null m_pDInput = 0; m_pKeyboard = 0; m_pMouse = 0; } Input* Input::getInstance() { static Input instance; return &instance; } Input::~Input() { release(); } void Input::initialize(HINSTANCE hInst, HWND hWnd) { m_hWnd = hWnd; // Create dInput Object DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDInput, 0); // Create Mouse and Keyboard Objects m_pDInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, 0); m_pDInput->CreateDevice(GUID_SysMouse, &m_pMouse, 0); // Set Mouse and Keyboard Data Formats m_pKeyboard->SetDataFormat( &c_dfDIKeyboard); m_pMouse->SetDataFormat(&c_dfDIMouse2); // Set the Cooperative Level of both the Mouse and Keyboard m_pKeyboard->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); m_pMouse->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); // Aquire both the Mouse and Keyboard m_pKeyboard->Acquire(); m_pMouse->Acquire(); } void Input::pollDevices() { /////////////////////////////////////////// // Poll Keyboard & Mouse for Input /////////////////////////////////////////// // Create Temp structures to hold Keyboard & Mouse states // Keyboard for(int i = 0; i < 256; i++) mKeyboardState[i] = 0; // refresh key input // Mouse mMouseState.lX = 0; // refresh mouse state mMouseState.lY = 0; mMouseState.lZ = 0; mMouseState.rgbButtons[0] = 0; mMouseState.rgbButtons[1] = 0; mMouseState.rgbButtons[2] = 0; // Poll the Keyboard HRESULT hr = m_pKeyboard->GetDeviceState(sizeof(mKeyboardState), (void**)mKeyboardState); // refesh pressed buttons for(int i = 0; i < 256; ++i) { if( (!(mKeyboardState[i] & 0x80)) && keysLastUpdate[i] ) keysLastUpdate[i] = false; } // make sure this call was successful if( FAILED(hr) ) { // keyboard lost, zero out keyboard data structure ZeroMemory(mKeyboardState, sizeof(mKeyboardState)); // Try to re-acquire for next time we poll m_pKeyboard->Acquire(); } // Poll the mouse hr = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (void**)&mMouseState); // make sure this call was successful if( FAILED(hr) ) { // keyboard lost, zero out keyboard data structure ZeroMemory(&mMouseState, sizeof(mMouseState)); // Try to re-acquire for next time we poll m_pMouse->Acquire(); } } bool Input::keyDown(int key) { return (mKeyboardState[key] & 0x80); } // only valid input is 0,1, or 2 bool Input::mouseButtonDown(int button) { return (mMouseState.rgbButtons[button] & 0x80); } bool Input::keyPressed(int key) { if( mKeyboardState[key] & 0x80 && !keysLastUpdate[key] ) { keysLastUpdate[key] = true; return true; } return false; } V2DF Input::getMousePos() { POINT p; V2DF v; GetCursorPos(&p); ScreenToClient(m_hWnd, &p); v.x = p.x; v.y = p.y; return v; } void Input::release() { // Keyboard & Mouse // safe release all created direct input objects m_pKeyboard->Unacquire(); m_pMouse->Unacquire(); if (!m_pKeyboard) m_pKeyboard->Release(); if (!m_pMouse) m_pMouse->Release(); if (!m_pDInput) m_pDInput->Release(); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Input.cpp
C++
bsd
3,288
#include "World.h" // default constructor World::World() {} // default destructor, make sure release is called World::~World() { release(); } // safetly release all data void World::release() { } // setup the world void World::initialize() { m_currentFloor = 0; // setup every floor for(int i = 0; i < NUM_FLOORS; i++) m_floors[i].intialize(0); } // update the current floor void World::update(float dT) { m_floors[m_currentFloor].update(dT); } // render the current floor void World::render() { m_floors[m_currentFloor].render(); } // set the current floor if the new floor exists void World::setCurrentFloor(int nFloor) { // make sure the floor exists if(nFloor < 0 || nFloor >= NUM_FLOORS) return; // set the current floor m_currentFloor = nFloor; } // make sure the floor exists then check bool World::FloorVisited(int floor) { // make sure the floor exists if(floor < 0 || floor >= NUM_FLOORS) return false; return m_floors[floor].FloorVisited(); } // make sure the floor exists then check bool World::FloorCleared(int floor) { // make sure the floor exists if(floor < 0 || floor >= NUM_FLOORS) return false; return m_floors[floor].FloorCleared(); } // check current floors walls for collision with the given entity bool World::WallCollision(Entity * entity) { return m_floors[m_currentFloor].WallCollision(entity); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/World.cpp
C++
bsd
1,422
#pragma once #include "Entity.h" #include "v2d.h" #include "templatevector.h" extern class Player; enum ENEMY_TYPE {BASIC_ENEMY, RANGED_ENEMY, STRONG_ENEMY}; class Enemy : public Entity { Player * target; int Attack_force; TemplateVector<GraphNode*> Math; GraphNode * node; bool See_Player; bool PlayerInRange; bool Player_Lost; enum EnemyState { Wander,Chase,Attack,Advanced_Attack,Flank }; EnemyState State; public: Enemy(); ~Enemy(); void initialize(ENEMY_TYPE,V2DF); void update(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Enemy.h
C++
bsd
547
#pragma once #include "HelpfulData.h" #include "Input.h" #include "Entity.h" class Player : public Entity { private: //TemplateVector<Item> inventory; ClDwn invincible; int level; int experience; //Item* activeItem; float speed; int score; /* Input */ Input* pInput; public: Player(void); ~Player(void); void Update(float dT); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Player.h
C++
bsd
367
#pragma once #include "HelpfulData.h" class GraphNode; // used to easily store connections struct Connection { GraphNode* neighbor; float cost; }; class GraphNode { public: // all connections this node has TemplateVector<Connection> m_neighbors; // position in world space V2DF m_position; public: int totalNeighbors; GraphNode(); ~GraphNode(); void release(); void initialize(V2DF a_pos); void addNeighbor(GraphNode* a_neighbor, float a_cost); int getNeighborCount(); TemplateVector<Connection>* getNeighbors(); float Hueristic(GraphNode* other); V2DF getPosition(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/GraphNode.h
C++
bsd
619
#include "Sound.h" void Sound::initialize() { //////////////////////////////////////////////////////////////////////////// // Set up FMOD and sounds /////////////////////////////////////////////////////////////////////////// // create system FMOD::System_Create(&system); // get version system->getVersion(&version); // get number of drivers system->getNumDrivers(&numdrivers); // get driver caps system->getDriverCaps(0, &caps, 0, &speakermode); // get driver info system->getDriverInfo(0, name, 256, 0); // initialize system system->init(100, FMOD_INIT_NORMAL, 0); // create sounds system->createSound("audio/hit.wav", FMOD_DEFAULT, 0, &m_soundEffects[HIT]); system->createSound("audio/press.wav", FMOD_DEFAULT, 0, &m_soundEffects[PRESS]); system->createSound("audio/fire.wav", FMOD_DEFAULT, 0, &m_soundEffects[FIRE]); } Sound::Sound() { } Sound* Sound::getInstance() { static Sound instance; return &instance; } Sound::~Sound() { release(); } void Sound::update() { system->update(); } void Sound::playSound(int sound) { system->playSound(FMOD_CHANNEL_FREE, m_soundEffects[sound], false, 0); } void Sound::release() { for(int i = 0; i < 5; ++i) { if(m_soundEffects[i]) m_soundEffects[i]->release(); } if(system) system->release(); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Sound.cpp
C++
bsd
1,338
#include "HelpfulData.h" void seedRand() { srand(time(NULL)); } bool colliding(FRect r1, FRect r2) { // check veritcal first if( (r1.top > r2.top && r1.top < r2.bottom) || (r1.bottom > r2.top && r1.bottom < r2.bottom) ) { // check horizantally if( (r1.left > r2.left && r1.left < r2.right) || (r1.right > r2.left && r1.right < r2.right) ) { return true; } } return false; } float randomFloat(float min, float max) { // multiply by 1000 to increase accuracy since % only works with integers float temp = ( rand() % (int)(((max + 1) - min) * 1000.0f) ) + (min * 1000.0f); temp /= 1000.0f; return temp; } int randomInt(int min, int max) { return ( rand() % ((max + 1) - min) ) + min; } RECT fRectToRECT(FRect a_rect) { RECT temp; temp.top = a_rect.top; temp.bottom = a_rect.bottom; temp.left = a_rect.left; temp.right = a_rect.right; return temp; } FRect RECTtoFRect(RECT a_rect) { FRect temp; temp.top = a_rect.top; temp.bottom = a_rect.bottom; temp.left = a_rect.left; temp.right = a_rect.right; return temp; } bool colliding(V2DF point, FRect rect) { if( point.x <= rect.right && point.x >= rect.left && point.y <= rect.bottom && point.y >= rect.top ) return true; return false; } // ************************************************************* // ClDwn Class definitions // ************************************************************* // basic constructor ClDwn::ClDwn() { // set basic values m_newDuration = -1; m_duration = m_timePassed = 0.0f; m_active = false; } // skeleton destructor ClDwn::~ClDwn() {} // setup cool down for the given duration void ClDwn::initialize(float duration) { // make sure timer is reset m_newDuration = -1; m_active = false; m_timePassed = 0.0f; m_duration = duration; } // if not already active activate void ClDwn::activate() { m_active = true; } // de-activate and reset time passed void ClDwn::deActivate() { m_active = false; m_timePassed = 0.0f; } // if not active set duration to given duration... // ... if active save duration and change when done // if ignore active is true then set duration no matter what void ClDwn::changeDuration(float duration, bool ignoreActive) { if( ignoreActive || !m_active ) { m_newDuration = -1; m_duration = duration; } else { m_newDuration = duration; } } // if cool down is active then update time passed // if cool down is not active and a newDuration is waiting change duration void ClDwn::update(float dT) { // check whether on cooldown or not if (m_timePassed < m_duration && m_active) { // increment cooldown timer m_timePassed += dT; } // check if cooldown is done and needs reseting else if (m_timePassed >= m_duration) { m_timePassed = 0.0f; m_active = false; } // check if duration needs to be augmented if( m_newDuration != -1 && !m_active) { m_duration = m_newDuration; // set new duration back to non-active m_newDuration = -1; } } // *************************************************************
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/HelpfulData.cpp
C++
bsd
3,139
#include "DX2DEngine.h" #include "Texture.h" #include <string.h> #include <stdlib.h> // make all pointers zero DX2DEngine::DX2DEngine() { m_pD3DObject = 0; m_pD3DDevice = 0; m_pSprite = 0; m_bVsync = false; fps = 0; frameCount = 0; elapsedTime = 0.0; } // make sure the release is called DX2DEngine::~DX2DEngine() { release(); } // set up direct x and other class components void DX2DEngine::initialize(HWND& hWnd, HINSTANCE& hInst, bool bWindowed) { m_hWnd = hWnd; // initialize fps, frameCount, and elapsed time to 0 elapsedTime = 0.0f; fps = frameCount = 0; // Calculate RECT structure for text drawing placement, using whole screen RECT rect; GetClientRect(m_hWnd, &rect); // Create the D3D Object m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION); // calculate width/height of window int width = rect.right - rect.left; int height = rect.bottom - rect.top; // Set D3D Device presentation parameters before creating the device D3DPRESENT_PARAMETERS D3Dpp; ZeroMemory(&D3Dpp, sizeof(D3Dpp)); // NULL the structure's memory D3Dpp.hDeviceWindow = hWnd; // Handle to the focus window D3Dpp.Windowed = bWindowed; // Windowed or Full-screen boolean D3Dpp.AutoDepthStencilFormat = D3DFMT_D24S8; // Format of depth/stencil buffer, 24 bit depth, 8 bit stencil D3Dpp.EnableAutoDepthStencil = TRUE; // Enables Z-Buffer (Depth Buffer) D3Dpp.BackBufferCount = 1; // Change if need of > 1 is required at a later date D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // Back-buffer format, 8 bits for each pixel D3Dpp.BackBufferHeight = height; // Make sure resolution is supported, use adapter modes D3Dpp.BackBufferWidth = width; // (Same as above) D3Dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // Discard back-buffer, must stay discard to support multi-sample D3Dpp.PresentationInterval = m_bVsync ? D3DPRESENT_INTERVAL_DEFAULT : D3DPRESENT_INTERVAL_IMMEDIATE; // Present back-buffer immediately, unless V-Sync is on D3Dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; // This flag should improve performance, if not set to NULL. D3Dpp.FullScreen_RefreshRateInHz = bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT; // Full-screen refresh rate, use adapter modes or default D3Dpp.MultiSampleQuality = 0; // MSAA currently off, check documentation for support. D3Dpp.MultiSampleType = D3DMULTISAMPLE_NONE; // MSAA currently off, check documentation for support. // Check device capabilities DWORD deviceBehaviorFlags = 0; m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps); // Determine vertex processing mode if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING) { // Hardware vertex processing supported? (Video Card) deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; } else { // If not, use software (CPU) deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // If hardware vertex processing is on, check pure device support if(m_D3DCaps.DevCaps & D3DDEVCAPS_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) { deviceBehaviorFlags |= D3DCREATE_PUREDEVICE; } // Create the D3D Device with the present parameters and device flags above m_pD3DObject->CreateDevice( D3DADAPTER_DEFAULT, // which adapter to use, set to primary D3DDEVTYPE_HAL, // device type to use, set to hardware rasterization hWnd, // handle to the focus window deviceBehaviorFlags, // behavior flags &D3Dpp, // presentation parameters &m_pD3DDevice); // returned device pointer // Create a sprite object, note you will only need one for all 2D sprites D3DXCreateSprite( m_pD3DDevice, &m_pSprite ); ////////////////////////////////////////////////////////////////////////// // Create a Font Object ////////////////////////////////////////////////////////////////////////// // Load D3DXFont, each font style you want to support will need an ID3DXFont D3DXCreateFont( m_pD3DDevice, 20, 0, FW_BOLD, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Courier New"), &m_pFont ); // Set up camera RECT screen; GetClientRect(m_hWnd,&screen); // start camera looking at 0,0 screen_center = camera = V2DF(screen.right/2.0f,screen.bottom/2.0f); // start zoom at standard 1.0 (no scale) zoom = 1.0f; } DX2DEngine* DX2DEngine::getInstance() { static DX2DEngine instance; return &instance; } // calculate frames per second void DX2DEngine::update(float dT) { // increment frame count frameCount++; // update elapsed time elapsedTime += dT; // check if more than 1s has elapsed if (elapsedTime >= 1.0f) { // calculate fps since we are using 1 sec no division required... // ...simple use current frame count fps = frameCount; // now reset frameCount and elapsed time frameCount = 0; elapsedTime = 0.0f; } } // get fps float DX2DEngine::getFPS() { return fps; } // Clear the screen and begin the scene void DX2DEngine::start2DRender() { // Make sure the device is working if(!m_pD3DDevice) return; // Clear the back buffer, call BeginScene() m_pD3DDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DXCOLOR(0.0f, 0.4f, 0.8f, 1.0f), 1.0f, 0); m_pD3DDevice->BeginScene(); } // end the entire scene void DX2DEngine::end2DRender() { m_pD3DDevice->EndScene(); m_pD3DDevice->Present(NULL, NULL, NULL, NULL); } // start the sprite object during render void DX2DEngine::startSprite() { m_pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_DEPTH_FRONTTOBACK); } // stop the sprite object during render void DX2DEngine::endSprite() { m_pSprite->End(); } // return a reference to the d3d device IDirect3DDevice9* DX2DEngine::deviceRef() { return m_pD3DDevice; } // return a reference to the d3d device ID3DXSprite* DX2DEngine::spriteRef() { return m_pSprite; } ID3DXFont* DX2DEngine::fontRef() { return m_pFont; } // safetly release all data used void DX2DEngine::release() { // release the sprite object if(m_pSprite) m_pSprite->Release(); m_pSprite = 0; // release the d3d device if(m_pD3DDevice) m_pD3DDevice->Release(); m_pD3DDevice = 0; // now release the textures for(int i = 0; i < m_textures.size(); i++) { if(m_textures.get(i) && m_textures.get(i)->m_pTexture) { m_textures.get(i)->m_pTexture->Release(); m_textures.get(i)->m_pTexture = 0; delete m_textures.get(i)->name; delete m_textures.get(i); m_textures.get(i) = 0; } } // release the vector itself m_textures.release(); // release the d3d object if(m_pD3DObject) m_pD3DObject->Release(); m_pD3DObject = 0; } void DX2DEngine::writeText(char * text, RECT bounds, D3DCOLOR color) { m_pFont->DrawTextA(0, text, -1, &bounds, DT_TOP | DT_LEFT | DT_NOCLIP, color ); } void DX2DEngine::writeText(char * text, V2DF pos, float width, float height, D3DCOLOR color) { RECT bounds; bounds.left = pos.x - width/2; bounds.right = pos.x + width/2; bounds.top = pos.y - height/2; bounds.bottom = pos.y + height/2; m_pFont->DrawTextA(0, text, -1, &bounds, DT_TOP | DT_LEFT | DT_NOCLIP, color ); } void DX2DEngine::writeCenterText(char * text, RECT bounds, D3DCOLOR color) { m_pFont->DrawTextA(0, text, -1, &bounds, DT_CENTER | DT_VCENTER | DT_NOCLIP, color ); } // write text within given rect using the given formating and color void DX2DEngine::writeText(char * text, RECT bounds, D3DCOLOR color, DWORD format) { m_pFont->DrawTextA(0, text, -1, &bounds, format, color); } // Load the given texture from a file if it is not already loaded // also takes in the length of the string // if the texture already exists simply return its id // return its ID int DX2DEngine::createTexture(LPCWSTR file, int length) { bool alreadyExists = false; int index = -1; // make sure this file has not been added prior for(int i = 0; i < m_textures.size() && !alreadyExists ; ++i) { // firs make sure they are even the same length if(length = m_textures.get(i)->length) { // now compare the names for(int j = 0; j < length; ++j) { if( !(file[j] == m_textures.get(i)->name[j]) ) break; // if the final char has been checked and is the same this texture already exists if(j == length-1) { index = i; alreadyExists = true; } } } } // now only load the texture if it doesn't already exist // if it does return the index of the one already created if(alreadyExists) { return index; } // first load up the texture from the given file TextureInfo * temp = 0; temp = new (std::nothrow) TextureInfo; // used for error catching HRESULT hr; hr = D3DXCreateTextureFromFileEx(m_pD3DDevice, file, 0, 0, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), &temp->m_imageInfo, 0, &temp->m_pTexture); // make sure the texture is created correctly // if an error occurs return an error value if(hr != S_OK) { // delete the texture delete temp; return -1; } // add its name and length temp->length = length; // make sure this is initialized to 0 temp->name = new (std::nothrow) char[length]; for(int i = 0; i < length; ++i) temp->name[i] = 0; for(int i = 0; i < length ; ++i) { temp->name[i] = file[i]; } // now attempt to add this file to the vector m_textures.add(temp); return m_textures.size()-1; } // draw the given texture with the given attributes if it exists // if drawing from a sprite sheet pass in the correct rect // pass in NULL for a_sheetRect if not drawing from a sheet void DX2DEngine::renderTexture(int index, V2DF pos, float layer, float scale, float angle, RECT *a_sheetRect, int r, int g, int b, bool relativeToCamera) { // make sure the texture exists if(index < m_textures.size() && index >= 0) { // make sure the texture pointer itself isn't null if(m_textures.get(index)->m_pTexture) { // move relative to camera if(relativeToCamera) { // apply zoom level pos.multiply(zoom); // move to camera space pos.subtract(camera.difference(screen_center)); // scale based on zoom level scale *= zoom; } // perform culling RECT screen; GetClientRect(m_hWnd,&screen); FRect Fscreen; Fscreen.top = screen.top-100; Fscreen.bottom = screen.bottom+100; Fscreen.left = screen.left-100; Fscreen.right = screen.right+100; if(!colliding(pos, Fscreen)) return; // Scaling D3DXMATRIX scaleMat; D3DXMatrixScaling( &scaleMat, scale, scale, 1.0f ); // objects don't scale in the z layer // Rotation on Z axis, value in radians, converting from degrees D3DXMATRIX rotMat; D3DXMatrixRotationZ( &rotMat, D3DXToRadian(angle) ); // Translation D3DXMATRIX transMat; D3DXMatrixTranslation( &transMat, pos.x, pos.y, layer ); // World matrix used to set transform D3DXMATRIX worldMat; // Multiply scale and rotation, store in scale // Multiply scale and translation, store in world worldMat = scaleMat * rotMat * transMat; // Set Transform m_pSprite->SetTransform( &worldMat ); // check if a rect has been given if(a_sheetRect) { // calculate the rects center rather than the whole images float width = a_sheetRect->right - a_sheetRect->left; float height = a_sheetRect->bottom - a_sheetRect->top; // draw the texture at the rects center HRESULT hr = m_pSprite->Draw( m_textures.get(index)->m_pTexture, a_sheetRect, &D3DXVECTOR3(width * 0.5f, height * 0.5f, 0.0f), NULL, D3DCOLOR_ARGB(255, r, g, b) ); } else { // draw the texture at its center HRESULT hr = m_pSprite->Draw( m_textures.get(index)->m_pTexture, 0, &D3DXVECTOR3(m_textures.get(index)->m_imageInfo.Width * 0.5f, m_textures.get(index)->m_imageInfo.Height * 0.5f, 0.0f), NULL, D3DCOLOR_ARGB(255, r, g, b) ); } } } } void DX2DEngine::setCamera(V2DF pos) { camera = pos; } void DX2DEngine::moveCamera(V2DF dist) { camera.add(dist); } V2DF DX2DEngine::getCamera() { return camera; } void DX2DEngine::setZoom(float a_zoom) { zoom = a_zoom; } void DX2DEngine::zoomInOut(float aug) { float oldZOOM = zoom; // augment zoom zoom += aug; // make sure zoom doesn't reach or fall bellow zero and cap zoom to 10x if(zoom <= 0.1f || zoom > 3.0f) zoom = oldZOOM; } float DX2DEngine::getZoom() { return zoom; } V2DF DX2DEngine::screenCenter() { RECT temp; GetClientRect(m_hWnd,&temp); return V2DF((float)temp.right/2.0f,(float)temp.bottom/2.0f); }; D3DXIMAGE_INFO DX2DEngine::imageInfo(int index) { return m_textures.get(index)->m_imageInfo; }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/DX2DEngine.cpp
C++
bsd
13,041
#include "Item.h" #include "Player.h"
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Item.cpp
C++
bsd
38
#include "Entity.h" Entity::Entity() { stats.health = 0; stats.str = 0; stats.tough = 0; stats.agil = 0; stats. weight = 0; rotation = 0.0f; dead = false; } Entity::~Entity() {} void Entity::takeDamage(int amount) { stats.health -= amount/(amount+stats.tough); if(stats.health <= 0) dead = true; } void Entity::setFacing(Facing a_orientation) { switch(a_orientation) { case NORTH: rotation = 0; break; case EAST: rotation = 90; break; case SOUTH: rotation = 180; break; case WEST: rotation = 270; break; } }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Entity.cpp
C++
bsd
560
#pragma once #include "DX2DEngine.h" #include "v2d.h" #include "HelpfulData.h" enum Texture_Type {BASIC, SHEET, ANIMATION}; // Basic 2D Sprite object // contains the necessary information to store for a single d3d texture // ...and draw it to the screen class Texture { protected: // graphics engine reference DX2DEngine* engine; // Texture reference int textureID; // tint of the texture int m_R; // Red level int m_G; // Green level int m_B; // blue level // controls wether the image is drawn in respect to the camera bool m_relativeToCamera; // used to only show a portion of a texture RECT m_viewRect; // used to discern what inherited class of texture is being used // mostly for abstraction purposes in the case of Texture pointers Texture_Type m_type; public: Texture(); ~Texture(); virtual void release(); void initialize(LPCWSTR fileName, bool relativeToCamera); void setRelativeToCamera(bool relativeToCamera) { m_relativeToCamera = relativeToCamera; } bool relativeToCamera() { return m_relativeToCamera; } void setTint(int R, int G, int B); virtual void setViewRect(RECT rect); void resetViewRect(); virtual void draw(V2DF pos, float rotAngle, float scale); int imageHeight(); int imageWidth(); Texture_Type getType() { return m_type; } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Texture.h
C++
bsd
1,325
#include "GameEngine.h" #include "HelpfulData.h" GameEngine::GameEngine() { } // Make sure release is called GameEngine::~GameEngine() { release(); } // set up all game components void GameEngine::initialize() { // get sound engine reference pSound = Sound::getInstance(); // set camera move speed m_cameraSpeed = 50.0f; // get input reference pInput = Input::getInstance(); // get 2D graphics engine reference p2DEngine = DX2DEngine::getInstance(); m_state = GAME; running = true; // **************************** // put game stuff here // **************************** // **************************** FRect rect; rect.top = rect.left = 0; rect.bottom = rect.right = 32.0f; test.initialize(V2DF(300.0f,300.0f), L"images/test.png", rect, 1.0f); player.initialize(V2DF(300.0f,300.0f), L"images/test.png", rect, 1.0f); tWorld.initialize(); } // update all game components void GameEngine::update(float dT) { // backup escape key if(pInput->keyDown(DIK_DELETE)) running = false; // update based on given game state switch(m_state) { case MENU: break; case CLASS: break; case GAME: test.setPosition(pInput->getMousePos()); player.Update(dT); tWorld.update(dT); break; case VICTORY: break; case DEAD: break; } } // render all game components void GameEngine::render() { // render the given objects for each state switch(m_state) { case MENU: break; case CLASS: break; case GAME: tWorld.render(); test.render(); player.render(); break; case VICTORY: case DEAD: break; } } void GameEngine::drawText() { switch(m_state) { case MENU: break; case CLASS: break; case GAME: break; case VICTORY: case DEAD: break; } } // safetly release all game components void GameEngine::release() { tWorld.release(); } bool GameEngine::isRunning() { return running; } void GameEngine::setRunning(bool a_run) { running = a_run; } void GameEngine::setState(G_State state) { m_state = state; }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/GameEngine.cpp
C++
bsd
2,099
#pragma once #include "templatearray.h" /** * simple templated vector. Ideal for dynamic lists of primitive types and single pointers. * @WARNING template with virtual types, or types that will be pointed to at your own risk! * in those situations, templates of pointers to those types are a much better idea. * @author mvaganov@hotmail.com December 2009 */ template<typename DATA_TYPE> class TemplateVector : public TemplateArray<DATA_TYPE> { protected: /** the default size to allocate new vectors to */ static const int DEFAULT_ALLOCATION_SIZE = 10; /** number of valid elements that the caller thinks we have.. */ int m_size; public: /** sets all fields to an initial data state. WARNING: can cause memory leaks if used without care */ inline void init() { TemplateArray<DATA_TYPE>::init(); m_size = 0; } /** cleans up memory */ inline void release() { TemplateArray<DATA_TYPE>::release(); m_size = 0; } /** @return true of the copy finished correctly */ inline bool copy(const TemplateVector<DATA_TYPE> & a_vector) { if(ensureCapacity(a_vector.m_size)) { for(int i = 0; i < a_vector.m_size; ++i) { set(i, a_vector.get(i)); } m_size = a_vector.m_size; return true; } return false; } /** copy constructor */ inline TemplateVector( const TemplateVector<DATA_TYPE> & a_vector) { init(); copy(a_vector); } /** default constructor allocates no list (zero size) */ inline TemplateVector(){init();} /** format constructor */ inline TemplateVector(const int & a_size, const DATA_TYPE & a_defaultValue) { init(); ensureCapacity(a_size); for(int i = 0; i < a_size; ++i) add(a_defaultValue); } /** @return the last value in the list */ inline DATA_TYPE & getLast() { return m_data[m_size-1]; } /** @return the last added value in the list, and lose that value */ inline DATA_TYPE & pop() { return m_data[--m_size]; } /** * @param value to add to the list * @note adding a value may cause memory allocation */ void add(const DATA_TYPE & a_value) { // where am i storing these values? // if i don't have a place to store them, i better make one. if(m_data == 0) { // make a new list to store numbers in allocateToSize(DEFAULT_ALLOCATION_SIZE); } // if we don't have enough memory allocated for this list if(m_size >= m_allocated) { // make a bigger list allocateToSize(m_allocated*2); } set(m_size, a_value); m_size++; } /** * @param a_value to add to the list if it isnt in the list already * @return true the index where the element exists */ int addNoDuplicates(const DATA_TYPE & a_value) { int index = indexOf(a_value); if(index < 0) { index = m_size; add(a_value); } return index; } /** @param a_vector a vector to add all the elements from */ inline void addVector(const TemplateVector<DATA_TYPE> & a_vector) { for(int i = 0; i < a_vector.size(); ++i) { add(a_vector.get(i)); } } /** @return the size of the list */ inline const int & size() const { return m_size; } /** * @param size the user wants the vector to be (chopping off elements) * @return false if could not allocate memory * @note may cause memory allocation if size is bigger than current */ inline bool setSize(const int & a_size) { if(!ensureCapacity(a_size)) return false; m_size = a_size; return true; } /** sets size to zero, but does not deallocate any memory */ inline void clear() { setSize(0); } /** * @param a_index is overwritten by the next element, which is * overwritten by the next element, and so on, till the last element */ void remove(const int & a_index) { moveDown(a_index, -1, m_size); setSize(m_size-1); } /** * @param a_index where to insert a_value. shifts elements in the vector. */ void insert(const int & a_index, const DATA_TYPE & a_value) { setSize(m_size+1); moveUp(a_index, 1, m_size); set(a_index, a_value); } /** * @return first element from the list and moves the rest up * @note removes the first element from the list */ inline const DATA_TYPE pull() { DATA_TYPE value = get(0); remove(0); return value; } /** @param a_index is replaced by the last element, then size is reduced. */ inline void removeFast(const int & a_index) { swap(a_index, m_size-1); setSize(m_size-1); } /** @return the index of the first appearance of a_value in this vector. uses == */ inline int indexOf(const DATA_TYPE & a_value) const { for(int i = 0; i < m_size; ++i) { if(get(i) == a_value) return i; } return -1; } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex) const { return TemplateArray::indexOf(a_value, a_startingIndex, m_size); } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex, int const & a_size) const { return TemplateArray::indexOf(a_value, a_startingIndex, a_size); } /** * will only work correctly if the TemplateVector is sorted. * @return the index of the given value, -1 if the value is not in the list */ int indexOfWithBinarySearch(const DATA_TYPE & a_value) { if(m_size) { return TemplateArray::indexOfWithBinarySearch(a_value, 0, m_size); } return -1; // failed to find key } /** * uses binary sort to put values in the correct index. safe if soring is always used * @param a_value value to insert in order * @param a_allowDuplicates will not insert duplicates if set to false * @return the index where a_value was inserted */ int insertSorted(const DATA_TYPE & a_value, const bool & a_allowDuplicates) { int index; if(!m_size || a_value < get(0)) { index = 0; } else if(!(a_value < get(m_size-1))) { index = m_size; } else { int first = 0, last = m_size; while (first <= last) { index = (first + last) / 2; if (!(a_value < m_data[index])) first = index + 1; else if (a_value < m_data[index]) last = index - 1; } if(!(a_value < m_data[index])) index++; } if(!m_size || a_allowDuplicates || a_value != m_data[index]) insert(index, a_value); return index; } /** * @param a_value first appearance replaced by last element. breaks if not in list */ inline void removeDataFast(const DATA_TYPE & a_value) { removeFast(indexOf(a_value)); } /** * @param a_listToExclude removes these elements from *this list * @return true if at least one element was removed */ inline bool removeListFast(const TemplateVector<DATA_TYPE> & a_listToExclude) { bool aTermWasRemoved = false; for(int e = 0; e < a_listToExclude.size(); ++e) { for(int i = 0; i < size(); ++i) { if(a_listToExclude.get(e) == get(i)) { removeFast(i); --i; aTermWasRemoved = true; } } } return aTermWasRemoved; } /** @param a_value first appearance is removed. breaks if not in list */ inline void removeData(const DATA_TYPE & a_value) { remove(indexOf(a_value)); } /** destructor */ inline ~TemplateVector() { release(); } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/templatevector.h
C++
bsd
7,504
#include "Animation.h" // basic constructor Animation::Animation() { m_index = 0; m_playing = false; } // make sure safer release is called Animation::~Animation() {} // setup the animation based on the appopriate spritesheet values void Animation::initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, float fps, bool a_loop, bool relativeToCamera) { // setup sprite sheet of animation SpriteSheet::initialize(fileName,count,numRows,numColumns,spriteWidth,spriteHeight, relativeToCamera); // set type to animation m_type = ANIMATION; m_playing = false; m_loop = a_loop; // calculate frames per second m_frameSwitch.initialize( (float)m_rects.size() / fps ); } // update the animation timer void Animation::update(float dT) { // if the animation is running update the frames if( m_playing ) { // update timer m_frameSwitch.update(dT); // if the timer has finished then switch frames if( !m_frameSwitch.isActive() ) { // if the end has been reached either loop or end animation if( m_index >= m_rects.size() - 1) { // loop the animation if( m_loop ) { m_index = 0; m_frameSwitch.activate(); } // end the animation else { m_frameSwitch.deActivate(); m_playing = false; } } // animation has not reached the end else { m_index++; m_frameSwitch.activate(); } } } } // set current frame and reset the timer void Animation::setCurrentFrame(int index) { // make sure the sprite exists if( setCurrentSprite(index) ) { // reset frameswitch if it is currently running if(m_frameSwitch.isActive()) { m_frameSwitch.deActivate(); m_frameSwitch.activate(); } } } // pause the animation at its current frame void Animation::pause() { m_playing = false; } // start the animation from its current frame void Animation::play() { m_playing = true; // start the timer m_frameSwitch.activate(); } // reset to the first frame // pause afterwards if true void Animation::reset(bool pause) { // first reset to first frame m_index = 0; // reset the timer m_frameSwitch.deActivate(); if(pause) { // stop the animation m_playing = false; } else // otherwise re-activate the timer m_frameSwitch.activate(); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Animation.cpp
C++
bsd
2,405
#pragma once #include "HelpfulData.h" #include "Texture.h" extern class Item; // used as return type for collision function // NONE = no collision occured // MAIN = only the main rect was collided with or only the main rect was checked // RIGHT, LEFT, TOP, BOT = corresponding side was collided enum SIDE {NONE,RIGHT,LEFT,TOP,BOT,MAIN}; enum Facing { NORTH, SOUTH, EAST, WEST }; enum EntityType { PLAYER, ENEMY, BOSS, OTHER }; struct Stats { int health; int str; int tough; int agil; int weight; }; // used to save collisions that have occured struct Collision { FRect m_rect; SIDE m_side; float m_pen; }; class Entity { protected: V2DF position; bool dead; float scale; int rotation; Texture tex; Facing orientation; Stats stats; FRect m_boundRect; FRect m_right; FRect m_left; FRect m_top; FRect m_bottom; TemplateVector<Collision> m_collisions; public: Entity(); ~Entity(); virtual void initialize(V2DF pos, const wchar_t* a_tex, FRect a_rect, float a_scale) { position = pos; tex.initialize(a_tex, true); scale = a_scale; } virtual void render() { tex.draw(position, rotation, scale); } virtual void update() {}; virtual void onDeath() {} void setPosition(V2DF nPos) { position = nPos; } V2DF getPosition() { return position; } void takeDamage(int amount); void setFacing(Facing orientation); void heal() { stats.health++; } // Detects if the given entity is colliding with this entity // If the checkSides flag is true it will detect which side the collision occurded on and ... // ...calculate interpentration as well as move the entities apart. // All collisions that occured this frame are stored in the m_collisions vector and are resovled by the... // ...resolveCollisions() function // returns a SIDE to based on what occured NONE = no collision, MAIN = only the main // RIGHT, LEFT, TOP, BOT = the appropriate side was collided with // checkSides true = check sub rects, false = ignore // NOTE:: the entity making the function call is the one that will be moved, other will be left were it is... // ...this also means that only the calling entities sub rects will be taken into account SIDE collisionCheck(Entity * other, bool checkSides) { // first determine if the entites main rects are colliding // get the rects relative to positions FRect rectA = getRelativeBoundRect(); // get the relative rect of the other entity FRect rectB = other->getRelativeBoundRect(); Collision col; // check if they are colliding if( colliding(rectA, rectB) ) { // used to store return value SIDE temp = MAIN; // now determine if sides need to be checked if(checkSides) { // check each subRect in the order RIGHT, LEFT, TOP, BOTTOM // RIGHT rectA = getSubRect(RIGHT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.right - rectB.left); col.m_side = RIGHT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = RIGHT; } // LEFT rectA = getSubRect(LEFT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.left - rectB.right); col.m_side = LEFT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = LEFT; } // TOP rectA = getSubRect(TOP); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.top - rectB.bottom); col.m_side = TOP; col.m_rect = rectB; m_collisions.add(col); // set return value temp = TOP; } // BOTTOM rectA = getSubRect(BOT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.bottom - rectB.top); col.m_side = BOT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = BOT; } } return temp; } // no collision occurd return none return NONE; } // overload of the previous function // functions exactly the same although it takes in a rect rather than another entity SIDE collisionCheck(FRect rectB, bool checkSides) { // first determine if the entites main rects are colliding // get the rects relative to positions FRect rectA = getRelativeBoundRect(); Collision col; // check if they are colliding if( colliding(rectA, rectB) ) { // used to store return value SIDE temp = MAIN; // now determine if sides need to be checked if(checkSides) { // check each subRect in the order RIGHT, LEFT, TOP, BOTTOM // RIGHT rectA = getSubRect(RIGHT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.right - rectB.left); col.m_side = RIGHT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = RIGHT; } // LEFT rectA = getSubRect(LEFT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.left - rectB.right); col.m_side = LEFT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = LEFT; } // TOP rectA = getSubRect(TOP); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.top - rectB.bottom); col.m_side = TOP; col.m_rect = rectB; m_collisions.add(col); // set return value temp = TOP; } // BOTTOM rectA = getSubRect(BOT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.bottom - rectB.top); col.m_side = BOT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = BOT; } } return temp; } // no collision occurd return none return NONE; } // resovle all collisions saved in the m_collisions vector and then clears the vector void resolveCollisions() { // get a copy of this entity's bound rect FRect rectA = getRelativeBoundRect(); // used to hold the current collisions being resloved Collision bestVert; bestVert.m_pen = 0.0f; bestVert.m_rect = rectA; bestVert.m_side = MAIN; Collision bestHoriz; bestHoriz.m_pen = 0.0f; bestHoriz.m_rect = rectA; bestHoriz.m_side = MAIN; // only search through the list if there was more than 1 collision if(m_collisions.size() > 0) { //assume the first collision is the best if( m_collisions.get(0).m_side == RIGHT || m_collisions.get(0).m_side == LEFT ) bestHoriz = m_collisions.get(0); else bestVert = m_collisions.get(0); // go through the list of collisions and find the closest horizantel and vertical components to the entity for(int i = 1; i < m_collisions.size(); ++i) { // first determine if this was a horizantal or vertical collision if ( m_collisions.get(i).m_side == RIGHT || m_collisions.get(i).m_side == LEFT ) { // check against the best horizantal if( m_collisions.get(i).m_pen < bestHoriz.m_pen || bestHoriz.m_pen == 0) bestHoriz = m_collisions.get(i); } else { // check against the best vertical if( m_collisions.get(i).m_pen < bestVert.m_pen || bestVert.m_pen == 0) bestVert = m_collisions.get(i); } } // now augment the position based on these values position.x -= bestHoriz.m_pen; position.y -= bestVert.m_pen; // remember to clear the list of collisions m_collisions.clear(); } } // return a bound rect relative to position FRect getRelativeBoundRect() { FRect temp; temp.top = position.y + m_boundRect.top; temp.left = position.x + m_boundRect.left; temp.right = position.x + m_boundRect.right; temp.bottom = position.y + m_boundRect.bottom; return temp; } // return a copy of the bound rect FRect getBoundRect() { return m_boundRect; } // return a sub bound rect of the given side relative to position FRect getSubRect(SIDE side) { FRect temp; switch(side) { case RIGHT: temp.top = position.y + m_right.top; temp.left = position.x + m_right.left; temp.right = position.x + m_right.right; temp.bottom = position.y + m_right.bottom; break; case LEFT: temp.top = position.y + m_left.top; temp.left = position.x + m_left.left; temp.right = position.x + m_left.right; temp.bottom = position.y + m_left.bottom; break; case TOP: temp.top = position.y + m_top.top; temp.left = position.x + m_top.left; temp.right = position.x + m_top.right; temp.bottom = position.y + m_top.bottom; break; case BOT: temp.top = position.y + m_bottom.top; temp.left = position.x + m_bottom.left; temp.right = position.x + m_bottom.right; temp.bottom = position.y + m_bottom.bottom; break; } return temp; } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Entity.h
C++
bsd
9,118
#pragma once /** * a simple HashMap data structure, using TemplateVectors of KeyValuePairs as * buckets. The hash size is DEFAULT_BUCKET_SIZE, or 32. The hashFunction * values between 0 and 31 by bitshifting and masking */ template <class KEY, class VALUE> class TemplateHashMap { struct KeyValuePair { KEY k; VALUE v; KeyValuePair(){} KeyValuePair(KEY k):k(k){} KeyValuePair(KEY k, VALUE v):k(k),v(v){} // operators overloaded for TemplateVector bool operator<(KeyValuePair const & kvp){return k < kvp.k;} bool operator>(KeyValuePair const & kvp){return k > kvp.k;} bool operator==(KeyValuePair const& kvp){return k ==kvp.k;} }; TemplateVector<TemplateVector<KeyValuePair>> hash; static const int DEFAULT_BUCKET_SIZE = 32; public: void clear(){ for(int i = 0; i < hash.size(); ++i) hash.get(i).clear(); } TemplateHashMap() { hash.setSize(DEFAULT_BUCKET_SIZE); } int hashFunction(KEY k) { // the KEY could very likely be pointer. This hash will turn memory // addresses that are int-aligned into possibly consecutive keys, and // essentially modulo 32, accomplished here by bitwise-and-ing 32-1 return (((int)k) >> (sizeof(int) >> 1)) & 31; } /** @return the value associated with the given KEY */ VALUE * getByKey(KEY k) { int index = hashFunction(k); TemplateVector<KeyValuePair> * bucket = &hash.get(index); KeyValuePair kvp(k); int bucketIndex = bucket->indexOf(kvp); if(bucketIndex < 0) return 0; return &bucket->get(bucketIndex).v; } /** sets up a key/value pair association */ void set(KEY k, VALUE v) { int index = hashFunction(k); TemplateVector<KeyValuePair> * bucket = &hash.get(index); bucket->add(KeyValuePair(k,v)); } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/templatehashmap.h
C++
bsd
1,781
#pragma once #include <math.h> // drawing and math methods that require the libraries above #define V2D_SIN sin #define V2D_COS cos // modify this if changing V2D's data types #define V2D_GLVERTEX_METHOD glVertex2fv // PI defined to reduce dependency on other math libraries #define V2D_PI (3.14159265358979323846) #define V2D_2PI (V2D_PI*2) #define V2D_HALFPI (V2D_PI/2) #define V2D_QUARTERPI (V2D_PI/4) // standard for V2D floats #define __VTYPE float // standard V2D using floats #define V2DF V2D<__VTYPE> #define V2DI V2D<int> /** * a two dimensional vector class, which includes methods to handle 2D * geometric calculation, including rotation in various circumstances. * @author mvaganov@hotmail.com April 2010 */ template<typename VTYPE> class V2D { protected: public: /** position in 2 Dimensional space */ VTYPE x, y; /** how many dimensions a V2D<VTYPE> keeps track of (sizeof(V2D)/sizeof(VTYPE)) */ static const int NUM_DIMENSIONS = 2; /** to access this class's type later */ typedef VTYPE type; /** the first (initial) dimension */ static const int _X = 0; /** the second dimension */ static const int _Y = 1; /** access X */ inline const VTYPE & getX()const{return x;} /** access Y */ inline const VTYPE & getY()const{return y;} /** mutate X */ inline void setX(const VTYPE & a_value){x=a_value;} /** mutate Y */ inline void setY(const VTYPE & a_value){y=a_value;} /** mutate X */ inline void addX(const VTYPE & a_value){x+=a_value;} /** mutate Y */ inline void addY(const VTYPE & a_value){y+=a_value;} /** @return array containing points of this vector ([V2D::X], [V2D::Y]) */ inline const VTYPE * getDimensions()const{return &x;} /** @return getDimensions()[a_dimensionField] */ inline VTYPE getField(const int & a_dimensionField)const{return getDimensions()[a_dimensionField];} /** getDimensions()[a_dimensionField]=a_value; */ inline void setField(const int & a_dimensionField, const VTYPE & a_value){(&x)[a_dimensionField]=a_value;} /** @param a_axis {X, Y} */ inline void flipAxis(const int & a_axis){(&x)[a_axis]*=-1;} /** resets the value of this vector */ inline void set(const VTYPE & a_x, const VTYPE & a_y){x = a_x; y = a_y;} /** copy another vector */ inline void set(const V2D<VTYPE> & a_v2d){set(a_v2d.x, a_v2d.y);} /** default constructor */ V2D():x(0.0),y(0.0){} /** complete constructor */ V2D(VTYPE a_x, VTYPE a_y):x(a_x),y(a_y){} /** turns a pi-radians angle into a vector */ V2D(VTYPE a_piRadians):x(V2D_COS(a_piRadians)), y(V2D_SIN(a_piRadians)){} /** copy constructor */ V2D(const V2D<VTYPE> & v):x(v.x),y(v.y){} /** sets x and y to zero */ inline void zero(){x=y=0;} /** * declares a "global" variable in a function, which is OK in a template! * (can't declare globals in headers otherwise) */ inline static const V2D<VTYPE> & ZERO() {static V2D<VTYPE> ZERO(0,0); return ZERO;} inline static const V2D<VTYPE> & ZERO_DEGREES() {static V2D<VTYPE> ZERODEGREES(1,0); return ZERODEGREES;} /** * @return true if both x and y are zero * @note function is not allowed to modify members in V2D */ inline bool isZero() const {return x == 0 && y == 0;} /** @return if both x and y are less than the given x and y */ inline bool isLessThan(const V2D<VTYPE> & p)const{return x<p.x&&y<p.y;} /** @return if both x and y are greaterthan or equl to the given x and y */ inline bool isGreaterThanOrEqualTo(const V2D<VTYPE> & p)const{return x>=p.x&&y>=p.y;} /** @return the squared length of the vector (avoids sqrt) "quadrance" */ inline VTYPE lengthSq() const{return (VTYPE)(x*x+y*y);} /** @return the length of the vector (uses sqrt) */ inline VTYPE length() const{return sqrt((VTYPE)lengthSq());} /** @return dot product of this and v2 */ inline VTYPE dot(const V2D<VTYPE> & v2) const { return (VTYPE)(x * v2.x + y * v2.y); } /** * @return positive if v2 is clockwise of this vector * (assume Y points down, X to right) */ inline VTYPE sign(const V2D<VTYPE> & v2) const{return (x*v2.y)-(y*v2.x);} /** @return the vector perpendicular to this one */ inline V2D<VTYPE> perp() const{return V2D(-y, x);} /** @param a_length what to set this vector's magnitude to */ inline void setLength(const VTYPE & a_length) { VTYPE l = length(ll); // "x = (x * a_maxLength) / l" is more precise than "x *= (a_maxLength/l)" x = (x * a_maxLength) / l; y = (y * a_maxLength) / l; } /** * @param a_maxLength x and y adjusts so that the length does not exceed this */ inline void truncate(const VTYPE & a_maxLength) { VTYPE max2 = a_maxLength*a_maxLength; VTYPE ll = lengthSq(); if(ll > max2) { VTYPE l = sqrt(ll); // "x = (x * a_maxLength) / l" is more precise than "x *= (a_maxLength/l)" x = (x * a_maxLength) / l; y = (y * a_maxLength) / l; } } /** @return the distance square between this vector and v2 (avoids sqrt) */ inline VTYPE distanceSq(const V2D<VTYPE> & v) const { VTYPE dx = x-v.x, dy = y-v.y; return dx*dx+dy*dy; } /** @return the distance between this vector and v2 */ inline VTYPE distance(const V2D<VTYPE> & v) const{return sqrt(distanceSq(v));} /** @return the vector that is the reverse of this vector */ inline V2D<VTYPE> getReverse() const { return V2D<VTYPE>(-x, -y); } /** @return a new V2D<VTYPE> that is the sum of this V2D<VTYPE> and v */ inline V2D<VTYPE> sum(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x+v.x, y+v.y); } /** @return a new V2D<VTYPE> that is the difference of this V2D<VTYPE> and v */ inline V2D<VTYPE> difference(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x-v.x, y-v.y); } /** @return a new V2D<VTYPE> that is the product of this V2D<VTYPE> and v */ inline V2D<VTYPE> product(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x*v.x, y*v.y); } /** @return a new V2D<VTYPE> that is the product of this V2D<VTYPE> and v */ inline V2D<VTYPE> product(const VTYPE & a_value) const { return V2D<VTYPE>(x*a_value, y*a_value); } /** @return a new V2D<VTYPE> that is the quotient of this V2D<VTYPE> and the given V2D*/ inline V2D<VTYPE> quotient(const VTYPE & a_value) const { return V2D<VTYPE>(x/a_value, y/a_value); } /** @return a new V2D<VTYPE> that is the quotient of this V2D<VTYPE> and the given V2D<VTYPE> */ inline V2D<VTYPE> quotient(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x/v.x, y/v.y); } /** @return this V2D<VTYPE> after adding v */ inline const V2D<VTYPE> & add(const V2D<VTYPE> & v) { x += v.x; y += v.y; return *this; } /** @return this V2D<VTYPE> after subtracting v */ inline const V2D<VTYPE> & subtract(const V2D<VTYPE> & v) { x -= v.x; y -= v.y; return *this; } /** @return this V2D<VTYPE> after multiplying v */ inline V2D<VTYPE> & multiply(const VTYPE & a_value) { x *= a_value; y *= a_value; return *this; } /** @return this V2D<VTYPE> after multiplying v */ inline V2D<VTYPE> & multiply(const V2D<VTYPE> & v) { x *= v.x; y *= v.y; return *this; } /** @return this V2D<VTYPE> after dividing v */ inline V2D<VTYPE> & divide(const VTYPE & a_value) { x /= a_value; y /= a_value; return *this; } /** @return this V2D<VTYPE> after dividing v */ inline V2D<VTYPE> & divide(const V2D<VTYPE> & v) { x /= v.x; y /= v.y; return *this; } /** @return if this V2D<VTYPE> is euqal to v */ inline bool isEqual(const V2D<VTYPE> & v) const { return (x == v.x && y == v.y); } /** @return true if this point is within a_radius from a_point */ inline bool isWithin(const VTYPE & a_radius, const V2D<VTYPE> & a_point) const { VTYPE rr = a_radius*a_radius; return this->distanceSq(a_point) <= rr; } /** @return if this point is between the rectangle inscribed by the given corners */ inline bool isBetweenRect(const V2D<VTYPE> & a, const V2D<VTYPE> & b) { return((a.x <= b.x)?(x>=a.x&&x<=b.x):(x>=b.x&&x<=a.x)) &&((a.y <= b.y)?(y>=a.y&&y<=b.y):(y>=b.y&&y<=a.y)); } /** @return true if the given vector is equivalant to this one */ inline bool equals(const V2D<VTYPE> & v)const {return x == v.x && y == v.y;} /** forces vector to have a length of 1 */ inline V2D<VTYPE> & normalize() { divide(length()); return *this; } /** a normalized verson of this vector */ inline V2D<VTYPE> normal() const { V2D<VTYPE> norm(*this); return norm.normalize(); } /** @return radians between these normalized vector is */ inline VTYPE piRadians(const V2D<VTYPE> & v) const { return V2D_COS(dot(v)); } /** @return radians that this normalized vector is */ inline VTYPE piRadians() const { return (y<0?-1:1)*piRadians(ZERO_DEGREES()); } /** @return how many degrees (standard 360 degree scale) this is */ inline VTYPE degrees() const { // altered by ME // Math. is not needed here return ((y > 0)?-1:1) * acos(x) * 180/V2D_PI; } /** @param a_normal cos(theta),sin(theta) as x,y values */ inline void rotate(const V2D<VTYPE> & a_normal) { VTYPE len = length(); // remember length data // normalize() // turn vector into simple angle, lose length data divide(len); // same as normalize, but one less function call // calculate turn in-place within a new data structure V2D<VTYPE> turned( // x_ = x*cos(theta) - y*sin(theta) x*a_normal.x - y*a_normal.y, // y_ = x*sin(theta) + y*cos(theta) x*a_normal.y + y*a_normal.x); // memory copy of structure *this = turned; // put length data back into normalized vector multiply(len); } /** @param a_degreePiRadians in piRadians */ inline void rotate(const VTYPE & a_degreePiRadians) { rotate(V2D<VTYPE>(V2D_COS(a_degreePiRadians), V2D_SIN(a_degreePiRadians))); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_pos) const { return V2D<VTYPE>( (a_fwd.x*x) + (a_side.x*y) + (a_pos.x), (a_fwd.y*x) + (a_side.y*y) + (a_pos.y)); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_pos, const V2D<VTYPE> & a_scale) const { return V2D<VTYPE>( (a_scale.x*a_fwd.x*x) + (a_scale.y*a_side.x*y) + (a_pos.x), (a_scale.x*a_fwd.y*x) + (a_scale.y*a_side.y*y) + (a_pos.y)); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side) const { return V2D<VTYPE>((a_fwd.x*x) + (a_side.x*y), (a_fwd.y*x) + (a_side.y*y)); } /** * @param a_fwd vector of translated x dimension * @param a_side vector of translated y dimension * @param a_origin origin to translate this point in relation to */ inline V2D<VTYPE> toLocalSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_origin) const { VTYPE tx = -a_origin.dot(a_fwd); VTYPE ty = -a_origin.dot(a_side); return V2D<VTYPE>( (a_fwd.x*x) + (a_fwd.y*y) + (tx), (a_side.x*x) + (a_side.y*y) + (ty)); } /** * organizes a list of 2D vectors into a circular curve (arc) * @param a_startVector what to start at (normalized vector) * @param a_angle the angle to increment the arc by V2D(piRadians) * @param a_list the list of 2D vectors to map along the arc * @param a_arcs the number of elements in a_list */ static void arc(const V2D<VTYPE> & a_startVector, const V2D<VTYPE> & a_angle, V2D<VTYPE> * a_list, const int & a_arcs) { VTYPE len = a_startVector.length(); // remember length data a_list[0] = a_startVector; // copy starting point for calculations a_list[0].divide(len); // normalize starting point V2D<VTYPE> * lastPoint = &a_list[0]; // faster memory reference than a_list[i-1] // calculate all points in the arc as normals (faster: no division) for(int i = 1; i < a_arcs; ++i) { // calculate rotation in next point (lastPoint+1)->set( // x_ = x*cos(theta) - y*sin(theta) lastPoint->x*a_angle.x - lastPoint->y*a_angle.y, // y_ = x*sin(theta) + y*cos(theta) lastPoint->x*a_angle.y + lastPoint->y*a_angle.x); ++lastPoint; } if(len != 1) { // put length data back into normalized vector for(int i = 0; i < a_arcs; ++i) { // embarassingly parallel a_list[i].multiply(len); } } } /** * ensures wraps this V2D's x/y values around the given rectangular range * @param a_min the minimum x/y * @param a_max the maximum x/y */ inline void wrapAround(const V2D<VTYPE> & a_min, const V2D<VTYPE> & a_max) { VTYPE width = a_max.x - a_min.x; VTYPE height= a_max.y - a_min.y; while(x < a_min.x){ x += width; } while(x > a_max.x){ x -= width; } while(y < a_min.y){ y +=height; } while(y > a_max.y){ y -=height; } } /** @return the position half-way between line a->b */ inline static V2D<VTYPE> between(const V2D<VTYPE> & a, const V2D<VTYPE> & b) { V2D<VTYPE> average = b.sum(a); average.divide(2.0); return average; } /** * @param A,B line 1 * @param C,D line 2 * @param point __OUT to the intersection of line AB and CD * @param dist __OUT the distance along line AB to the intersection * @return true if intersection occurs between the lines */ static inline bool lineIntersection(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & C, const V2D<VTYPE> & D, VTYPE & dist, V2D<VTYPE> & point) { VTYPE rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y); VTYPE rBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x); VTYPE sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y); VTYPE sBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x); if ( (rBot == 0) || (sBot == 0)) { //lines are parallel return false; } VTYPE r = rTop/rBot; VTYPE s = sTop/sBot; dist = A.distance(B) * r; point = A.sum(B.difference(A).product(r)); return ( (r > 0) && (r < 1) && (s > 0) && (s < 1) ); } /** * @param a_out_closestPoint will be closest point to a_point on line AB * @return true if a_out_closestPoint is actually on line AB */ static bool closestPointOnLine(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & a_point, V2D<VTYPE> & a_out_closestPoint) { V2D<VTYPE> r = B.difference(A).perp(); V2D<VTYPE> d = r.product(2).sum(a_point); V2D<VTYPE> c = a_point.difference(r); VTYPE dist; bool intersected = lineIntersection(A, B, c, d, dist, a_out_closestPoint); return intersected; } /** @return if circle (a_point,a_radius) crosses line (A,B) */ static bool lineCrossesCircle(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & a_point, const VTYPE & a_radius, V2D<VTYPE> & a_out_closePoint) { bool connectionOnLine = closestPointOnLine(A, B, a_point, a_out_closePoint); return(connectionOnLine && a_out_closePoint.distance(a_point) <= a_radius) || a_point.distance(A) < a_radius || a_point.distance(B) < a_radius; } // overloaded operators... used sparingly to avoid confusion const V2D<VTYPE> & operator+=(const V2D<VTYPE> & rhs){return add(rhs);} const V2D<VTYPE> & operator-=(const V2D<VTYPE> & rhs){return subtract(rhs);} const V2D<VTYPE> & operator*=(const VTYPE & rhs){return multiply(rhs);} const V2D<VTYPE> & operator/=(const VTYPE & rhs){return divide(rhs);} bool operator==(const V2D<VTYPE> & rhs) const{return isEqual(rhs);} bool operator!=(const V2D<VTYPE> & rhs) const{return !isEqual(rhs);} };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/v2d.h
C++
bsd
16,091
#include "Graph.h" // default constructor Graph::Graph() {} // default destructor // :make sure safer release is called Graph::~Graph() { release(); } // safetly release all data void Graph::release() { // release the adjacency matrix for(int i = 0; i < m_size; ++i) { delete [] m_AdjacencyMatrix[i]; } delete [] m_AdjacencyMatrix; // release the graphNodes for(int i = 0; i < m_nodes.size(); ++i) { m_nodes.get(i)->release(); } // now release the list of nodes itself m_nodes.release(); // release the debug texture m_nodeTex.release(); m_neighborTex.release(); } // set up the graph to be the given size void Graph::initialize(int a_size) { // setup debug texture m_nodeTex.initialize(L"images/graph.png",true); m_neighborTex.initialize(L"images/neighbor.png",true); // setup graph to be the given size m_size = a_size; // create the adjaceny matrix m_AdjacencyMatrix = new bool*[m_size]; for(int i = 0; i < m_size; i++) m_AdjacencyMatrix[i] = new bool[m_size]; // initialize the entire matrix to false for(int y = 0; y < m_size; y++) for(int x = 0; x < m_size; x++) m_AdjacencyMatrix[y][x] = false; } // create a new node with the given world position // the node's id is returned // if -1 is returned an error occured // most likely cause is the graph is full int Graph::createNode(V2DF a_pos) { // first check if the graph is to big if( m_nodes.size() >= m_size ) return -1; // if the graph has room add the node GraphNode* temp = new GraphNode(); temp->initialize(a_pos); m_nodes.add(temp); // return this new nodes id return m_nodes.size() - 1; } // return a reference to the given graph node // return NULL if the node doesn't exist GraphNode* Graph::getNode(int a_node) { // make sure node exists if(a_node >= 0 && a_node < m_nodes.size()) { // return a reference to the node return m_nodes.get(a_node); } // node doesn't exist return NULL return 0; } // creates a one way connection between the two nodes going from start node to end node with the given cost void Graph::setOneWayConnection(int a_start, int a_end, int a_cost) { // make sure the nodes exist if( a_start <= -1 || a_start >= m_size || a_end <= -1 || a_end >= m_size || a_start >= m_nodes.size() || a_end >= m_nodes.size() ) return; // the nodes exist so create the connection // first update the adjacency matrix m_AdjacencyMatrix[a_start][a_end] = true; // second update the start node m_nodes.get(a_start)->addNeighbor( m_nodes.get(a_end), a_cost ); } // create a two way connection between nodes start and end each with their own cost // costA = start -> end // costB = end -> start void Graph::setTwoWayConnection(int a_start, int a_end, int costA, int costB) { // set first connection setOneWayConnection(a_start, a_end, costA); // set second connection setOneWayConnection(a_end, a_start, costB); } // create a two way connection between nodes start and end with the same cost void Graph::setTwoWayConnection(int a_start, int a_end, int a_cost) { // set first connection setOneWayConnection(a_start, a_end, a_cost); // set second connection setOneWayConnection(a_end, a_start, a_cost); } // Used for debugging void Graph::render() { for(int i = 0; i < m_nodes.size(); ++i) { V2DF parent = m_nodes.get(i)->getPosition(); V2DF dif(0.0f,0.0f); V2DF child(0.0f,0.0f); m_nodeTex.draw( parent, 0.0f, 1.0f ); // draw its neighbors float angle = 0.0f; TemplateVector<Connection>* m_neighbors = m_nodes.get(i)->getNeighbors(); for(int j = 0; j < m_neighbors->size(); ++j) { child = m_neighbors->get(j).neighbor->getPosition(); dif = child.difference(parent); angle = atan2f(dif.y,dif.x)*(180.0f/V2D_PI) + 90.0f; m_neighborTex.draw( parent, angle, 1.0f ); } } }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Graph.cpp
C++
bsd
3,908
#pragma once #include "Texture.h" #include "Animation.h" #include "HelpfulData.h" #include "Entity.h" enum WeaponType { FISTS, MANUAL, BAT, AIRPLANE, STAPLEGUN, SPRAY, NAILGUN } ; class Item { private: enum Type {CURRENCY, WEAPON, MISC, AMMO}; Type itemType ; int amount ; public: Item( ) {} //copy constructor Item( int type ) { itemType = (Type)type ; } ~Item( ) {} virtual void use() { --amount ; } void pickup() { ++amount ; } int GetItemType( ) { return itemType ; } }; class Weapon : Item { private: int str; int force; float range; Texture held; Animation animation; Entity bullets ; ClDwn atkDelay; WeaponType weapon ; public: }; class Misc : Item { private: //type of misc items available enum MiscType { KIT, KEY, SUPERGLUE, MEAT, REPELLENT, THROWING } ; Entity miscItem ; Entity* player ; //stores texture type and animation Texture held ; Animation animation ; //holds the type of this item MiscType type ; //used items that have an effect on the map for a time has a duration float duration ; //throwing weapons cause a fixed amount of damage int damage ; public: }; class Ammo : Item { private: enum AmmoType {NONE, TOY, PAPER, STAPLES, HOLYWATER, NAILS}; AmmoType type ; int amount ; public: int GetAmmoType( int w ) ; } ;
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Item.h
C++
bsd
1,370
#include "Tile.h" // default constructor Tile::Tile() {} // default destructor make sure release is called Tile::~Tile() { release(); } // safetly release all data void Tile::release() { m_tex.release(); } // setup tile of given type void Tile::initialize(V2DF pos, int tileType) { // load texture m_tex.initialize(L"images/tileset.png",2,1,2,32,32,true); // setup bounds m_bounds.top = m_tex.SpriteHeight()/-2.0f; m_bounds.bottom = m_tex.SpriteHeight()/2.0f; m_bounds.left = m_tex.SpriteWidth()/-2.0f; m_bounds.right = m_tex.SpriteWidth()/2.0f; // set tileType m_tileType = tileType; m_tex.setCurrentSprite(m_tileType); // set position m_position = pos; } void Tile::render() { m_tex.draw(m_position,0.0f,1.0f); } void Tile::update(float dT) {} // returns collision boundry relative to position FRect Tile::getBounds() { FRect temp = m_bounds; temp.right += m_position.x; temp.left += m_position.x; temp.top += m_position.y; temp.bottom += m_position.y; return temp; }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Tile.cpp
C++
bsd
1,043
#pragma once /** ideal when the size is known at creation time */ template<typename DATA_TYPE> class TemplateArray { protected: /** pointer to the allocated data for the vector */ DATA_TYPE * m_data; /** actual number of allocated elements that we can use */ int m_allocated; public: /** @return value from the list at given index */ inline DATA_TYPE & get(const int & a_index) const { return m_data[a_index]; } /** simple mutator sets a value in the list */ inline void set(const int & a_index, const DATA_TYPE & a_value) { // complex types must overload DATA_TYPE & operator=(const DATA_TYPE &) m_data[a_index] = a_value; } inline void moveDown(const int & a_from, const int & a_offset, int a_size) { for(int i = a_from-a_offset; i < a_size; ++i) { set(i+a_offset, get(i)); } } inline void moveUp(const int & a_from, const int & a_offset, int a_last) { for(int i = a_last-a_offset-1; i >= a_from; --i) { set(i+a_offset, get(i)); } } public: /** @param a_size reallocate the vector to this size */ const bool allocateToSize(const int & a_size) { // reallocate a new list with the given size DATA_TYPE * newList = new DATA_TYPE[a_size]; // if the list could not allocate, fail... if(!newList) return false; // the temp list is the one we will keep, while the old list will be dropped. DATA_TYPE * oldList = m_data; // swap done here so set(index, value) can be called instead of the equals operator m_data = newList; // if there is old data if(oldList) { // when copying old data, make sure no over-writes happen. int smallestSize = m_allocated<a_size?m_allocated:a_size; // fill the new list with the old data for(int i = 0; i < smallestSize; ++i) { set(i, oldList[i]); } // get rid of the old list (so we can maybe use the memory later) delete [] oldList; } // mark the new allocated size (held size of oldList) m_allocated = a_size; return true; } /** note: this method is memory intesive, and should not be in any inner loops... */ void add(const DATA_TYPE & a_value) { allocateToSize(size()+1); set(size()-1, a_value); } /** note: this method is memory intesive, and should not be in any inner loops... */ DATA_TYPE * add() { allocateToSize(size()+1); return &get(size()-1); } /** sets all fields to an initial data state. WARNING: can cause memory leaks if used without care */ inline void init() { m_data = 0; m_allocated = 0; } /** cleans up memory */ inline void release() { if(m_data) { delete [] m_data; m_data = 0; m_allocated = 0; } } ~TemplateArray(){release();} /** @return true if vector allocated this size */ inline bool ensureCapacity(const int & a_size) { if(a_size && m_allocated < a_size) { return allocateToSize(a_size); } return true; } /** @return true of the copy finished correctly */ inline bool copy(const TemplateArray<DATA_TYPE> & a_array) { if(m_allocated != a_array.m_allocated) { release(); allocateToSize(a_array.m_allocated); } for(int i = 0; i < a_array.m_allocated; ++i) { set(i, a_array.get(i)); } return false; } /** copy constructor */ inline TemplateArray( const TemplateArray<DATA_TYPE> & a_array) { init(); copy(a_array); } /** default constructor allocates no list (zero size) */ inline TemplateArray(){init();} /** size constructor */ inline TemplateArray(const int & a_size) { init(); ensureCapacity(a_size); } /** format constructor */ inline TemplateArray(const int & a_size, const DATA_TYPE & a_defaultValue) { init(); ensureCapacity(a_size); for(int i = 0; i < a_size; ++i) set(i, a_defaultValue); } /** @return the size of the list */ inline const int & size() const { return m_allocated; } /** @return the last value in the list */ inline DATA_TYPE & getLast() { return get(size()-1); } /** * @return the raw pointer to the data... * @note dangerous accessor. use it only if you know what you're doing. */ inline DATA_TYPE * getRawList() { return m_data; } /** * @param a_index is overwritten by the next element, which is * overwritten by the next element, and so on, till the last element * @note this operation is memory intensive! */ void remove(const int & a_index) { moveDown(a_index, -1, size()); allocateToSize(m_allocated-1); } /** * @param a_index where to insert a_value. shifts elements in the vector. * @note this operation is memory intensive! */ void insert(const int & a_index, const DATA_TYPE & a_value) { setSize(m_size+1); moveUp(m_data, a_index, 1, size()); set(a_index, a_value); } /** swaps to elements in the vector */ inline void swap(const int & a_index0, const int & a_index1) { DATA_TYPE temp = get(a_index0); set(a_index0, get(a_index1)); set(a_index1, temp); } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex, const int & a_endingIndex) const { for(int i = a_startingIndex; i < a_endingIndex; ++i) { if(get(i) == a_value) return i; } return -1; } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value) const { return indexOf(a_value, 0, size()); } /** * will only work correctly if the TemplateVector is sorted. * @return the index of the given value, -1 if the value is not in the list */ int indexOfWithBinarySearch(const DATA_TYPE & a_value, const int & a_first, const int & a_limit) { if(m_allocated) { int first = a_first, last = a_limit; while (first <= last) { int mid = (first + last) / 2; // compute mid point. if (a_value > m_data[mid]) first = mid + 1; // repeat search in top half. else if (a_value < m_data[mid]) last = mid - 1; // repeat search in bottom half. else return mid; // found it. return position } } return -1; // failed to find key } void setAll(const DATA_TYPE & a_value) { for(int i = 0; i < size(); ++i) { set(i, a_value); } } bool isSorted() { bool sorted = true; for(int i = 1; sorted && i < size(); ++i) { sorted = get(i) >= get(i-1); } return sorted; } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/templatearray.h
C++
bsd
6,548
#pragma once #include "Sound.h" #include "Input.h" #include "Graphics_Lib.h" #include "Entity.h" #include "Player.h" #include "World.h" enum G_State {MENU, CLASS, GAME, DEAD, VICTORY}; // contains all game components class GameEngine { private: bool running; G_State m_state; // audio Sound* pSound; // Input Input* pInput; // Graphics DX2DEngine* p2DEngine; float m_cameraSpeed; /** entity test */ Entity test; Player player; World tWorld; public: GameEngine(); ~GameEngine(); void initialize(); void update(float dT); void render(); void drawText(); void release(); bool isRunning(); void setRunning(bool a_run); void setState(G_State state); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/GameEngine.h
C++
bsd
720
// // This header file is full of usual unversal functions, structs, classes and other includes // #pragma once #include <math.h> #include <time.h> #include <stdlib.h> #include <Windows.h> #include "templatearray.h" #include "templatevector.h" #include "v2d.h" #include <stdio.h> //#include <vld.h> #include <new.h> #define GRID_SIZE 32.0f #define HALF_GRID 16.0f #define BORDER 32.0f struct FRect { float top; float bottom; float right; float left; }; // used to control cool downs of actions // cooldowns/timers are based on the active bool // if active is false then the ability/action is useble // otherwise it is not // make sure to set active to true when the ability is used... // ... to start the timer class ClDwn { private: // cool down control variables float m_duration; float m_newDuration; float m_timePassed; bool m_active; public: ClDwn(); ~ClDwn(); void initialize(float duration); void update(float dT); void activate(); void deActivate(); bool isActive() { return m_active; } void changeDuration(float duration, bool ignoreAcitve); float getTimePassed() { return m_timePassed; } float getDuration() { return m_duration; } }; // seed the random number generator // WARNING: ONLY CALL ONCE AT INITIALIZATION OF GAME void seedRand(); // returns true if the two rects are colliding bool colliding(FRect r1, FRect r2); // returns true if the points lies within the rect bool colliding(V2DF point, FRect rect); // returns a random float between the two given numbers float randomFloat(float min, float max); // returns a random int between the two given numbers int randomInt(int min, int max); // takes in an float rect and converts it to an equivelent windows rect RECT fRectToRECT(FRect a_rect); // takes in a rect and converts it to an equivelent float rect FRect RECTtoFRect(RECT a_rect);
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/HelpfulData.h
C++
bsd
1,911
#pragma once #include "SpriteSheet.h" #include "HelpfulData.h" class Animation : public SpriteSheet { private: ClDwn m_frameSwitch; bool m_playing; bool m_loop; public: Animation(); ~Animation(); void initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, float fps, bool a_loop, bool relativeToCamera); void update(float dT); void setCurrentFrame(int index); void loop(bool a_loop) { m_loop = a_loop; } void pause(); void reset(bool pause); void play(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Animation.h
C++
bsd
539
#include "Texture.h" // default constructor setting initial values to 0 Texture::Texture() { // set view rect to default m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; // set pointers to null engine = 0; } // make sure that safe release is called Texture::~Texture() { release(); } void Texture::setTint(int R, int G, int B) { m_R = R; m_G = G; m_B = B; } // setup texture object and load the given file void Texture::initialize(LPCWSTR fileName, bool relativeToCamera) { // set type to base texture m_type = BASIC; // save relativity to camera m_relativeToCamera = relativeToCamera; // set view rect to default m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; // first get an instance of the graphics engine if(!engine) engine = DX2DEngine::getInstance(); // set color to white by default m_R = m_G = m_B = 255; // get the length of fileName int i = 0; while(fileName[i] != 0) { i++; } // increment one more time for the null terminator i++; // also load from graphics engine textureID = engine->createTexture(fileName, i); } // safetly release all data void Texture::release() { //m_rects.release(); } // draw the texture with the given coordinates // layer is the Z layer the texture will be drawn at void Texture::draw(V2DF pos, float rotAngle, float scale) { int layer = 0; // make sure layer is less than 1 and greater than -1 if(layer >= 0.1) layer = .9; if(layer < 0) layer = 0; // check if a view rect has been set if(m_viewRect.top == -1) { // pass in view rect engine->renderTexture(textureID, pos, layer, scale, rotAngle, 0, m_R, m_G, m_B, m_relativeToCamera); } else { // pass in 0 for sprite sheet rect engine->renderTexture(textureID, pos, layer, scale, rotAngle, &m_viewRect, m_R, m_G, m_B, m_relativeToCamera); } } int Texture::imageHeight() { return engine->imageInfo(textureID).Height; } int Texture::imageWidth() { return engine->imageInfo(textureID).Width; } void Texture::resetViewRect() { m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; } // if the view rect is larger than the image it will be set to image limits void Texture::setViewRect(RECT a_viewRect) { // make sure that the rect is limited to the size of the image m_viewRect = a_viewRect; // restrict left if(m_viewRect.left < 0) m_viewRect.left = 0; if(m_viewRect.left > imageWidth()) m_viewRect.left = imageWidth(); // restrict right if(m_viewRect.right < 0) m_viewRect.right = 0; if(m_viewRect.right > imageWidth()) m_viewRect.right = imageWidth(); // restrict top if(m_viewRect.top < 0) m_viewRect.top = 0; if(m_viewRect.top > imageHeight()) m_viewRect.top = imageHeight(); // restrict bottom if(m_viewRect.bottom < 0) m_viewRect.bottom = 0; if(m_viewRect.bottom > imageHeight()) m_viewRect.bottom = imageHeight(); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Texture.cpp
C++
bsd
3,021
#pragma once ////////////////////////////////////////////////////////////////////////// // FMOD ////////////////////////////////////////////////////////////////////////// #include <fmod.h> #include <fmod.hpp> #pragma comment(lib, "Fmodex_vc.lib") #define HIT 0 #define PRESS 1 #define FIRE 2 class Sound { private: FMOD::System *system; FMOD_RESULT result; unsigned int version; int numdrivers; FMOD_SPEAKERMODE speakermode; FMOD_CAPS caps; char name[256]; FMOD::Sound *m_soundEffects[3]; FMOD::Channel *m_BGMChannel; Sound(); public: static Sound* getInstance(); ~Sound(); void update(); void initialize(); void release(); void playSound(int sound); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Sound.h
C++
bsd
705
#include "SpriteSheet.h" SpriteSheet::SpriteSheet() {} // make sure safer release is called SpriteSheet::~SpriteSheet() { release(); } // safetly release all data void SpriteSheet::release() { m_rects.release(); } // setup the texture and rects for the sprite sheet // numColumns : number of columns in sheet // numRows : number of rows in sheet // count : total number of sprites in sheet ( can be less than rows * columns ) // spriteHeight : height in pixels of each sprites // spriteWidth : width in pixels of each sprites void SpriteSheet::initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, bool relativeToCamera) { // setup basic sprite Texture::initialize(fileName,relativeToCamera); // set type to sprite sheet m_type = SHEET; // save rows and columns m_rows = numRows; m_columns = numColumns; // default draw sprite to 0 m_index = 0; // generate rects for the sheet // temp rect used to hold the data RECT temp; temp.top = 0; temp.left = 0; temp.right = spriteWidth; temp.bottom = spriteHeight; // control variable to stop generating rects when all are done bool done = false; // generate the individual rects for each sprite for(int y = 0; y < m_rows && !done; ++y) { for(int x = 0; x < m_columns && !done; ++x) { // first make sure count hasn't been succeed if( (x+(m_columns*y)) >= count ) { // all of the rects are finished exit the loops done = true; break; } // set up the rect temp.top = (y * spriteHeight); temp.bottom = (y + 1) * spriteHeight; temp.left = (x * spriteWidth); temp.right = (x + 1) * spriteWidth; // store in the rects list m_rects.add(temp); } } } // the rhe sprite to be drawn during render // returns true if the sprite existed and was set successfully // returns false otherwise bool SpriteSheet::setCurrentSprite(int index) { if( index >= 0 && index < m_rects.size() ) { m_index = index; return true; } return false; } // draw the current sprite at the given position with the given scale and angle void SpriteSheet::draw(V2DF pos, float rotAngle, float scale) { int layer = 0; // make sure layer is less than 1 and greater than -1 if(layer > 1) layer = 1; if(layer < 0) layer = 0; // get the sprite's rect RECT temp = m_rects.get(m_index); if(m_viewRect.top != -1) { // augment this rect by the view rect // only augment them if they are not equal if(temp.top != m_viewRect.top) temp.top -= m_viewRect.top; if(temp.left != m_viewRect.left) temp.left -= m_viewRect.left; if(temp.right != m_viewRect.right) temp.right -= m_viewRect.right; if(temp.bottom != m_viewRect.bottom) temp.bottom -= m_viewRect.bottom; } // draw the texture engine->renderTexture(textureID, pos, layer, scale, rotAngle, &temp, m_R, m_G, m_B, m_relativeToCamera); } // will be restricted to size of individual sprite void SpriteSheet::setViewRect(RECT a_viewRect) { // make sure that the rect is limited to the size of the image m_viewRect = a_viewRect; // restrict left if(m_viewRect.left < 0) m_viewRect.left = 0; if(m_viewRect.left > SpriteWidth()) m_viewRect.left = SpriteWidth(); // restrict right if(m_viewRect.right < 0) m_viewRect.right = 0; if(m_viewRect.right > SpriteWidth()) m_viewRect.right = SpriteWidth(); // restrict top if(m_viewRect.top < 0) m_viewRect.top = 0; if(m_viewRect.top > SpriteHeight()) m_viewRect.top = SpriteHeight(); // restrict bottom if(m_viewRect.bottom < 0) m_viewRect.bottom = 0; if(m_viewRect.bottom > SpriteHeight()) m_viewRect.bottom = SpriteHeight(); // now it will be re-made so that it represents the difference between a sprite-rect m_viewRect.top = m_rects.get(0).top - m_viewRect.top; m_viewRect.bottom = m_rects.get(0).bottom - m_viewRect.bottom; m_viewRect.left = m_rects.get(0).left - m_viewRect.left; m_viewRect.right = m_rects.get(0).right - m_viewRect.right; }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/SpriteSheet.cpp
C++
bsd
4,094
#pragma once #include "Player.h" Player::Player() { tex.initialize(L"\images\test.png",true); stats.str = 0; stats.health = 0; stats.tough = 0; stats.agil = 0; stats.weight = 0; orientation = NORTH; speed = 300.0f; pInput = Input::getInstance(); } Player::~Player() { pInput->release(); } void Player::Update(float dT) { // Movement if(pInput->keyDown(DIK_W)) { position.y -= speed * dT; } if(pInput->keyDown(DIK_S)) { position.y += speed * dT; } if(pInput->keyDown(DIK_A)) { position.x -= speed * dT; } if(pInput->keyDown(DIK_D)) { position.x += speed * dT; } // Facing if(pInput->keyPressed(DIK_UP)) { orientation = NORTH; } if(pInput->keyPressed(DIK_DOWN)) { orientation = SOUTH; } if(pInput->keyPressed(DIK_LEFT)) { orientation = WEST; } if(pInput->keyPressed(DIK_RIGHT)) { orientation = EAST; } setFacing(orientation); DX2DEngine::getInstance()->setCamera(position); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Player.cpp
C++
bsd
972
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" #include "Floor.h" extern class Entity; extern class GraphNode; #define NUM_FLOORS 10 class World { private: Floor m_floors[NUM_FLOORS]; int m_currentFloor; public: World(); ~World(); void release(); void initialize(); void setCurrentFloor(int nFloor); inline int getCurrentFloor() { return m_currentFloor; } bool FloorVisited(int floor); inline bool FloorVisited() { return m_floors[m_currentFloor].FloorVisited(); } bool FloorCleared(int floor); inline bool FloorCleared() { return m_floors[m_currentFloor].FloorCleared(); } bool WallCollision(Entity * entity); void update(float dT); void render(); //void renderMiniMap(); //void renderWorldMap(); inline GraphNode * getNode(V2DF position) { return m_floors[m_currentFloor].getNode(position); } inline GraphNode * getNode(int id) { return m_floors[m_currentFloor].getNode(id); } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/World.h
C++
bsd
953
#pragma once // Direct Input includes #include <dinput.h> #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") #include "v2d.h" // This class handles input for the entire game and is a singleton for ease of use class Input { private: HWND m_hWnd; IDirectInput8 * m_pDInput; // Direct Input Object IDirectInputDevice8 * m_pKeyboard; // Keyboard Object IDirectInputDevice8 * m_pMouse; // Mouse Object // keyboard states bool keysLastUpdate[256]; // used to detect whether a given key was pressed last frame char mKeyboardState[256]; // mouse states DIMOUSESTATE2 mMouseState; Input(); public: ~Input(); void initialize(HINSTANCE hInst, HWND hWnd); void pollDevices(); void release(); bool keyDown(int key); bool keyPressed(int key); bool mouseButtonDown(int button); V2DF getMousePos(); static Input* getInstance(); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Input.h
C++
bsd
890
#pragma once #include "HelpfulData.h" #include "GraphNode.h" #include "Texture.h" class Graph { private: // the number of nodes in the graph int m_size; // relation ship of nodes in the graph bool **m_AdjacencyMatrix; // all nodes in the graph TemplateVector<GraphNode*> m_nodes; // texture used for debugging Texture m_nodeTex; Texture m_neighborTex; public: Graph(); ~Graph(); void release(); void initialize(int a_size); int createNode(V2DF a_pos); void setOneWayConnection(int a_start, int a_end, int cost); void setTwoWayConnection(int a_start, int a_end, int costA, int costB); void setTwoWayConnection(int a_start, int a_end, int costA); void render(); GraphNode* getNode(int a_node); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Graph.h
C++
bsd
742
#pragma once #include "DX2DEngine.h" #include "HelpfulData.h" enum Orientation {TOP_LEFT,TOP_RIGHT,CENTER,BOT_RIGHT,BOT_LEFT,TOP_CENTER,BOT_CENTER}; class Message_Box { private: char * m_message; int m_length; V2DF m_pos; int m_width; int m_height; Orientation m_drawPoint; Orientation m_textPoint; int m_A; int m_R; int m_G; int m_B; public: Message_Box(); ~Message_Box(); void release(); void initialize(char * message, int length, V2DF pos, int width, int height, Orientation drawPoint, Orientation textPoint, int A, int R, int G, int B); void drawText(); void changeDrawPoint(Orientation drawPoint) { m_drawPoint = drawPoint; } void changeTextPoint(Orientation textPoint) { m_textPoint = textPoint; } V2DF getPosition() { return m_pos; } void changeMessage(char * message, int length); void changePosition(V2DF pos) { m_pos = pos; } float getWidth() { return m_width; } float getHeight() { return m_height; } void changeBounds(int width, int height) { m_width = width; m_height = height; } };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/MessageBox.h
C++
bsd
1,056
#pragma once // all DirectX 2D classes #include "DX2DEngine.h" #include "Texture.h" #include "SpriteSheet.h" #include "Animation.h" #include "Line.h" #include "MessageBox.h"
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Graphics_Lib.h
C
bsd
182
#include "GraphNode.h" GraphNode::GraphNode() {} // make sure the safer release is called GraphNode::~GraphNode() {release();} void GraphNode::release() { m_neighbors.release(); } // setup node at given position void GraphNode::initialize(V2DF a_pos) { totalNeighbors = 0; m_position = a_pos; } // create a connection with the given neighbor and add it to the list void GraphNode::addNeighbor(GraphNode* a_neighbor, float a_cost) { totalNeighbors++; Connection temp; temp.neighbor = a_neighbor; temp.cost = a_cost; m_neighbors.add(temp); } int GraphNode::getNeighborCount() { return totalNeighbors; } TemplateVector<Connection>* GraphNode::getNeighbors() { return &m_neighbors; } V2DF GraphNode::getPosition() { return m_position; } // returns the hueristic value between the given node and this node float GraphNode::Hueristic(GraphNode* other) { // make sure other exists if(!other) return 0.0f; // calculate hueristic return other->getPosition().difference( m_position ).length(); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/GraphNode.cpp
C++
bsd
1,063
#include "MessageBox.h" // set data to defaults Message_Box::Message_Box() { m_message = 0; m_length = 0; } // make sure safer release is called Message_Box::~Message_Box() { release(); } // safetly release all data void Message_Box::release() { if(m_message) { delete [] m_message; m_message = 0; m_length = 0; } } // setup message box void Message_Box::initialize(char * message, int length, V2DF pos, int width, int height, Orientation drawPoint, Orientation textPoint, int A, int R, int G, int B) { // if a message already exists release it first if(m_message) release(); // setup message m_length = length; m_message = new char[m_length+1]; for(int i = 0; i < m_length; i++) { m_message[i] = message[i]; } m_message[m_length] = 0; // save position and bounds m_pos = pos; m_height = height; m_width = width; // save orientations m_drawPoint = drawPoint; m_textPoint = textPoint; // set color m_A = A; m_R = R; m_G = G; m_B = B; } // draw the message void Message_Box::drawText() { // get engine reference DX2DEngine * p2dEngine = DX2DEngine::getInstance(); // build rect from position and orientation RECT bounds; switch (m_drawPoint) { case TOP_LEFT: bounds.top = -m_height; bounds.left = -m_width; bounds.right = 0; bounds.bottom = 0; break; case TOP_RIGHT: bounds.top = -m_height; bounds.left = 0; bounds.right = m_width; bounds.bottom = 0; break; case CENTER: bounds.top = -m_height/2; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = m_height/2; break; case BOT_RIGHT: bounds.top = 0; bounds.left = 0; bounds.right = m_width; bounds.bottom = m_height; break; case BOT_LEFT: bounds.top = 0; bounds.left = -m_width; bounds.right = 0; bounds.bottom = m_height; break; case TOP_CENTER: bounds.top = -m_height; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = 0; break; case BOT_CENTER: bounds.top = 0; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = m_height; break; default: break; } // add position bounds.right += m_pos.x; bounds.left += m_pos.x; bounds.top += m_pos.y; bounds.bottom += m_pos.y; DWORD formating; // determine orientation switch (m_textPoint) { case TOP_LEFT: formating = DT_TOP | DT_LEFT | DT_NOCLIP; break; case TOP_RIGHT: formating = DT_TOP | DT_RIGHT | DT_NOCLIP; break; case CENTER: formating = DT_CENTER | DT_VCENTER | DT_NOCLIP; break; case BOT_RIGHT: formating = DT_BOTTOM | DT_RIGHT | DT_NOCLIP; break; case BOT_LEFT: formating = DT_BOTTOM | DT_LEFT | DT_NOCLIP; break; case TOP_CENTER: formating = DT_TOP | DT_CENTER | DT_NOCLIP; break; case BOT_CENTER: formating = DT_BOTTOM | DT_CENTER | DT_NOCLIP; break; default: break; } // write text to the screen p2dEngine->writeText(m_message,bounds,D3DCOLOR_ARGB(255,m_R,m_G,m_B),formating); }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/MessageBox.cpp
C++
bsd
3,052
#pragma once #include "Texture.h" class SpriteSheet : public Texture { protected: TemplateVector<RECT> m_rects; int m_index; int m_rows; int m_columns; public: SpriteSheet(); ~SpriteSheet(); void release(); void initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, bool relativeToCamera); bool setCurrentSprite(int index); virtual void draw(V2DF pos, float rotAngle, float scale); int getCurrentSprite() { return m_index; } int getImageCount() { return m_rects.size(); } int SpriteHeight() { return m_rects.get(0).bottom; } int SpriteWidth() { return m_rects.get(0).right; } int rows() { return m_rows; } int columns() { return m_columns; } void setViewRect(RECT a_viewRect); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/SpriteSheet.h
C++
bsd
771
#pragma once /////////////////////////////////////////////////////////////////////////// // General Windows includes /////////////////////////////////////////////////////////////////////////// #include <stdio.h> #pragma comment(lib, "winmm.lib") ////////////////////////////////////////////////////////////////////////// // Direct3D 9 headers and libraries required ////////////////////////////////////////////////////////////////////////// #include <d3d9.h> #include <d3dx9.h> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") // used for windows error text box #include <WinUser.h> #include "v2d.h" #include "templatearray.h" #include "templatevector.h" #include "HelpfulData.h" // texture struct // saves the need for two lists of image info and images themselves struct TextureInfo { int length; // file name length char* name; // File name IDirect3DTexture9* m_pTexture; // Texture Object for a sprite D3DXIMAGE_INFO m_imageInfo; // File details of a texture }; // Singleton for basic graphics use // Simply an in-between making drawing 2d sprites in direct x easier class DX2DEngine { private: // Application variables HWND m_hWnd; bool m_bVsync; // Direct X objects/devices IDirect3D9* m_pD3DObject; // Direct3D 9 Object IDirect3DDevice9* m_pD3DDevice; // Direct3D 9 Device D3DCAPS9 m_D3DCaps; // Device Capabilities // Direct X sprites variable ID3DXSprite* m_pSprite; // Sprite Object // Direct X font variable ID3DXFont* m_pFont; // Font Object // Vector of currently loaded textures TemplateVector<TextureInfo*> m_textures; // frames per second int fps; // current number of frames rendered int frameCount; // elapsed time // used to calculate fps float elapsedTime; // camera controllers V2DF camera; V2DF screen_center; float zoom; DX2DEngine(); public: // basic functions ~DX2DEngine(); static DX2DEngine* getInstance(); void initialize(HWND& hWnd, HINSTANCE& hInst, bool bWindowed); void release(); // update to calculate fps void update(float dT); float getFPS(); // render controlers void start2DRender(); void end2DRender(); void startSprite(); void endSprite(); // accessors ID3DXSprite* spriteRef(); ID3DXFont* fontRef(); IDirect3DDevice9* deviceRef(); // Text drawing/writing functions void writeText(char *text, V2DF pos, float width, float height, D3DCOLOR color); void writeText(char *text, RECT bounds, D3DCOLOR color); void writeText(char *text, RECT bounds, D3DCOLOR color, DWORD format); void writeCenterText(char *text, RECT bounds, D3DCOLOR color); // Texture creation functions int createTexture(LPCWSTR file, int length); // Texture rendering functions void renderTexture(int index, // index of the texture V2DF pos, float layer, float scale, float angle, // position data RECT *m_sheetRect, // culling rect : used for sprite sheets int r, int g, int b, // color tint bool relativeToCamera); // true:draw relative to the camera false:don't void moveCamera(V2DF dist); void setCamera(V2DF pos); V2DF getCamera(); V2DF screenCenter(); void setZoom(float a_zoom); void zoomInOut(float aug); float getZoom(); D3DXIMAGE_INFO imageInfo(int textureID); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/DX2DEngine.h
C++
bsd
3,328
#include "Line.h" // make sure pointer is 0 Line::Line() { m_tex = 0; } // make sure safe release is called Line::~Line() { release(); } // safetly release all stored data void Line::release() { } // setup texture and start and end points void Line::initialize(Texture * a_tex, V2DF start, V2DF end) { // save texture reference m_tex = a_tex; // set start and end points m_start = start; m_end = end; calculate(); } // set start point and recalculate length/angle void Line::setStart(V2DF start) { // set start m_start = start; calculate(); } // set end point and recalculate length/angle void Line::setEnd(V2DF end) { // end points m_end = end; calculate(); } // determine how many times the texture must be drawn and if .... // a portion of the texture must be drawn void Line::calculate() { // save sprite height and width // if the texture is a sprite sheet or animation get the individual height and widht if(m_tex->getType() == SHEET || m_tex->getType() == ANIMATION) { // a sprite sheet pointer will work fine for either SpriteSheet * temp = (SpriteSheet*)m_tex; m_spriteHeight = temp->SpriteHeight(); m_spriteWidth = temp->SpriteWidth(); } // otherwise get the image height and width else { m_spriteHeight = m_tex->imageHeight(); m_spriteWidth = m_tex->imageWidth(); } // calculate length V2DF difference = m_end.difference(m_start); m_length = difference.length(); // calculate angle m_angle = atan2f(difference.y,difference.x)*(180.0f/V2D_PI); // determine the number of times the image must be drawn m_numSprites = (int)m_length / m_spriteHeight; // now check if a portion of a sprite must be drawn if( (int)m_length % m_spriteHeight != 0 ) { float remainder = m_spriteHeight - ( m_length - (m_spriteHeight * m_numSprites) ) ; RECT temp; // cut off the top of the texture temp.top = (int)remainder; // leave the rest the same temp.left = 0; temp.right = m_spriteWidth; temp.bottom = m_spriteHeight; m_lastSprite = temp; } } // render the line from start point to end point void Line::render() { // float angleRad = (V2D_PI / 180.0f) * wanderAngle; // steeringForce = V2DF( cos(angleRad), sin(angleRad) ).product( 10 ); // calculate half of the image length float halfImage = (float)m_spriteHeight / 2.0f; // convert angle to radians float angleRad = (V2D_PI / 180.0f) * m_angle; // create vector based on half image length and angle in radians V2DF halfImageLength( cos(angleRad), sin(angleRad) ); // get vector of full image length V2DF imageLength = halfImageLength.product( m_spriteHeight ); halfImageLength.multiply( halfImage ); // set up draw position V2DF drawPos; if(m_numSprites > 0) drawPos = m_start.sum( halfImageLength ); else drawPos = m_end; // reset textures view rect m_tex->resetViewRect(); // draw each sprite for(int i = 0; i < m_numSprites; i++) { // add image length if(i > 0) drawPos.add(imageLength); m_tex->draw(drawPos, m_angle+90.0f,1.0f); } // now check if a portion of a sprite must be drawn if( (int)m_length % m_spriteHeight != 0 ) { m_tex->setViewRect(m_lastSprite); if(m_numSprites > 0) { // determine mid point between end of the last full texture drawn and the end of the line drawPos.add(halfImageLength); drawPos = drawPos.difference(m_end).product(0.5f).sum(m_end); } else { // the length of the line is less than // determine the mid point between the start and end points of the line drawPos = m_start.difference(m_end).product(0.5f).sum(m_end); } // draw the final partial sprite m_tex->draw(drawPos,m_angle+90.0f,1.0f); } } // used if the texture is an animation void Line::update(float dT) { if( m_tex->getType() == ANIMATION ) { // update the texture Animation * temp = (Animation*)m_tex; temp->update(dT); } }
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Line.cpp
C++
bsd
3,971
#pragma once #include "Tile.h" #include "Entity.h" #include "Graph.h" #define FLOORSIZE 30 class Floor { private: Tile m_layout[FLOORSIZE][FLOORSIZE]; bool m_cleared; bool m_visited; public: Floor(); ~Floor(); void release(); void intialize(char * fileName); void update(float dT); void render(); bool WallCollision(Entity * entity); inline bool FloorCleared() { return m_cleared; } inline bool FloorVisited() { return m_visited; } GraphNode * getNode(V2DF position); GraphNode * getNode(int id); };
011913-gdg-incorpserated
trunk/Incorpserated/Incorpserated/Floor.h
C++
bsd
540
#region Header /** * IJsonWrapper.cs * Interface that represents a type capable of handling all kinds of JSON * data. This is mainly used when mapping objects through JsonMapper, and * it's implemented by JsonData. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System.Collections; using System.Collections.Specialized; namespace LitJson { public enum JsonType { None, Object, Array, String, Int, Long, Double, Boolean } public interface IJsonWrapper : IList, IOrderedDictionary { bool IsArray { get; } bool IsBoolean { get; } bool IsDouble { get; } bool IsInt { get; } bool IsLong { get; } bool IsObject { get; } bool IsString { get; } bool GetBoolean (); double GetDouble (); int GetInt (); JsonType GetJsonType (); long GetLong (); string GetString (); void SetBoolean (bool val); void SetDouble (double val); void SetInt (int val); void SetJsonType (JsonType type); void SetLong (long val); void SetString (string val); string ToJson (); void ToJson (JsonWriter writer); } }
13159828-litjsonmd
IJsonWrapper.cs
C#
gpl3
1,407
#region Header /** * JsonReader.cs * Stream-like access to JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, Double, String, Boolean, Null } public class JsonReader { #region Fields private static IDictionary<int, IDictionary<int, int[]>> parse_table; private Stack<int> automaton_stack; private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors static JsonReader() { PopulateParseTable(); } public JsonReader(string json_text) : this(new StringReader(json_text), true) { } public JsonReader(TextReader reader) : this(reader, false) { } private JsonReader(TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException("reader"); parser_in_string = false; parser_return = false; read_started = false; automaton_stack = new Stack<int>(); automaton_stack.Push((int)ParserToken.End); automaton_stack.Push((int)ParserToken.Text); lexer = new Lexer(reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } #endregion #region Static Methods private static void PopulateParseTable() { parse_table = new Dictionary<int, IDictionary<int, int[]>>(); TableAddRow(ParserToken.Array); TableAddCol(ParserToken.Array, '[', '[', (int)ParserToken.ArrayPrime); TableAddRow(ParserToken.ArrayPrime); TableAddCol(ParserToken.ArrayPrime, '"', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, '[', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, ']', ']'); TableAddCol(ParserToken.ArrayPrime, '{', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, (int)ParserToken.Number, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, (int)ParserToken.True, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, (int)ParserToken.False, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddCol(ParserToken.ArrayPrime, (int)ParserToken.Null, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']'); TableAddRow(ParserToken.Object); TableAddCol(ParserToken.Object, '{', '{', (int)ParserToken.ObjectPrime); TableAddRow(ParserToken.ObjectPrime); TableAddCol(ParserToken.ObjectPrime, '"', (int)ParserToken.Pair, (int)ParserToken.PairRest, '}'); TableAddCol(ParserToken.ObjectPrime, '}', '}'); TableAddRow(ParserToken.Pair); TableAddCol(ParserToken.Pair, '"', (int)ParserToken.String, ':', (int)ParserToken.Value); TableAddRow(ParserToken.PairRest); TableAddCol(ParserToken.PairRest, ',', ',', (int)ParserToken.Pair, (int)ParserToken.PairRest); TableAddCol(ParserToken.PairRest, '}', (int)ParserToken.Epsilon); TableAddRow(ParserToken.String); TableAddCol(ParserToken.String, '"', '"', (int)ParserToken.CharSeq, '"'); TableAddRow(ParserToken.Text); TableAddCol(ParserToken.Text, '[', (int)ParserToken.Array); TableAddCol(ParserToken.Text, '{', (int)ParserToken.Object); TableAddRow(ParserToken.Value); TableAddCol(ParserToken.Value, '"', (int)ParserToken.String); TableAddCol(ParserToken.Value, '[', (int)ParserToken.Array); TableAddCol(ParserToken.Value, '{', (int)ParserToken.Object); TableAddCol(ParserToken.Value, (int)ParserToken.Number, (int)ParserToken.Number); TableAddCol(ParserToken.Value, (int)ParserToken.True, (int)ParserToken.True); TableAddCol(ParserToken.Value, (int)ParserToken.False, (int)ParserToken.False); TableAddCol(ParserToken.Value, (int)ParserToken.Null, (int)ParserToken.Null); TableAddRow(ParserToken.ValueRest); TableAddCol(ParserToken.ValueRest, ',', ',', (int)ParserToken.Value, (int)ParserToken.ValueRest); TableAddCol(ParserToken.ValueRest, ']', (int)ParserToken.Epsilon); } private static void TableAddCol(ParserToken row, int col, params int[] symbols) { parse_table[(int)row].Add(col, symbols); } private static void TableAddRow(ParserToken rule) { parse_table.Add((int)rule, new Dictionary<int, int[]>()); } #endregion #region Private Methods private void ProcessNumber(string number) { if (number.IndexOf('.') != -1 || number.IndexOf('e') != -1 || number.IndexOf('E') != -1) { double n_double; if (Double.TryParse(number, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse(number, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol() { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int)ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int)ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int)ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int)ParserToken.Number) { ProcessNumber(lexer.StringValue); parser_return = true; } else if (current_symbol == (int)ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int)ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken() { if (end_of_input) return false; lexer.NextToken(); if (lexer.EndOfInput) { Close(); return false; } current_input = lexer.Token; return true; } #endregion public void Close() { if (end_of_input) return; end_of_input = true; end_of_json = true; if (reader_is_owned) reader.Close(); reader = null; } public bool Read() { if (end_of_input) return false; if (end_of_json) { end_of_json = false; automaton_stack.Clear(); automaton_stack.Push((int)ParserToken.End); automaton_stack.Push((int)ParserToken.Text); } parser_in_string = false; parser_return = false; token = JsonToken.None; token_value = null; if (!read_started) { read_started = true; if (!ReadToken()) return false; } int[] entry_symbols; while (true) { if (parser_return) { if (automaton_stack.Peek() == (int)ParserToken.End) end_of_json = true; return true; } current_symbol = automaton_stack.Pop(); ProcessSymbol(); if (current_symbol == current_input) { if (!ReadToken()) { if (automaton_stack.Peek() != (int)ParserToken.End) throw new JsonException( "Input doesn't evaluate to proper JSON text"); if (parser_return) return true; return false; } continue; } try { entry_symbols = parse_table[current_symbol][current_input]; } catch (KeyNotFoundException e) { throw new JsonException((ParserToken)current_input, e); } if (entry_symbols[0] == (int)ParserToken.Epsilon) continue; for (int i = entry_symbols.Length - 1; i >= 0; i--) automaton_stack.Push(entry_symbols[i]); } } } }
13159828-litjsonmd
JsonReader.cs
C#
gpl3
14,303
#region Header /** * JsonMapper.cs * JSON to .Net object and object to JSON conversions. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof(JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof(JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc(object obj, JsonWriter writer); public delegate void ExporterFunc<T>(T obj, JsonWriter writer); internal delegate object ImporterFunc(object input); public delegate TValue ImporterFunc<TJson, TValue>(TJson input); public delegate IJsonWrapper WrapperFactory(); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object(); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object(); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object(); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object(); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object(); #endregion #region Constructors static JsonMapper() { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata>(); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>>(); object_metadata = new Dictionary<Type, ObjectMetadata>(); type_properties = new Dictionary<Type, IList<PropertyMetadata>>(); static_writer = new JsonWriter(); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc>(); custom_exporters_table = new Dictionary<Type, ExporterFunc>(); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>>(); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>>(); RegisterBaseExporters(); RegisterBaseImporters(); } #endregion #region Private Methods private static void AddArrayMetadata(Type type) { if (array_metadata.ContainsKey(type)) return; ArrayMetadata data = new ArrayMetadata(); data.IsArray = type.IsArray; if (type.GetInterface("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters(); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof(int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add(type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata(Type type) { if (object_metadata.ContainsKey(type)) return; ObjectMetadata data = new ObjectMetadata(); if (type.GetInterface("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata>(); foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters(); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof(string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add(p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields()) { PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add(f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add(type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties(Type type) { if (type_properties.ContainsKey(type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata>(); foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = p_info; p_data.IsField = false; props.Add(p_data); } foreach (FieldInfo f_info in type.GetFields()) { PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = f_info; p_data.IsField = true; props.Add(p_data); } lock (type_properties_lock) { try { type_properties.Add(type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp(Type t1, Type t2) { lock (conv_ops_lock) { if (!conv_ops.ContainsKey(t1)) conv_ops.Add(t1, new Dictionary<Type, MethodInfo>()); } if (conv_ops[t1].ContainsKey(t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add(t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue(Type inst_type, JsonReader reader) { reader.Read(); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { if (!inst_type.IsClass) throw new JsonException(String.Format( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType(); if (inst_type.IsAssignableFrom(json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey(json_type) && custom_importers_table[json_type].ContainsKey( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer(reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey(json_type) && base_importers_table[json_type].ContainsKey( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer(reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) return Enum.ToObject(inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp(inst_type, json_type); if (conv_op != null) return conv_op.Invoke(null, new object[] { reader.Value }); // No luck throw new JsonException(String.Format( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata(inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (!t_data.IsArray && !t_data.IsList) throw new JsonException(String.Format( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (!t_data.IsArray) { list = (IList)Activator.CreateInstance(inst_type); elem_type = t_data.ElementType; } else { list = new ArrayList(); elem_type = inst_type.GetElementType(); } while (true) { object item = ReadValue(elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) { list.Add(item); list.RemoveAt(list.Count - 1); break; } list.Add(item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance(elem_type, n); for (int i = 0; i < n; i++) ((Array)instance).SetValue(list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata(inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance(inst_type); while (true) { reader.Read(); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string)reader.Value; if (t_data.Properties.ContainsKey(property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo)prop_data.Info).SetValue( instance, ReadValue(prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo)prop_data.Info; if (p_info.CanWrite) p_info.SetValue( instance, ReadValue(prop_data.Type, reader), null); else ReadValue(prop_data.Type, reader); } } else { if (!t_data.IsDictionary) throw new JsonException(String.Format( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary)instance).Add( property, ReadValue( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) { reader.Read(); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory(); if (reader.Token == JsonToken.String) { instance.SetString((string)reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble((double)reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt((int)reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong((long)reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean((bool)reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType(JsonType.Array); while (true) { IJsonWrapper item = ReadValue(factory, reader); if (reader.Token == JsonToken.ArrayEnd && item == null) break; ((IList)instance).Add(item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType(JsonType.Object); while (true) { reader.Read(); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string)reader.Value; ((IDictionary)instance)[property] = ReadValue( factory, reader); } } return instance; } private static void RegisterBaseExporters() { base_exporters_table[typeof(byte)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt32((byte)obj)); }; base_exporters_table[typeof(char)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToString((char)obj)); }; base_exporters_table[typeof(DateTime)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToString((DateTime)obj, datetime_format)); }; base_exporters_table[typeof(decimal)] = delegate(object obj, JsonWriter writer) { writer.Write((decimal)obj); }; base_exporters_table[typeof(sbyte)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt32((sbyte)obj)); }; base_exporters_table[typeof(short)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt32((short)obj)); }; base_exporters_table[typeof(ushort)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt32((ushort)obj)); }; base_exporters_table[typeof(uint)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToUInt64((uint)obj)); }; base_exporters_table[typeof(ulong)] = delegate(object obj, JsonWriter writer) { writer.Write((ulong)obj); }; } private static void RegisterBaseImporters() { ImporterFunc importer; importer = delegate(object input) { return Convert.ToByte((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(byte), importer); importer = delegate(object input) { return Convert.ToUInt64((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(ulong), importer); importer = delegate(object input) { return Convert.ToSByte((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(sbyte), importer); importer = delegate(object input) { return Convert.ToInt16((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(short), importer); importer = delegate(object input) { return Convert.ToUInt16((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(ushort), importer); importer = delegate(object input) { return Convert.ToUInt32((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(uint), importer); importer = delegate(object input) { return Convert.ToSingle((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(float), importer); importer = delegate(object input) { return Convert.ToDouble((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(double), importer); importer = delegate(object input) { return Convert.ToDecimal((double)input); }; RegisterImporter(base_importers_table, typeof(double), typeof(decimal), importer); importer = delegate(object input) { return Convert.ToUInt32((long)input); }; RegisterImporter(base_importers_table, typeof(long), typeof(uint), importer); importer = delegate(object input) { return Convert.ToChar((string)input); }; RegisterImporter(base_importers_table, typeof(string), typeof(char), importer); importer = delegate(object input) { return Convert.ToDateTime((string)input, datetime_format); }; RegisterImporter(base_importers_table, typeof(string), typeof(DateTime), importer); } private static void RegisterImporter( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (!table.ContainsKey(json_type)) table.Add(json_type, new Dictionary<Type, ImporterFunc>()); table[json_type][value_type] = importer; } private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); else ((IJsonWrapper)obj).ToJson(writer); return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Single) { writer.Write((double)(float)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) WriteValue(elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) WriteValue(elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) writer.Write((ulong)obj); else writer.Write((int)obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); } #endregion public static string ToJson(object obj) { lock (static_writer_lock) { static_writer.Reset(); WriteValue(obj, static_writer, true, 0); return static_writer.ToString(); } } public static void ToJson(object obj, JsonWriter writer) { WriteValue(obj, writer, false, 0); } public static JsonData ToObject(JsonReader reader) { return (JsonData)ToWrapper( delegate { return new JsonData(); }, reader); } public static JsonData ToObject(TextReader reader) { JsonReader json_reader = new JsonReader(reader); return (JsonData)ToWrapper( delegate { return new JsonData(); }, json_reader); } public static JsonData ToObject(string json) { return (JsonData)ToWrapper( delegate { return new JsonData(); }, json); } public static T ToObject<T>(JsonReader reader) { return (T)ReadValue(typeof(T), reader); } public static T ToObject<T>(TextReader reader) { JsonReader json_reader = new JsonReader(reader); return (T)ReadValue(typeof(T), json_reader); } public static T ToObject<T>(string json) { JsonReader reader = new JsonReader(json); return (T)ReadValue(typeof(T), reader); } public static IJsonWrapper ToWrapper(WrapperFactory factory, JsonReader reader) { return ReadValue(factory, reader); } public static IJsonWrapper ToWrapper(WrapperFactory factory, string json) { JsonReader reader = new JsonReader(json); return ReadValue(factory, reader); } public static void RegisterExporter<T>(ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate(object obj, JsonWriter writer) { exporter((T)obj, writer); }; custom_exporters_table[typeof(T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue>( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate(object input) { return importer((TJson)input); }; RegisterImporter(custom_importers_table, typeof(TJson), typeof(TValue), importer_wrapper); } public static void UnregisterExporters() { custom_exporters_table.Clear(); } public static void UnregisterImporters() { custom_importers_table.Clear(); } } }
13159828-litjsonmd
JsonMapper.cs
C#
gpl3
32,111
#region Header /** * JsonWriter.cs * Stream-like facility to output JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter() { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter() { inst_string_builder = new StringBuilder(); writer = new StringWriter(inst_string_builder); Init(); } public JsonWriter(StringBuilder sb) : this(new StringWriter(sb)) { } public JsonWriter(TextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); this.writer = writer; Init(); } #endregion #region Private Methods private void DoValidation(Condition cond) { if (!context.ExpectingValue) context.Count++; if (!validate) return; if (has_reached_end) throw new JsonException( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (!context.InArray) throw new JsonException( "Can't close an array here"); break; case Condition.InObject: if (!context.InObject || context.ExpectingValue) throw new JsonException( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && !context.ExpectingValue) throw new JsonException( "Expected a property"); break; case Condition.Property: if (!context.InObject || context.ExpectingValue) throw new JsonException( "Can't add a property here"); break; case Condition.Value: if (!context.InArray && (!context.InObject || !context.ExpectingValue)) throw new JsonException( "Can't add a value here"); break; } } private void Init() { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext>(); context = new WriterContext(); ctx_stack.Push(context); } private static void IntToHex(int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char)('0' + num); else hex[3 - i] = (char)('A' + (num - 10)); n >>= 4; } } private void Indent() { if (pretty_print) indentation += indent_value; } private void Put(string str) { if (pretty_print && !context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write(' '); writer.Write(str); } private void PutNewline() { PutNewline(true); } private void PutNewline(bool add_comma) { if (add_comma && !context.ExpectingValue && context.Count > 1) writer.Write(','); if (pretty_print && !context.ExpectingValue) writer.Write('\n'); } private void PutString(string str) { Put(String.Empty); writer.Write('"'); int n = str.Length; for (int i = 0; i < n; i++) { switch (str[i]) { case '\n': writer.Write("\\n"); continue; case '\r': writer.Write("\\r"); continue; case '\t': writer.Write("\\t"); continue; case '"': case '\\': writer.Write('\\'); writer.Write(str[i]); continue; case '\f': writer.Write("\\f"); continue; case '\b': writer.Write("\\b"); continue; } //if ((int) str[i] >= 32 && (int) str[i] <= 126) { writer.Write(str[i]); continue; //} // Default, turn into a \uXXXX sequence //IntToHex ((int) str[i], hex_seq); //writer.Write ("\\u"); //writer.Write (hex_seq); } writer.Write('"'); } private void Unindent() { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString() { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString(); } public void Reset() { has_reached_end = false; ctx_stack.Clear(); context = new WriterContext(); ctx_stack.Push(context); if (inst_string_builder != null) inst_string_builder.Remove(0, inst_string_builder.Length); } public void Write(bool boolean) { DoValidation(Condition.Value); PutNewline(); Put(boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write(decimal number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write(double number) { DoValidation(Condition.Value); PutNewline(); string str = Convert.ToString(number, number_format); Put(str); if (str.IndexOf('.') == -1 && str.IndexOf('E') == -1) writer.Write(".0"); context.ExpectingValue = false; } public void Write(int number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write(long number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write(string str) { DoValidation(Condition.Value); PutNewline(); if (str == null) Put("null"); else PutString(str); context.ExpectingValue = false; } [CLSCompliant(false)] public void Write(ulong number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void WriteArrayEnd() { DoValidation(Condition.InArray); PutNewline(false); ctx_stack.Pop(); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek(); context.ExpectingValue = false; } Unindent(); Put("]"); } public void WriteArrayStart() { DoValidation(Condition.NotAProperty); PutNewline(); Put("["); context = new WriterContext(); context.InArray = true; ctx_stack.Push(context); Indent(); } public void WriteObjectEnd() { DoValidation(Condition.InObject); PutNewline(false); ctx_stack.Pop(); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek(); context.ExpectingValue = false; } Unindent(); Put("}"); } public void WriteObjectStart() { DoValidation(Condition.NotAProperty); PutNewline(); Put("{"); context = new WriterContext(); context.InObject = true; ctx_stack.Push(context); Indent(); } public void WritePropertyName(string property_name) { DoValidation(Condition.Property); PutNewline(); PutString(property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write(' '); writer.Write(": "); } else writer.Write(':'); context.ExpectingValue = true; } } }
13159828-litjsonmd
JsonWriter.cs
C#
gpl3
12,184
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("LitJSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("LitJSON")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("958a5a19-af5f-4b6c-b3e7-c0dbd26c61c7")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13159828-litjsonmd
Properties/AssemblyInfo.cs
C#
gpl3
1,364
#region Header /** * Lexer.cs * JSON lexer implementation based on a finite state machine. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LitJson { internal class FsmContext { public bool Return; public int NextState; public Lexer L; public int StateStack; } internal class Lexer { #region Fields private delegate bool StateHandler(FsmContext ctx); private static int[] fsm_return_table; private static StateHandler[] fsm_handler_table; private bool allow_comments; private bool allow_single_quoted_strings; private bool end_of_input; private FsmContext fsm_context; private int input_buffer; private int input_char; private TextReader reader; private int state; private StringBuilder string_buffer; private string string_value; private int token; private int unichar; #endregion #region Properties public bool AllowComments { get { return allow_comments; } set { allow_comments = value; } } public bool AllowSingleQuotedStrings { get { return allow_single_quoted_strings; } set { allow_single_quoted_strings = value; } } public bool EndOfInput { get { return end_of_input; } } public int Token { get { return token; } } public string StringValue { get { return string_value; } } #endregion #region Constructors static Lexer() { PopulateFsmTables(); } public Lexer(TextReader reader) { allow_comments = true; allow_single_quoted_strings = true; input_buffer = 0; string_buffer = new StringBuilder(128); state = 1; end_of_input = false; this.reader = reader; fsm_context = new FsmContext(); fsm_context.L = this; } #endregion #region Static Methods private static int HexValue(int digit) { switch (digit) { case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return digit - '0'; } } private static void PopulateFsmTables() { fsm_handler_table = new StateHandler[28] { State1, State2, State3, State4, State5, State6, State7, State8, State9, State10, State11, State12, State13, State14, State15, State16, State17, State18, State19, State20, State21, State22, State23, State24, State25, State26, State27, State28 }; fsm_return_table = new int[28] { (int) ParserToken.Char, 0, (int) ParserToken.Number, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, 0, (int) ParserToken.True, 0, 0, 0, (int) ParserToken.False, 0, 0, (int) ParserToken.Null, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, 0, 0 }; } private static char ProcessEscChar(int esc_char) { switch (esc_char) { case '"': case '\'': case '\\': case '/': return Convert.ToChar(esc_char); case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'b': return '\b'; case 'f': return '\f'; default: // Unreachable return '?'; } } private static bool State1(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') continue; if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '"': ctx.NextState = 19; ctx.Return = true; return true; case ',': case ':': case '[': case ']': case '{': case '}': ctx.NextState = 1; ctx.Return = true; return true; case '-': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 2; return true; case '0': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 4; return true; case 'f': ctx.NextState = 12; return true; case 'n': ctx.NextState = 16; return true; case 't': ctx.NextState = 9; return true; case '\'': if (!ctx.L.allow_single_quoted_strings) return false; ctx.L.input_char = '"'; ctx.NextState = 23; ctx.Return = true; return true; case '/': if (!ctx.L.allow_comments) return false; ctx.NextState = 25; return true; default: return false; } } return true; } private static bool State2(FsmContext ctx) { ctx.L.GetChar(); if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '0': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 4; return true; default: return false; } } private static bool State3(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State4(FsmContext ctx) { ctx.L.GetChar(); if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } private static bool State5(FsmContext ctx) { ctx.L.GetChar(); if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 6; return true; } return false; } private static bool State6(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 1; return true; case 'e': case 'E': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State7(FsmContext ctx) { ctx.L.GetChar(); if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 8; return true; } switch (ctx.L.input_char) { case '+': case '-': ctx.L.string_buffer.Append((char)ctx.L.input_char); ctx.NextState = 8; return true; default: return false; } } private static bool State8(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append((char)ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } return true; } private static bool State9(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'r': ctx.NextState = 10; return true; default: return false; } } private static bool State10(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'u': ctx.NextState = 11; return true; default: return false; } } private static bool State11(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State12(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'a': ctx.NextState = 13; return true; default: return false; } } private static bool State13(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'l': ctx.NextState = 14; return true; default: return false; } } private static bool State14(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 's': ctx.NextState = 15; return true; default: return false; } } private static bool State15(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State16(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'u': ctx.NextState = 17; return true; default: return false; } } private static bool State17(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'l': ctx.NextState = 18; return true; default: return false; } } private static bool State18(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'l': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State19(FsmContext ctx) { while (ctx.L.GetChar()) { switch (ctx.L.input_char) { case '"': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 20; return true; case '\\': ctx.StateStack = 19; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append((char)ctx.L.input_char); continue; } } return true; } private static bool State20(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case '"': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State21(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case 'u': ctx.NextState = 22; return true; case '"': case '\'': case '/': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': ctx.L.string_buffer.Append( ProcessEscChar(ctx.L.input_char)); ctx.NextState = ctx.StateStack; return true; default: return false; } } private static bool State22(FsmContext ctx) { int counter = 0; int mult = 4096; ctx.L.unichar = 0; while (ctx.L.GetChar()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' || ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' || ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') { ctx.L.unichar += HexValue(ctx.L.input_char) * mult; counter++; mult /= 16; if (counter == 4) { ctx.L.string_buffer.Append( Convert.ToChar(ctx.L.unichar)); ctx.NextState = ctx.StateStack; return true; } continue; } return false; } return true; } private static bool State23(FsmContext ctx) { while (ctx.L.GetChar()) { switch (ctx.L.input_char) { case '\'': ctx.L.UngetChar(); ctx.Return = true; ctx.NextState = 24; return true; case '\\': ctx.StateStack = 23; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append((char)ctx.L.input_char); continue; } } return true; } private static bool State24(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case '\'': ctx.L.input_char = '"'; ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State25(FsmContext ctx) { ctx.L.GetChar(); switch (ctx.L.input_char) { case '*': ctx.NextState = 27; return true; case '/': ctx.NextState = 26; return true; default: return false; } } private static bool State26(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char == '\n') { ctx.NextState = 1; return true; } } return true; } private static bool State27(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char == '*') { ctx.NextState = 28; return true; } } return true; } private static bool State28(FsmContext ctx) { while (ctx.L.GetChar()) { if (ctx.L.input_char == '*') continue; if (ctx.L.input_char == '/') { ctx.NextState = 1; return true; } ctx.NextState = 27; return true; } return true; } #endregion private bool GetChar() { if ((input_char = NextChar()) != -1) return true; end_of_input = true; return false; } private int NextChar() { if (input_buffer != 0) { int tmp = input_buffer; input_buffer = 0; return tmp; } return reader.Read(); } public bool NextToken() { StateHandler handler; fsm_context.Return = false; while (true) { handler = fsm_handler_table[state - 1]; if (!handler(fsm_context)) throw new JsonException(input_char); if (end_of_input) return false; if (fsm_context.Return) { string_value = string_buffer.ToString(); string_buffer.Remove(0, string_buffer.Length); token = fsm_return_table[state - 1]; if (token == (int)ParserToken.Char) token = input_char; state = fsm_context.NextState; return true; } state = fsm_context.NextState; } } private void UngetChar() { input_buffer = input_char; } } }
13159828-litjsonmd
Lexer.cs
C#
gpl3
25,621
#region Header /** * JsonData.cs * Generic type to hold JSON data (objects, arrays, and so on). This is * the default type returned by JsonMapper.ToObject(). * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace LitJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } public IDictionary<String, JsonData> Inst_Object { get { if (type == JsonType.Object) return inst_object; else return null; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary(); IList<string> keys = new List<string>(); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add(entry.Key); } return (ICollection)keys; } } ICollection IDictionary.Values { get { EnsureDictionary(); IList<JsonData> values = new List<JsonData>(); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add(entry.Value); } return (ICollection)values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary()[key]; } set { if (!(key is String)) throw new ArgumentException( "The key has to be a string"); JsonData data = ToJsonData(value); this[(string)key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary(); return object_list[idx].Value; } set { EnsureDictionary(); JsonData data = ToJsonData(value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList()[index]; } set { EnsureList(); JsonData data = ToJsonData(value); this[index] = data; } } #endregion #region Public Indexers public JsonData this[string prop_name] { get { EnsureDictionary(); return inst_object[prop_name]; } set { EnsureDictionary(); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(prop_name, value); if (inst_object.ContainsKey(prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add(entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection(); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection(); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData>(entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData() { } public JsonData(bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData(double number) { type = JsonType.Double; inst_double = number; } public JsonData(int number) { type = JsonType.Int; inst_int = number; } public JsonData(long number) { type = JsonType.Long; inst_long = number; } public JsonData(object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool)obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double)obj; return; } if (obj is Single) { type = JsonType.Double; inst_double = (float)obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int)obj; return; } if (obj is Int16) { type = JsonType.Int; inst_int = (short)obj; return; } if(obj is UInt16) { type = JsonType.Int; inst_int = (ushort)obj; return; } if (obj is sbyte) { type = JsonType.Int; inst_int = (sbyte)obj; return; } if (obj is byte) { type = JsonType.Int; inst_int = (byte)obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long)obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string)obj; return; } throw new ArgumentException( "Unable to wrap the given object with JsonData"); } public JsonData(string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData(Boolean data) { return new JsonData(data); } public static implicit operator JsonData(Double data) { return new JsonData(data); } public static implicit operator JsonData(Int32 data) { return new JsonData(data); } public static implicit operator JsonData(Int64 data) { return new JsonData(data); } public static implicit operator JsonData(String data) { return new JsonData(data); } #endregion #region Explicit Conversions public static explicit operator Boolean(JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double(JsonData data) { if (data.type != JsonType.Double && data.type != JsonType.Int && data.type != JsonType.Long) throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32(JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64(JsonData data) { if (data.type != JsonType.Long && data.type != JsonType.Int) throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String(JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo(Array array, int index) { EnsureCollection().CopyTo(array, index); } #endregion #region IDictionary Methods void IDictionary.Add(object key, object value) { JsonData data = ToJsonData(value); EnsureDictionary().Add(key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>((string)key, data); object_list.Add(entry); json = null; } void IDictionary.Clear() { EnsureDictionary().Clear(); object_list.Clear(); json = null; } bool IDictionary.Contains(object key) { return EnsureDictionary().Contains(key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return ((IOrderedDictionary)this).GetEnumerator(); } void IDictionary.Remove(object key) { EnsureDictionary().Remove(key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string)key) { object_list.RemoveAt(i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator() { return EnsureCollection().GetEnumerator(); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean() { if (type != JsonType.Boolean) throw new InvalidOperationException( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble() { if (type != JsonType.Double) throw new InvalidOperationException( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt() { if (type != JsonType.Int) throw new InvalidOperationException( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong() { if (type != JsonType.Long) throw new InvalidOperationException( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString() { if (type != JsonType.String) throw new InvalidOperationException( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean(bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble(double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt(int val) { type = JsonType.Int; inst_double = inst_long = inst_int = val; json = null; } void IJsonWrapper.SetLong(long val) { type = JsonType.Long; inst_double = inst_long = val; json = null; } void IJsonWrapper.SetString(string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson() { return ToJson(); } void IJsonWrapper.ToJson(JsonWriter writer) { ToJson(writer); } #endregion #region IList Methods int IList.Add(object value) { return Add(value); } void IList.Clear() { EnsureList().Clear(); json = null; } bool IList.Contains(object value) { return EnsureList().Contains(value); } int IList.IndexOf(object value) { return EnsureList().IndexOf(value); } void IList.Insert(int index, object value) { EnsureList().Insert(index, value); json = null; } void IList.Remove(object value) { EnsureList().Remove(value); json = null; } void IList.RemoveAt(int index) { EnsureList().RemoveAt(index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator() { EnsureDictionary(); return new OrderedDictionaryEnumerator( object_list.GetEnumerator()); } void IOrderedDictionary.Insert(int idx, object key, object value) { string property = (string)key; JsonData data = ToJsonData(value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(property, data); object_list.Insert(idx, entry); } void IOrderedDictionary.RemoveAt(int idx) { EnsureDictionary(); inst_object.Remove(object_list[idx].Key); object_list.RemoveAt(idx); } #endregion #region Private Methods private ICollection EnsureCollection() { if (type == JsonType.Array) return (ICollection)inst_array; if (type == JsonType.Object) return (ICollection)inst_object; throw new InvalidOperationException( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary() { if (type == JsonType.Object) return (IDictionary)inst_object; if (type != JsonType.None) throw new InvalidOperationException( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData>(); object_list = new List<KeyValuePair<string, JsonData>>(); return (IDictionary)inst_object; } private IList EnsureList() { if (type == JsonType.Array) return (IList)inst_array; if (type != JsonType.None) throw new InvalidOperationException( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData>(); return (IList)inst_array; } private JsonData ToJsonData(object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData)obj; return new JsonData(obj); } private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) WriteJson((JsonData)elem, writer); writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)obj)) { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } writer.WriteObjectEnd(); return; } } #endregion public int Add(object value) { JsonData data = ToJsonData(value); json = null; return EnsureList().Add(data); } public void Clear() { if (IsObject) { ((IDictionary)this).Clear(); return; } if (IsArray) { ((IList)this).Clear(); return; } } public bool Equals(JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals(x.inst_object); case JsonType.Array: return this.inst_array.Equals(x.inst_array); case JsonType.String: return this.inst_string.Equals(x.inst_string); case JsonType.Int: return this.inst_int.Equals(x.inst_int); case JsonType.Long: return this.inst_long.Equals(x.inst_long); case JsonType.Double: return this.inst_double.Equals(x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals(x.inst_boolean); } return false; } public JsonType GetJsonType() { return type; } public void SetJsonType(JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData>(); object_list = new List<KeyValuePair<string, JsonData>>(); break; case JsonType.Array: inst_array = new List<JsonData>(); break; case JsonType.String: inst_string = default(String); break; case JsonType.Int: inst_int = default(Int32); break; case JsonType.Long: inst_long = default(Int64); break; case JsonType.Double: inst_double = default(Double); break; case JsonType.Boolean: inst_boolean = default(Boolean); break; } this.type = type; } public string ToJson() { if (json != null) return json; StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); writer.Validate = false; WriteJson(this, writer); json = sw.ToString(); return json; } public string ToJson(bool isReal) { if (isReal) { json = null; } return ToJson(); } public void ToJson(JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson(this, writer); writer.Validate = old_validate; } public override string ToString() { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString(); case JsonType.Double: return inst_double.ToString(); case JsonType.Int: return inst_int.ToString(); case JsonType.Long: return inst_long.ToString(); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } public void Remove(String key) { IDictionary _this = (IDictionary)this; if (_this.Contains(key)) { _this.Remove(key); } } public bool ContainsKey(String key) { return ((IDictionary)this).Contains(key); } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry(curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext() { return list_enumerator.MoveNext(); } public void Reset() { list_enumerator.Reset(); } } }
13159828-litjsonmd
JsonData.cs
C#
gpl3
28,517
#region Header /** * JsonException.cs * Base class throwed by LitJSON when a parsing error occurs. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; namespace LitJson { public class JsonException : ApplicationException { public JsonException () : base () { } internal JsonException (ParserToken token) : base (String.Format ( "Invalid token '{0}' in input string", token)) { } internal JsonException (ParserToken token, Exception inner_exception) : base (String.Format ( "Invalid token '{0}' in input string", token), inner_exception) { } internal JsonException (int c) : base (String.Format ( "Invalid character '{0}' in input string", (char) c)) { } internal JsonException (int c, Exception inner_exception) : base (String.Format ( "Invalid character '{0}' in input string", (char) c), inner_exception) { } public JsonException (string message) : base (message) { } public JsonException (string message, Exception inner_exception) : base (message, inner_exception) { } } }
13159828-litjsonmd
JsonException.cs
C#
gpl3
1,487
#region Header /** * ParserToken.cs * Internal representation of the tokens used by the lexer and the parser. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion namespace LitJson { internal enum ParserToken { // Lexer tokens None = System.Char.MaxValue + 1, Number, True, False, Null, CharSeq, // Single char Char, // Parser Rules Text, Object, ObjectPrime, Pair, PairRest, Array, ArrayPrime, Value, ValueRest, String, // End of input End, // The empty rule Epsilon } }
13159828-litjsonmd
ParserToken.cs
C#
gpl3
781
package b_Money; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AccountTest { Currency SEK, DKK; Bank Nordea; Bank DanskeBank; Bank SweBank; Account testAccount; @Before public void setUp() throws Exception { SEK = new Currency("SEK", 0.15); SweBank = new Bank("SweBank", SEK); SweBank.openAccount("Alice"); testAccount = new Account("Hans", SEK); testAccount.deposit(new Money(10000000, SEK)); SweBank.deposit("Alice", new Money(1000000, SEK)); } @Test public void testAddRemoveTimedPayment() { fail("Write test case here"); } @Test public void testTimedPayment() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testAddWithdraw() { fail("Write test case here"); } @Test public void testGetBalance() { fail("Write test case here"); } }
123-taimur
trunk/b_Money_1/AccountTest.java
Java
gpl3
876
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class CurrencyTest { Currency SEK, DKK, NOK, EUR; @Before public void setUp() throws Exception { /* Setup currencies with exchange rates */ SEK = new Currency("SEK", 0.15); DKK = new Currency("DKK", 0.20); EUR = new Currency("EUR", 1.5); } @Test public void testGetName() { fail("Write test case here"); } @Test public void testGetRate() { fail("Write test case here"); } @Test public void testSetRate() { fail("Write test case here"); } @Test public void testGlobalValue() { fail("Write test case here"); } @Test public void testValueInThisCurrency() { fail("Write test case here"); } }
123-taimur
trunk/b_Money_1/CurrencyTest.java
Java
gpl3
746
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class MoneyTest { Currency SEK, DKK, NOK, EUR; Money SEK100, EUR10, SEK200, EUR20, SEK0, EUR0, SEKn100; @Before public void setUp() throws Exception { SEK = new Currency("SEK", 0.15); DKK = new Currency("DKK", 0.20); EUR = new Currency("EUR", 1.5); SEK100 = new Money(10000, SEK); EUR10 = new Money(1000, EUR); SEK200 = new Money(20000, SEK); EUR20 = new Money(2000, EUR); SEK0 = new Money(0, SEK); EUR0 = new Money(0, EUR); SEKn100 = new Money(-10000, SEK); } @Test public void testGetAmount() { fail("Write test case here"); } @Test public void testGetCurrency() { fail("Write test case here"); } @Test public void testToString() { fail("Write test case here"); } @Test public void testGlobalValue() { fail("Write test case here"); } @Test public void testEqualsMoney() { fail("Write test case here"); } @Test public void testAdd() { fail("Write test case here"); } @Test public void testSub() { fail("Write test case here"); } @Test public void testIsZero() { fail("Write test case here"); } @Test public void testNegate() { fail("Write test case here"); } @Test public void testCompareTo() { fail("Write test case here"); } }
123-taimur
trunk/b_Money_1/MoneyTest.java
Java
gpl3
1,326
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class BankTest { Currency SEK, DKK; Bank SweBank, Nordea, DanskeBank; @Before public void setUp() throws Exception { DKK = new Currency("DKK", 0.20); SEK = new Currency("SEK", 0.15); SweBank = new Bank("SweBank", SEK); Nordea = new Bank("Nordea", SEK); DanskeBank = new Bank("DanskeBank", DKK); SweBank.openAccount("Ulrika"); SweBank.openAccount("Bob"); Nordea.openAccount("Bob"); DanskeBank.openAccount("Gertrud"); } @Test public void testGetName() { fail("Write test case here"); } @Test public void testGetCurrency() { fail("Write test case here"); } @Test public void testOpenAccount() throws AccountExistsException, AccountDoesNotExistException { fail("Write test case here"); } @Test public void testDeposit() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testWithdraw() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testGetBalance() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testTransfer() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testTimedPayment() throws AccountDoesNotExistException { fail("Write test case here"); } }
123-taimur
trunk/b_Money_1/BankTest.java
Java
gpl3
1,391
package b_Money; public class Currency { private String name; private Double rate; /** * New Currency * The rate argument of each currency indicates that Currency's "universal" exchange rate. * Imagine that we define the rate of each currency in relation to some universal currency. * This means that the rate of each currency defines its value compared to this universal currency. * * @param name The name of this Currency * @param rate The exchange rate of this Currency */ Currency (String name, Double rate) { this.name = name; this.rate = rate; } /** Convert an amount of this Currency to its value in the general "universal currency" * (As mentioned in the documentation of the Currency constructor) * * @param amount An amount of cash of this currency. * @return The value of amount in the "universal currency" */ public Integer universalValue(Integer amount) { } /** Get the name of this Currency. * @return name of Currency */ public String getName() { } /** Get the rate of this Currency. * * @return rate of this Currency */ public Double getRate() { } /** Set the rate of this currency. * * @param rate New rate for this Currency */ public void setRate(Double rate) { } /** Convert an amount from another Currency to an amount in this Currency * * @param amount Amount of the other Currency * @param othercurrency The other Currency */ public Integer valueInThisCurrency(Integer amount, Currency othercurrency) { } }
123-taimur
trunk/b_Money/Currency.java
Java
gpl3
1,532
package b_Money; import java.util.Hashtable; public class Account { private Money content; private Hashtable<String, TimedPayment> timedpayments = new Hashtable<String, TimedPayment>(); Account(String name, Currency currency) { this.content = new Money(0, currency); } /** * Add a timed payment * @param id Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String id, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { TimedPayment tp = new TimedPayment(interval, next, amount, this, tobank, toaccount); timedpayments.put(id, tp); } /** * Remove a timed payment * @param id Id of timed payment to remove */ public void removeTimedPayment(String id) { timedpayments.remove(id); } /** * Check if a timed payment exists * @param id Id of timed payment to check for */ public boolean timedPaymentExists(String id) { return timedpayments.containsKey(id); } /** * A time unit passes in the system */ public void tick() { for (TimedPayment tp : timedpayments.values()) { tp.tick(); tp.tick(); } } /** * Deposit money to the account * @param money Money to deposit. */ public void deposit(Money money) { content = content.add(money); } /** * Withdraw money from the account * @param money Money to withdraw. */ public void withdraw(Money money) { content = content.sub(money); } /** * Get balance of account * @return Amount of Money currently on account */ public Money getBalance() { return content; } /* Everything below belongs to the private inner class, TimedPayment */ private class TimedPayment { private int interval, next; private Account fromaccount; private Money amount; private Bank tobank; private String toaccount; TimedPayment(Integer interval, Integer next, Money amount, Account fromaccount, Bank tobank, String toaccount) { this.interval = interval; this.next = next; this.amount = amount; this.fromaccount = fromaccount; this.tobank = tobank; this.toaccount = toaccount; } /* Return value indicates whether or not a transfer was initiated */ public Boolean tick() { if (next == 0) { next = interval; fromaccount.withdraw(amount); try { tobank.deposit(toaccount, amount); } catch (AccountDoesNotExistException e) { /* Revert transfer. * In reality, this should probably cause a notification somewhere. */ fromaccount.deposit(amount); } return true; } else { next--; return false; } } } }
123-taimur
trunk/b_Money/Account.java
Java
gpl3
2,811
package b_Money; public class Money implements Comparable { private int amount; private Currency currency; /** * New Money * @param amount The amount of money * @param currency The currency of the money */ Money (Integer amount, Currency currency) { this.amount = amount; this.currency = currency; } /** * Return the amount of money. * @return Amount of money in Double type. */ public Integer getAmount() { } /** * Returns the currency of this Money. * @return Currency object representing the currency of this Money */ public Currency getCurrency() { } /** * Returns the amount of the money in the string form "(amount) (currencyname)", e.g. "10.5 SEK". * Recall that we represent decimal numbers with integers. This means that the "10.5 SEK" mentioned * above is actually represented as the integer 1050 * @return String representing the amount of Money. */ public String toString() { } /** * Gets the universal value of the Money, according the rate of its Currency. * @return The value of the Money in the "universal currency". */ public Integer universalValue() { } /** * Check to see if the value of this money is equal to the value of another Money of some other Currency. * @param other The other Money that is being compared to this Money. * @return A Boolean indicating if the two monies are equal. */ public Boolean equals(Money other) { } /** * Adds a Money to this Money, regardless of the Currency of the other Money. * @param other The Money that is being added to this Money. * @return A new Money with the same Currency as this Money, representing the added value of the two. * (Remember to convert the other Money before adding the amounts) */ public Money add(Money other) { } /** * Subtracts a Money from this Money, regardless of the Currency of the other Money. * @param other The money that is being subtracted from this Money. * @return A new Money with the same Currency as this Money, representing the subtracted value. * (Again, remember converting the value of the other Money to this Currency) */ public Money sub(Money other) { } /** * Check to see if the amount of this Money is zero or not * @return True if the amount of this Money is equal to 0.0, False otherwise */ public Boolean isZero() { } /** * Negate the amount of money, i.e. if the amount is 10.0 SEK the negation returns -10.0 SEK * @return A new instance of the money class initialized with the new negated money amount. */ public Money negate() { } /** * Compare two Monies. * compareTo is required because the class implements the Comparable interface. * (Remember the universalValue method, and that Integers already implement Comparable). * Also, since compareTo must take an Object, you will have to explicitly downcast it to a Money. * @return 0 if the values of the monies are equal. * A negative integer if this Money is less valuable than the other Money. * A positive integer if this Money is more valuiable than the other Money. */ public int compareTo(Object other) { } }
123-taimur
trunk/b_Money/Money.java
Java
gpl3
3,160
package b_Money; public class AccountDoesNotExistException extends Exception { static final long serialVersionUID = 1L; }
123-taimur
trunk/b_Money/AccountDoesNotExistException.java
Java
gpl3
125
package b_Money; import java.util.Hashtable; public class Bank { private Hashtable<String, Account> accountlist = new Hashtable<String, Account>(); private String name; private Currency currency; /** * New Bank * @param name Name of this bank * @param currency Base currency of this bank (If this is a Swedish bank, this might be a currency class representing SEK) */ Bank(String name, Currency currency) { this.name = name; this.currency = currency; } /** * Get the name of this bank * @return Name of this bank */ public String getName() { return name; } /** * Get the Currency of this bank * @return The Currency of this bank */ public Currency getCurrency() { return currency; } /** * Open an account at this bank. * @param accountid The ID of the account * @throws AccountExistsException If the account already exists */ public void openAccount(String accountid) throws AccountExistsException { if (accountlist.containsKey(accountid)) { throw new AccountExistsException(); } else { accountlist.get(accountid); } } /** * Deposit money to an account * @param accountid Account to deposit to * @param money Money to deposit. * @throws AccountDoesNotExistException If the account does not exist */ public void deposit(String accountid, Money money) throws AccountDoesNotExistException { if (accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Withdraw money from an account * @param accountid Account to withdraw from * @param money Money to withdraw * @throws AccountDoesNotExistException If the account does not exist */ public void withdraw(String accountid, Money money) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Get the balance of an account * @param accountid Account to get balance from * @return Balance of the account * @throws AccountDoesNotExistException If the account does not exist */ public Integer getBalance(String accountid) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { return accountlist.get(accountid).getBalance().getAmount(); } } /** * Transfer money between two accounts * @param fromaccount Id of account to deduct from in this Bank * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, Bank tobank, String toaccount, Money amount) throws AccountDoesNotExistException { if (!accountlist.containsKey(fromaccount) || !tobank.accountlist.containsKey(toaccount)) { throw new AccountDoesNotExistException(); } else { accountlist.get(fromaccount).withdraw(amount); tobank.accountlist.get(toaccount).deposit(amount); } } /** * Transfer money between two accounts on the same bank * @param fromaccount Id of account to deduct from * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, String toaccount, Money amount) throws AccountDoesNotExistException { transfer(fromaccount, this, fromaccount, amount); } /** * Add a timed payment * @param accountid Id of account to deduct from in this Bank * @param payid Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String accountid, String payid, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { Account account = accountlist.get(accountid); account.addTimedPayment(payid, interval, next, amount, tobank, toaccount); } /** * Remove a timed payment * @param accountid Id of account to remove timed payment from * @param id Id of timed payment */ public void removeTimedPayment(String accountid, String id) { Account account = accountlist.get(accountid); account.removeTimedPayment(id); } /** * A time unit passes in the system */ public void tick() throws AccountDoesNotExistException { for (Account account : accountlist.values()) { account.tick(); } } }
123-taimur
trunk/b_Money/Bank.java
Java
gpl3
4,814
package b_Money; public class AccountExistsException extends Exception { static final long serialVersionUID = 1L; }
123-taimur
trunk/b_Money/AccountExistsException.java
Java
gpl3
119
addpath([pwd,"/lib"]); addpath([pwd,"/src"]); load("rec.dat"); load("tstl.dat"); stats=[rec, tstl]; scores=[]; startTime = cputime; confidenceLevel=0.44; errors=[]; credibilityMatrix=[]; for(trial=1:size(rec,1)) trainSet=stats(1:end!=trial,:); testSet=stats(trial,:); credibilityMatrix = getPerformanceMatrix(trainSet); [testAnswers confidence] = maxCredibilityAnswer(testSet(:,1:end-1), credibilityMatrix,0.0078); testAnswers(confidence<confidenceLevel)=10; if(testAnswers(1,1)!=10 && testAnswers(1,1)!=testSet(1,6)) errors=[errors;trial]; end; scores=[scores; sum(testAnswers==testSet(:,6))/size(testSet,1), sum(testAnswers==10)/size(testSet,1)]; if(mod(trial,250)==0) printf("ITERATION: %d, TIME ELAPSED: %d sec \n",trial,cputime-startTime); printf("Last-> score : %f, discarded: %f \n",scores(size(scores,1),1),scores(size(scores,1),2)); printf("Mean-> score : %f, discarded: %f, errors: %f \n",mean(scores(:,1)), ... mean(scores(:,2)), 1-mean(scores(:,1))-mean(scores(:,2))); fflush(stdout); end; end; printf("Average over %d iterations -> score: %f, discarded: %f \n", size(stats,1), mean(scores(:,1)), mean(scores(:,2)), ... 1-mean(scores(:,1))-mean(scores(:,2)));
12l-rob-lab
trunk/lab7/initHandicapLeaveOneOut.m
MATLAB
gpl3
1,217
addpath([pwd,"/lib"]); addpath([pwd,"/src"]); load("rec.dat"); load("tstl.dat"); stats=[rec, tstl]; scores=[]; iterations = 10; startTime = cputime; confidenceLevel=0.44; for(trial=1:iterations) [trainSet testSet] = splitSet(stats, 0.5); credibilityMatrix = getPerformanceMatrix(trainSet); [testAnswers confidence] = maxCredibilityAnswer(testSet(:,1:end-1), credibilityMatrix, 0.78); testAnswers(confidence<confidenceLevel)=10; scores=[scores; sum(testAnswers==testSet(:,6))/size(testSet,1), sum(testAnswers==10)/size(testSet,1)]; printf("ITERATION: %d, TIME ELAPSED: %d sec \n",trial,cputime-startTime); printf("Last-> score : %f, discarded: %f \n",scores(size(scores,1),1),scores(size(scores,1),2)); printf("Mean-> score : %f, discarded: %f, errors: %f \n",mean(scores(:,1)), ... mean(scores(:,2)), 1-mean(scores(:,1))-mean(scores(:,2))); fflush(stdout); end; printf("Average over %d iterations -> score: %f, discarded: %f \n", iterations, mean(scores(:,1)), mean(scores(:,2)), ... 1-mean(scores(:,1))-mean(scores(:,2)));
12l-rob-lab
trunk/lab7/initHandicap.m
MATLAB
gpl3
1,047
function [answers confidence times] = bayesianMeta(results, cms, zeroSubstitute=0.000001) answers=[]; confidence=[]; times=zeros(1,10); for(sample=1:size(results,1)) bel=zeros(10,1); for(i=1:size(bel,1)) if(sum(results(sample,:)==(i-1))==0) continue; end; numerator=NaN; firstLoopStart=cputime; for(classifier=1:size(cms,2)) if(isnan(numerator)) numerator=1; end; predicted = results(sample,classifier); if(sum(cms{classifier}(:,predicted+1))==0) printf("upper %f \n", sum(cms{classifier}(:,predicted+1))); end; numerator*=(max(cms{classifier}(i,results(sample,classifier)+1),zeroSubstitute)/sum(cms{classifier}(:,predicted+1))); fflush(stdout); end; #printf("numerator: %f \n", numerator); times(1,1)+=cputime-firstLoopStart; denominator=0; #clazz - no "+1" term! secLoopStart=cputime; for(clazz=1:size(cms{1},1)) partial=NaN; for(classifier=1:size(cms,2)) if(isnan(partial)) partial=1; end; predicted = results(sample,classifier); if(sum(cms{classifier}(:,predicted+1))==0) printf("lower %f \n", sum(cms{classifier}(:,predicted+1))); end; partial*=(max(cms{classifier}(clazz,results(sample,classifier)+1),zeroSubstitute) / sum(cms{classifier}(:,predicted+1))); fflush(stdout); end; denominator+=partial; end; times(1,2)+=cputime-secLoopStart; if(numerator==0) bel(i,1)=0; elseif(denominator==0) bel(i,1)=NaN; else bel(i,1)=numerator/denominator; end; end; [maxVal maxPos] = max(bel); if(maxVal==0) answers=[answers; 10]; else answers=[answers; maxPos-1]; confidence=[confidence; maxVal/sum(bel)]; end; end; end;
12l-rob-lab
trunk/lab7/src/bayesianMeta.m
MATLAB
gpl3
1,726
#assumes last column contains labels function perfMat = getPerformanceMatrix(stats) classes = unique(stats(:,size(stats,2))); perfMat= zeros(size(classes,1),size(stats,2)-1); ansCol = size(stats,2); for(i=1:size(classes)) digit=classes(i); for(classifier=1:size(stats,2)-1) falseNegatives = sum(stats(:,classifier)!=digit & stats(:,ansCol)==digit); truePositives = sum(stats(:,classifier)==digit & stats(:,ansCol)==digit); trueNegatives = sum(stats(:,classifier)!=digit & stats(:,ansCol)!=digit); falsePositives= sum(stats(:,classifier)==digit & stats(:,ansCol)!=digit); specificity = trueNegatives/(trueNegatives+falsePositives); sensitivity = truePositives/(truePositives+falseNegatives); perfMat(digit+1,classifier)=2*specificity*sensitivity/(specificity+sensitivity); end; end; end;
12l-rob-lab
trunk/lab7/src/getPerformanceMatrix.m
MATLAB
gpl3
837