custom dynamic link libraries are being loaded for every application Results


Sponsored Links:



Not sure what is going on here, but the Event Viewer keeps telling me that "Custom dynamic link libraries are being loaded for every application. The system administrator should review the list of libraries to ensure they are related to trusted applications." What can I do to fix this?




I have attached a good sized Zip file that has all my info.

It's bizarre, either my computer freezes or blue screens, most commonly when playing a game (although it will all of a sudden Blue screen without any warning or degradation in performance). Often when it crashes a horrible continuos buzzing noise will play through the speakers.

However there are times when I can use the computer without problems for hours.

Sometimes after recovering from a blue screen my computer actually fails to boot, the fans are running but the single 'beep' to notify a boot doesn't work. I tend to find though that if i take out the mains leave it for 5 mins and then turn it on again it does boost.

I have ran Memtest (several runs through) and Memory is fine, and I can't think of any hardware changes that may trigger the issue.

After a BSOD the most common code I get when windows starts up and tells me about the previous Blue Screen is '768_1'

In Event Log the main repeated errors I get are

ID:3 ''The configuration of the AdminConnectionTCP protocol in the SQL instance MSSMLBIZ is not valid.''

and

ID 11:Custom dynamic link libraries are being loaded for every application. The system administrator should review the list of libraries to ensure they are related to trusted applications.

If anyone can take a look i'd be grateful, it really has me stumped Attached Files Seven Forums.zip (1.37 MB, 12 views) Share Share this post on Digg Del.icio.us Technorati Twitter
Reply With Quote .postbitlegacy .postfoot .textcontrols a.post_info_button, .postbit .postfoot .textcontrols a.post_info_button { background: url(/images/post_infobox.png) no-repeat transparent left; padding-left: 20px; } .postbitlegacy .postfoot .textcontrols a.post_info_button:hover, .postbit .postfoot .textcontrols a.post_info_button:hover { background: url(/images/post_infobox-hover.png) no-repeat transparent left;   JavaScript must be enabled 08-08-2012 #2 Davonator Junior Member  Thread Starter Enjoys Windows 7 Forums  
Join Date Aug 2012 Posts 2 Re: BSODs??? No idea! Please Help Lots of views but no replies, are those dumps pointing to one single issue. Any feedback would be great




I simply closed out of Tunebite 7 and I got a BSOD. I will give you all the events that are suspicious (red):

Error - 3:17:41AM - 6008 - None - The previous system shutdown at 3:16:12AM on 4/8/2010 was unexpected.
Critical - 3:17:08AM - (41) - (63) - The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly.
Warning - 3:17:42AM - 11 - None - Custom dynamic link libraries are being loaded for every application. The system administrator should review the list of libraries to ensure they are related to trusted applications.
Error - 3:17:53AM - 1001 - None - The computer has rebooted from a bugcheck. The bugcheck was: 0x0000004e (0x00000099, 0x0000e3e1, 0x00000003, 0x0006c5f3). A dump was saved in C:WindowsMEMORY.DMP. Report Id: 040810-43671-01.
Error - 3:17:44AM - 7000 - None - The DgiVecp service failed to start due to the following error: The system cannot find the device specified.

I get these errors too often.

I also attached my files. Let me know if you need anything else. Attached Files files.zip (37.6 KB, 314 views) Share Share this post on Digg Del.icio.us Technorati Twitter
Operating System Windows 7 Professional 32-bit
Computer Type Custom
OS Service Pack 1
DirectX Version 10
CPU Type and Speed AMD Phenom II X4 925
Motherboard Chipset MSI NF750-G55 (MS-7578)
System Memory Type 4GB
Video Card Type and Speed NVIDIA GeForce 210
Power Supply Unit (PSU) Cooler Master 550W
Computer Monitor HP w1907
Sound Card Integrated
Speakers Logitech X540
Hard Drive 500GB WDC WD5000ADS-00S9B0
Optical Drives ATAPI DH20A4P
Keyboard and Mouse Microsoft
Network Adapter Realtek
Anti-virus Software AVG Free 9.5
Computer Skill Level Average Ability
Windows Experience Index 4.6
Reply With Quote .postbitlegacy .postfoot .textcontrols a.post_info_button, .postbit .postfoot .textcontrols a.post_info_button { background: url(/images/post_infobox.png) no-repeat transparent left; padding-left: 20px; } .postbitlegacy .postfoot .textcontrols a.post_info_button:hover, .postbit .postfoot .textcontrols a.post_info_button:hover { background: url(/images/post_infobox-hover.png) no-repeat transparent left;   JavaScript must be enabled 04-08-2010 #2 kemical Administrator Microsoft MVP  
Join Date Aug 2007 Posts 10,085 Hi hg3300,
could you please post whether your running with the latest drivers and system Bios. Oh and system spec would be handy too..




A day or so ago my laptop did some Windows updates and since then it has a couple of weird issues with displaying pictures and with networking or security permissions.

Symptoms:

Pictures - Can browse the web fine with any browser, but powerpoint presentations don't display embedded pictures and the windows picture viewer says it "can't open this picture because the file appears damaged, corrupted or is too large." - but I can open the same file over the network from another computer so the file seems fine.

Dropbox won't connect - and talks about permissions being incorrect. A reinstall doesn't fix it.

Google Chrome won't update - server error 7.

I am getting fleeting glimpses of a black window with a thick border - which could be some sort of command prompt window - first thought is a virus, but ESET Smart Security i.e. NOD32 says no infections. Second thought was some sort of scheduled task failing - and when I opened Task Scheduler I got "TaskBackgroundConfigSurveyor: The task image is corrupt or has been tampered with."

Tried a system restore back to before recent Windows Update, but it failed on a missing or corrupt file.

Event Viewer runs and yu can see events that have been logged, but whenever I try to look at the details of an event it crashes.

Whilst I don't use bitlocker explicitly, there are a few event log entries dating back a couple of months saying that an encrypted volume cannot be read.
There is another few entries from wininit saying that custom dynamic link libraries are being loaded for every application, though these go back some time.

Next steps - run chkdsk on all volumes.

Otherwise I am stumped. Any advice on how to fix without a complete reinstall of Windows would be appreciated.

P

P.S. Changed post title to better reflect the problem.




With the release of Windows Phone 8, a few new developer API endpoints were made available that allow third-party applications to change the device lockscreen image. In this article, I am establishing the infrastructure and building a mobile application that provides the ability to choose from a number of dynamic image sets, from which images can be selected and then cycled as lockscreen wallpapers.
What do you need

You will need to download and install ASP.NET MVC3 to work on the web frontend and Windows Phone 8 SDK to work on the mobile applications. An Azure Mobile Services account will be necessary, and of course don’t forget to download and install the Azure Mobile Services client libraries. All three components are available at no additional charge.
NOTE: Without the Azure Mobile Services SDK installed on the development machine, the compilation process will fail for the Windows Phone application.
Setting up The Data Store

First we need to establish the general design of the application and organize the workflow. The application will provide two ways to assign the dynamic lockscreen:

With the help of custom image sets that are provided by the service;With the help of self-created image sets, aggregated from images provided by the service but ultimately managed by the end-user.
Let’s talk about the general data model. Every image belongs to a certain category and to keep track of each we need a table with two columns—category ID and category name. We also need another core table containing the image references themselves, with the following columns: image URL, descriptive name, and the category ID to which it belongs. The overall structure looks like this:

Now to the Windows Azure Management Portal and creating a new Mobile Service.

Once created, you need to specify database information, just like you would with a standard SQL Server database:

As the database is being created, you can easily integrate it with SQL Server Management Studio. You will need the server address, which may be obtained in the Azure Management Portal. To login, use the credentials that you set when creating the core database.
Create the two tables mentioned above, with the following column configuration:
Categories

ID - intName – varchar(100)
Images

ID – intURL – varchar(500)Name – varchar(100)CategoryID – int
You can create these tables either in the SQL Server Management Studio or through the Azure Management Portal. However, you will need the Management Studio to create the column structure, as the Azure Management Portal does not offer this functionality right now.
By default, the id column will be created automatically. To add the Name column to the Categories table, run this query:

ALTER TABLE c4flockscreen.CategoriesADD Name VARCHAR(100)To add the missing columns to the Images table, simply execute this query:

ALTER TABLE c4flockscreen.ImagesADD URL VARCHAR(500),Name VARCHAR(100),CategoryID INTNow that the database is ready, we’ll proceed to working on the web layer, which will effectively be the administrative portal for the service.
Creating the Web Portal

There should be a way to easily manage images and constantly expand the collection of possible lockscreen wallpapers. One way to do this is create a basic management portal that can carry basic CRUD operations.
Start by creating an empty project:

If you are not yet aware of the Model-View-Controller (MVC) development pattern, here is a good read explaining the fundamentals.
Create a new controller in the Controllers folder, named HomeController. This will be the only controller created in this project. For now, add an ActionResult-based function that will return the main view:

using System.Web.Mvc;namespace Coding4Fun.Lockscreen.Web.Controllers{ public class HomeController : Controller { public ActionResult MainView() { return View(); } }}Having the controller without the proper views is pointless, so create a new view in Views/Home and name it MainView. For now, do not focus on the visual layout of the page, but rather on the functional aspect of the web frontend. If you run the application now, you will most likely get a 404 response. That is because the associated home view is by default not found. Open App_Start/RouteConfig.cs and make sure that the default view is set to MainView instead of Index.

routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "MainView", id = UrlParameter.Optional });The core is created and now if running the web application you will see a basic HTML page:

We now need to handle data from the Azure Mobile Services database. Out-of-the-box, there is no ASP.NET SDK available, but the database can be easily accessed through a REST API. But before that, we need to define the data models for the Categories and Images table. Begin by creating two classes in the Models folder:
Category.cs:

public class Category{public int? id { get; set; }public string Name { get; set; }}Image.cs:

public class Image{public int? id { get; set; } public string URL { get; set; }public string Name { get; set; }public int CategoryID { get; set; }}Each of the properties is tied to the associated column in the database we created earlier. Notice that the ID values are nullable. This is introduced because the index will by default be automatically assigned. When new instances of Category or Image are created, I will not explicitly set the id property, so keeping it null instead of at a potential default value of 0 will ensure that it is properly set on the backend.
Let’s now create the connectivity engine that will allow us to query the content of the data store. For this purpose, I created a DataStore folder and a DataEngine class inside it. We will need a unique API key for each of our requests, so open the Azure Management Portal and obtain it from there:

In order to keep consistency between projects, and to be able to re-use the same Azure Mobile Services API key and core URL, I created an AuthConstants class in the context of the Coding4Fun.Lockscreen.Core project. It carries three static fields:

public static class AuthConstants{ public static string AmsApiKey = "YOUR_KEY_HERE"; public const string AmsUrl = "https://c4flockscreen.azure-mobile.net/"; public const string AmsTableUrl = AmsUrl + "tables/";}Back in the ASP.NET project, the query operations are carried with the help of HttpClient initialized in the class constructor, which also includes the key used to authenticate the requests via the X-ZUMO-APPLICATION header:

private HttpClient client;public DataEngine(){ client = new HttpClient(); client.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", KEY); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }This is the basic data harness. I also implemented two core methods in order to get all existing categories:

public IEnumerable GetAllCategories(){ var result = client.GetStringAsync(string.Concat(CORE_URL,"Categories")).Result; IEnumerable categories = JsonConvert.DeserializeObject(result); return categories; }And images:

public IEnumerable GetAllImages(){ var result = client.GetStringAsync(string.Concat(CORE_URL, "Images")).Result; IEnumerable images = JsonConvert.DeserializeObject(result); return images; }For each of these, a basic request is made with the table name appended to the base URL (represented by the CORE_URL constant). Since JSON.NET is now bundled with ASP.NET, I am able to easily deserialize the returned JSON data array to an IEnumerable. There is one problem, however, with the GetAllImages approach. It implies that even if I want to use LINQ to query the existing image collection, I have to first download the entire set locally.
Fortunately, the Azure Mobile Services REST API provides an endpoint with filtering, and that’s what I am using in GetCategoryById and GetImagesByCategoryId:

public Category GetCategoryById(int id){ string composite = string.Concat(CORE_URL, "Categories?$filter=(id%20eq%20", id.ToString(), ")"); var result = client.GetStringAsync(composite).Result; IEnumerable categories = JsonConvert.DeserializeObject(result); return categories.FirstOrDefault();}public IEnumerable GetImagesByCategoryId(int id){ string composite = string.Concat(CORE_URL, "Images?$filter=(CategoryID%20eq%20", id.ToString(), ")"); var result = client.GetStringAsync(composite).Result; IEnumerable images = JsonConvert.DeserializeObject(result); return images();}Notice the ?$filter= parameter, in which the conditional is URL encoded and is wrapped in parentheses. For the category query, I am checking the id value, and for the image I’m checking CategoryID.
In the Views/Home folder, create a new view and name it Images. It will be used to list existing images that are associated with one of the selected categories. You also need to adjust the controller code to handle the incoming data:

using Coding4Fun.Lockscreen.Web.DataStore;using System.Web.Mvc;namespace Coding4Fun.Lockscreen.Web.Controllers{ public class HomeController : Controller { DataEngine engine; public HomeController() { engine = new DataEngine(); } public ActionResult MainView() { var categories = engine.GetAllCategories(); return View(categories); } public ActionResult Images(int categoryId) { var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { return View(images); } return View("MainView"); } }}For the main view, I am getting the list of categories and passing them as the bound model. For the Images view, the category ID is passed as an argument that will later enable the engine to return a list of all images that have CategoryID set to that value. In case the returned list is not null, the view is shown. Otherwise, the main view is the terminal point.
In its current state, I’ll be able to use the frontend to list existing categories and images, but not to add, remove, or update items. Adding a category and an image is a matter of modifying an HttpClient request, with the help of HttpRequestMessage. For example, here is how I can add a category through my DataEngine class:

public HttpStatusCode AddCategory(Category category){ var serializedObject = JsonConvert.SerializeObject(category, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var request = new HttpRequestMessage(HttpMethod.Post, string.Concat(CORE_URL, "Categories")); request.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json"); var response = client.SendAsync(request).Result; return response.StatusCode;}JSON.NET capabilities are used to serialize the object that needs to be inserted. The POST request is executed against the standard table URL, with the UTF8 encoded JSON string. Since the client is already carrying the basic authentication header, all that needs to be done is calling the SendAsync function.
Updating a category follows the same approach, though a PATCH method is used for the request and the URL contains the index of the category that needs to be updated:

public HttpStatusCode UpdateCategory(Category category){ var request = new HttpRequestMessage(new HttpMethod("PATCH"), string.Concat(CORE_URL, "Categories", "/", category.id)); var serializedObject = JsonConvert.SerializeObject(category); request.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json"); var response = client.SendAsync(request).Result; return response.StatusCode;}To delete a category from the data store, one simply needs to pass a parameter to it that identifies the index of the category that needs to be removed:

public HttpStatusCode DeleteCategoryFromId(int categoryId){ var request = new HttpRequestMessage(HttpMethod.Delete, string.Concat(CORE_URL, "Categories", "/", categoryId)); var response = client.SendAsync(request).Result; return response.StatusCode;}For images, the same methods can be used, with the Images table passed as the name for the target in the composite URL. Let’s now get back to working on some of the views. A static category list is not fun, so let’s create a way to add new categories. Right click on the Views/Home folder and select Add View:

A great thing about the view creation process in Visual Studio is the fact that you are able to use a basic scaffold template for a strongly-typed view. In this case, I am associating it with a Category class and using the Create template. I now need to modify the controller code to process requests to AddCategory. I need to handle two types of requests, GET and POST, because the view will be displayed to both add an item and submit an item:

public ActionResult AddCategory(){ return View(); }[HttpPost]public ActionResult AddCategory(Category category){ if (ModelState.IsValid) { engine.AddCategory(category); return RedirectToAction("MainView"); } return View();}For a GET request, I am simply returning the view. For a POST view, I am adding the category that was defined by the bound model through the local DataEngine instance, after which the user is redirected to the main view. But we also need to add an ActionResult for the MainView to obtain the list of items that are currently in the Categories table:

public ActionResult MainView(){ var categories = engine.GetAllCategories(); return View(categories);}The DataEngine instance will return all categories in an IEnumerable form that are passed as the model for the main view. The layout of MainView.cshtml can be as simple as a table:

@{ ViewBag.Title = "Coding4Fun Dynamic Lockscreen"; }Coding4Fun Dynamic Lockscreen - Categories

ID Category Name @p.id @p.Name @Html.ActionLink("Images", "Images", new { categoryId = p.id }) @Html.ActionLink("Edit", "EditCategory", new { categoryId = p.id }) @Html.ActionLink("Delete", "DeleteCategory", new { categoryId = p.id }) @Html.ActionLink("Add Category", "AddCategory")The ActionLink helper allows me to invoke a view and, if necessary, pass specific parameters to it (e.g., when I need to identify the category that needs to be deleted or edited). Some of the views listed here are not yet created, but I can easily use placeholder names in any case.
The ultimate result for the main page will look like this:

Notice that you are also able to add new categories now by clicking on the Add Category link on the bottom. This will redirect you to the AddCategory view that we created:

Let’s see how to implement the category editing in the web frontend. First of all, create a new view in Views/Home and name it EditCategory. Use the Edit scaffold template. Like AddCategory, EditCategory needs to be handled in two separate ways for GET and POST requests in the controller:

public ActionResult EditCategory(int categoryId){ Category category; category = engine.GetCategoryById(categoryId); if (category != null) return View(category); return View("MainView");}[HttpPost]public ActionResult EditCategory(Category category){ if (ModelState.IsValid) { engine.UpdateCategory(category); return RedirectToAction("MainView"); } return View();}For a GET request, we need to identify the category that needs to be added by its index, so we are using a categoryId argument passed to the view, which is later used by the DataEngine instance to retrieve the category from the data store. For a POST action, the implementation for UpdateCategory from above is used, where a PATCH request is run with the serialized object bound to the view.
For the Delete action, no additional view is necessary but the controller still needs a handler, so we can use a snippet like this:

public ActionResult DeleteCategory(int categoryId){ engine.DeleteCategoryFromId(categoryId); return RedirectToAction("MainView");}You can use the same approach to add, delete, and edit items in the list of images. For adding images, however, you might want to pass the category identifier. When images are listed after the category has been selected, it is necessary to provide a way to identify the category to which new entities should be added. To do this, we can. in the main controller. pass the category index to the view when the Images action is being triggered:

public ActionResult Images(int categoryId){ var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { ViewData["CID"] = categoryId; return View(images); } return View("MainView");}Afterwards, the categoryId value can be obtained by using the CID key for ViewData inside the view itself.
Let’s now take a look at how images are represented for each category. I created a custom view to list all the images associated with the Images category. If you look above at the controller code, you will notice that I am passing the category ID, through which the image set query is executed, and the returned collection is set as the bound model:

public ActionResult Images(int categoryId){ var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { ViewData["CID"] = categoryId; return View(images); } return View("MainView");}When an image needs to be added, call the AddImage view. In HomeController.cs, it carries implementations for both GET and POST requests:

public ActionResult AddImage(int categoryId){ Image image = new Image(); image.CategoryID = categoryId; return View(image); }[HttpPost]public ActionResult AddImage(HttpPostedFileBase file, Image image){ if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Uploads"), image.CategoryID.ToString(), fileName); string dirPath = Path.GetDirectoryName(path); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); file.SaveAs(path); string applicationUrl = string.Format("{0}://{1}{2}", HttpContext.Request.Url.Scheme, HttpContext.Request.ServerVariables["HTTP_HOST"], (HttpContext.Request.ApplicationPath.Equals("/")) ? string.Empty : HttpContext.Request.ApplicationPath ); image.URL = Path.Combine(applicationUrl, "Uploads", image.CategoryID.ToString(), fileName); } if (ModelState.IsValid && image.URL != null) { engine.AddImage(image); return RedirectToAction("Images", new { categoryID = image.CategoryID }); } return View();}When a GET request is executed against the AddImage endpoint, I pass the category ID as the flag, signaling which category the image should be included in. When a POST request is executed, it can go two ways—either the user is passing an existing link to a hosted image or the user is uploading his own image to the local server. When an upload is inbound, HttpPostedFileBase carries the content that needs to be pushed to the server.
The upload component on the view itself is done by creating a form with a file input:

Or you could upload your own file:

@if (Model != null){ using (Html.BeginForm("AddImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data", image = Model })) { @Html.HiddenFor(model => model.CategoryID); }}If there is no file selected, the system assumes that the user just decided to add an existing URL.
It’s important to mention that the upload workflow relies on the availability of the Upload folder. It is created by default when the project is deployed to the server, but you also need to make sure that the ASP.NET user on the machine where IIS is located has the appropriate write permission for the folder.
The Windows Phone 8 Application Foundation

Create a new Windows Phone 8 application and add a reference to Windows Azure Mobile Services Managed Client. It should be available in the Extensions section if you installed the Windows Azure Mobile Services SDK as I mentioned at the beginning of the article:

In App.xaml.cs you need to create an instance of MobileServiceClient that will be used as the central connection point to the database. Notice that I am using the predefined AMS and API KEY string constants:

public static MobileServiceClient MobileService =new MobileServiceClient(AuthConstants.AmsUrl, AuthConstants.AmsApiKey);The mobile application should also carry the data models for both the categories and images. That said, we can reorganize those a bit for a more convenient data binding layout. To ensure that we can reuse the classes from different application components, I am once again using the Coding4Fun.Lockscreen.Core project.
Create a new folder called Models and add a new class called Category:

using System.Collections.ObjectModel;namespace Coding4Fun.Lockscreen.Core.Models{ public class Category { public Category() { Images = new ObservableCollection(); } public int? id { get; set; } public string Name { get; set; } public ObservableCollection Images { get; set; } public override string ToString() { return Name; } }}We are still relying on a nullable index value, but now there is an ObservableCollection for images. The reason for using this specific collection type is because with an ObservableCollection, binding updates are performed automatically when new items are added or removed, therefore cutting the need to implement the notification mechanism.
The ToString function is overridden to simplify data extraction on binding. When a collection with categories will be hooked to a list, for example, I don’t have to create a converter or a property link.
For the Image model, create a new class called Image in the same Models folder:

namespace Coding4Fun.Lockscreen.Core.Models{ public class Image { public int? id { get; set; } public string URL { get; set; } public string Name { get; set; } public int CategoryID { get; set; } }}Application Workflow & Storage

Let’s talk about how image categories will be handled in the application. On application startup, the database is queried for the available categories and each of them is listed on the home screen. If the user taps on one of the categories, the database is queried for the images that are associated with the category index.
However, the user should also be able to create his own custom categories that will only be available in-app. Those categories can carry images from multiple other categories, if necessary, with the default reference set to the internal storage.
Since we are working with local storage, let’s create a helper class called LocalStorageHelper in the Coding4Fun.Lockscreen.Core project in the Storage folder. This class will carry basic read and write functions, allowing us to store data internally:

public static class LocalStorageHelper{ public async static void WriteData(string folderName, string fileName, byte[] content) { IStorageFolder rootFolder = ApplicationData.Current.LocalFolder; if (folderName != string.Empty) { rootFolder = await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); } IStorageFile file = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var s = await file.OpenStreamForWriteAsync()) { s.Write(content, 0, content.Length); } } public static async void ClearFolder(string folderName) { var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(folderName); if (folder != null) { foreach (IStorageFile file in await folder.GetFilesAsync()) { await file.DeleteAsync(); } } } public static async Task ReadData(string fileName) { byte[] data; StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync(fileName); using (Stream s = await file.OpenStreamForReadAsync()) { data = new byte[s.Length]; await s.ReadAsync(data, 0, (int)s.Length); } return Encoding.UTF8.GetString(data, 0, data.Length); } }Notice that I am using the newly-introduced StorageFolder/StorageFile capabilities. If you worked with Windows Store application development, you are probably already familiar with them. Application.Current.LocalFolder gives me direct access to the local directory. which can be modified from within the application itself. It works in a manner similar to IsolatedStorageFile in Windows Phone 7, but with more flexibility when it comes to creating new folders and files and well doing file sweeps.
As I mentioned above, there will be internal data stored as XML. For this purpose, I need a class that carries serialization and deserialization routines, and I can simplify this task by using the Coding4Fun Toolkit Serialize.Save and Serialize.Open capabilities. Calls to these functions allow flexible serialization, where by default the static class is not aware of the serialization type, but is instead able to dynamically infer it from the incoming data. Once the byte layout is obtained for the content, I use the LocalStorageHelper class to write it to a file.
As there are multiple UI items that need to be bound to collections and object instances, I have a CentralBindingPoint class in my main project that is my main view model (it implements INotifyPropertyChanged). It implements the singleton pattern, so that the main instance is created on initialization and is subsequently re-used as necessary:

using Coding4Fun.Lockscreen.Core.Models;using System;using System.Collections.ObjectModel;using System.ComponentModel;namespace Coding4Fun.Lockscreen.Mobile{ public class CentralBindingPoint : INotifyPropertyChanged { static CentralBindingPoint instance = null; static readonly object padlock = new object(); public CentralBindingPoint() { Categories = new ObservableCollection(); CustomCategories = new ObservableCollection(); } public static CentralBindingPoint Instance { get { lock (padlock) { if (instance == null) { instance = new CentralBindingPoint(); } return instance; } } } private ObservableCollection _categories; public ObservableCollection Categories { get { return _categories; } set { if (_categories != value) { _categories = value; NotifyPropertyChanged("Categories"); } } } private ObservableCollection _customCategories; public ObservableCollection CustomCategories { get { return _customCategories; } set { if (_customCategories != value) { _customCategories = value; NotifyPropertyChanged("CustomCategories"); } } } private Category _currentCategory; public Category CurrentCategory { get { return _currentCategory; } set { if (_currentCategory != value) { _currentCategory = value; NotifyPropertyChanged("CurrentCategory"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke( () => { PropertyChanged(this, new PropertyChangedEventArgs(info)); }); } } }}On the main page, I create a Pivot-based layout to have an easy way to transition between the web collections (categories) and the local ones:

For each of the collection types, there is a ListBox with a custom DataTemplate assigned for each item. The items are obtained from the Categories collection for web sets and the CustomCategories collection for local sets, both in the CentralBindingPoint view model.
The categories are loaded with the help of the DataEngine class that I added in the Data folder in the main application project. It is a wrapper for the Azure Mobile Services data operations, allowing me to aggregate the list of categories and images, given that I know the category index:

public class DataEngine{ async public Task GetCategoryList() { IMobileServiceTable table = App.MobileService.GetTable(); List data = await table.ToListAsync(); return data; } async public Task GetImagesByCategoryId(int categoryId) { IMobileServiceTable table = App.MobileService.GetTable(); List data = await table.Where(x => x.CategoryID == categoryId).ToListAsync(); return data; }}When the main page loads, I use the local DataEngine instance to call GetCategoryList and obtain a List collection that is subsequently transformed into an ObservableCollection through one of the default constructors:

async void MainPage_Loaded(object sender, RoutedEventArgs e){ CentralBindingPoint.Instance.Categories = new ObservableCollection(await dataEngine.GetCategoryList()); }When a category is selected in the web sets list, I assign the selected item as the current category and navigate to the ImageSetPage.xaml page that will display the associated images:

async void ListBox_SelectionChanged_1(object sender, System.Windows.Controls.SelectionChangedEventArgs e){ var box = (ListBox)sender; if (box.SelectedItem != null) { Category selectedCategory = (Category)box.SelectedItem; selectedCategory.Images = new ObservableCollection (await dataEngine.GetImagesByCategoryId((int)selectedCategory.id)); CentralBindingPoint.Instance.CurrentCategory = selectedCategory; NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative)); }}Notice that the images are not loaded at the same time as the categories; rather, they’re loaded only when a category has been selected, hence the GetImagesByCategoryId call on selection.
For a custom set, the procedure is pretty much the same, the only difference being the fact that image references are already present since those were deserialized from the local storage:

private void lstCustomSets_SelectionChanged_1(object sender, SelectionChangedEventArgs e){ var box = (ListBox)sender; if (box.SelectedItem != null) { Category selectedCategory = (Category)box.SelectedItem; CentralBindingPoint.Instance.CurrentCategory = selectedCategory; NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative)); }}In ImageSetPage.xaml I use a ListBox with a WrapPanel in the ItemsPanelTemplate, which ensures that I can have only two images in a row and any additions will be wrapped, with a fixed row length. You can get that control from the WPToolkit (formerly known as Silverlight Toolkit for Windows Phone, available on NuGet).

Here is the basic XAML layout:

Now that we have a basic skeleton for the incoming data, let’s see how it can be transformed into a live lockscreen, on which wallpapers can be cycled. In the ImageSetPage.xaml page I have a button in the application bar that allows me to set the current category as the source for the switching wallpapers.
Currently, each Image instance carries an image URL and the images can be located anywhere outside the application. This can cause problems with the wallpaper setting process, however, since the API only allows local images to be set as background. This means that I need to download each image to the local application folder:

private async void btnSetStack_Click_1(object sender, EventArgs e){ var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication; if (!isProvider) { var op = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync(); isProvider = op == Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted; } if (isProvider) { downloadableItems = new List(); fileItems = new List(); foreach (var image in CentralBindingPoint.Instance.CurrentCategory.Images) { downloadableItems.Add(image.URL); fileItems.Add(Path.GetFileName(image.URL)); } SerializationHelper.SerializeToFile(fileItems, "imagestack.xml"); LocalStorageHelper.ClearFolder("CurrentSet"); DownloadImages(); grdDownloading.Visibility = System.Windows.Visibility.Visible; }}First of all, I need to make sure that the application can set a lockscreen background and is registered in the OS as a provider. The application needs to state its intent to be able to access the wallpaper by adding this snippet to the WMAppManifest.xml, right after the Tokens node:

downloadableItems is a collection that represents the download queue. fileItems contains the local file names for each image that is about to be downloaded and will be serialized and used in the background agent to iterate through the category files. Whenever the download process is started, an overlay becomes visible to notify the user that the image acquisition process is in progress.
Also, notice the fact that I am calling LocalStorageHelper.ClearFolder, passing the name of the folder as the first argument. I do not want to keep images for sets that are not active, therefore when a new set is selected, the currently stored images are deleted from the CurrentSet folder and replaced by the ones that are about to be downloaded. The implementation of the ClearFolder function looks like this:

public static void ClearFolder(string folderName{ if (store.DirectoryExists(folderName)) { foreach (string file in store.GetFileNames(folderName + "*.*")) { store.DeleteFile(folderName + "" + file); } }}Once the file names are stored in imagestack.xml, the image contents are downloaded via DownloadImages:

void DownloadImages(){ WebClient client = new WebClient(); string fileName = Path.GetFileName(downloadableItems.First()); client.OpenReadAsync(new Uri(downloadableItems.First())); client.OpenReadCompleted += (sender, args) => { Debug.WriteLine("Downloaded " + fileName); LocalStorageHelper.WriteData("CurrentSet", fileName, StreamToByteArray(args.Result)); downloadableItems.Remove(downloadableItems.First()); if (downloadableItems.Count != 0) DownloadImages(); else { grdDownloading.Visibility = System.Windows.Visibility.Collapsed; LocalStorageHelper.CycleThroughImages(); //ScheduledActionService.LaunchForTest("LockscreenChanger", TimeSpan.FromSeconds(5)); } };}Here you can see that I am making a call to LocalStorageHelper.CycleThroughImages—a function that reads the file that contains the current set and picks the first image, assigning it to be the current wallpaper and then pushing it to the back of the list, making the succeeding image the next in line for the wallpaper:

public static void CycleThroughImages(){ List images = Coding4Fun.Phone.Storage.Serialize.Open("imagestack.xml"); if (images != null) { string tempImage = images.First(); Uri currentImageUri = new Uri("ms-appdata:///Local/CurrentSet/" + tempImage, UriKind.Absolute); Windows.Phone.System.UserProfile.LockScreen.SetImageUri(currentImageUri); images.Remove(tempImage); images.Add(tempImage); Coding4Fun.Phone.Storage.Serialize.Save("imagestack.xml", images); }}You might be wondering why I’m not using Queue for this. After all, Enqueue and Dequeue would make things a bit easier. The problem is that a Queue instance cannot be directly serialized without being transformed to a flat list. Therefore, I am sticking to minimal resource processing by manipulating a List instance instead.
The recursive image download method runs until the download queue is emptied, after which the overlay is hidden.
Background Agent

At this point, we have the images locally stored and listed in an XML file. If the user accepted the system prompt, the application has also been registered as a lockscreen background provider, but there is not yet a single piece of code that would actually set the wallpaper cycle. For that, create a new Background Agent project in your solution. I named mine Coding4Fun.Lockscreen.Agent.
The OnInvoke function in ScheduledAgent.cs is executed at 30-minute intervals. This is a time limit defined by the PeriodicTask background agent type that we’ll be using here. You need to add the following snippet to it:

protected override void OnInvoke(ScheduledTask task){ var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication; if (isProvider) { LocalStorageHelper.CycleThroughImages(); } NotifyComplete();}As with the download snippet, I am ensuring that before I attempt to change the wallpaper the application is a registered provider. Otherwise, an exception will be thrown and the background agent will crash. The bad thing about periodic tasks crashing is the fact that once two consecutive crashes occur, the task is removed from the task queue and the backgrounds will not be changed.
If the application is a provider, call CycleThroughImages to set the new background and push the old one to the end of the list. To make sure that a different image is selected each time, the original deserialized list is modified, where the first image now becomes last, switching the stack up, after which it is serialized back into imagestack.xml.
The background agent needs to be registered in the WMAppManifest.xml. Inside the Tasks node, add an ExtendedTask:

Also, when the application starts, you need to ensure that the task is registered, and register it if it isn’t yet. Use the Application_Launching event handler for this task:

private void Application_Launching(object sender, LaunchingEventArgs e){ string taskName = "LockscreenChanger"; var oldTask = ScheduledActionService.Find(taskName) as PeriodicTask; if (oldTask != null) { ScheduledActionService.Remove(taskName); } PeriodicTask task = new PeriodicTask(taskName); task.Description = "Change lockscreen wallpaper."; ScheduledActionService.Add(task); LoadCustomCategories(); }Here, LoadCustomCategories will deserialize the existing custom categories, so that those can be shown in the main page after the application starts:

private async void LoadCustomCategories(){ try { CentralBindingPoint.Instance.CustomCategories = (ObservableCollection)await SerializationHelper.DeserializeFromFile( typeof(ObservableCollection), "customcat.xml"); } catch { Debug.WriteLine("No customcat.xml - no registered custom categories."); }}Now the backgrounds will automatically change based on the web sets that you will activate every 30 minutes.
Working with Custom Categories

Let’s create some custom sets. To manage user input, I leverage the CustomMessageBox control available in the Windows Phone Toolkit. It has enough flexibility to let me choose between adding a TextBox control, to have the user create the new category or use a ListPicker to show the available custom categories in a consistent UI layout.
When the user decides to create a new category, he taps the plus button in the application bar on the main page:

The implementation for the call is simple:

private void btnSetStack_Click_1(object sender, EventArgs e){ TextBox textBox = new TextBox(); CustomMessageBox box = new CustomMessageBox() { Caption = "Add Custom Category", Message = "Enter a unique name for the new category.", LeftButtonContent = "ok", RightButtonContent = "cancel", Content = textBox }; box.Dismissed += (s, boxEventArgs) => { if (boxEventArgs.Result == CustomMessageBoxResult.LeftButton) { if (!string.IsNullOrWhiteSpace(textBox.Text)) { var categoryCheck = (from c in CentralBindingPoint.Instance.CustomCategories where c.Name == textBox.Text select c).FirstOrDefault(); if (categoryCheck == null) { Category category = new Category() { Name = textBox.Text }; CentralBindingPoint.Instance.CustomCategories.Add(category); Coding4Fun.Toolkit.Storage.Serialize.Save( "customcat.xml", CentralBindingPoint.Instance.CustomCategories); } else { MessageBox.Show("Add Custom Category", "This category name was already taken!", MessageBoxButton.OK); } } } }; box.Show(); }When the message box is dismissed, I check which button is pressed to take the appropriate course of action. Let’s assume that the user decided to add the new category—we need to check and make sure that there isn’t already a category with the same name in the existing collection. If there isn’t one, a new Category instance is created, added to the collection in the main view model, and serialized to customcat.xml.
The user also needs to be able to add images from any category to another custom category. To do this, I decided to give the user the option to carry across the image name and URL when he taps on an image in the ImageSetPage.xaml.
Remember, if there are no current custom categories registered, the user should be informed that he should create some first, so the alternative route for the dialog with custom category name selection should be a message box alert:

Here is the snippet that does this:

private void lstImages_SelectionChanged_1(object sender, SelectionChangedEventArgs e){ if (CentralBindingPoint.Instance.CustomCategories.Count > 0) { if (lstImages.SelectedItem != null) { ListPicker picker = new ListPicker() { Header = "Custom category name:", ItemsSource = CentralBindingPoint.Instance.CustomCategories, Margin = new Thickness(12, 42, 24, 18) }; CustomMessageBox messageBox = new CustomMessageBox() { Caption = "Add To Custom Category", Message = "Select a registered custom category to add this image to.", Content = picker, LeftButtonContent = "ok", RightButtonContent = "cancel" }; messageBox.Dismissing += (s, boxEventArgs) => { if (picker.ListPickerMode == ListPickerMode.Expanded) { boxEventArgs.Cancel = true; } }; messageBox.Dismissed += (s2, e2) => { switch (e2.Result) { case CustomMessageBoxResult.LeftButton: { if (picker.SelectedItem != null) { Category category = (from c in CentralBindingPoint.Instance.CustomCategories where c.Name == picker.SelectedItem.ToString() select c).FirstOrDefault(); if (category != null) { category.Images.Add((Coding4Fun.Lockscreen.Core.Models.Image)lstImages.SelectedItem); Coding4Fun.Toolkit.Storage.Serialize.Save( "customcat.xml", CentralBindingPoint.Instance.CustomCategories); } lstImages.SelectedItem = null; lstImages.IsEnabled = true; } break; } case CustomMessageBoxResult.RightButton: case CustomMessageBoxResult.None: { lstImages.SelectedItem = null; break; } } }; messageBox.Show(); } } else { MessageBox.Show("Add To Custom Category", "Tapping on an image will prompt you to add it to a custom category" + Environment.NewLine + "Seems like you don't have any custom categories yet.", MessageBoxButton.OK); }}Once the category is selected from the list, the image is added to the Images collection in the Category instance, and the category list is serialized to preserve the changes. There are no restrictions as to which categories can fetch images to other categories—we can even select images from custom categories and include them in other categories. The image can be added multiple times to the same category as well.
Conclusion

With Azure Mobile Services and a managed SDK available for Windows Phone, as well as an open REST API, it is fairly easy to build connected applications on multiple platforms at once without major logic and code base modifications.

More...




For //build/ 2012, we wanted to showcase what Windows 8 can offer developers. There are a lot of projects showing off great things like contracts and Live Tiles, but we wanted to show off some of the lesser known features. This project focuses on one of those: stereoscopic 3D with DirectX 11.1.
Prior to DirectX 11.1, stereoscopic 3D required specific hardware and a custom API written for that hardware. With DX11.1, stereoscopic 3D has been "democratized." Any GPU that supports DirectX 11.1 can be connected to any device which supports stereoscopic 3D, be it a projector, an LCD TV, or anything else. Plug it in and DirectX does the rest.
From the software side of things, any DX11.1 application can determine if the connected display supports stereoscopic 3D, and choose to render itself separately for the player's left and right eye.
To showcase this feature, we decided to build a very simple game that would give the illusion of depth, but be easy to explain and play. What's easier than Pong? So, we built the world's most over-engineered game of 3D Pong named Maelstrom.

Software

Each player setup consists of two applications: the DirectX 11.1 game written in C++, and the touch-screen controller written in C#/XAML. Both are Windows Store applications. Since this is a two player game, there are two instances of each application running, one per player. All for applications are networked together using StreamSockets from the Windows Runtime. The two controllers and player two's DirectX game connect to player one's DirectX game, which acts as the "master". Controller input is sent here, and, once the ball and paddle positions are calculated, the data is drawn for player one and sent to player two which draws the world from the other player's perspective.

Direct3D Application

Getting Started with stereoscopic DirectX11, C++, and XAML

If you have never worked with DirectX before, it can be a little overwhelming at first. And even if you have worked with it some in the past, targeting the new Windows 8 ecosystem, along with C++ and XAML have added some additional changes in how you may have designed your solution previously.
Fortunately, the Windows Dev Center for Windows Store Apps has some great samples to get you started, and we took full advantage of them to get to speed. For a great, simple example of how to leverage the new stereoscopic feature in Direct3D 11.1, we started with Direct3D Stereoscopic Sample which shows the basic adjustments to the Render loop for toggling your virtual cameras. However, to see a great example of a simple game structure that also leverages stereoscopic rendering where available, the tutorial found at Walkthrough: a simple Windows Store game with DirectX is invaluable. Further in this article, we will dive deeper into the specifics of stereoscopic rendering in our game.
One thing to note, if you follow the link in the above Walkthrough to the original project, it will take you to a C++ only implementation of the game. Now, of course, all the DirectX game objects such as the paddle, puck and walls are all rendered using D3D. However, for HUD (Heads up Display) elements, this C++ only sample also uses DirectX exclusively. If you are coming from a managed code background, this will definitely seem like unnecessary overhead. That is because this C++ only sample was created after last year's BUILD conference in 2011 and C++ and DirectX still did not play well with XAML.
However, a few months later, the ability to nest DirectX content in a XAML project became available for true hybrid style solutions (see the article DirectX and XAML interop - Windows Store apps using C++ and DirectX for more information). After this feature was added, the simple Shooter Game referenced above had its HUD logic rewritten in XAML and posted up to Dev Center as XAML DirectX 3D shooting game sample, which shows both stereoscopic support, a simple Game Engine structure in C++ and XAML integration. At this point, we had all the starter code we needed to start writing our own game.
Game Engine

We modified the base sample to accommodate our needs. We created specific GameObjects, such as Paddle, Puck, etc. to add the behaviors we needed. We also added an Update and Render method to the base GameObject so that, for every frame, we could do any calculations required, and then draw the object to the screen. This is very similar to how XNA sets up its game engine.
Game Constants

Because we were tweaking a variety of values like colors, sizes, camera locations, etc., we created a GameConstants.h header file which contains nothing but these types of values in a single location. This made it very easy for us to quickly try out various tweaks and see the results on the next run. Using namespaces helped keep the code a bit more manageable here as well. Here’s a quick snippet of that file:

namespace GameConstants{ // bounds of the arena static const DirectX::XMFLOAT3 MinBound = DirectX::XMFLOAT3( 0.0f, 0.0f, 0.0f); static const DirectX::XMFLOAT3 MaxBound = DirectX::XMFLOAT3(19.0f, 10.0f, 90.0f); // game camera "look at" points static const DirectX::XMFLOAT3 LookAtP1 = DirectX::XMFLOAT3(9.5f, 5.0f, 90.0f); static const DirectX::XMFLOAT3 LookAtP2 = DirectX::XMFLOAT3(9.5f, 5.0f, 0.0f); // Waiting Room camera positions static const DirectX::XMFLOAT3 WaitingEyeP1 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MaxBound.z - 12.0f); static const DirectX::XMFLOAT3 WaitingEyeP2 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z + 12.0f); static const DirectX::XMFLOAT3 WaitingEyeMjpegStation = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z + 9.6f); // game camera eye position static const DirectX::XMFLOAT3 EyeP1 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z - 6.0f); static const DirectX::XMFLOAT3 EyeP2 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MaxBound.z + 6.0f); static const float Paddle2Position = MaxBound.z - 5.0f; namespace PaddlePower { // power level to light paddle at maximum color static const float Max = 9.0f; // max paddle power color...each component will be multiplied by power factor static const DirectX::XMFLOAT4 Color = DirectX::XMFLOAT4(0.2f, 0.4f, 0.7f, 0.5f); // factor to multiply mesh percentage based on power static const float MeshPercent = 1.2f; }; // time to cycle powerups namespace Powerup { namespace Split { static const float Time = 10.0f; static const float NumTiles = 4; static const DirectX::XMFLOAT4 TileColor = DirectX::XMFLOAT4(0.1f, 0.4f, 1.0f, 1.0f); static const float TileFadeUp = 0.20f; static const float TileDuration = 2.10f; static const float TileFadeDown = 0.20f; static const float TileMeshPercent = 2.0f; static const float TileDiffusePercent = 2.0f; }; };}Stereoscopic 3D

Direct3D must be initialized properly to support stereoscopic displays. When the swap chains are created, an additional render target is required, such that one render target is for the left eye, and one render target is for the right eye. Direct3D will let you know if a stereoscopic display is available, so you can create the swap chain and render targets appropriately.
With those in place, it’s simply a matter of rendering your scene twice, once per eye…that is, once per render target.
For our game this was very simple. Our in-game camera contains two projection matrices, one representing the view from the left eye, and one from the right eye. These are calculated when the projection parameters are set.

void Camera::SetProjParams( _In_ float fieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane ){ // Set attributes for the projection matrix. m_fieldOfView = fieldOfView; m_aspectRatio = aspectRatio; m_nearPlane = nearPlane; m_farPlane = farPlane; XMStoreFloat4x4( &m_projectionMatrix, XMMatrixPerspectiveFovLH( m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane ) ); STEREO_PARAMETERS* stereoParams = nullptr; // Update the projection matrix. XMStoreFloat4x4( &m_projectionMatrixLeft, MatrixStereoProjectionFovLH( stereoParams, STEREO_CHANNEL::LEFT, m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane, STEREO_MODE::NORMAL ) ); XMStoreFloat4x4( &m_projectionMatrixRight, MatrixStereoProjectionFovLH( stereoParams, STEREO_CHANNEL::RIGHT, m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane, STEREO_MODE::NORMAL ) );}Depending on which eye we are rendering, we grab the appropriate projection matrix and pass it down to the vertex shader, so the final scene is rendered offset for the proper eye.
Collision Detection

If you are just starting to move into 3D modeling and programming, one of the trickier aspects of your game can be collision detection and response. Maelstrom uses primitives for all of the game elements, so our collision code was able to be a bit more straightforward compared to complex mesh collisions, but understanding a few core math concepts is still critical to grasp what the code is doing.
Fortunately, DirectX provides us with an DirectX Math Library that is able to do the serious heavy lifting, so the main complexity comes from framing the problem and learning how to apply the library.
For example, In our situation we had up to three very fast moving spheres and needed to check for wall collisions and then handle to appropriate bounce, since some of the walls would also be angled. In a 2D game, a collision detection between a sphere and an axis line is very easy. If the distance between a circle and the line is less than or equal to the radius of the sphere, they are touching. On every frame, you move your circle based on its velocity and do your collision test again. But even here, your solution may not be that easy for two reasons.
First, what if the line is angled and not lying flat on the X or Y axis? You have to find the point on the line based on the line's angle that is closest to the sphere to do your distance calculations. And if you then want it to bounce, you have to rotate the velocity of the circle by the line's angle, calculate your bounce, and then rotate back. And that's just rotated walls in 2D. When you move up to 3D, you have to take into account the surface normal (which way the 3D plane is facing) in your calculations.
The second complexity that we needed to account for and which pops up in either 2D or 3D collision detection is travel between frames. In other words, if your ball is travelling very fast, it may have completely travelled through your collision boundary in between frames and you wouldn't notice it if you are only doing a distance / overlap check as outlined above. In our case, the pucks had the ability of travelling very fast with a speed boost, so we needed a more robust solution. Therefore, instead of implementing a simple sphere plane intersection test, we needed to create a line of motion that represented where the ball ended on the previous frame and where it currently is after it's new velocity is added to it's position. That line then needs to first be tested to see if it crosses a WallTile. If it does cross, then we know an collision has occurred between frames. We then solve for the time (t) between frames the Sphere would have first made contact to know the exact point of impact and calculate the appropriate "bounce off" direction.
The final code for a puck (or moving sphere) and wallTile collision test looks like this:

bool GameEngine::CheckWallCollision(Puck^ puck){ bool isIntersect = false; bool wallCollision = false; for(unsigned int i = 0; i < m_environmentCollisionWalls.size(); i++) { WallTile^ wall = m_environmentCollisionWalls[i]; float radius = puck->Radius(); float signedRadius = puck->Radius(); float contactTime = 0.0f; XMVECTOR contactPlanePoint = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); XMVECTOR contactPuckPosition = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); bool intersectsPlane = false; // Determine the velocity of this tick by subtracting the previous position from the proposed current position. // in the previous update() cycle, puck->Position() = puck->OldPosition() + ( puck->velocity * timerDelta ). // Therefore, this calculated velocity for the current frame movement differs from the stored velocity // since the stored velocity is independent of each game tick's timerDelta. XMVECTOR puckVectorVelocity = puck->VectorPosition() - puck->OldVectorPosition(); float D = XMVectorGetX( XMVector3Dot( wall->VectorNormal(), wall->VectorPosition() ) ); // Determine the distance of the puck to the plane of the wall. float dist = XMVectorGetX( XMVector3Dot(wall->VectorNormal(), puck->OldVectorPosition() )) - D; signedRadius = dist > 0 ? radius : -radius; // if the distance of the puck to the plane is already less than the radius, the oldPosition() was intersecting already if ( fabs(dist) < radius ) { // The sphere is touching the plane. intersectsPlane = true; contactTime = 0.0f; contactPuckPosition = puck->OldVectorPosition(); contactPlanePoint = puck->OldVectorPosition() + wall->VectorNormal()*XMVectorSet(signedRadius,signedRadius,signedRadius,1.0f); } else { // See if the time it would take to cross the plane from the oldPosition() with the current velocity falls within this game tick. // puckVelocityNormal is the amount of force from the velocity exerted directly toward the plane. float puckVelocityNormal = XMVectorGetX(XMVector3Dot(wall->VectorNormal(), puckVectorVelocity )); // if the puckvVelocityNormal times the distance is less than zero, a plane intersection will occur if ( puckVelocityNormal * dist < 0.0f ) { // determine the contactTime, taking into account the shell of the sphere ( position() + radius ) // is what will make contact, not the position alone. contactTime = (signedRadius - dist) / puckVelocityNormal; // if the contact time is bewteen zero and one, the intersection has occured bewteen oldPosition() and position() if ( contactTime > 0.0f && contactTime < 1.0f ) { intersectsPlane = true; // this is the position of the puck when its shell makes contact on the plane contactPuckPosition = puck->OldVectorPosition() + XMVectorScale(puckVectorVelocity, contactTime); // this is the position on the plane where the shell touches. contactPlanePoint = contactPuckPosition - XMVectorScale(wall->VectorNormal(), signedRadius); } } } // If the puck has contacted the wall plane, determine if the point of contact falls within the wall boundary for true contact. if (intersectsPlane) { float Kr = 1.0f; // Kr is the coefficient of restitution. At 1.0, we have a totally elastic bounce with no dampening. At Kr = 0.0, the ball would stop at the wall. // Make sure the puck velocity and wall normal are facing each other float impact = XMVectorGetX ( XMVector3Dot ( wall->VectorNormal(), puck->VectorVelocity()) ); if (impact < 0.0f) { wallCollision = true; //// bounce the vector off the plane XMVECTOR VectorNormal = XMVector3Dot(wall->VectorNormal(), puck->VectorVelocity())*wall->VectorNormal(); XMVECTOR VectorTangent = puck->VectorVelocity() - VectorNormal; puck->Velocity(VectorTangent - (XMVectorScale(VectorNormal, Kr))); puck->Position(contactPuckPosition); int segment = (int)(puck->Position().z / GameConstants::WallSegmentDepth); segment = max(min(segment, GameConstants::NumWallSegments-1), 0); auto tiles = m_wallTiles[segment]; WallTile^ tile = tiles[i]; if(tile->GetPowerup() == Powerup::Split) SplitPucks(); break; } } } return wallCollision;}Drawing Maelstrom

To draw the game, we wanted to use some advanced techniques. We decided to go with a light pre-pass deferred rendering pipeline with normal mapping. That’s a lot of jargon but it isn’t all that complicated once you know what the jargon means, so let’s break it down.
When you draw something in 3D, there are three things that come together to determine the final color of each pixel on the screen: meshes, materials, and lights. A mesh is a collection of triangles that make up a game object (such as a wall tile in Maelstrom). On its own, a mesh is just a bunch of dots and lines. A material makes a mesh look like something. It could be as simple as a solid color but usually it’s a texture and sometimes it’s more (the wall tiles in Maelstrom use both a texture and a normal map to define their material properties). Lastly, lights transform materials by determining how bright they should appear and what sort of tint, if any, they should have. Without lights you would either have complete darkness or you would have flat lighting (where everything has a uniform brightness and adding a tint color would uniformly tint everything on the screen).
Forward Rendering vs. Deferred Rendering vs. Light Pre-Pass Rendering

The simplest approach to drawing 3D graphics is something called forward rendering. With forward rendering, drawing consists of rendering the mesh and calculating its material and all the lights that affect the material all at the same time. The more lights you add, the more complicated your shaders become since you have to determine whether each light affects the material and if so how much. (Ok, so there’s also multi-pass forward rendering, but that has its own problems – more passes mean longer render times and thus a lower frame rate – and we wanted to keep the descriptions simple).
In the last 5 years, many games started using a technique called deferred rendering. In classic deferred rendering, there are two rendering passes. The first pass renders the positions, normals, and material values of all the meshes in the scene to something called a G-Buffer (two or more render targets); nothing is actually drawn to the screen in this first pass. The second pass uses the data from the G-Buffer (which tells us everything we need to know about the geometry that appears at each screen pixel) and combines it with the lights to create the final image that you see. By doing this, we decouple geometry and lighting. This makes it possible to add more lights to the scene with a much smaller performance impact than in forward rendering since we don’t need to create a really complex pixel shader to handle all the lights (single-pass forward rendering) or draw the geometry over and over again for each light (multi-pass forward rendering).
There are drawbacks to classic deferred rendering though. Even a minimal G-Buffer takes up quite a bit of memory and the more different types of materials you want to support, the larger the G-Buffer will need to be. Wolfgang Engel, an XNA/DirectX MVP, came up with a variation on deferred rendering which he called Light Pre-Pass Rendering. This is a three pass technique. We once again use a G-Buffer, but in this case it is smaller than the classic deferred rendering G-Buffer and can even be squeezed down to a single render target which makes it viable for graphics hardware which does not support drawing to multiple render targets at the same time.
The G-Buffer is created in the first pass by rendering all the scene geometry. It only needs to store normals and the geometry’s world position. We stored the world position of the geometry at that screen position in one render target and its normal at that screen position in second render target for simplicity.
The next pass draws the lights to a light accumulation buffer. The buffer starts out entirely dark and each light that is rendered adds brightness (and tint, if any) to the light buffer. These lighting calculations take into account the normal and world position of the geometry that is at each screen position, drawing the values from the G-Buffer, such that each light only affects the pixels it is supposed to have an impact on. In Maelstrom we ended up only using point lights (spheres of light that fade out as you get further from the light’s position), but you can use any kind of light you can imagine (spot lights and directional lights are the two other common light types). Adding more lights has a very low impact on rendering time and this kind of lighting tends to be much easier for the designer to work with since there’s no need for him or her to understand HLSL or even any complicated C++ in order to add, remove, reposition, or otherwise change any lights.
The final pass draws the geometry a second time. This time, though, all the lighting calculations are done so all we do here is just render the meshes with their appropriate materials, adjust the color values and intensities from the material based on the light buffer value, and we’re done. Each rendering style (forward, deferred, and light pre-pass) has its own benefits and drawbacks, but in this case light pre-pass was a good solution and choosing it let us show how a state-of-the-art graphics technique works.
Normal Mapping

We also incorporated normal mapping. Normal mapping makes us of a special texture (a normal map) in addition to the regular texture that a material has. Normals are values used in lighting calculations to determine how much a particular light should affect a particular pixel. If you wanted to draw a brick wall, you would typically create two triangles that lined up to form a rectangle and you would apply a texture of a brick wall to them as their material. The end result of that doesn’t look very convincing though since unlike a real brick wall there are no grooves in the mortared area between each brick since our brick and mortar is just a flat texture applied to flat triangles. We could fix this by changing from two triangles to a fully modeled mesh with actual grooves, but that would add thousands of extra vertices which would lower the frame rate.
So instead we use a normal map, which fakes it. One of the reasons that the two triangles + a brick wall texture approach doesn’t look right is because the lighting doesn’t behave correctly when compared to a real brick wall (or to a fully modeled mesh of a real brick wall). The normals point straight out perpendicular from the face of the rectangle whereas if we had the fully modeled mesh with actual grooves, the surface normals would only point straight out on the bricks themselves and they would curve along the mortared areas such that the lighting calculations would end up giving us the right levels of light and dark depending on the location and direction of the light. That’s where a normal map comes in. The normal map (which you can generate using a plugin for Adobe Photoshop or GIMP or by modeling a real brick wall in 3DSMax, Maya, or Blender which you then “bake” a normal map from) allows us to get the same lighting effect as we would with a fully modeled mesh while still keeping the simple two triangle + a brick wall texture approach that gives us really good performance for our game. There are limits to the effectiveness of normal mapping (you can’t use it to fake anything too deep and it doesn’t hold up as well if the camera can get really close to the object) but in Maelstrom it allowed us to keep the walls as simple triangles (like the two triangles + a brick wall texture example above) while making it seem like there were geometric grooves in the wall. Here’s a before and after screenshot using normal mapping:

Post-Processing Effects

We also used several post-processing effects. The first was the bloom effect. Bloom is an effect that analyzes a rendered image, identifies parts that are above a certain brightness threshold, and makes those areas brighter and adds a peripheral glow to them as well, giving it a look and feel that is similar to a neon sign or to the light cycles in the movie Tron. Here’s the same shot as above with the addition of bloom:

We also made use of two different damage effects. Whenever the player took damage, we had a reddish tinge around the edge of the screen. This was simply a full screen overlay texture that is actually white but is tinted red by the shader. It is alpha-blended over the final rendered scene and fades out over the course of a couple of seconds. Rather than fading out linearly, we use a power curve which helps to sell the effect as being more complicated than it really is.
Lastly we added in some damage particles. The particles themselves were created using a geometry shader. The vertex shader took in a series of points in world space and passed these points along to the geometry shader. The geometry shader expanded these points into two triangles by generating the missing vertices and applying the world-view-projection transformation matrix to transform the positions from world coordinates to homogeneous coordinates so that they can then be rasterized correctly by D3D and the resulting pixels passed along to the pixel shader. Once again we used a simple texture with alpha blending to simulate much more complicated geometry than we were actually drawing. In this case we also made use of a texture atlas (an image made up of smaller images) which, in conjunction with the randomizer we used to generate the initial vertices for the particles, allowed us to have several different particle textures. Like with the power curve for the damage texture, the texture atlas allowed us to make the particles seem more complex than they really were. It also let us show off the use of a geometry shader, a feature that was added in DirectX 10 and requires DirectX 10 or higher hardware.
Audio

All audio was done using the XAudio2 API. Thankfully, we were able to get a huge head start by using some of the code from the sample project we started from. The audio engine sets up the very basics of XAudio2, and then wraps that with a simpler API for the rest of the application to call.
We don’t have many sound effects, so we on startup, we load all sounds effects and music cues into a std::map, keyed on a SoundCue enum. Sounds are loaded using the Media Foundation classes, and the resulting byte data of the sound (and some format information) are stored in our SoundEffect class.

void AudioEngine::Initialize(){ m_audio = ref new Audio(); m_audio->CreateDeviceIndependentResources(); m_mediaReader = ref new MediaReader(); // Impacts m_soundMap[SoundCue::BallLaunch] = LoadSound("SoundsImpactsBallLaunch.wav"); m_soundMap[SoundCue::Buzz] = LoadSound("SoundsImpactsBuzz.wav"); m_soundMap[SoundCue::Impact1] = LoadSound("SoundsImpactsImpact1.wav"); m_soundMap[SoundCue::Impact2] = LoadSound("SoundsImpactsImpact2.wav");...}SoundEffect^ AudioEngine::LoadSound(String^ filename){ Array^ soundData = m_mediaReader->LoadMedia(filename); auto soundEffect = ref new SoundEffect(); soundEffect->Initialize(m_audio->SoundEffectEngine(), m_mediaReader->GetOutputWaveFormatEx(), soundData); return soundEffect;}When the game needs to play a sound, it simply calls the PlaySound method, passing in the cue to play, and the volume to play it at. PlaySound keys into the sound map, getting the associated SoundEffect, and plays it.

void AudioEngine::PlaySound(SoundCue cue, float volume, bool loop){ m_soundMap[cue]->Play(volume, loop);}MJPEG Cameras

To achieve the effect of seeing the opponent in stereoscopic 3D, we strapped two Axis M1014 network cameras side-by-side. Using Brian’s MJPEG Decoder library, with a special port to Windows Runtime (available soon), individual JPEG frames were pulled off each camera, and then applied to a texture at the back of the arena. The image from the left camera is drawn when DirectX renders the player’s left eye, and the frame from the right camera is drawn when DirectX renders the right eye. This is a cheap and simple way to pull off live stereoscopic 3D.

void MjpegCamera::Update(GameEngine^ engine){ if(m_decoderLeft != nullptr) UpdateTexture(m_decoderLeft->CurrentFrame, &textureLeft); if(m_decoderRight != nullptr) UpdateTexture(m_decoderRight->CurrentFrame, &textureRight); Face::Update(engine);}void MjpegCamera::Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer, _In_ bool isFirstPass, int eye){ if(eye == 1 && textureRight != nullptr) m_material->SetTexture(textureRight.Get()); else if(textureLeft != nullptr) m_material->SetTexture(textureLeft.Get()); GameObject::Render(context, primitiveConstantBuffer, isFirstPass);}With the distance between the cameras being about the distance of human eyes (called the intra-axial distance), the effect works pretty well!

Tablet/Controller

The Tablet controller is the touch screen that lets the player control their 3D paddle in the Game Console app. For this part of the game system, there wasn't a reason to dive deep into DirectX and C++ since the controller is neither stereoscopic or visually intense, so we kept things simple with C#.
Since the controller would also serve as our attract screen in the podium to entice potential players, we wanted to have the wait screen do something eye-catching. However, if you are moving from C# in WPF to C# and XAML in WinRT and are used to taking advantage of some of the more common "memory hoggish UX hacks" from WPF, you'll quickly find them absent in WinRT! For example, we no longer have OpacityMask, non-rectangular clipping paths or the ability to render a UIElement to a Bitmap. Our bag of UX tricks may be in need of an overhaul. However, what we do get in C# / XAML for WinRT is Z rotation, which is something we've had in Silverlight but I personally have been begging for in WPF for a long time.
Therefore, the opening animation in the controller is a procedurally generated effect that rotates PNG "blades" in 3D space, creating a very compelling effect. Here is how it works. The Blade user control is a simple canvas that displays one of a few possible blade images. The Canvas has a RenderTransform to control the scale and rotation and a PlaneProjection which allows us to rotate the blade graphic in X, Y and Z space.

Each Blade is added dynamically to the Controller when the Tablet application first loads, stored in a List to have it's Update() method called during the CompositionTarget.Rendering() loop.

protected override void OnNavigatedTo(NavigationEventArgs e){ canvas_blades.Children.Clear(); _blades.Clear(); for (int i = 0; i < NumBlades; i++) { Blade b = new Blade { X = 950.0, Y = 530.0 }; int id = _rand.Next(0, 5); b.SetBlade(id); b.Speed = .1 + id * .1; SeedBlade(b); _blades.Add(b); canvas_blades.Children.Add(b); }}void CompositionTarget_Rendering(object sender, object e){ if(_inGame) { paddle.Update(); } else if(_isClosing) { foreach (Blade b in _blades) b.UpdateExit(); } else { foreach (Blade b in _blades) b.Update(); }}Since each Blade has been assigned an individual speed and angle of rotation along all three axis, they have a very straightforward Update function. The reason we keep the rotation values between -180 and 180 during the spinning loop is to make it easier to spin them out zero when we need them to eventually leave the screen.

public void Update(){ _rotX += Speed; _rotZ += Speed; _rotY += Speed; if (_rotX > 180) _rotX -= 360.0; if (_rotX < -180) _rotX += 360.0; if (_rotY > 180) _rotY -= 360.0; if (_rotY < -180) _rotY += 360.0; if (_rotZ > 180) _rotZ -= 360.0; if (_rotZ < -180) _rotZ += 360.0; projection.RotationX = _rotX; projection.RotationY = _rotY; projection.RotationZ = _rotZ;}public void UpdateExit(){ _rotX *= .98; _rotZ *= .98; _rotY += (90.0 - _rotY) * .1; projection.RotationX = _rotX; projection.RotationY = _rotY; projection.RotationZ = _rotZ;}Network

To continue the experiment of blending C# and C++ code, the network communication layer was written in C# as a Windows Runtime component. Two classes are key to the system: SocketClient and SocketListener. Player one’s game console starts a SocketListener to listen for incoming connections from each game controller, as well as player two’s game console. Each of those use a SocketClient object to make the connection.
In either case, once the connection is made, the client and the listener sit and wait for data to be transmitted. Data must be sent as an object which implements our IGamePacket interface. This contains two important methods: FromDataReaderAsync and WritePacket. These methods serialize and deserialze the byte data to/from an IGameState packet of whatever type is specified in the PacketType property.

namespace Coding4Fun.Maelstrom.Communication{ public enum PacketType { UserInputPacket = 0, GameStatePacket } public interface IGamePacket { PacketType Type { get; } IAsyncAction FromDataReaderAsync(DataReader reader); void WritePacket(DataWriter writer); }}The controllers write UserInputPackets to the game console, consisting of X,Y positions of the paddle, as well as whether the player has tapped the screen to begin.

public sealed class UserInputPacket : IGamePacket{ public PacketType Type { get { return PacketType.UserInputPacket; } } public UserInputCommand Command { get; set; } public Point3 Position { get; set; }}Player one’s game console writes a GameStatePacket to player' two’s game console, which consists of the positions of each paddle, each ball, the score, and which tiles are lit for the ball splitter power up. Player two’s Update and Render methods use this data to draw the screen appropriately.
Hardware

The hardware layer of this project is responsible for two big parts. One is a rumble effect that fires every time the player is hit, and the other is a lighting effect that changes depending on the game state.
As all good programmers do, we reused code from another project. We leveraged the proven web server from Project Detroit for our Netduino, but with a few changes. Here, we had static class “modules” which knew how to talk to the physical hardware, and “controllers” which handled items like a player scoring, game state animations, and taking damage. Because the modules are static classes, we can have them referenced in multiple classes without issue.
NETMF Web Server

When a request comes in, we perform the requested operation, and then return a new line character to verify we got the request. If you don’t return any data, some clients will actually fire a second request which then can cause some odd behaviors. The flow is as follows:

Parse the URLGet the target controllerExecute the appropriate action

private static void WebServerRequestReceived(Request request){ var start = DateTime.Now; Logger.WriteLine("Start: " + request.Url + " at " + DateTime.Now); try { var data = UrlHelper.ParseUrl(request.Url); var targetController = GetController(data); if (targetController != null) { targetController.ExecuteAction(data); } } catch (Exception ex0) { Logger.WriteLine(ex0.ToString()); } request.SendResponse(NewLine); Logger.WriteLine("End: " + request.Url + " at " + DateTime.Now + " took: " + (DateTime.Now - start).Milliseconds);}public static IController GetController(UrlData data){ if (data.IsDamage) return Damage; if (data.IsScore) return Score; if (data.IsGameState) return GameState; // can assume invalid return null;}Making It Shake

We used a Sparkfun MP3 trigger board, a subwoofer amplifier, and bass rumble plates to create this effect. The MP3 board requires power, and two jumpers to cause the MP3 to play. It has an audio jack that then gets plugged into the amplifier which powers the rumble plates.
From here, we just needed to wire a ground to the MP3 player’s ground pin, and the target pin on the MP3 player to a digital IO pin on the Netduino. In the code, we declare it as an OutputPort and give it an initial state of true. When we get a request, we toggle the pin on a separate thread.

private static readonly OutputPort StopMusic = new OutputPort(Pins.GPIO_PIN_D0, true);private static readonly OutputPort Track1 = new OutputPort(Pins.GPIO_PIN_D1, true);// .. more pinspublic static void PlayTrack(int track){ switch (track) { case 1: TogglePin(Track1); break; // ... more cases default: // stop all, invalid choice TogglePin(StopMusic); break; }}public static void Stop(){ TogglePin(StopMusic);}private static void TogglePin(OutputPort port){ var t = new Thread(() => { port.Write(false); Thread.Sleep(50); port.Write(true); }); t.Start();}Lighting Up the Room

For lighting, we used some RGB Lighting strips. The strips can change a single color and use a PWM signal to do this. This is different than the lighting we used in Project Detroit which allowed us to individually control each LED and used SPI to communicate. We purchased an RGB amplifier to allow a PWM signal to power a 12 volt strip. We purchased ours from US LED Supply and the exact product was RGB Amplifier 4A/Ch for interfacing with a Micro-Controller (PWM/TTL Input).
We alter the Duty Cycle to shift the brightness of the LEDs and do this on a separate thread. Below is a stripped down version of the lighting hardware class.

public static class RgbStripLighting{ private static readonly PWM RedPwm = new PWM(Pins.GPIO_PIN_D5); private static readonly PWM GreenPwm = new PWM(Pins.GPIO_PIN_D6); private static readonly PWM BluePwm = new PWM(Pins.GPIO_PIN_D9); private const int ThreadSleep = 50; private const int MaxValue = 100; const int PulsePurpleIncrement = 2; const int PulsePurpleThreadSleep = 100; private static Thread _animationThread; private static bool _killThread; #region game state animations public static void PlayGameIdle() { AbortAnimationThread(); _animationThread = new Thread(PulsePurple); _animationThread.Start(); } #endregion private static void PulsePurple() { while (!_killThread) { for (var i = 0; i = 0; i -= PulsePurpleIncrement) { SetPwmRgb(i, 0, i); } Thread.Sleep(PulsePurpleThreadSleep); } } private static void AbortAnimationThread() { _killThread = true; try { if(_animationThread != null) _animationThread.Abort(); } catch (Exception ex0) { Debug.Print(ex0.ToString()); Debug.Print("Thread still alive: "); Debug.Print("Killed Thread"); } _killThread = false; } private static void SetPwmRgb(int red, int green, int blue) { // typically, 0 == off and 100 is on // things flipped however for the lighting so building this in. red = MaxValue - red; green = MaxValue - green; blue = MaxValue - blue; red = CheckBound(red, MaxValue); green = CheckBound(green, MaxValue); blue = CheckBound(blue, MaxValue); RedPwm.SetDutyCycle((uint) red); GreenPwm.SetDutyCycle((uint) green); BluePwm.SetDutyCycle((uint) blue); Thread.Sleep(ThreadSleep); } public static int CheckBound(int value, int max) { return CheckBound(value, 0, max); } public static int CheckBound(int value, int min, int max) { if (value = max) value = max; return value; }}Conclusion

We built this experience over the course of around 4 to 5 weeks. It was our first DirectX application in a very long time, and our first C++ application in a very long time. However, we were able to pick up the new platform and language changes fairly easily and create a simple, yet fun game in that time period.
Attributions

Music track - "FatLoad- The Bullet(no master)" by FreaK NeoSSound effects + music edition - David WallimannDirectX shaders - Michael McLaughlin

More...




When you have a Ferrari you might want to test drive it on a circuit, where there are none of the limitations of a town street. Well, when you have Internet Explorer 9 Beta you need a “circuit” on which to test it, something more than just your average Internet websites, applications and services.

Somewhere where you could really go “pedal to the metal” on IE9. Where the browser will show just what it is capable of.

Fortunately enough, a wide range of such sites designed for Internet Explorer 9 already exist, with a plethora of Microsoft partners introducing new IE9-related web projects with the launch of the Beta on September 15th, 2010.

The Beauty of the Web launch event for IE9 Beta earlier this week was a real show of force from Microsoft partners.

At the bottom of the screen I included a range of photos from the partner section of the event. Below you will also be able to find a list of links with some amazing IE9 websites from the software giant’s Beauty of the Web event.

“Richer Web experiences can blend into the consumer's desktop experience comfortably and consistently. So, today we have an A to Z, literally, of Web sites, partners, live with Web experiences that take advantage of IE9, even more than the A to Z of the Web,” revealed Dean Hachamovitch, Corporate Vice President, Internet Explorer, Microsoft earlier this week.

Users will be able to easily notice that IE9 can enhance the experiences associated with social networks such as Facebook, Twitter, and Netlog.

But there is additional bleeding edge content from various web design firms, and new perspectives on entertainment and news from BBC, CNN, Hulu, Vimeo, and Daily Motion.

Over 50 projects were on display in total, many of them built in very short time, just a matter of weeks, in preparation for the event.

But all of them extremely impressive, and all of them already live on the web, and available to testers around the world.

It’s important to underline that although the Redmond company catalyzed the creation of the projects, it made sure to have them work not only across Internet Explorer 9, but also across rival browsers.

Superb projects such as Endless Mural will function in IE9, as well as any other browser that supports HTML5.

All the websites featured at the Beauty of the web event in fact, are set up to take advantage of modern web standards, such as HTML5, CSS3, SVG, etc.

And usage is in no way restricted to IE9, which is a brilliant move from Microsoft, showing its commitment to users, developers and partners alike, and a strong focus on driving the web forward by making the same markup vision a reality.

“Today partners around the Internet join us in releasing new experiences for the Web. Over 70 top sites and brands that reach over two-thirds of active Internet users. Together that's over 800 million visitors whose Web experience just got better on Windows with IE9,” Hachamovitch added on September 15th.

Here is the list of IE9 websites, with short descriptions from Microsoft:

“1. Amazon - Amazon.com, Inc. seeks to be Earth's most customer-centric company.

By integrating the pinning and Jump List features enabled by Internet Explorer 9, Amazon continues to enhance the on-line shopping experience for customers by giving them easy access to Amazon.com favorites such as Gold Box Deals and Best Sellers as well as enabling customers to manage their accounts and check the status of orders quickly and effortlessly.

2. Agent 008 Ball by Pixel Lab - Agent 008 Ball is an addictive game that combines billiards with the high stakes world of international espionage. Cutting edge HTML5 features (like Audio and Canvas) supported by Internet Explorer 9, combined with stunning graphics draw you in as you attempt to beat a timer and avoid the nefarious tricks of the terrorist organization CHALK.

3. Always Beautiful by Big Spaceship - Using the new features included in Internet Explorer 9, Big Spaceship created Always Beautiful, an interactive visualization set to music.

Users manipulate colors and objects that adapt to the song's rhythm and structure. At the end of the song, the user is shown the high-resolution artwork they've created using the powerful SVG capabilities and improved JavaScript performance of Internet Explorer 9.

4. AP News Reader by Vectorform - The AP News Lab "Timeline Reader" is a collaboration between Vectorform and The Associated Press (AP) exploring new ways of visualizing and reading online news.

We sought out to create a fully featured online reader application that showcases the beautiful high-res imagery from the AP side-by-side with a full article reading experience.

Users can browse through all of their favorite news categories simultaneously in a timeline visualization that frames the day’s events in a complete chronological sequence. The site is also a showcase of the latest advances in HTML5 and CSS3 supported in modern web browsers.

Some of the new technologies utilized were the HTML5 canvas tag to create a fast loading and snappy intro animation/splash screen, HTML5 local storage to keep track of read articles and a reading queue, and CSS3 support for embedding web fonts.

5. AMD Space Command - AMD Space Command is a fun game that shows the graphics acceleration of Direct2D technology in the Internet Explorer 9 browser.

Shoot as many space attackers possible, and use the “GPU capacitor” to adjust the intensity of the game. AMD Space Command is built in HTML5, leveraging the GPU in your PC to improve graphics.

You can see this first hand by keeping track of the Frames Per Second (FPS) as you adjust your GPU capacitor!

6. BeatKeep by Archetype - Community and creativity are the driving forces behind Archetype’s BeatKeep application.

BeatKeep allows drummers, musicians, and music enthusiasts to discover, create, and share beats of any genre. Through intuitive interactions and the power of HTML5 on Internet Explorer 9, BeatKeep allows users to create unique audio tracks and share them on social networks like Facebook.

7. Beautiful Explorer by Soleil Noir - Web is beautiful, spontaneous, ephemeral and so creative. The beauty of the web is the creative contents produced by everyday people. This website is a design trends daily overview. We hope you'll enjoy it.

8. BMW Vision by EMC - EMC Consulting and BMW have a created the BMW Car Configurator, a ground-breaking tool that shows off the extraordinary BMW Vision EfficientDynamics concept car.

The experience relies on the high performance of Internet Explorer 9, bringing together the awesome power of Chakra, its new JavaScript engine, and GPU acceleration to enable car enthusiasts to manipulate both the car and its environment with a fluid three-dimensional feel.

9. Brain Power by R2Integrated and Scientific America - R2integrated developed Brain Power, a website and interactive learning tool to introduce users to the many parts of the human brain and its functionality.

Brain Power uses HTML5, SVG, CSS3, and JavaScript. An animation layer produces real-time interactions with elements drawn within the HTML5 canvas.

The HTML5/CSS3 engine within Internet Explorer 9 makes full rich interactive applications practical for all new websites. In short, HTML5 and Internet Explorer 9 introduce end users to new levels of flexibility, capability, and expression.

10. Chinese Shadow Play by RedSAFI - Chinese Shadow Play is a traditional form of Chinese art. This demo lets users choose an iconic Chinese shadow puppets, play with puppets individually and organize the puppets in formations.

This demo shows off the power of the Internet Explorer 9 Canvas by featuring a physics engine and a bones system, as well as beautiful bitmap art to create an engaging viewing experience.

11. Also by RedSAFI: Chinese Kite Experiment - In this demo, a user can select a kite and choose a flight pattern.

The user can also add fans to the stage and add collision detection to alter the kite’s flight. This demo shows off Internet Explorer 9 Canvas performance by featuring a physics engine to create the flying environment.

12. Comicx Parallax by Steaw Design - As web technologies continue to evolve, we prepare to enter the age of HTML5. Created for Beauty of The Web in honor of the Internet Explorer 9 launch, “Never Mind the Bullets” offers the traditional comic strip experience enriched by parallax.

With a simple movement of the mouse, the strip is animated and the story comes to life. It unfolds at LongHorn Gush, a quiet town troubled by a band of outlaws, The Red Bandanas.

However, with the arrival of the famous Bill “One Shot” Collins, things are about to change.

13. Cracked.com by Demand Media - Pinning Cracked.com to your task bar allows you easier access to one of the fastest growing humor sites in the world.

Now all of Cracked’s award-winning content is only one click away – no matter where you are online!

14. DailyMotion - Dailymotion is pleased to announce the release of its new HTML5 Player Beta and Demo.

This development takes advantage of the latest web standards, and permits streaming video playback without the need for plugins," said Olivier Poitrey, CTO and Co-Founder.

"We are excited to partner with Microsoft for this announcement as the new Internet Explorer 9 shows commitment to both web standards and innovation. Internet Explorer 9 sets itself apart by supporting hardware accelerated graphics and offering users a more app-like experience with their new Site Mode.

15. Digital News Archive (DNA) by Nave - The web site provides Korean newspapers from various publishers dates starting from 1960's to 1990's.

Users can easily browse through the newspapers using simple UI. To maximize the user experience, the Canvas element was heavily utilized. With the Canvas, we could make zoom, page navigation and other transitions smooth and enjoyable for the users.

16. Discovery - As the world’s number one nonfiction media company, Discovery Communications is always looking for new ways to engage with our passionate fans.

By building new Internet Explorer 9 functionality into Discovery.com, TLC.com and AnimalPlanet.com, we are able to give audiences even more ways to interact with and learn from their favorite TV shows and personalities.

17. EBay

18. eHow by Demand Media - eHow offers more than 2 million articles and videos, providing visitors with trusted solutions for completing life’s daily tasks or larger projects.

With Internet Explorer 9, users enjoy an optimized and more dynamic eHow, a faster loading and immersive video experience - without the need for 3rd party software - plus new tools to bring relevant eHow content straight to our user’s fingertips.

19. Facebook - More than 500 million people actively engage with their friends on Facebook each month.

With IE9, Facebook users will be able to more quickly access and manage their social activities through the browser and get back to their friends via a seamless and rich experience.

20. Flixster - Flixster is the largest online movie community and the leading movie application for mobile devices.

Flixster is using Internet Explorer 9’s new features to give users quick and easy access to great movie content right from the desktop.

21. Floweroscope by LA Surprise - Floweroscope provides users with a kaleidoscope-like online artistic experience that explores the new capacities of Internet Explorer 9 to create a unique animation experience.

Floweroscope provides symmetrical effects and randomly generated shapes, and the user controls the shape colors and sizes.

An HTML5-supported volume effect and the new Chakra JavaScript engine immerse the user into the experience. The Internet Explorer 9 Canvas element provides an innovative way to draw hardware-accelerated animations without plugins.

22. Gorillaz - Gorillaz.com has been optimised for Internet Explorer 9 to take advantage of some great new integration features with Windows 7.

Fans can now drag the Gorillaz favicon to their taskbar and access it like an app. Right-clicking on the Gorillaz icon in the taskbar provides access to site features like News or the G Player.

Gorillaz fans can even personalise this list by clicking the star to save any page. Powered by HTML5, Murdoc’s Reading Room is turned into an interactive space.

He'll talk you through it as you zoom up to the gallery wall and listen to tracks, bring up the Story So Far book off his coffee table with stunning pictures, html5 video and audio, and have a nosey look through the contents of his laptop. Click on the video to play an HTML5 video!

23. Hulu - Hulu on Internet Explorer 9 and Windows 7 will allow users to customize their Jump List menu with the most popular destinations on the site.

To customize, users simply select the menu items in their profile page and they become accessible whenever/wherever you are on Hulu.com.

The site will also enable contextual menus on Show Pages and Watch Pages allowing users to Subscribe to shows or control their video watching experience during content playback.

24. IMDb - More than 100 million unique visitors per month turn to IMDb to discover which movies are coming out and decide what to watch.

IMDb’s new HD Trailer Gallery utilizes HTML5 and Internet Explorer 9 hardware acceleration to dramatically enhance the trailer viewing and movie discovery experience on IMDb.

25. Jack & the Beanstalk, an Animated, Interactive Storybook by Clarity Consulting - The site blends fantasy and realism in custom illustrations animated by physics-based JavaScript.

The GPU acceleration in Internet Explorer 9 allows for smooth rendering of animations, even when leveraging heavy physics libraries. Coupled with SVG graphics and embedded audio most are surprised to hear the entire site has been created using HTML5, CSS, and JavaScript.

The newly supported features of Internet Explorer 9 allows for rich interactivity without the overhead of the traditional plug-in based model.

26. JitterBug by Cynergy - JitterBug is a fast, fun game built exclusively in HTML5. Showing off the rich media and rendering power of Internet Explorer 9, the game challenges the player to draw lassos around fast moving bugs to unlock the Band and start the show before the time runs out.

Relying heavily on Internet Explorer 9’s impressive Canvas abilities, this rich playing experience redefines what’s possible in HTML based game play.

27. Kaboodle - Kaboodle is the Internet’s largest social website for passionate shoppers. Kaboodle’s shopping tools allow users to add products from anywhere online to their Kaboodle lists and to share those products with others.

The site’s integration with Internet Explorer 9 will provide Kaboodle community members with easy access to their personalized shopping content via a custom Jump List, ensuring that it is always just one click away.

28. LinkedIn - LinkedIn is an Internet platform company focused on connecting the world's professionals.

The company is privately held and has a diversified business model with revenues driven from user subscriptions, advertising sales and enterprise software licensing.

The LinkedIn Web site launched in 2003 and is the largest professional networking site in the world with more than 75 million members, representing 200 countries and executives from every Fortune 500 company.

LinkedIn’s integration with Internet Explorer 9 will provide its members with one-click access to their professional network and business insights via a custom Jump List.

29. Live Strong by Demand Media - LIVESTRONG.COM inspires and empowers people to achieve their daily goals around living healthy.

With Internet Explorer 9, users enjoy a more dynamic experience including an expanded HD video browsing and improved recipe discovery.

A newly optimized experience of the popular MyPlate food and fitness tracking application keeps users engaged in real-time.

30. Lost World’s Fairs by Friends of Mighty - To celebrate Internet Explorer 9’s support for the Web Open Font Format (WOFF) Jason Santa Maria, Frank Chimero, Naz Hamid, and Trent Walton have teamed up to create a series of web broadsheets for World’s Fairs that never were.

Each piece uses fully live text (with some HTML5 and CSS3) to showcase what’s typographically possible on the web.

31. MONA (Museum Of Neverending Art) by groupeReflect - At the MONA, users work together to create the biggest online artwork ever.

Everyone can create, draw, write, upload pictures, and add and alter things on the canvas. It’s a user-generated piece of art, which is constantly in motion.

Using Internet Explorer 9 technologies such as HTML5 / CSS3, WebFonts, Canvas and the new Internet Explorer 9 JavaScript Engine, MONA makes you rediscover the beauty of the web, as well as recreate it.

32. MySpace - MySpace Video offers music videos, full episodes of TV shows, and user generated content and creates a social environment for users to view, create and share videos with friends.

In Internet Explorer 9, MySpace Video serves over 200,000 videos and UGC video clips in state of the art high-def H.264 in full compliance with HTML5. Jump Lists in Internet Explorer 9 offer quick content discovery and easy navigation.

33. National Museum Gallery China by NX - One of the most famous museums in China, National Museum of China (NMC) now allows visitors to explore the galleries on their feet or on the web.

Internet Explorer 9’s HTML5 support is just right for this scenario: easy to develop with great flexibility, smooth video and audio playback and a fast experience with the new JavaScript engine.

34. Netlog - Netlog is an online platform where users can keep in touch with and extend their social network and is currently available in 37 languages and has more than 69 million members throughout Europe, and this number increases every day.

Netlog is taking advantage of pinning site to the taskbar and thereby making sure users get to the activities within Netlog they care about via the Jump List.

35. One Day in Beijing by Toujie - One Day in Beijing provides a virtual tour of famous Beijing sites, including the Great Wall, Temple of Heaven, Beihai Park, Tian An Men, and National Stadium China (Bird Nest).

These are the must-go places for anyone touring Beijing. By harnessing the power of Internet Explorer 9 and HTML5 along with the Internet Explorer 9 Canvas 2D API, we created a multitude of interactive scenarios.

Users can experience flying clouds and mouse sensitive navigation, as well as other HTML 5 demos like flying kites, and piyingxi.

36. Photobucket - Photobucket is the premier destination for saving, sharing, searching, and creating images and video on the Web.

With Internet Explorer 9, Photobucket is using Jump List, which will allow users to access both their own content and content from topical “Find Stuff” categories directly from their desktop.

37. Quiksilver

38. Red Bull by Archetype - Archetype has created a next generation global media and social experience for Red Bull.

This interactive application allows users to browse Red Bull’s rich set of photos and video, dynamically surfacing content based on its popularity in social networking sites and on users' interests.

It takes advantage of HTML 5, SVG, CSS3, Jump Lists, Scaling, Audio/Video tags and custom font features and functionality offered by Internet Explorer 9 to raise the bar for interactivity and design in standards based websites.

39. Rough Guides by Metia - Members of this interactive community use an animated compass to navigate a map of the world; view geo-located photographs pulled from the Flickr database; and explore 200 travel experiences selected by Rough Guides.

Members can also submit their own images to the community, and share favourite experiences from their online travels using Facebook, Twitter and email.

40. RTL - RTL Group is a house of excellent content and powerful brands, which is able to deliver its content to all media platforms worldwide and to repeat its broadcasting success story in every country while fulfilling its obligation to society.

By combining pinning, Jump List and previews into the RTL experience, Internet Explorer 9 users get convenient access to the most popular RTL content.

41. Sohu NBA by Digital Hall nbadata.sports.sohu.com - Sohu Sports is one of the most popular interactive sports information network among sport enthusiasts.

Being the NBA-licensed live video broadcast site for NBA events in China, NBA fans can access team schedules, game videos and team/player data, photos, chat rooms, voting and other interactive features. Internet Explorer 9 plus HTML 5 gives an unparalleled high performance hardware accelerated graphics and video experience.

42. t-online.de - This showcase is a sneak peek at the future of t-online.de.

Core features are new picture and video galleries, a 360 degree view of consumer products and a fun and challenging online game, all completely realized in HTML 5.

This, as well as the implementation of the Internet Explorer’s Jump List feature, offers the user a glimpse of what a modern news website could be like when fully implementing the power and simplicity of HTML 5 in combination with the Internet Explorer’s unique way to surf the web.

43. The Doll Parade by Freetouch - The Doll Parade allows its users to assemble a wide variety of dolls by customizing their arms, legs, faces and apparel.

Once the doll is assembled the users doll along with other creations march smoothly via an HTML5 Canvas. The experiences takes advantage of HTML 5 (Canvas), SVG and CSS3.

44. The Killers by SparKart - The Killers' website chronicles the band's career, and offers users a seamless browsing experience of the band’s music and video content.

The website takes advantage of HTML5, Canvas & SVG across the site's panoramic landscape & internal sections, leveling the playing field in displaying content to users across multiple platforms & devices.

45. The Shodo by Business Architects - The Kanji Calligraphy website takes advantage of powerful new Internet Explorer 9 features to introduce users to the beautiful Japanese calligraphy known as Shodo.

Even better, Kanji Calligraphy allows users to create their own calligraphy-based art work and share it on Twitter and Facebook.

This site is based on several of the features supported by Internet Explorer 9 HTML5 (canvas, video element, audio element), SVG, and WOFF.

46. The Wall Street Journal - WSJ.com offers breaking news coverage, real time quotes, and in-depth analysis and commentary to the business elite.

Its high-end magazine, WSJ., emphasizes luxury and discerning lifestyle content. To make it easier for users to find and enjoy the content, WSJ is implementing favicons, pinning and the Jump List functionality of Internet Explorer 9 and employing HTML5 features for the visually enriched magazine.

Users can more quickly and easily access Journal content on their faster Internet Explorer 9 browsers.

47. TopGear.com by BBC - TopGear.com is the award-winning website of the world famous motoring entertainment brand, Top Gear.

Top Gear presenters, producers, magazine team, and contributors regularly post on TopGear.com. The Cool Wall leverages the HTML5 and hardware accelerated graphics support in Internet Explorer 9 to provide amazingly smooth transitions, Deep Zoom functionality and slick video playback.

48. Twitter - Twitter lets you share and discover what's happening in your world. The Twitter pinned app in Internet Explorer 9 makes it easy to jump into your Twitter timeline, read and send direct messages, and more, so it's never more than a click away.

49. USA Today - As a part of the fifth anniversary of Hurricane Katrina, USA TODAY built a multimedia project examining where things now stand in New Orleans and the Gulf Coast.

To build the site, we used a variety of web standards, including HTML5 video tag and several CSS3 features, that take advantage of the capabilities of cutting-edge web technologies in Internet Explorer 9.

50. Vodpod - Vodpod makes it easy to build your own video channel with your favorite videos from the Web, and to tune in to channels by other members who share your tastes and interests.

By pinning Vodpod to the taskbar in Internet Explorer 9, users will be able to jump right to their real-time Vodpod feed, to their video collection, or to their favorite channels.

51. WebVizBench by Stimulant and KEXP - WebVizBench lets fans of Seattle’s non-profit radio station KEXP explore historical airplay data, while putting HTML 5's new features to the test. Sift and sort through 6+ years of music, or use the benchmark mode to see how your browser, CPU and GPU stack up against a thorough battery of DOM, canvas, typographic, SVG and video rendering tests.

52. XING - XING is a social network for business professionals with more than 9.6 million members worldwide.

Using Internet Explorer 9 technology such as Jump Lists, XING members can perform tasks like sending messages faster than ever and also receive real-time updates about their network. This supports our XING Anywhere strategy and our efforts to provide our members with great usability.

53. Yahoo! Japan - Through Jump Lists in Internet Explorer 9, users of Yahoo! can enjoy the ‘People’, 'TV', 'Game/Animation', and 'Sports' categories of search ranking, and further enjoy it by switching to Yahoo! Auction, and Yahoo! Answer to see what is actively traded or discussed related to popular queries.

54. ZKM - “Exhibition and Archive” presents a historic online exhibition and a new experience of archival survey.

The side is driven by HTML5, CANVAS, CSS3, SVG and Jump List, which allow graphically rich, standard conform applications and avoids plugins. The pure implementation supports the modern claim of “form follows function” and adds sustainability.”

54 Amazing IE9 Websites You Have to Try - Softpedia