Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2017-05

GLM library alternative?

35 messages · 12 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Ryan Joseph

I’m trying to following some OpenGL tutorials to learn the matrix transforms but I’m getting stuck because I don’t have the c++ GLM library which everyone is using. I see FPC has a matrix class but it doesn’t include all the helpers in GLM like rotation, transform, perspective transforms (https://open.gl/transformations). If I knew enough I think I could just build these myself but I’ll likely introduce a bunch of anyone converted these to Pascal before or having some similar I could look at?

Regards,
Ryan Joseph

Reply by email

leledumbo
to Ryan Joseph
Has anyone converted these to Pascal before or having some similar I could

look at?

I don't usually do the matrix calculation myself, I delegate that by calling OpenGL functions in proper order. However, just a few days ago I found this: https://paginas.fe.up.pt/~paco/pmwiki/index.php?n=DynMatrix.DynMatrix

which does seem to have enough matrix operations for most use cases.

View this message in context: http://free-pascal-general.1045716.n5.nabble.com/GLM-library-alternative-tp5728879p5728887.html Sent from the Free Pascal - General mailing list .

Reply by email

Ryan Joseph
to leledumbo
Show quoted text 7 lines
On May 27, 2017, at 4:20 PM, leledumbo via fpc-pascal wrote: I don't usually do the matrix calculation myself, I delegate that by calling OpenGL functions in proper order. However, just a few days ago I found this: https://paginas.fe.up.pt/~paco/pmwiki/index.php?n=DynMatrix.DynMatrix which does seem to have enough matrix operations for most use cases.

There are no such functions as part of the OpenGL API. I’m talking about functions that return a 4x4 rotation matrix or a perspective matrix, lookAt matrix etc… Everyone uses glm because it uses similar syntax as the shader language GLSL but you need to know how to construct these yourself otherwise.

Regards,
Ryan Joseph

Reply by email

Graeme Geldenhuys
to Ryan Joseph: I’m trying to following some OpenGL tutorials to learn the matrix transforms but I’m…
Ryan Joseph wrote
I see FPC has a matrix class but it doesn’t include all the helpers in GLM like rotation, transform, perspective transforms

I've implemented that by porting the Java Game Libirary code to Object Pascal. Give me a day or two and I'll share the OpenGL code I have on Github.

Regards,
Graeme

fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal http://fpgui.sourceforge.net/ My public PGP key: http://tinyurl.com/graeme-pgp

Reply by email

Ryan Joseph
to Graeme Geldenhuys
On May 27, 2017, at 4:30 PM, Graeme Geldenhuys wrote: I've implemented that by porting the Java Game Libirary code to Object Pascal. Give me a day or two and I'll share the OpenGL code I have on Github.

Thanks that would be great if someone had those common functions in Pascal. Not having glm::perspective or glm::lookAt is enough to really stop you in your tracks and running off to Google for hours.

Regards,
Ryan Joseph

Reply by email

Mark Morgan Lloyd
to leledumbo: look at? I don't usually do the matrix calculation myself, I delegate that by calling…
leledumbo wrote
> Has anyone converted these to Pascal before or having some similar I couldlook at? I don't usually do the matrix calculation myself, I delegate that by callingOpenGL functions in proper order.

But working from a hazy recollection of such things, it's possible to merge the translation/rotation matrices so that the final transformation can be reduced to a single operation.

Mark Morgan Lloyd markMLl .AT. telemetry.co .DOT. uk [Opinions above are the author's, not those of his employers or colleagues]

Reply by email

Ryan Joseph
to Mark Morgan Lloyd
On May 27, 2017, at 5:16 PM, Mark Morgan Lloyd wrote: But working from a hazy recollection of such things, it's possible to merge the translation/rotation matrices so that the final transformation can be reduced to a single operation.

Oh I’m sorry, I’m using 3.x core and the fixed pipeline has been removed which glRotate etc… were part of. I’m using this now but I wanted to learn the “new” stuff some.

Regards,
Ryan Joseph

Reply by email

Benjamin Rosseaux
to Ryan Joseph

I've put some units of my still work-in-progress UE4-style SupraEngine on my root server, after I've read this mailing list thread =>

http://rootserver.rosseaux.net/stuff/supraengineunits/

where the SupraEngine.Math.pas + SupraEngine.Math.*.inc + SupraEngine.Types.Standard.pas will be maybe interesting for you.

It's a complete 3D Math unit based on overloaded operators, advanced
records, etc. and even with GLSL-style swizzle support, where you can type
something like My3DVector.xzy := MyOther3DVector.yyx; My4DVector.zyx :=
TVector3.Create(3.0, 2.0, 1.0); or even My2DVector.yx := My3DVector.yz; etc.

Furthermore many routines are SSE optimized for the x86-32 and x86-64 targets.

This is the result of many years of evolution-based work, starting from the original math routines of my old PAPPE physics engine, which I've always further developed over the years (incl. many refactorings and rewrites).

And if you will do using it, then you add the following line to your start of your code (where the Math unit must be in the uses clause):

SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow,
exUnderflow, exPrecision]);

for disable some floating point exceptions, which could occur at 3D stuff, especially divide-by-zero exceptions at speed-SIMD-optimized normalization operations.

And credits would be nice :)

Regards,
Benjamin 'BeRo' Rosseaux

Ryan Joseph wrote 19 lines
> On May 27, 2017, at 5:16 PM, Mark Morgan Lloyd < > wrote: > > But working from a hazy recollection of such things, it's possible to merge the translation/rotation matrices so that the final transformation can be reduced to a single operation. Oh I’m sorry, I’m using 3.x core and the fixed pipeline has been removed which glRotate etc… were part of. I’m using this now but I wanted to learn the “new” stuff some. Regards, Ryan Joseph _______________________________________________ fpc-pascal maillist - http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply by email

Ryan Joseph
to Benjamin Rosseaux
On May 28, 2017, at 1:54 PM, Benjamin Rosseaux wrote: I've put some units of my still work-in-progress UE4-style SupraEngine on my root server, after I've read this mailing list thread =>

Thanks for sharing. The GLM functions I wanted seem to be here so I’m going to try them.

Btw, I’m not sure Sven fixed this or is going to but we found out record constructors were not producing optimal instructions when compared to static inline class functions so you may want to change those. I had to go back and make changes to some low-level record constructors after I found this out also.

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to denisgolovan
Show quoted text 5 lines
On May 28, 2017, at 3:22 PM, denisgolovan wrote: Looks nice. Thanks for sharing. How about publishing it on Github with small readme to ease contributions?

There’s some dead 403 links also btw.

Regards,
Ryan Joseph

Reply by email

Ingemar Ragnemalm
Ryan Joseph wrote 6 lines
I’m trying to following some OpenGL tutorials to learn the matrix transforms but I’m getting stuck because I don’t have the c++ GLM library which everyone is using. I see FPC has a matrix class but it doesn’t include all the helpers in GLM like rotation, transform, perspective transforms (https://open.gl/transformations). If I knew enough I think I could just build these myself but I’ll likely introduce a bunch of errors at first. Has anyone converted these to Pascal before or having some similar I could look at? Regards, Ryan Joseph

I use my own vector/matrix library VectorUtils3, which is written in plain C (thereby FPC friendly), and included in the common code of my OpenGL demo library:

http://computer-graphics.se/demopage/

Actually, there is also an FPC version of VectorUtils, FPC interfaces to most of my common code, and even a bunch of demos that I made FPC for. (Modern OpenGL, not old-style code, no immediate mode.) I never uploaded them anywhere, since there didn't seem to be much interest, but if someone wants them, no problem.

/Ingemar

Reply by email

Benjamin Rosseaux
to Ryan Joseph: There’s some dead 403 links also btw. Ryan Joseph

Fixed, repacked & reuploaded as ZIP in the same directory

Ryan Joseph wrote 18 lines
> On May 28, 2017, at 3:22 PM, denisgolovan wrote: > > Looks nice. Thanks for sharing. > How about publishing it on Github with small readme to ease contributions? > There’s some dead 403 links also btw. Regards, Ryan Joseph _______________________________________________ fpc-pascal maillist - http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply by email

Benjamin Rosseaux
to Ryan Joseph: Thanks for sharing. The GLM functions I wanted seem to be here so I’m going to try them.

I know that issue, so that the record constructors in the SupraEngine.Math.pas are fully optional, so therefore you do must not using these :-) It's just a optional option for key-tap-lazy peoples, since all record member fields are also free directly accessible and public visible.

Ryan Joseph wrote 23 lines
> On May 28, 2017, at 1:54 PM, Benjamin Rosseaux wrote: > > I've put some units of my still work-in-progress UE4-style SupraEngine on my root server, after I've read this mailing list thread => Thanks for sharing. The GLM functions I wanted seem to be here so I’m going to try them. Btw, I’m not sure Sven fixed this or is going to but we found out record constructors were not producing optimal instructions when compared to static inline class functions so you may want to change those. I had to go back and make changes to some low-level record constructors after I found this out also. Regards, Ryan Joseph _______________________________________________ fpc-pascal maillist - http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply by email

Benjamin Rosseaux
to denisgolovan:

On GitHub I've already some SupraEngine subprojects, for example:

- https://github.com/BeRo1985/pasmp My
parallel-processing/multi-processing library for Object Pascal
- https://github.com/BeRo1985/kraft My newer 3D physics Engine for Object Pascal
- https://github.com/BeRo1985/pasvulkan Vulkan header generator and Vulkan OOP-style API wrapper for Object Pascal (it had also news articles on
http://www.phoronix.com/scan.php?page=news_item&px=PasVulkan-Vulkan--Pascal-Bind and https://www.khronos.org/news/tags/tag/Pascal )
- https://github.com/BeRo1985/pasdblstrutils Pascal library for cross-compiler consistent and exact conversion between double-precision floating point number values and strings
- https://github.com/BeRo1985/pasenet Pascal port of ENet with IPv6 support
- etc.

But the SupraEngine main core project itself is still closed source (as long as it is not yet ready), except these already excerpt-uploaded (for users of this mailing list) zlib-licensed Math units, because SupraEngine will have a UE4-style licensing model, say, when it will be released, it will be free and quasi-open-source for free projects (it does not matter whether it are open source or closed source projects), but it will be revenue-share-based for non-free paid projects. A lawyer (a corresponding lawyer I have already in the selection) will formulate the appropriate license text for it, but this will be the last task, just before the release.

But because the engine market is already largely saturated, it will be primarly for projects (at least for the first time), for example, Supraleiter (here some prototype videos with the old OpenGL-based engine: https://www.youtube.com/watch?v=SWanRYNNTUA&list=PLoqdQblnX8vS11pAzGXOak3nsC4UoaC4-&index=4 and
https://www.youtube.com/watch?v=dR8OJoHWuGs&index=3&list=PLoqdQblnX8vS11pAzGXOak3nsC4UoaC4- and https://youtu.be/_SVL0_Z3WL8 and https://youtu.be/-mi2wOnks_A ), a StarTrek Voyager first-person-shooter (here some prototype videos, which had made my graphic-artist-contact testwise with UE4: http://www.indiedb.com/games/voyager-game-project/videos/scorpion#imagebox and
http://www.indiedb.com/games/voyager-game-project/videos/deltaflyer-12-10-2016#imagebox and
http://www.indiedb.com/games/voyager-game-project/videos/bridge-preview-9#imagebox ),
etc.

And I've testwise partly-reverse.engineered and partly-reimplemented the first two Original WipeOut titles (in ObjectPascal of course): https://youtu.be/MI_jtU2kiQk and https://youtu.be/zKpAWaByyyc for to test my newer physics engine in a real test game, as preparation for usage in my Supraleiter game project with the then new Vulkan-based SupraEngine.

denisgolovan wrote 22 lines
28.05.2017, 09:55, "Benjamin Rosseaux" : I've put some units of my still work-in-progress UE4-style SupraEngine on my root server, after I've read this mailing list thread => http://rootserver.rosseaux.net/stuff/supraengineunits/ Looks nice. Thanks for sharing. How about publishing it on Github with small readme to ease contributions? -- Regards, Denis Golovan _______________________________________________ fpc-pascal maillist - http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply by email

Anthony Walter
to Ryan Joseph: Thanks for sharing. The GLM functions I wanted seem to be here so I’m going to try them.

You might want to try using this geometry library I've written to go along with OpenGL, fixed function or otherwise:

https://github.com/sysrpl/Bare.Game/blob/master/source/bare.geometry.pas#L317

Basic usage might be like this:

var
  M: TMatrix;
  V: TVertex;
begin
  M.Identity;
  M.Translate(10, 0, 0);
  V := M * Vec(10, 10, 10);
  M.Rotate(0, 10, 0);
  V := M * V;
  WriteLn('X: ', V.X, ' Y: ', V.Y, 'Z: ', V.Z)
  M.Scale(0.5, 0.5, 0.5);
  V := M * V;
  WriteLn('X: ', V.X, ' Y: ', V.Y, 'Z: ', V.Z)
end;

And these matrices are compatible with OpenGL functions.

Reply by email

Ryan Joseph
On May 28, 2017, at 10:33 PM, Ryan Joseph wrote: projTransform := TMatrix4x4.CreatePerspective(60.0, 500 / 500, 0.1, 10.0); modelTransform := TMatrix4x4.CreateTranslation(0, 0, -3.0) * TMat4.CreateRotateX(54);

I found out the problem. I was expecting the multiply to work like with GLM where you could do:

translation * rotation

but with the operator overloads I need to do protation * translation. Anthony’s multiply matrix 4 operators did this in the order I expected and how I figured it out. Not sure why and it’s probably not safe to swap the parameters because it would likely break other parts of the unit.

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Anthony Walter: You might want to try using this geometry library I've written to go along with OpenGL,…
On May 29, 2017, at 8:24 AM, Anthony Walter wrote: And these matrices are compatible with OpenGL functions.

Thanks for sharing. I got your matrix multiplication functions to work in the order I expected and helped me find a bug.

Btw, given what we just learned about loops in FPC I would remove the nested for..loops in your matrix overloads.

Regards,
Ryan Joseph

Reply by email

Benjamin Rosseaux
to Anthony Walter: You might want to try using this geometry library I've written to go along with OpenGL,…

All SupraEngine.Math matrices are also compatible with OpenGL (and Vulkan, of course). SupraEngine.Math's TMatrix3x3 and TMatrix4x4 implementation have also advanced stuff as such as lerp, nlerp, slerp interpolation method functions, decomposing (into Perspective, Translation, Scale, Skew and Rotation components), recomposing (from Perspective, Translation, Scale, Skew and Rotation components). And SupraEngine.Math have also GLSL-style and in the most cases GLSL-Function-Parameter-compatible functions as such as Cross, Dot, Normalize, FaceForward, Reflect, Refract, Clamp, Mix, Step, SmoothStep, etc.

Example usages:

FaceNormal := (p2 - p0).Cross(p1 - p0).Normalize; // or alternatively also:
FaceNormal := Normalize(Cross(p2 - p0,p1 - p0));
if FaceNormal.Dot((Normals[NormalIndices[0]]+
                               Normals[NormalIndices[1]]+
                               Normals[NormalIndices[2]]).Normalize) < 0.0
then begin
   FaceNormal := -FaceNormal;
end;
 TriangleTangent:=((p2-p0)*(uv1.v-uv0.v))-((p1-p0)*(uv2.v-uv0.v));
 TriangleBitangent:=((p2-p0)*(uv1.u-uv0.u))-((p1-p0)*(uv2.u-uv0.u));
 TriangleTangent:=(TriangleTangent-(TriangleNormal*TriangleTangent.Dot(TriangleNormal))).Normalize;
 TriangleBitangent:=(TriangleBitangent-(TriangleNormal*TriangleBitangent.Dot(TriangleNormal))).Normalize;
 if (TriangleBitangent.Cross(TriangleTangent)).Dot(TriangleNormal)<0.0 then
begin
   TriangleTangent:=-TriangleTangent;
   TriangleBitangent:=-TriangleBitangent;
 end;
 Matrix := Transform.Matrix * Matrix;
 Vector := Matrix * Vector; (like at GLSL)
 Vector := Vector * Matrix; (in the other way transposed mul like at GLSL)
 Vector := Quaternion * Vector;
 Vector := Vector * Quaternion; (with the same transposed-matrix-like
effect)
 Vector := DualQuaternion * Vector;
 Vector := Vector * DualQuaternion; (with the same transposed-matrix-like
effect)
 RightVector := Matrix.Right.xyz;
 UpVector := Matrix.Up.xyz;
 ForwardVector := Matrix.Forwards.xyz;
 TranslationVector := Matrix.Translation.xyz;
 Matrix := Matrix.Normalize;
 Matrix := Matrix.OrthoNormalize;
 Matrix := Matrix.RobustOrthoNormalize;
 Quaternion := Matrix.ToQuaternion;
 QTangent := Matrix.ToQTangent;
 Matrix3x3 := Matrix4x4.ToMatrix3x3;
 ModelMatrix := Matrix4x4Identity;
 ViewMatrix := TMatrix4x4.CreateTranslation(0.0, 0.0, -4.0);
 ProjectionMatrix := TMatrix4x4.CreatePerspective(45.0, Width / Heighz,
1.0, 1024.0);
 ModelViewMatrix := ModelMatrix * ViewMatrix;
 InverseModelViewMatrix := ModelViewMatrix.Inverse;
 ModelViewProjectionMatrix := ModelMatrix * ViewMatrix * ProjectionMatrix;
 InverseModelViewProjectionMatrix := ModelViewMatrixProjection.Inverse;
 TangentSpaceRotationMatrix := ModelViewMatrix.Inverse.Transpose;
 InverseTangentSpaceRotationMatrix := TangentSpaceRotationMatrix.Transpose;
 ClipMatrix := CreateProjectionMatrixClip(ProjectionMatrix, ClipPlane);

etc.

Reply by email

Ryan Joseph
to Anthony Walter
On May 29, 2017, at 12:58 PM, Anthony Walter wrote: I'm curious, what's the problem with fpc and loops? Also, from my OpenGL experience the limiting factor in speed (frames per second) is usually the pixel complexity and not whatever method is used to feed vertex data or shader uniforms.

It’s buried now but look at the “FPC Graphics options” thread from a few days ago and spanning back weeks I think. After all that I still failed to get a clear answer I could understand well but some poor loop optimization and floating point division was causing a ray caster example written in Java to get low single digit frame rates where the same code ran 40+fps in Java and C. There seems to be some changes in FPC 3.1.1 but I’m not sure what changed. Some one else may correct what I said but feel free to take a loop. Bottom line for me is I’m nervous about loops in highly optimized low level code now but that may be unfounded.

Regards,
Ryan Joseph

Reply by email

Mattias Gaertner
to Ryan Joseph
> On May 29, 2017, at 12:58 PM, Anthony Walter wrote: [...] It’s buried now but look at the “FPC Graphics options” thread from a few days ago and spanning back weeks I think. After all that I still failed to get a clear answer I could understand well but some poor loop optimization and floating point division was causing a ray caster example written in Java to get low single digit frame rates where the same code ran 40+fps in Java and C. There seems to be some changes in FPC 3.1.1 but I’m not sure what changed. Some one else may correct what I said but feel free to take a loop. Bottom line for me is I’m nervous about loops in highly optimized low level code now but that may be unfounded.

I will try to summarize the thread:

Jonas told that the benchmark program contains a number of bugs/wrong translation from the C code:
1) casting a floating point number to an int in C does not round
2) The usage of floor in the test program is wrong.
3) The Pascal version uses longword instead of int32...getting evaluated as 64 bit on 32 bit
4) frac() is only used to get a monotonous increasing value...

C compilers know what "floor" is doing and optimizes it.

FPC default config does not use optimal settings for todays machines. Java does, C libs do. I didn't find what Graeme used for his C version.

Some pointed out that the Math unit misses some SSE and double versions of functions.

Florian improved FPC 3.1.1 boosting the speed from 8 to 23FPS.

Martin used MSELang with LLVM backend, fixed some bugs in the code and used some optimization flags to get 41 FPS, which looks similar to Graeme's numbers for the C and Java version.

There were various suggestions for optimizations, which C compilers are doing and could be added to FPC, but they would be specific to these benchmarks. Including some loop optimizations.

Mattias

Reply by email

Reimar Grabowski
to Ryan Joseph: Thanks that would be great if someone had those common functions in Pascal. Not having…
Not having glm::perspective or glm::lookAt is enough to really stop you in your tracks and running off to Google for hours.

Then perhaps you have to improve your google skills. ^^

https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml

Has all the info you need to implement them.

Unoptimized pascal versions (but fast enough for general use):

function TCamera.LookAt(Eye, Center, Up: TVector3): TMatrix4x4;
var
  View, Right: TVector3;
  TransMatrix: TMatrix4x4;
begin
  View:=Normalized(fCoV-Position);
  Right:=Normalized(CrossProduct(View, Up));
  Up:=CrossProduct(Right, View);
  Result[0][0]:=Right.X;
  Result[1][0]:=Right.Y;
  Result[2][0]:=Right.Z;
  Result[3][0]:=0;
  Result[0][1]:=Up.X;
  Result[1][1]:=Up.Y;
  Result[2][1]:=Up.Z;
  Result[3][1]:=0;
  Result[0][2]:=-View.X;
  Result[1][2]:=-View.Y;
  Result[2][2]:=-View.Z;
  Result[3][2]:=0;
  Result[0][3]:=0;
  Result[1][3]:=0;
  Result[2][3]:=0;
  Result[3][3]:=1;
  Result:=MultglMatrix(IdentityMatrix4x4, Result);
  TransMatrix:=IdentityMatrix4x4;
  TransMatrix[3][0]:=-Eye.X;
  TransMatrix[3][1]:=-Eye.Y;
  TransMatrix[3][2]:=-Eye.Z;
  Result:=MultglMatrix(Result, TransMatrix);
end;
function TScene.BuildPerspectiveMatrix(FoV, AspectRatio, NearPlane,
  FarPlane: GLfloat): TMatrix4x4;
var
  XYMax, XMin, YMin, Width, Height, Depth: GLfloat;
begin
  XYMax:=NearPlane*tan(FoV*pi/360);
  YMin:=-XYMax;
  XMin:=-XYMax;
  Width:=XYMax-XMin;
  Height:=XYMax-YMin;
  Depth:=FarPlane-NearPlane;
  Result[0][0]:=(2*NearPlane/Width)/AspectRatio;
  Result[0][1]:=0;
  Result[0][2]:=0;
  Result[0][3]:=0;
  Result[1][0]:=0;
  Result[1][1]:=2*NearPlane/Height;
  Result[1][2]:=0;
  Result[1][3]:=0;
  Result[2][0]:=0;
  Result[2][1]:=0;
  Result[2][2]:=-(NearPlane+FarPlane)/Depth;
  Result[2][3]:=-1;
  Result[3][0]:=0;
  Result[3][1]:=0;
  Result[3][2]:=-2*(FarPlane*NearPlane)/Depth;
  Result[3][3]:=0;
end;

R.

Reply by email

Anthony Walter
to Reimar Grabowski

Thanks for posting those LookAt and Perspective routines. They're kind of needed with OpenGL ES 2.0, as it no longer has matrix modes. You need to build your own perspective and model view matrices and pass them to your vertex shaders as uniforms.

uniform mat4 modelview; // modelview matrix uniform
uniform mat4 projection; // projection matrix uniform
attribute vec3 xyz; // vertex position attribute
attribute vec2 uv; // uv texture coordinate attribute
varying vec2 texcoord; // varying texture coordinate

void main()
{

    vec4 vertex = modelview * vec4(xyz, 1.0); // transform vertex with

modelview matrix uniform

    gl_Position = projection * vertex; // project the transformed vertex

and write it to gl_Position

    texcoord = uv; // assign the uv texture coordinate to the varying

}

By the way, what's stopping you guys from using OpenGL ES 2.0? It works on most all Windows, Mac, and Linux systems, and it's the only 3D graphics API on Raspberry Pi and most smart phones/tablets.

Reply by email

Marco van de Voort
to Ryan Joseph: I found out the problem. I was expecting the multiply to work like with GLM where you…

In our previous episode, Ryan Joseph said:

Show quoted text 13 lines
> On May 28, 2017, at 10:33 PM, Ryan Joseph wrote: > > projTransform := TMatrix4x4.CreatePerspective(60.0, 500 / 500, 0.1, 10.0); > modelTransform := TMatrix4x4.CreateTranslation(0, 0, -3.0) * TMat4.CreateRotateX(54); I found out the problem. I was expecting the multiply to work like with GLM where you could do: translation * rotation but with the operator overloads I need to do protation * translation. Anthony?s multiply matrix 4 operators did this in the order I expected and how I figured it out. Not sure why and it?s probably not safe to swap the parameters because it would likely break other parts of the unit.

For the 2Ders, in old GL I used glortho2d a lot. In newer ones I missed that, but I found an equivalent on stackoverflow:

// http://stackoverflow.com/questions/21323743/modern-equivalent-of-gluortho2d
procedure MyOrtho2D(var mat : TGLMatrixf4;left,right,bottom,top:single);
var inv_y,inv_x : single;
begin
      inv_y := 1.0 / (top - bottom);
      inv_x := 1.0 / (right - left);
    // this is basically from
    // http://en.wikipedia.org/wiki/Orthographic_projection_(geometry)
    //first column
    mat[0][0] := (2.0*inv_x);
    mat[0][1] := (0.0);
    mat[0][2] := (0.0);
    mat[0][3] := (0.0);
    //second
    mat[1][0] := (0.0);
    mat[1][1] := (2.0*inv_y);
    mat[1][2] := (0.0);
    mat[1][3] := (0.0);
    //third
    mat[2][0] :=  (0.0);
    mat[2][1] :=  (0.0);
    mat[2][2] :=  (-2.0*inv_z);
    mat[2][3] :=  (0.0);
    //fourth
    mat[3][0] :=  (-(right + left)*inv_x);
    mat[3][1] :=  (-(top + bottom)*inv_y);
    mat[3][2] :=  (-(zFar + zNear)*inv_z);
    mat[3][3] :=  (1.0);
end;

I have a TGLvector for zoom (X/Y) and one for pan (offset, also in X and Y direction).

// calcs a matrix for the shader. pass the matrix as an uniform and multiply  in vertex or geometry shader
procedure myorthohelp(var mat : TGLMatrixf4;const
aoffs,azoom:TGLVectorf2;topdown:boolean=false);
begin
  myOrtho2D(mat,aoffs[0], 1.0 / (aZoom[0]) + (aoffs[0]), 1.0 / (aZoom[1]) + (aoffs[1]), aoffs[1])
end;

Reply by email

Marco van de Voort
to Anthony Walter: Thanks for posting those LookAt and Perspective routines. They're kind of needed with…

In our previous episode, Anthony Walter said:

By the way, what's stopping you guys from using OpenGL ES 2.0? It works on most all Windows, Mac, and Linux systems, and it's the only 3D graphics API on Raspberry Pi and most smart phones/tablets.

IIRC I went for opengl 3.3-4 because one could find more about it and because opengl ES afaik has no geometry shader support.

The GL stuff is only for Windows PC (and very maybe Linux PC) anyway.

Reply by email

Anthony Walter
to Marco van de Voort: In our previous episode, Ryan Joseph said: For the 2Ders, in old GL I used glortho2d a…

Marco,

Regarding 2D animation, what I've far far more effective than an orthographic projection is to draw 2D billboard sprite at a distance and size to align exactly with your screen's resolution. That is each width and height of "1" gl world equals "1" screen pixel, and coordinate (0, 0) equals the top left corner of your screen.

This type of 2D setup in OpenGL allows for allows you to freely mix in both 2D and 3D effects. Here's are two examples of how 2D in a 3D world can work:

Card Games: https://www.youtube.com/watch?v=lOUB4pqRLjY Animation of vector graphics: https://www.youtube.com/watch?v=P1cd-kWBz0E

Reply by email

Marco van de Voort
to Anthony Walter

In our previous episode, Anthony Walter said:

This type of 2D setup in OpenGL allows for allows you to freely mix in both 2D and 3D effects. Here's are two examples of how 2D in a 3D world can work:

If you check the myorthohelp function that called it, you'll already see it is normalized to [0..1] coordinates.

But there are some special cases (e.g. sometimes zoomxzoomy to get square pixels), vertical inversion etc where not everything is 0..1,0..1

I don't need 3D effects, this is a business app. For an (older) demo based on the code see

http://forum.lazarus.freepascal.org/index.php/topic,30556.msg194484.html#msg194484

Reply by email

Ingemar Ragnemalm

Den 2017-05-30 kl. 12:00, skrev Marco van de Voort:

For the 2Ders, in old GL I used glortho2d a lot. In newer ones I missed that, but I found an equivalent on stackoverflow:

My FPC vector unit has overloading and many other functions (determinant, rotation around arbitrary axis...). Some functions like lookAt, frustum, ortho, matrix inverse etc are only in my C version so far. Not hard to port.

mat4 ortho(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top,
GLfloat near, GLfloat far)
{
         float a = 2.0f / (right - left);
         float b = 2.0f / (top - bottom);
         float c = -2.0f / (far - near);
         float tx = - (right + left)/(right - left);
         float ty = - (top + bottom)/(top - bottom);
         float tz = - (far + near)/(far - near);

mat4 o = SetMat4(
a, 0, 0, tx,
0, b, 0, ty,
0, 0, c, tz,

             0, 0, 0, 1);
         return o;

}

So I have a pile of code on the topic, much of it for FPC. But shouldn't there really be a good OpenGL support package for FPC that was some kind of "standard"?

BTW, when I ported my OpenGL demos to FPC, I found that the FPC glext.pp had some fatal bugs. (Easy to fix, but I never figured out who would want the corrections, so I hope someone else noted that it crashed for modern OpenGL.)

/Ingemar

Reply by email

Graeme Geldenhuys
to Ingemar Ragnemalm
Ingemar Ragnemalm wrote
so I hope someone else noted that it crashed for modern OpenGL.)

Huh? I've been using it for 4 months with "modern OpenGL 4.x" (non-fixed rendering pipeline) and it hasn't crashed on me.

Next time it crashes, please supply a small code example if you can, or at least a backtrace so we can see where the error originated.

Regards,
Graeme

fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal http://fpgui.sourceforge.net/ My public PGP key: http://tinyurl.com/graeme-pgp

Reply by email

Graeme Geldenhuys
to Mattias Gaertner: On Mon, 29 May 2017 15:29:24 +0700 I will try to summarize the thread: Jonas told that…
Mattias Gaertner wrote
Jonas told that the benchmark program contains a number of bugs/wrong translation from the C code:

And all of those recommendations were applied by Jon Foster and yielded only a 0.6% increase in speed.

"I ended up with an hour of extra time so I went over Jonas' suggestions again. I made tweaks fixing integer types, using trunc() instead of round, ... The over all improvement is only +0.6%, as I predicted nowhere near the 10x+ needed to compete with the other languages."

-- Jon Foster (in the MSEide+MSEgui mailing list dated 2017-05-24)

So the major speed problem still seems to be the FPC optimisation with looping and not using SSEx when it is available.

I personally haven't tested with the latest FPC 3.1.1 yet.

Regards,
Graeme

fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal http://fpgui.sourceforge.net/ My public PGP key: http://tinyurl.com/graeme-pgp

Reply by email

code dz
to Graeme Geldenhuys

tested with the fpc trunk , got only 3 fps increased . but even with this result fpc does great job , compared with gcc7 , gcc is faster only about 45% . so when compared with a compiler like gcc which get tens of patches par day from from around the world including big companies like sumsung . and you get only 45% deference in speed , no doubt fpc is great compiler .

Reply by email

Anthony Walter
to Graeme Geldenhuys: And all of those recommendations were applied by Jon Foster and yielded only a 0.6%…

I've done a bit of assembly programming for IA-32, none recently and zero compiler development other than simple parsers, but from what I know optimizing with newer instructions like SSEx is only part of there story. There's also optimizing for out of order instruction execution (OoOIE), or instruction reordering. Even on a single core, when optimized done properly it can yield 4x or more increase in processing speed, avoiding CPU stalls, which is likely happening a lot given the descriptions people have provided in this thread.

Obviously properly using SSEx instructions and optimizing for OoOIE is a non trivial undertaking. I think probably the best way to test FPC out is to stop writing speed tests against other languages, and to view the CPU instructions generated for a few different loop types, including trunc()/floor() functions. Next rewrite those parts in assembler, include SSE whatever instructions and pepper in OoOIE, and finally test the speed difference.

My instincts tell me if the compiler could then generate both SSEx and OoOIE properly it could automatically applied in many places, resulting in a huge speed up for FPC programs. But for me, the main advantage of Free Pascal is that it generates native language, leading to easier reuse of C style APIs such as Cairo/GTK/SDL, and also allowing for the PME (properties, methods, events) plus all the other nice features Free Pascal offers. Most of the time my programs are either idle waiting for user input, or idle waiting for other APIs or in the case of OpenGL the graphics hardware to complete. As such the execution speed of the pascal portion of my programs isn't as important.

Reply by email