Silverlight game development experience (2) -- other topic of the Scheduler

Source: Internet
Author: User
Tags exit in

The access volume of the previous Article exceeded 1000. Haha, so many people have never read my article. Although within the company, I highly value communication and mutual experience to avoid repeated wheel-building events, there have not been so many people looking at their own things.

I still want to emphasize one thing, although I have already stressed it multiple times: friends, if you want to spare your precious time to read my article, so please make up more time to practice and use code to practice it all. This is much more difficult than reading. I spent only one hour finishing the scheduler chapter, but it took me a whole month to implement it. However, only in such a process can you learn your own things-"practice to learn the truth ".

  I: scheduler Extension

In the previous article, I showed you the structure of a simple scheduler. On this basis, there are still many things that can be done. Among them, performance balancing is very important. We recommend that you read this article "clock in the game". The figure for deleting the peak is interesting. Of course it is an ideal situation, but it is not impossible. First, we need to get the system load. This is easy to do in Silverlight. If you are familiar with the Silverlight API, you can think of this Analytics class, in fact, even if you are not familiar with it, you can refer to the Silverlight documentation ---- "Manual is your friend. "A better way is to write a tool class where it can be called at any time. Once the CPU load is obtained, the next thing will be much easier. This will reflect the power of the scheduler, in the structure of the scheduler, you need to execute time tasks and frame tasks in the queue one by one, and each frame is executed once and never stops rendering tasks. (In actual development, you can also define more task types if necessary .) Maybe in a special period of time, the CPU load is very high, reaching the threshold you set, for example, 60%, the players in the game become very stuck, this is a very bad thing, at this time, it is necessary to adjust the clock.

In the simple scheduler, the tasks in the task queue are executed unconditionally, so now, it may only be executed if the CPU load does not exceed the threshold, otherwise it will be adjusted: there are various adjustment methods. The adjustment policies are based on specific situations. You can simply skip some tasks when they are higher than the warning threshold. You can also extend the frame interval/interval of a task, for example, a task executed once at two frames, it can be executed three frames at a time, or even you can stop the continuous rendering task, depending on your situation. It should be said that this is not just a problem with the scheduler, but it also requires many other modules to work together, but it is finally solved in the scheduler. Maybe now I want to praise the scheduler. How wonderful it is to have such a separate exit in the development process.

An example shows the performance tuning of the scheduler in the game: when a new login in the game, there are always a lot of people in the place of birth, and the game will become very stuck at this time, although you will soon leave here for adventure elsewhere, it is very slow, exercise is slow, and it is difficult to leave this place. At this time, we can execute a "visual Focus" adjustment strategy. Assume that your attention is concentrated in a small area centered on you, and you are not so concerned about other areas, although the area is changing as you move around, it's just like you have a light on the stage. Then we can adjust the scheduler to execute all the tasks in this region as usual, but the tasks outside this region should be adjusted. Note that the scheduler should be very careful during this period, not the more the better, but the less the better. For example, you can slow down the Frame Rate of animation rendering for other characters and cancel some special effects in the scenario, however, you must ensure that your network data packets are sent as scheduled. We need to find the task with the largest load, but it doesn't mean we need to adjust it. If this task is very important, we have to find a solution elsewhere. It all depends on the specific situation of your game. It should be said that it is not easy to design a set of good adjustment policies.

When performing your adjustment strategy, you also need to prevent the occurrence of the adjustment shock. For example, if your current CPU load exceeds the threshold, you decide to ignore the execution of task, after task A is ignored, the CPU load quickly drops. At this time, the system feels that everything is normal, so it restores everything and task A also recovers. As A result, the CPU immediately exceeds the load, as a result, the system began to oscillate on both sides of the warning line. This is not our hope. To avoid this, we should make the adjustment limit more appropriate or improve the statistical analysis of the effect.

II: Multithreading

When Moore's law no longer works, the importance of parallel programming is always mentioned.

I would like to say a frustrating thing. In the current structure and experience, the whole is based on a single thread. They are all exploring efficient algorithms and exquisite structures. However, there is not much and little experience in parallelism. I also tried to introduce parallelism in the game. I have to admit that this is hard. Of course, it may be very easy for you to solve my difficulties. After all, I am not a "Smart Guy ". The scheduler is based on the structure of the task system and provides convenience for using multithreading. First, you need to split functions that are too complex in the code. For example, in this method, public void ExecuteFrame (), execution frame task queue, time task queue, and rendering task. If you split the frame task queue and time task queue, you can create two threads to execute them separately. One thing I should mention is to avoid executing tasks associated with the UI in different threads, even if the cross-thread operation permission is obtained through asynchronous delegation, the result is still congested and serialized, which makes little sense. During the design process, we should be careful to identify and split the execution sequence and Association of tasks to avoid competing resources and put logic processing in front (as long as the UI is not involved, silverlight can still be real multi-thread parallel processing), and UI rendering can be performed in a unified manner.

I am afraid that all the problems involved here will only be realized in practice. I hope that this piece of Brick will attract the film of Meiyu and we will discuss it together.

Here, I will share a CPU statistics Tool class I wrote to you.

Code

 Public class CPUCounter
{
Private static TextBlock txtCpuLoader;
Private static Canvas _ canvas;
Private static System. Windows. Threading. DispatcherTimer dt;
Private static Analytics analytics;

// This method enables FPS to be displayed on the IE status bar
// Add <param name = "EnableFrameRateCounter" value = "true"/> in Html for most tutorials,
// However, my experiment results show FPS when added or not, but I need to modify the Security Settings of IE.
Public static void ShowFrameFrequency (bool _ showFrequency, int _ maxFrameRate)
{
System. Windows. Interop. SilverlightHost host = Application. Current. Host;
System. Windows. Interop. Settings settings = host. Settings;
Settings. EnableFrameRateCounter = _ showFrequency;
Settings. MaxFrameRate = _ maxFrameRate;
}

// Add a CPU statistics to the specified Canvas. You can specify the color size and position.
// This statistician is self-started
Public static void AddCPULoader (Canvas _ rootCanvas, int _ fontSize, Color _ color, Point _ pos)
{
_ Canvas = _ rootCanvas;
TxtCpuLoader = new TextBlock ()
{
FontSize = _ fontSize,
Foreground = new SolidColorBrush (_ color ),
FontWeight = FontWeights. Bold
};

_ Canvas. Children. Add (txtCpuLoader );
Canvas. SetLeft (txtCpuLoader, _ pos. X );
Canvas. SetTop (txtCpuLoader, _ pos. Y );
Dt = new System. Windows. Threading. DispatcherTimer ();
Dt. Interval = new TimeSpan (0, 0, 0, 0, 1 );
Analytics = new Analytics ();
Dt. Tick + = new EventHandler (PrintTxt );
Dt. Start ();
}

Static void PrintTxt (object sender, EventArgs e)
{
TxtCpuLoader. Text = "CourseCPU:" + GetSuitableDouble (analytics. AverageProcessLoad, 2) +
"% AllCPU:" + GetSuitableDouble (analytics. AverageProcessorLoad, 2) + "% ";
}

// Uninstall the CPU statistician
Public static void RemoveCPULoader ()
{
If (_ canvas! = Null)
{
_ Canvas. Children. Remove (txtCpuLoader );
If (dt! = Null)
{
Dt. Tick-= new EventHandler (PrintTxt );
Dt. Stop ();
}
}
}

Public static string GetSuitableDouble (double _ d, int _ digit)
{
String result = string. Empty;
Int d = (int) (_ d * Math. Pow (10, _ digit ));
Double dd = d/Math. Pow (10, _ digit );
If (dd = 0)
{
For (int I = 0; I <_ digit; I ++)
{
Result + = "0 ";
}
Return ("0." + result );
}
If (dd. ToString (). Length! = D. ToString (). Length + 1)
{
Result = dd. ToString (). PadRight (d. ToString (). Length + 1, '0 ');
Return result;
}
Result = dd. ToString ();
Return result;
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.