OpenGL, GLFW et textures

note

Ce texte paraphrase plus ou moins bien cette page: Textures. C’est volontaire, cela me permet de mieux mémoriser en français ce que j’apprends.

texture en OpenGL, les principes

On peut se représenter les textures comme des portions de papier peint que l’on collerait aux surfaces créées avec OpenGL. Pour ce faire, il faut associer des coordonnées de la texture avec chaque sommet de la surface que l’on veut habiller.

Une texture est une surface en 2D, ce qui correspond bien à la métaphore du papier peint. Les coordonnées x et y de la texture varient, pour chaque axe, entre 0 et 1. Voici un exemple d’association de coordonnées d’une texture à un triangle:

float texCoords[] = {
    0.0f, 0.0f,  // lower-left corner  
    1.0f, 0.0f,  // lower-right corner
    0.5f, 1.0f   // top-center corner
};

Que se passe-t-il lorsqu’on sort de l’intervalle [0, 1]? Ce comportement de la texture est paramétrable avec des constantes:

  • GL_REPEAT: répète la texture,
  • GL_MIRRORED_REPEAT: répète la texture mais avec un effet miroir à chaque répétition,
  • GL_CLAMP_TO_EDGE: l’image est étirée jusqu’aux bords de la surface, c’est à dire que toute la surface est immergée dans l’intervalle [0, 1],
  • GL_CLAMP_TO_BORDER: tout ce qui est hors de l’intervalle [0, 1] est considéré comme étant le bord.

Notez bien que les coordonnées de la texture sont notées non pas x et y mais s et t.

May 9, 2022

Nuklear, GLFW3 et les images

Nuklear

Nuklear s’appuie sur diverses APIs graphiques dont GLFW, SDL ou DirectX. C’est une bibliothèque facile à utiliser pour fabriquer des interfaces utilisateurs évolués avec quelques effets secondaires dont une charge CPU plus importante et des performances légèrement en retrait lorsqu’on le compare à d’autres bibliothèques.

En attendant, la simplicité de création des boîtes de dialogue tout comme la portabilité vers Linux, Windows, ou Mac me conviennent parfaitement.

premiers soucis

Pas d’exemple simple pour afficher une image! En fait, il faut utiliser les textures OpenGL pour afficher des pixels en 2D. Et, pour le moment, je ne maîtrise pas et je n’ai qu’une envie modérée de travailler la question. Ce qui m’intéresse, c’est transformer l’image.

May 7, 2022

OneColor, un projet qui me fait patiner dans la semoule

le but de OneColor

Le but de l’exercice est, à priori, pas trop compliqué:

  • afficher une image (format JPEG, PNG, … au choix),
  • manipuler les pixels dans tous les sens à partir de boîtes de dialogue diverses et variées pdans un but artistique,
  • sauvegarder l’image transformée,
  • éventuellement, recommencer.

Faire un mix afficher une image / la manipuler depuis des boîte de dialogue est un peu moins simple que prévu en tenant compte des points suivants:

  • langage C,
  • portabilité maximale (Linux, Windows, Mac, BSD et, si possible, Android),
  • simplicité de gestion des éléments de dialogue,
  • simplicité de l’affichage d’une image.

Je n’avais pas envie de me plonger dans les méandres de l’affichage d’une image, pourtant il semble bien que c’est ce que je dois faire. Mais peut-être n’ai-je pas choisi les bons éléments au départ? Pourtant, OpenGL me semblait une évidence en terme de portabilité - d’accord, c’est fait pour la 3D! Avec Nuklear, tout aurait du se fonctionner simplement! Et bien non, je dois maîtriser les textures. d’où les quelques notes suivantes à ce sujet.

May 7, 2022

Le retour!

Oups! j’avais oublié cet endroit…

Chômage et désespoir, errance dans les nuées de l’histoire qui avorte et se lamente, il y aurait tant à raconter, mais ce n’est plus d’époque.

Et puis la retraite approche. Bref, le monde n’est plus le même, moi non plus.

May 7, 2022

SML, the revenge

I love SML. After some evenings and nights with Java, I’m really glad to go back to this old but still good language. Some of my work in progress can be find there: TheReturnOfTheSonOfSML. In this post, I just recall some basic rules that I forget after a few weeks of inactivity in this domain.

interpreters and compilers

The easiest implementation is PolyML which have an interpreter and a good compiler. The project is still alive, which is very important.

MLton is a good compiler, which is easy to use but without interpreter. The last version is from February of this year and the previous from 2013. Low activity but not null.

The historic SML/NJ implementation offers an interpreter with a compiler. The latter is not easy to use and I won’t.

There are more but today I will only use these.

a sample program

There is a great hello project which can help us to learn how to structure a source for PolyML and MLTon. If there is a strong standardisation of the language, it’s not the case of the compiling system. It’s why we must do different things for each implementation.

PolyML, first steps

It’ a very permissive system whith one rule: you must provide a main function as the entry point of your program:

fun main() =
	print "Hello, world!\n"

Put that code in a file called hello1.sml and run this:

$ polyc -o hello1.exe hello1.sml
$ ./hello1.exe
Hello, world!

MLTon, first steps

Now, testing with MLTon give a unexpected result:

$ mlton hello1.sml
$ ./hello1

If we create a main.sml like this:

(* main.sml *)

val _ = main ()

and a sort of project file hello1.mlb like that:

$(SML_LIB)/basis/basis.mlb

hello1.sml
main.sml

The test can give us now what we expect:

$ mlton -output hello1.mlt.exe -verbose 1 hello1.mlb
MLton 20180207
MLton starting
   Compile SML starting
      pre codegen starting
      pre codegen finished in 2.28 + 0.71 (24% GC)
      amd64 code gen starting
      amd64 code gen finished in 0.15 + 0.00 (0% GC)
   Compile SML finished in 2.42 + 0.71 (23% GC)
   Compile and Assemble starting
      gcc -c -fPIC -DPIC -I/usr/local/lib/mlton/targets/self/include \
          -std=gnu11 -fno-common -O1 -fomit-frame-pointer \
          -fno-strict-aliasing -w -I/usr/local/lib/mlton/include -m64 -o \
          /tmp/filetXRrV4.o /tmp/filev8cCPy.1.c
      gcc -c -m64 -o /tmp/fileNPOJQ5.o /tmp/filedMrdjS.0.s
   Compile and Assemble finished in 0.14 + 0.00 (0% GC)
   Link starting
      gcc -o hello1.mlt.exe /tmp/filetXRrV4.o /tmp/fileNPOJQ5.o \
          -L/usr/local/lib/mlton/targets/self -lmlton-pic -lgdtoa-pic -lm \
          -lgmp -m64 -Wl,-znoexecstack
   Link finished in 0.03 + 0.00 (0% GC)
MLton finished in 2.64 + 0.72 (21% GC)
$  ./hello1.mlt.exe
Hello, world!

The -verbose option give some indication of the evolution of the compilation. Even if it’s verbose, it’s useful for big project because the compiler is really slower than polyc.

April 13, 2018

configuring Vim

Before doing anything, just go on Youtube to listen Eric Burdon and War, it will help you.

You can get the full .vimrc without plugins!

it’s a great job!

Vim configuration sits in one file (~/.vimrc by default) and a directory (~/.vim by default). The best way to configure Vim is with a plugin manager such Vundle. Since version 8, Vim has it’s own plugin manager. Today, Vim 8 can be easily installed on a lot of distributions.

The great job is I want a full IDE made with Vim!

reloading ~/.vimrc

While you’re listening Eric Burdon (his version of nights in white satin is really beautiful), learn the first useful command to know while configuring Vim and which is how to reload the configuration file. If your current buffer contains ~/.vimrc, you just do:

:source %

where the % design the file in the current buffer. You can use the name of the file like that:

:source ~/.vimrc

You had to be careful, too much source can create some problems, variables are not always reset to their default values.

getting help in Vim

To have more details about each elements of the configuration, ask Vim with, for example, :help nocompatible.

basic configuration

Before all, we had to tell Vim that we don’t want compatibility with old, very old, very very old versions of vi:

" no compatibility with old versions
" of vi, must be one of the first directives
set nocompatible
" modelines can be hatmful
set modelines=0

First, we set line numbers and show the most we can on the ruler. Add this in your ~/.vimrc:

" show line numbers
set number
set norelativenumber
" show line and column number of cursor position
set ruler
" show current mode
set showmode
set showcmd
" enable mouse on a terminal
" depending of the type of terminal emulation, X11 configuration, ...
" it can failed
set mouse=a

If you need to hide line numbers, just do ‘set nonumber’. Then, we enable indentation and syntax highlight following file type :

" encoding...
set encoding=utf-8
" enable indentation
filetype plugin indent on
" and syntax highlight
syntax on

After that, I set tabulations as 4 spaces:

" tabulations
set tabstop=4
set softtabstop=0
set expandtab
set shiftwidth=4
March 16, 2018

shell stuffs

using the command line

du and the biggest directory

du is a nice tool which can show you the total space occupied by all the files of a directory:

$ du -sm /bin /lib*
13	/bin
952	/lib
6	/lib32
1	/lib64

In that command, I asked the size of /bin and of all /lib* directory (flag -s) and the result is in megabytes (flag -m). On my computer, /bin files use 13 Mb. With sort and head, we can find the directories which occupies the most disk space:

$ du -sm /usr/local/* | sort -rn | head -3
4408	/usr/local/tools
928		/usr/local/java
141		/usr/local/bin

If I need to free space on my disk, I will clean /usr/local/tools in first, it occupies 4 Go. And to know more, I now do:

cd /usr/local/tools && du -sm * | sort -rn | head -3
1699	OracleDeveloperStudio12.6-solaris-x86-bin
883		idea-IC-173.3942.27
721		smalltalk-X

I can win more than 1 Gb by removing Oracle Developer Studio 12.6 which I do not use since a long time.

several commands and error handling

The last simple in du and the biggest directory show the use of && between the two commands which could be written like that:

cd /usr/local/tools; du -sm * | sort -rn | head -3
...

We will get the same result than before (unless I have deleted Oracle Developper Studio). If I did

March 15, 2018

a big failure, work in progress

in search of the magical CSS…

I said so many times to so many beginners: don’t do that. In fact, I did it, without shame. I took a simple aim, which was simplify css, and I opened files in Atom to modify them as quick as I could. Current conditions where the following:

  • I was really tired because of the lack of sleep,
  • I was trying to find some music from 60’s and 70’s, the music I could hear at that time,
  • I always did something else while editing as phoning, playing with the dogs and so on - and even eating which is very bad.

And you get all the sass and Liquid stuff (the style stuff) which is in a poor condition even if the result is not so bad.

If I want a clean code, the job will be 10 times harder than if I had think twice before modifying the files, but without shame, I did it, and it’s a big failure for the future of my code.

March 15, 2018

une histoire d'insomnie

une histoire d’insomnie

Soudainement, tout s’est transformé en la recherche de logiciels sous Electron, et, en particulier, d’éditeurs Markdown capables de produire du PDF tout en permettant de gérer un minimum le style.

Zettlr

Le premier trouvé, c’est Zettlr qui exporte en plusieurs formats dont le PDF. Sa principale originalité tient dans le fait qu’il utilise pandoc pour créer le PDF. Certes, l’efficacité est au rendez-vous, la simplicité du logiciel et donc sa qualité en bénéficie certainement, par contre nous avons l’installation de pandoc et LaTeX, ce qui peut faire reculer une grande part du public possible.

Parmi les points forts, il y a la présentation, la justification du texte grâce à LaTeX Avec ces quelques lignes, je ne trouve rien à redire d’extraordinaire si ce n’est que la version courante est la 0.12 ce qui semble prometteur pour la suite. Ah! si, je viens de trouver! Les PDF sont sauvés dans le répertoire /tmp sans que l’on soit prévenu. Mais avec une installation correcte de votre système, il ouvre directement ce PDF dans le lecteur adapté, ici, c’est evince.

MonteNote

Malgré ce que j’avais cru, le Markdown est en dehors de ses compétences ou bien les miennes ne m’ont pas permises d’importer ce fichier. Je passe donc à autre chose.

(Un)colored, l’étrange!

Il est vraiment très beau, il affiche directement le texte formaté et l’accès aux fonctions (gras, italic, …) parfois déroutantes. Encore en version béta, il n’y a pas d’export en PDF.

Moeditor

Un classique avec un pan Markdown, un pan avec le rendu. On peut sélectionner une feuille de style css et exporter en PDF. Le PDF n’est pas beau, il faut vraiment travailler le style.

Markdown Office

Une très classique fenêtre divisée verticalement avec, à gauche, le Markdown et à droite, le texte formaté. Son gros avantage est de se connecter aisément à Google Drive pour la sauvegarde des fichiers et une gestion de l’arborescence des documents assez simple mais efficace. Reste à savoir comment exporter dans un format différent, ce qui est loin d’être intuitif alors que ce type de commande doit être rapidement accessible.

March 7, 2018

blogging in the night

blogging in the night

I’m listening some old German pop music (GURU GURU-Ufo). I must be mad to love this music since I’m a teenager, but it does not matter, I won’t change now that I’m 60. It’s the night, the best moment to write and play with styles on this blog. I found how to test on my computer these stylish experiments - which can fail for any reason, from syntax errors to bad design choices.

It’s as easy as

sudo gem install github-pages

In case of compilation error, look at the last lines, you’ll find the name of the faulty library, something like:

Building nokogiri using packaged libraries.
Using mini_portile version 2.3.0
checking for gzdopen() in -lz... no
zlib is missing; necessary for building libxml2
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	...
  --enable-cross-build
	--disable-cross-build

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.2/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/nokogiri-1.8.2 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.2/gem_make.out

The most interesting line is:

zlib is missing; necessary for building libxml2

Search a package whose name is zlib*dev. Latest Ubuntu have zlib1g-dev. Always on Ubuntu, install this missing package like that:

sudo apt install zlib1g-dev

You can restart the broken install:

sudo gem install github-pages

When everything is alright, start jekyll at the root of your project:

jekyll serve --watch

You can see your site on this URL: http://127.0.0.1:4000/. When I want to see the results of my last modification, I stop jekyll and I restart it immediately but it’s not always necessary.

March 3, 2018

un blog dans Github

Un blog dans GitHub? un blog dans GitHub!

L’idée ne vient pas de moi, je l’ai prise dans mes lectures HTML-esque des jours et des nuits précédentes. Site statique présentant le grand avantage d’une belle mise en page du code, d’utiliser Markdown, sass, des templates HTML simples… Quoi demander de plus? Le remplir!

Facile à créer avec les explications données par jekyll-now, facile à maintenir depuis un navigateur avec le bel outil Prose, c’est une des meilleures affaires du moment en terme de blog d’autant plus qu’il est simple de travailler sur son PC avec l’un des nombreux éditeurs Markdown qui se développent en ce moment.