Optimal flexible box layout algorithm - algorithm

I'm implementing the CSS3 flexible box layout module as defined by the W3C, which is similar to Mozilla's box model for xul. While these standards specify how the model should behave, they don't give any details on how they should be implemented.
The parts of the model I'm interested in are:
Boxes have a width and height.
Boxes can contain other boxes.
Container boxes (parent boxes) are responsible for sizing and positioning the boxes they contain (child boxes).
Boxes have orientation which may be horizontal or vertical. The orientation determines how the child boxes are positioned and resized.
Child boxes may be flexible or inflexible. If the child box is inflexible it is drawn at the size specified in the width and height parameters. If it is flexible, then it is resized to fit into the available space in the parent container.
Flexibility is relative to other child boxes in the same container, boxes with higher flexibility are resized more than boxes with lower flexibility.
Child boxes can be constrained to a minimum or maximum size. If the child box is flexible, the parent box will never resize it below the minimum size, or above the maximum size.
Features 1-5 can be implemented quite efficiently. Feature 6 is problematic as the most efficient algorithm I can come up with is quite naive. The algorithm works as follows:
Place all the boxes in a list.
Loop through each child box and resize it using the flexibility to determine the amount to resize it by.
If the size exceeds one of the limits, then set the box size to the limit and remove it from the list, and start from the beginning of the list.
Step 3 is where the efficiency drops. For example, if there are ten items in the list, and the last one has a constraint, then the algorithm calculates the size for the first nine items, then when it reaches the tenth one it needs to redo all of the calculations. I have considered keeping the list sorted and first sizing all the constrained boxes, however this comes with the cost of added complexity and the overhead of sorting the list.
I expect there is a recognised optimal solution considering this is a fairly common feature in browsers and frameworks (XUL, .Net, Flex, etc).

Most box/container layout algorithms use a 2 pass algorithm. In the case of .NET (WPF) they are called "Measure" and "Arrange". Each control can measure its content and report a "desired size" in the recursive measure pass.
During the second pass (arrange) if the childrens desired sizes will not fit inside the parent, the parent uses its layout algorithm to provide the actual size to each child, for example by assigning the actual size weighted by desired size. Minimum/maximum sizes, box flexibility etc can come into play here.
More information on the WPF layout system
http://msdn.microsoft.com/en-us/library/ms745058.aspx
Xul layout
http://www-archive.mozilla.org/projects/xul/layout.html

Related

Fast layout algorithms for UI

I have a number of UI elements like panels, edit fields, buttons, labels etc. so panels contain other panels which contain input fields, editors and so on. Most of the elements are editable and/or resizable which means whenever I change anything, a lot of adjacent UI elements should change their width, height and x/y position on the pane. It works fine with a small number of elements but incredibly slow when the number of elements is thousands.
Is there a fast layout algorithm which can be used in this case? Note that I cannot use any existing layout managers and should come up with my own implementation.
I'd suggest taking a leaf out of the Android playbook and have a larger 'grid' and keep everything sized in modular multiples - this avoids you needing to solve the knapsack problem everytime!
For example, instead of having a button with an width of 80 and a height of 40 you store this as metadata as {2:1} (assuming your layout grid is 40^40 squares).
This way if you have a work panel with space of, say, {2:12} this could be filled with two objects of size {2:6} or maybe 3 of size {2:4}.
It's pretty simple to fit-to-max too as any available space can just be scaled up (say you delete a {1:1} item you can just expand the one next to it to take the space etc - you can of course create your own rules around whether objects can scale in single directions etc.
The other advantage of this approach is that you can easily manage different screen sizes and resolutions too while still keeping the same framework and look and feel.

Arrange blocks by 2D property without overlap

My app needs to show several buttons, without overlap, and preferably without scrolling or zooming. They must be big enough to poke with a finger and read the text. Button width depends on its text length, and the height is constant. The screen size is known.
Each button represents a food about which I know some nutritional information. I'll calculate a protein:carb ratio and a fat content, both ranging from 0% to 100%.
I want to put the buttons close to a position that reflects their nutritional content: e.g. protein-rich at the top, carby at the bottom, fatty on the right and lean on the left. So cake would be bottom right and meats would be somewhere on the top edge.
Often, there'll be overlap and I'll have to nudge them away from each other.
The puzzle is to invent an algorithm for that nudging. The desiderata in order of priority are:
1) Readable and pokeable size, no overlap.
2) No scrolling or zooming required, although it'll happen when there are so many buttons that they could never fit on the screen even if we didn't care where they were.
3) Buttons should be close to where the user would look based on knowing the nutritional content of the food.
Incidentally, I'm using JS on a smartphone, not prolog or the like.
(There are some seeming dupes, but no solutions. One is about diagonal stalks, another just advocates throwing it at a game engine, but most are devoid of answers.)
Ther MArVL group at Monash University does work on constraint-based layout work. Some of their software might be applicable to your problem.

Efficiently retrieve Z ordered objects in viewport in 2D game

Imagine a 2D game with a large play area, say 10000x10000 pixels. Now imagine there are thousands of objects spread across this area. All the objects are in a Z order list, so every object has a well-defined position relative to every other object even if they are far away.
Suppose there is a viewport in to this play area showing say a 500x500 area of this play area. Obviously if the algorithm is "for each object in Z order list, if inside viewport, render it" then you waste a lot of time iterating all the thousands of objects far outside the viewport. A better way would be to maintain a Z-ordered list of objects near or inside the viewport.
If both the objects and the viewport are moving, what is an efficient way of maintaining a Z-ordered list of objects which are candidates to draw? This is for a general-purpose game engine so there are not many other assumptions or details you can add in to take advantage of: the problem is pretty much just that.
You do not need to keep your memory layout strongly ordered by Z. Instead you need to store your objects in a space partitionning structure that is oriented along the viewing surface.
A typical partitionning structure, is a quad-tree, in 2D. You can use a binary tree, you can use a grid, or you can use a spatial hashing scheme. You can even mix those techniques and combine them one into each other.
There is no "best", but you can put in the balance the ease of writing and maintaining the code. And the memory you have available.
Let us consider the grid, it is the most simple to implement, fastest to access, and easiest to traverse. (traversing is the fact of going to neighborhood cells)
Imagine you allow yourself 20MB of RAM usage for your grid skeleton, considering the cell content is just a small object (like a std::vector or a c# List), say 50 bytes. for a 10k pixels square surface you then have:
sqrt(20*1024*1024 / 50) = 647
you get 647 cells for one dimension, therefore 10k/647 = 15 pixels wide cells.
Still very small, so I suppose perfectly acceptable. You can adjust the numbers to get cells of 512 pixels for example. It should be a good fit when a few cells fit in the viewport.
Then, it is trivially easy to determine which cells are activated by the viewport, by dividing the top left corner by the size of the cell and flooring that result, this gives you the index directly in the cell. (provided both your viewport space and grid space start at 0,0 both. otherwise you need to offset)
Finally take the bottom right corner, determine the grid coordinate for the cell; and you can do a dual loop (x and y) between the min and max to iterate over the activated cells.
When treating a cell, you can draw the objects it contains by going through the list of objects that you would have previously stowed.
Beware of objects that spans over 2 cells or more. You need to make a choice, either store them once and only, but then your search algorithms will always need to know the size of the biggest element in the region and also search the lists of the neighbooring cells (by going as far as necessary to be sure to cover at least the size of this biggest element).
Or, you can store it multiple times (my prefered way), and simply make sure when you iterate cells, that you treat objects once only per frame. This is very easily achieved by using a frame id, in the object structure (as a mutable member).
This same logic applies for more flexible parition like binary trees.
I have implementation for both available in my engine, check the code out, it may help you get through the details: http://sourceforge.net/projects/carnage-engine/
Final words about your Z Ordering, if you had multiple memory storage for each Z, then you already did a space partitionning, simply not along the good axis.
This can be called layering.
What you can do as an optimization, is instead of storing lists of objects in your cells, you can store (ordered) maps of objects and their keys is their Z, therefore the iteration will be ordered along Z.
A typical solution to this sort of problem is to group your objects according to their approximate XY location. For example, you can bucket them into 500x500 regions, i.e. objects intersecting [0,500]x[0,500], objects intersecting [500,1000]x[0,500], etc. Very large objects might be listed in multiple buckets, but presumably there are not too many very large objects.
For each viewport, you would need to check at most 4 buckets for objects to render. You will generally only look at about as many objects as you need to render anyway, so it should be efficient. This does require a bit more work updating when you reposition objects. However, assuming that a typical object is only in one bucket, it should still be pretty fast.

D3 show text for nodes when zoomed

The number of nodes in my d3 graph is too large. So I built a zoom mechanism in that graph. Now the problem is, I just cannot display text for each nodes since they will overlap each other. However when I zoom in to the nodes, the space is enough to display texts.
So how do I show texts when the space is enough to show all of them without overlapping?
I have had this same problem in the past. Unfortunately optimal label placement is not an easy problem. To mitigate overlap effects one option is to use a restricted force layout for label placement. You can also try using callouts to allow the labels to move farther away from the nodes.
In the past I have implemented a sort of greedy collision detection based algorithm that goes something like:
sort the labels in decreasing priority
for each label in the list // so most important first
if the label does not overlap any placed labels
place the label and add it to my collision data structure (e.g. quad tree)
else
hide the label
Obviously this will have some non-optimal cases and it can be slow if you have a lot of animations going on. But when you have the option to zoom in to see more label and if your absolute number of labels is not too high then it works quite well. There are also a number of obvious ways to speed it up like restricting testing to only labels within the view (but then you need to update on pan).
You may find some helpful suggestions here including an implementation of collision detection.

Efficiently detecting rectangular regions (maps) corresponding to a given point

We have a (w times h) canvas (width w and height h), which is used as a drawing area. We can define 'maps' or regions in the drawing area, on which the user can click to perform some pre-defined tasks. Each region is defined by a bounding rectangle. An image-map is activated when the user clicks inside it. Two regions may have overlapping rectangles. Whenever the user clicks on a point the canvas, we are required to find the find the image-map(s) to which the point belongs and start the execution of the corresponding task. We can always use a linear list to find the image-maps. But is there a better way, a data structure that could be used to store the image maps so that we can figure out efficiently (in less than O(n) time) which image-maps are activated on user click?
Yes - use any type of 2D spatial index. The most common is the quad-tree, which has O(log(n)) lookup complexity and is also quite quick to build. Implementations are available in all major languages; it is extensively used for all types of mapping applications.
You may create some sort of optimization to make this work less time in average, but efficient will be still O(n) , because there are possibility that users click will execute all N possible tasks.

Resources