2013/05/26

Polar grid drawing refined

Hello again

Last time I showed a preview of polar grids it was a full cycle starting from the origin containing all layers up to the edge. During runtime if only part of the grid is visible to the player rendering the whole thing can be a waste of resources, that's why you have the option of specifying a specific rendering range.

I was trying out several approaches of interpreting the rectangular range, but in the end I went for a polar approach. What does this mean? You have two Vector3 values, one called renderFrom, the other called renderTo. The x-coordinate tells what radius to start and end at, the y-coordinate gives us the starting and ending angle and the z-coordinate gives us the starting and ending layer. Here is an example of what if can look like:
The only limitations are that the starting radius cannot be less than 0 and starting values cannot be larger than ending values (and vice-versa). The only exception is the angle, this is is necessary in order to  be able to draw a sector from, let's say 300° to 15° (which can be seen as from 300° to 375°).

This has been the biggest roadblock so far, now I need to do some proper testing and final polish, write the new documentation and I can submit the update to Unity. Supporting a new type of grid is a substantial effort and, since everything is interconnected, it usually requires going through the code for the other grids as well. Sometimes parts that seemed general enough might need to be overridden and other parts that seemed very specific become more general and need to be moved up the hierarchy. Considering this and the updates since the release of version 12.0 I believe raising the price to from 20$ to 25$ is appropriate.

Of course, as usual, if you already bought Grid Framework all updates are free for you. If you intend to buy Grid Framework, now is the chance to still get it for the lower price. You don't need to rush and get it immediately though, I'll post an at least one more update before I submit version 1.3.0.

As always, thank you for your support
HiPhish

2013/05/17

Grid Framework version 1.2.5 released


This release serves as a preparation for Version 1.3.0, which will add polar grids

  • The methods NearestVertex/Face/BoxW and NearestVertex/Face/BoxG replace FindNearestVertex/Face/Box and GetVertex/Face/BoxCoordinates respectively. This is just a change in name, as the old nomencalture was confusing and makes no sense for grids with multiple coordinate systems, but the syntax stays the same. The old methods will throw compiler warnings but will still work fine. You can run a Search&Replace through your scripts to get rid of them.
  • The GFBoolVector3 class can now be instantiated via GFBoolVector3.True and GFBoolVector3.False to create an all-true or all-false vector
  • Similarly you use GFColorVector3.RGB, GFColorVector3.CMY and GFColorVector3.BGW for half-transparent standard colour vectors
I apologize for the inconvenience of having to rename the methods, but I'll try to explain my reasoning. When Grid Framework was originally conceived only rectangular grids were in place. For rectangular grids only one coordinate system really makes sense, so there were two spaces: world space and grid space. Consequently, every point could only exist in either of those two.

One of the most basic needs I implemented back then was to find the nearest vertex of a point, hence the name FindNearestVertex, and later the same for faces and boxes. I also needed a similar method for grid space, I wanted to get the point's grid coordinates.
The problem arises when you start having more than just one grid space. When I wrote hex grids I always considered the possibility of having a second coordinate system aside from the herringbone pattern, and that's when I should have realized that my naming convention was... well, stupid. Polar grids will have two coordinate systems from the start, so I had the choice to either use some band-aid solution and have a naming convention that makes even less sense, or I could make a clean cut here and now.

So, what does this mean for you? At the moment nothing aside from a bunch of compiler warnings. You can just ignore them if you want, the old methods are still in place, they just call the new ones instead. I don't have any intention of removing them anytime soon, so you don't need to rush ahead and replace your old calls. The syntax has stayed the same, so running a quick Search&Replace will fix things for good.
The new naming convention goes as follows (without the brackets): Nearest[Vertex/Face/Box][X], where X stands for the coordinate system in question. For world it's W, for grid it's G and for the upcoming polar coordinates it will be P. Obviously only W and G make sense for all grids, the rest depends on the specific type of grid. You will be able to convert a point from any system into another (like PolarToWord).

I am sincerely sorry for this, but please understand that this was a necessary step in order for Grid Framework to remain clean. I always find things to improve and tweak, but most of them are under the hood and go by unmentioned, it just happened that this one was on the surface.

2013/05/10

a first look at polar grids

I've been working on the next type of grid: polar grids. The polar grid is based on polar coordinates, meaning instead of identifying a point's position using X and Y coordinates we use a radius and an angle. The radius tells us how far from the origin the point is and the angle tells us the direction. This screenshot shows the new polar grid in Unity


A polar grid is defined by three values: radius, sectors and depth. Radius refers to how far apart the red circles in the picture are, sectors is how many sectors you have and depth is how far apart each two layers of a polar grid are. Since we have a third dimension the mathematically correct term would be a "cylindrical grid", but I'll call it polar just for the sake of simplicity. If you have cylindrical coordinates just ignore the third component and you get polar coordinates. You'll notice that the angle between sectors does not define the grid, because the sectors have to cover the grid completely; you can't have the last sector be only a third of the other sectors. I'll see if I can still make the angle adjustable via an accessor.

Polar grids have a few unique quirks that differentiate them from rectangular and hex grids. First of all we now have circles instead of straight lines, but we can't draw actual circles. My solution is to add a "smoothing" option; without smoothing the red lines inside the sectors will be all straight and the grid will look like a spider's web, but each increase in smoothing breaks up the line into more segments, coming closer to a round shape. Of course increasing the smoothing means that there will be more points to calculate, but fortunately a single-digit number is already enough to get a smooth look. Also, the more sectors you have, the less smoothing you need.

A more fundamental issue rather than just a cosmetic concern is the coordinate systems. Yes, plural. The first one is the regular cylindrical coordinate system where radius, angle and height are given as absolute from the origin with respect to world dimensions. This means, no matter what you set your grid's radius, sectors or depth to, a given point will always have the same coordinates. The other one is a grid coordinate system where each component represents the relative position inside the grid with respect to radius, angle (calculated from sectors) and depth. Changing the grid also changes the coordinates of a given point.

You can convert between both coordinate systems and world space on the fly and neither system is really "better" than the other. It would be just wrong to have a polar grid without polar coordinates and it is what you want to use when moving objects in the world. On the other hand, it you want to think in "grid space", it's easier to think in terms of fields, like a board game, so grid coordiantes appear more intuitive.

At this point all the math is done and the hardest to implement methods (drawing, coordinate transformation and finding nearest vertex/face/box in all three coordinate systems) have been written. The next parts should be easier to implement, but I'm not exactly sure how to design them (what exactly does "aligning" in a polar grid even mean?). I'll keep you updated once I have more to show.

2013/04/03

Grid Framework version 1.2.4 released

Version 1.2.4 has been approved by the Asset Store team. Here are the new features:

  • a caching feature that keeps the activity of the grabage collector low now, instead of re-calculating the end points of lines every frame we can re-use them instead as long as the grid hasn't been modified.
  • a new example shows you how to create seemingly endless grids without the overhead of actually having a gigantic grid
  • explanations about rendering performance in the user manual
Enjoy the new performance improvement and thank you for your support.

2013/03/30

Seemingly endless grids and performance

I've been dealing with performance in Grid Framework recently and added a feature that will keep the Garbage Collector from going crazy. Until now rendering always went like this: Manager requests rendering from grid -> grid calculates the end points of each line -> these points get passed to Unity's GL class for rendering. Every single frame. I have introduced a caching feature that will store all the calculated points and reuse them instad of calculating everything all over again as long as the grid has not been modified.

This still doesn't solve the second bottleneck: rendering all these lines. Unfortunately there just isn't anything I can do about this, the GL class needs to have every single point one way or another. So, what if you want a very large grid that extends way beyond your camera's view? The answer is to fake it!

The idea is to only have the grid large enough to go beyond the camera's view port. Once the camera tries to go off the grid change the grid's rendering range to fit into the view port again. However, every time we change the rendering range this causes the caching to recalculate the points (since our old points are no longer valid), so caching doesn't do anything. The solution here is to add a little buffer, to make the grid larger than the view port, so we can move the camera a bit without going off the grid. Here is the video showing it step by step:

With such a small grid there is no real difference in using caching of not, but the concept is there if you need it for larger cases. This example will work in the current version of Grid Framework, but caching is a feature of the upcoming version 1.2.4, which is still waiting for approval.

2013/02/28

Grid Framework version 1.2.3 released

This update brings you two new features, both were suggested by customers. The first one is the ability to set a separate set of colours for rendering instead of using the same colours as for drawing. Let's say you want a barely visible grid in the game but a clearly visible grid in the editor. Until now you either had had to have two grids or use a script to change the colours once the game starts. Both options worked fine but required more work than needed, now you can do it out of the box. Of course it is entirely optional, so if you don't set anything you will be using the same colours for rendering and drawing.
The other new feature is relative size. Usually the size and the renderFrom/renderTo vectors were interpreted as absolute world unit lengths. I did this intentionally so the grid's size would be independent from its spacing (or radius and depth for hex grids). Of course not everyone is concerned about that sort of thing, some people would simply like to say "make my grid this many blocks tall" instead of having to multiply the desired size with the spacing. Turning on relative size now does exactly that for you. Here is a visual example where the values are interpreted as absolute (left) and relative (right) length:

2013/02/14

Unity and properties/accessors

As mentioned in the previous post I'd like to relate my experience with using properties in Unity and how to make them work properly. Properties are a C# feature and not available in UnityScript (another reason to ditch UnityScript). To help demonstrate what I mean I will be using a "circle" class.
public class Circle{
 public float radius;
}

What are properties?

As we can see radius is public and there is nothing stopping someone from putting in nonsensical values like negative numbers. Since we are in Euclidean geometry there is no such thing as "anti-length" and we need some way to restrict the value of radius to positive numbers. One solution would be to make radius a pivate member and use getters and setters:

public class Circle{
 private float _radius;
 public void SetRadius(float value){
   _radius = Mathf.Max(0, value);
 }
 public float GetRadius(){
  return _radius;
 }
}
(the underscore in front of radius is there to mark it as a member variable; it's just a convention, not mandatory) This gets the job done, but it's ugly and bloats the syntax. What we need instead is some sort of variable/function hybrid that acts like a messenger. This is where properties come in. Here is the same code as above, except using properties:

public class Circle{
 private float _radius;
 public float radius{
  get{return _radius;}
  set{_radius = Mathf.Max(0, value);}
 }
}
The property looks like a function that missing the brackets for parameters and it is treated like a variable in coding. Whenever we assign a value to it by using the "=" sign we actually call the set and when we use it in computation we call the get. value always refers to the value on the right hand side of the "=" sign. Here is an example:
myCircle.radius = -3; //calls set and sets _radius to 0
Debug.Log(myCircle.radius); //calls get and returns 0
}

Why should you use properties?

As you can see accessors allow us to expose member variables in a controlled fashion. You can put up restrictions on what a certain variable can hold. You can also create read-only "variables" by omitting the set part. Let's say your circle class has several formulae using the circumference and you don't want to type the formula every time. Here is what it would look like using an accessor:
public class Circle{
 private float _radius;
 public float radius{
  get{return _radius;}
  set{_radius = Mathf.Max(0, value);}
 }
 public float circumference{
  get{return Mathf.Pi * radius * radius;}
 }
}
There is no such thing as a "circumference" variable, instead its value is computed on the fly, yet you can still use it as if it were an actual variable:
float volume = height * myCircle.circumference;
Unity handes rotation using quaternions but you can still use Euler angles in the editor and in scripting, this is (most likely) the result of using properties as well. Properties are also great for exposing member variables in custom inspectors, like I did or Grid Framework. Unfortunately there is a problem.

Member varibles and the editor

You can treat the property just like any other variable when writing a custom inspector. However, once you hit play you will notice that your values have been reset and once you exit play mode or change the scene or anything else your values reset again. This is because the properties cannot actually store anything, they just serve to expose private members. The values of private members don't stick though, that's why everything gets reset. The solution is to use [SerializeField]:

public class Circle{,
 [SerializeField]
 private float _radius;
 public float radius{
  get{return _radius;}
 set{_radius = Mathf.Max(0, value);}
 }
 public float circumference{
  get{return Mathf.Pi * radius * radius;}
 }
}
That's it, now your member variable will get serialized and will be remembered. It took me a while to find this, but I was finally able to throw out quite a lot of ugly workarounds. And now there is no reason not to use properties anymore. Let's end this post by using properties to limit the value of a float variable to something appropriate for angles:
private float _angle;
public float angle{
 get{return _angle;}
 set{return value >= 0 ? value % 360 : 360 + (value % 360);}
}