Is this code correct?

z z at z.com
Fri Mar 31 13:11:58 UTC 2023


On Thursday, 30 March 2023 at 12:59:31 UTC, Dennis wrote:
> On Thursday, 30 March 2023 at 10:29:25 UTC, z wrote:
>> Is this code correct or logically sound?
>
> You need to be exact on what 'correct' is. The comment above 
> `triangleFacesCamera` says:
>
>> Indicates wether a triangle faces an imaginary view point.
>
> There's no view point / camera position defined anywhere in 
> your code.
> Instead, all it's doing is comparing the angle of one triangle 
> side (A->B) with another (B->C) in the XZ plane. This suggests 
> you want to know the triangle winding order: clockwise or 
> counter clockwise.
>
> If you search for "triangle winding order" you'll find simple 
> and correct ways to do that. Your code needlessly computes 
> angles, only considers the XZ plane, and doesn't compare the 
> angles correctly.
>
>> r2 -= r1;
>>
>> return r2 > 0;
>
> You need to wrap (r2 - r1) into [-τ/2, τ/2] range, then you can 
> compare with 0.

Yes, the viewpoint/cam should be [0,0,0] for now. The old 
algorithm completely discards depth information after scaling 
triangle point data depending on depth distance from 0 hence why 
i ignored it.

I've tried to search before but was only able to find articles 
for 3D triangles, and documentation for OpenGL, which i don't use.

My description of the old algorithm was also badly written(it is 
confusing!) so here it is rewritten to be more understandable :

```D
enum {x, y}//leftright/side, updown/height
alias tri = byte[2];
/**
Determines if a triangle is visible.
*/
extern bool oldfunction(tri tA, tri tB, tri tC) {
short r0, r1;//r, "result"
r0 = cast(short) ((tB[y]-tA[y]) * (tC[x]-tB[x]));
r1 = cast(short) ((tC[y]-tA[y]) * (tB[x]-tA[x]));
r1 -= r0;
return r1 > 0;//"visible" means result is neither negative or zero
}
```
(replacing my code with this but in float point "works" but there 
is an apparent "angle bias" and other problems that are difficult 
to pinpoint or describe.)
Does this match anything known? It doesn't look like cross 
product to me because the subtractions occur earlier than the 
multiplications.

By correct i mean that it can be used exactly like the old 
algorithm. (to ignore subshapes from a 3D model)

Thanks again


More information about the Digitalmars-d-learn mailing list