LOGO - Editorial

Problem Link: contest, practice

Difficulty: Medium-Hard

Pre-requisites: Z-Buffering, Geometry, Stereometry, Implementation


We are given N polygons(triangles and quadrilaterals) in 3D. Our task is to project all of them on the 2D plane.


Firstly, in our further explanation we’ll assume, that triangles are the only polygons that we have(since every quadrilateral can be splited into two triangles).

OK, now we have M triangles(NM2N, since each quadrilateral has been splitted into two triangles).

Let’s fix cell(X,Y). What colour this cell should be coloured with? Intuitively, it should be the color of the triangle, which has the maximal Z for fixed (X,Y). Sounds pretty easy, huh?

But the key part of this problem is the implementation part.

Let’s fix a triangle with vertices P1(X1, Y1, Z1), P2(X2, Y2, Z2), P3(X3, Y3, Z3).

Also, let’s find a plane, in which triangle P1P2P3 lays. Each plane can be defined by an equation AX + BY + CZ + D = 0. Let’s find coefficients A, B, C and D.

A = Y1(Z2 - Z3) + Y2(Z3 - Z1) + Y3(Z1 - Z2);

B = Z1(X2 - X3) + Z2(X3 - X1) + Z3(X1 - X2);

C = X1(Y2 - Y3) + X2(Y3 - Y1) + X3(Y1 - Y2);

D = -X1(Y2*Z3 - Y3*Z2) - X2(Y3*Z1 - Y1*Z3) - X3(Y1*Z2 - Y2*Z1).

If you don’t understand why the coefficient look the way they are, please, visit the following link.

So, let’s determine the value of Z for triangle P1P2P3 at the cell(X, Y)(it’s also fixed, remember?).

Z = -(D - AX - BY) / C.

Shall we assume that triangle P1P2P3 has the distance Z above the fixed cell? No, we shall not. Well, the plane AX + BY + CZ + D = 0 definitely has the distance Z above the fixed cell, but point T with the coordinates (X, Y, Z) may not belong to our triangle P1P2P3. So, we should check if point T lays in our triangle. There are a lot of ways of doing this. I.e. you can check if S(P1, P2, P3) = S(T, P2, P3) + S(P1, T, P3) + S(P1, P2, T), where S(A, B, C) equals to the square of triangle ABC.

Here is a pseudocode, that shows the implementation of the algorithm described above.

for X from 0 to 319 do
	for Y from 0 to 239 do
		COLOR = 0
		for i from 0 to M do
			P_1, P_2, P_3 - points of i'th triangle

			A = Y_1(Z_2 - Z_3) + Y_2(Z_3 - Z_1) + Y_3(Z_1 - Z_2)
			B = Z_1(X_2 - X_3) + Z_2(X_3 - X_1) + Z_3(X_1 - X_2)
			C = X_1(Y_2 - Y_3) + X_2(Y_3 - Y_1) + X_3(Y_1 - Y_2)
			D = -X_1(Y_2 * Z_3 - Y_3 * Z_2) - X_2(Y_3 * Z_1 - Y_1 * Z_3) - X_3(Y_1 * Z_2 - Y_2 * Z_1)

			Z = Z = -(D - AX - BY) / C

			T - point with the coordinates(X, Y, Z)

			if S(P_1, P_2, P_3) = S(T, P_2, P_3) + S(P_1, T, P_3) + S(P_1, P_2, T) do
				if Z > MAX_Z do
					COLOR = the color of i'th triangle
					MAX_Z = Z
		print( COLOR )

The total complexity is O(N * MAXX * MAXY).

Setter’s Solution: link

Tester’s Solution: link


Hi can anyone explain what onright function in setter’s solution is doing ?

It checks if the points satisfy to the right-hand rule. http://en.wikipedia.org/wiki/Right-hand_rule