Apr 29, 2020 - What I like about D

import std.stdio;

void main() {
	writeln("Hello world");
}

A hello world in Dlang.

Sometime ago I discovered the D programming language which is now one of my favourite, if not my favourite, languages. In this post I’ll show you some D features that I love.

But first of all, a little intro.

The D programming language

D was created in 2001 by Walter Bright with lessons learned from C++. D is really close to C++ (especially modern C++) but has more features, a cleaner syntax, faster compile times, and so on. D also has fully optional garbage collector to manage memory (this means you can disable it in some part of your programs or even disable it in your whole project), which allows for more compact and readable code.

Some Great D features

For the remainder of this post, I will assume you already know most C++ features in order to compare it with D. I will also not show every D feature, but only some of my favourites.

D templates

D’s syntax for templates is a little shorter than the C++ syntax :

import std.stdio;
// here T is the type name
auto add(T)(T a, T b) {
	return a + b;
}

void main() {
	writeln("a + b = ", add(5, 3));
}

But where it become interesting is when we use templates in a slightly more advanced way :

import std.stdio;

void printEven(ArgTypes...)(ArgTypes args) {
	foreach (i, arg; args) {
		if (i % 2 == 0) write(arg, " ");
	}
}

void main() {
	printEven(0, "hello", "world", 5.4f);
}

output :

0 world

The above code iterates on each argument of the variadic template with the foreach statement, and then prints only the even arguments. Yes, it’s that easy to iterate on variadic template parameters in D. That’s what I love about D, metaprogramming and template stuff is much easier, more compact and more powerfull than in C++. Let’s look at another example :

import std.stdio;

void templatePrint(string str)() {
	pragma(msg, str);
}

void main() {
	templatePrint!("hello")();
}

D supports NTTP (Non Type Template Parameter), a feature comming in C++20, but which D has supported for a long time. The above exmaple will print hello during compilation, since str is a template parameter, the pragma(msg, str); is a special statement that tells the compiler to print str during compilation.

CTFE

D have also a really powerfull feature called CTFE (Compile Time Function Evaluation), which is somewhat similar to constexpr and consteval in modern C++. A simple example:

import std.stdio;

int add(int a, int b) {
	return a + b;
}

pragma(msg, add(5, 2));

void main() {
	writeln(add(4, 1));
}

This code will print 7 at compile time and 5 at run time, the same function can be used both at compile time and at run time without any specifiers unlike C++.

The true power of D metaprogramming

I see you, saying “yeah, theses features are great, but C++ has them too.” Now I’ll show you why D metaprogramming is so powerfull and why C++ is a way behind D in this domain.

String mixins

With string mixin D can compiles an arbitrary string as D code At compile time.

mixin("int b = 5;");
assert(b == 5); // compiles just fine

Okay but what’s the use of a such feature ?

Remember NTTP ? Let’s look at this example from dlang.org.

import std.stdio : writeln;

auto calculate(string op, T)(T lhs, T rhs) {
    return mixin("lhs " ~ op ~ " rhs");
}

void main() {
    // pass the operation to perform as a
    // template parameter.
    writeln("5 + 12 = ", calculate!"+"(5,12));
    writeln("10 - 8 = ", calculate!"-"(10,8));
    writeln("8 * 8 = ", calculate!"*"(8,8));
    writeln("100 / 5 = ", calculate!"/"(100,5));
}

Now you see it right ?

We can go even further with D’s static reflection and template mixins:

import std.stdio : writeln;

struct Vec3 {
    float x, y, z;
}

string getMemberArrays(T)()
if (is(T == struct)) {// template constraint T must be a struct
    string memArray;
    foreach (mem; __traits(allMembers, Vec3)) {
        // array / string concatenation can be done with ~ operator
        memArray ~= typeof(mixin("T." ~ mem)).stringof // get the type name of the current member
        ~ "[] "         // make an array of this type 
        ~ mem ~";\n";   // keep the same name as the original struct
    }
    return memArray;
}

// mixin template are used to generate boilerplate code
// it works like a C++ macro but at the AST level, so we can use template parameters with it.
mixin template makeSOA(T) {
    // declare the new struct with a prefix
    mixin("struct SOA_" ~ T.stringof ~ "{ \n" 
    ~ getMemberArrays!T // add the members as arrays
    ~ "}");
}

mixin makeSOA!Vec3; // generate the struct

void main() {
    SOA_Vec3 v;
    v.x = [5, 3, 2, 1];
    v.y = [2, 3, 1, 5];
    v.z = [7, 2 ,10 ,1];
    writeln(v);
}

Here we have a simple metaprogram that takes a struct type as input and generates another struct type as output containing an array of each of the input type’s members. And of course, all of this is generated at compile time. There are some features in the code above that we didn’t cover, but the goal here is more to demonstrate the power and the possibilities of D metaprogramming rather than provide a complete language tutorial (I may write one in the future though).

Going further

I highly encourage you to try D and do the Dlang tour (a really great tutorial about the D basics).
You can also join the D community on discord.
On my side, I will certainly write more about D, so stay tuned.

PS : An huge thanks to aldacron from the D discord for his proofreading, corrections and feedbacks.

Mar 1, 2020 - [WIP] A unity tool for L-Systems

Disclaimer

This post will assume you already know the basics of L-Systems. If you don’t I invit you to read my first post on that subject.

Introduction

Some weeks ago for school project I had to do some researches on the subject of my choice and I finished to examinate more in detail L-Systems. This is a presentation of this work. There were two distinct parts in this work, the research and the developement. The research part was learning and exploring how L-Systems works and how we can use them for various tasks. And the developement part was implement an Unity plugin that can generate meshes thanks to L-Systems.

Making a simple L-System

When I started this project I already known a little about L-Systems so, in this project the first step was implementing a basic L-System in unity (I already worked on a prototype before that using Dlang and SDL but since I was using unity I had to reimplement it in C#).

So I started with the initial system, a list of productions rules and an interpreter that draw gizmos with the path generated by the system.

So my first instructions were:

F : forward n following the current direction
f : forward n following the current direction without drawing lines
[ : save current state
] : restore last saved state
+ : rotate k degree aroud y axis
- : rotate -k degree aroud y axis
^ : rotate k degree aroud x axis
& : rotate -k degree aroud x axis
/ : rotate k degree aroud z axis
\ : rotate -k degree aroud z axis
| : rotate 180 degree aroud y axis

so after implementing that I was able to draw some things like this :

3D LSystem

Stochastic L-Systems

In The algorithmic beauty of plants Aristid Lindenmayer and Przemslaw Prusinkiewicz described a way to create non deterministic L-Systems by adding multiples possibles productions to an Axiom with each production a percentage of chance to occur. With this technique we can easly add some randomness to our generated figures and remove determinism.

Context Sensitive L-Systems

In The algorithmic beauty of plants context sensitive are described as a production rule that occur only if a context condition is met. For exmaple consider the following system:

ω = AFF
p1: A < F -> FX
n = 0 : AFF
n = 1 : AFXF

Here only the production rule p1 precise that F must be replaced only if an A is on the left of F in the last production so in this case only the first F meet this condition so only the first F will be replaced by it’s production.
On top of that rules can also describe a list of axiom that are ignored when checking for the context conditions.

Parametric L-Systems

Here is the hard (to implement) part, a parametric L-System associate parameters with axioms. So a production rule in a parametric L-System looks like that:

A(t) -> B(t+1)CD(t, t-2)

Where t is the parameter of the axiom A. Then parameters can be used by the interpreter in order to have more freedom when writing a L-System. So let’s describe the new parameters of the interpreters:

F(x) : forward x following the current direction
^(x) : rotate x degree aroud x axis
… and so on with other instructions axioms.
So the big difference here is that all rotation and forward instructions may not all have the same length / angle, this allow us to generate new things impossible (or very hard) to do with the older system.

Going further

In this small project I only implemented / studied a small part of L-Systems, there is a lot more to discover and to do. Yet we didn’t see nodes and edges rewritting, environment influence, inflorescence, …
If you want to learn more about L-Systems, I highly recommend The algorithmic beauty of plants by Aristid Lindenmayer and Przemslaw Prusinkiewicz, this is the best and most complete reference about L-Systems. I also recommend the research paper Evolving Lindenmayer systems in a competitive environment by Job J.V. Talle, which is an intersting work on top of The algorithmic beauty of plants.

Feb 28, 2020 - [WIP] A short introduction to L-Systems

Introduction

A L-system aka Lindenmayer system is a rewriting system and a type of formal grammar, that can be used to create and generate a bunch of things. I will not dig to deep in the theorical definition of L-Systems since wikipedia already does it very well.

What’s a L-System ?

Let V be an alphabet and V+ be the ensemble of valid words from V.
Let ω a starting axiom from V+.
Let S be a set of constants.
Let P be a ensemble of rewriting rules, that reproduce elements of V.

A L-Systems is the aggregate : L = { V, ω, S, P }

A rewriting rule (we will shorten that one in simply rule) is defined like this:
Axiom -> Production
Where Axiom is a element from V+ and Production is a valid sequence of elements from V+.

L-Systems from scratch

So let’s precise more concretly.

Let V = { F, A }
Let S = { }
Let P = {
F -> FA
A -> F
}
Let ω = F

Let n = 0 .. 5 be the iteration number.

n = 0 : F
n = 1 : FA
n = 2 : FAF
n = 3 : FAFFA
n = 4 : FAFFAFAF
n = 5 : FAFFAFAFFAFFA

At each iteration each Axiom that match a rule is replaced/rewritted by its production. This is this behavior allow us to express easly recusive patterns like fractals for example.

A practical Case

In this blog post we will mostly talk about using L-Systems for generate fractals and rendering stuff but the core of this system is a lot more generic than that and can be used for a lot of other uses cases.

We can easly interpret an L-Systems into graphics using technics such as turtle graphics. All we have to do is define a subset of V+ that will compose an ensemble of commands wich will be interpreted by the turtle. So let define them:

F : moving forward
+ : rotate right
- : rotate left

And only with this we can start drawing our firsts fractals !
(For convenience purposes I will define L-Systems as follow, starting from now)

ω = F
F -> F+F-F-F+F

n = 0 : F
n = 1 : F+F-F-F+F
n = 2 : F+F-F-F+F+F+F-F-F+F-F+F-F-F+F-F+F-F-F+F+F+F-F-F+F

L-System fractal example