<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.5">Jekyll</generator><link href="https://blog.kenanb.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://blog.kenanb.com/" rel="alternate" type="text/html" /><updated>2024-03-03T14:19:05+00:00</updated><id>https://blog.kenanb.com/feed.xml</id><title type="html">Kenan Bölükbaşı - Blog</title><subtitle>A blog about programming, graphics, and life.</subtitle><author><name>Kenan Bölükbaşı</name></author><entry><title type="html">Converting HSV to RGB</title><link href="https://blog.kenanb.com/code/cg/2024/03/03/converting-hsv-to-rgb.html" rel="alternate" type="text/html" title="Converting HSV to RGB" /><published>2024-03-03T10:00:00+00:00</published><updated>2024-03-03T10:00:00+00:00</updated><id>https://blog.kenanb.com/code/cg/2024/03/03/converting-hsv-to-rgb</id><content type="html" xml:base="https://blog.kenanb.com/code/cg/2024/03/03/converting-hsv-to-rgb.html"><![CDATA[<p>Exploring HSV to RGB conversion for fun.</p>

<p>I will talk a little bit about the most straightforward HSV to RGB conversion algorithm, and I will try to iterate on it, for better or worse. I don’t think the result of my iteration has any significance, because:</p>
<ul>
  <li>Most cases where the performance of HSV to RGB conversion matters probably involve GPU shader-based implementations.</li>
  <li>There are already well known alternative HSV to RGB implementations that I assume are much more suitable for GPUs than the approach I am iterating on.</li>
</ul>

<p>So this post is just documenting a programming puzzle I spent time on, for fun. I will mostly discuss using pseudo-code. But I might have a closer look at performance implications of various implementations in follow-up posts.</p>

<h2 id="intro">Intro</h2>

<p>Common algorithms for HSV to RGB conversion is documented in <a href="https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB">HSL and HSV</a> Wikipedia page.</p>

<p>I spent some time exploring the first algorithm. It is simple, and it involves an interesting <code class="language-plaintext highlighter-rouge">switch</code> that makes me want to replace with a different approach.</p>

<p>There are two aspects to it:</p>

<ul>
  <li>Calculating a set of values to be assigned to <code class="language-plaintext highlighter-rouge">R</code>, <code class="language-plaintext highlighter-rouge">G</code>, and <code class="language-plaintext highlighter-rouge">B</code> components.</li>
  <li>Distributing those values to each component.</li>
</ul>

<p>Latter aspect shows up in the description as:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(C, X, 0) if 0 &lt;= H' &lt; 1
(X, C, 0) if 1 &lt;= H' &lt; 2
(0, C, X) if 2 &lt;= H' &lt; 3
(0, X, C) if 3 &lt;= H' &lt; 4
(X, 0, C) if 4 &lt;= H' &lt; 5
(C, 0, X) if 5 &lt;= H' &lt; 6
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">H'</code> corresponds to a particular factor of <em>hue</em>, depending on how we represent hue.</p>

<p>If <code class="language-plaintext highlighter-rouge">H</code> is represented in degrees in range <code class="language-plaintext highlighter-rouge">[0, 360)</code>, then <code class="language-plaintext highlighter-rouge">H'</code> is:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H' = H / 60
</code></pre></div></div>

<p>If we were to represent <code class="language-plaintext highlighter-rouge">H</code> in range <code class="language-plaintext highlighter-rouge">[0, 1]</code>, then:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H' = H * 6
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">C</code> is <em>chroma</em>, where <code class="language-plaintext highlighter-rouge">V</code> is <em>value</em>, and <code class="language-plaintext highlighter-rouge">S</code> is <em>saturation</em>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>C = V x S
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">X</code> doesn’t directly map to a term I know of. It is the second largest component, and its formula is:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>X = C x (1 - |H'mod2 - 1|)
</code></pre></div></div>

<p>Once the right component ordering is found, each of those values will then be summed with <code class="language-plaintext highlighter-rouge">V - C</code> to get the final <code class="language-plaintext highlighter-rouge">RGB</code> values.</p>

<h3 id="example">Example</h3>

<p>Let’s manually try this with the HSV values below, all values being in [0,1] range:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H=0.6
S=0.8
V=0.7
</code></pre></div></div>

<p>Here is what the calculation would look like:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H' = 3.6
C = 0.8 * 0.7 = 0.56
X = 0.56 * ( 1 - |1.6-1|) = 0.56 * 0.4 = 0.224
</code></pre></div></div>
<p>Since <code class="language-plaintext highlighter-rouge">H'</code> is <code class="language-plaintext highlighter-rouge">3.6</code>, base values of components is: <code class="language-plaintext highlighter-rouge">(0, X, C)</code>. Using this, we can calculate <code class="language-plaintext highlighter-rouge">RGB</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>R = 0.7 - 0.56 + 0     = 0.14
G = 0.7 - 0.56 + 0.224 = 0.364
B = 0.7 - 0.56 + 0.56  = 0.7
</code></pre></div></div>

<p>Since the ordering of the <code class="language-plaintext highlighter-rouge">X</code>, <code class="language-plaintext highlighter-rouge">C</code>, and <code class="language-plaintext highlighter-rouge">0</code> values for each case doesn’t follow a very trivial pattern, the implementations I see usually have an actual <code class="language-plaintext highlighter-rouge">switch</code> statement. In fact, two variables are used instead of <code class="language-plaintext highlighter-rouge">X</code>, representing the two possible expansions of the absolute-value term.</p>

<p>Let’s assume <code class="language-plaintext highlighter-rouge">F</code> to be the <em>fractional part</em> of <code class="language-plaintext highlighter-rouge">H'</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>X0 = C * F
X1 = C * (1 - F)
</code></pre></div></div>

<p>For this variant, distribution of values becomes:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(C , X0, 0 ) if 0 &lt;= H' &lt; 1
(X1, C , 0 ) if 1 &lt;= H' &lt; 2
(0 , C , X0) if 2 &lt;= H' &lt; 3
(0 , X1, C ) if 3 &lt;= H' &lt; 4
(X0, 0 , C ) if 4 &lt;= H' &lt; 5
(C , 0 , X1) if 5 &lt;= H' &lt; 6
</code></pre></div></div>

<p>Revising the previous example:</p>

<p><code class="language-plaintext highlighter-rouge">H'</code> is <code class="language-plaintext highlighter-rouge">3.6</code>, base values of components is now: <code class="language-plaintext highlighter-rouge">(0, X1, C)</code>. Everything else being the same:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>X1 = 0.56 * ( 1 - 0,6 ) = 0.224
</code></pre></div></div>

<p>In this form, the pattern of how these 4 possible values are ordered for different values of <code class="language-plaintext highlighter-rouge">H'</code> is even more obfuscated.</p>

<h2 id="revising-the-algorithm">Revising the Algorithm</h2>

<p>I was trying to find a way to rewrite this in a way to have some kind of ordering pattern. Specifically, a pattern that’s simple enough that I can implement without a <code class="language-plaintext highlighter-rouge">switch</code>. One approach I found is this:</p>

<p>Instead of assuming <code class="language-plaintext highlighter-rouge">C</code> as a constant, and selecting either <code class="language-plaintext highlighter-rouge">X0</code> or <code class="language-plaintext highlighter-rouge">X1</code>, we can rewrite the distribution of components so that, both <code class="language-plaintext highlighter-rouge">X0</code> and <code class="language-plaintext highlighter-rouge">X1</code> always gets assigned to a component, but in each case, either <code class="language-plaintext highlighter-rouge">X0</code> or <code class="language-plaintext highlighter-rouge">X1</code> equals <code class="language-plaintext highlighter-rouge">C</code>. Now, there is a clear cycling ordering of values: <code class="language-plaintext highlighter-rouge">X1</code>, <code class="language-plaintext highlighter-rouge">X0</code>, and <code class="language-plaintext highlighter-rouge">0</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(X1, X0, 0 ) where X1 = C, if 0 &lt;= H' &lt; 1
(X1, X0, 0 ) where X0 = C, if 1 &lt;= H' &lt; 2
(0 , X1, X0) where X1 = C, if 2 &lt;= H' &lt; 3
(0 , X1, X0) where X0 = C, if 3 &lt;= H' &lt; 4
(X0, 0 , X1) where X1 = C, if 4 &lt;= H' &lt; 5
(X0, 0 , X1) where X0 = C, if 5 &lt;= H' &lt; 6
</code></pre></div></div>

<p>To achieve this, we can redefine <code class="language-plaintext highlighter-rouge">X0</code> and <code class="language-plaintext highlighter-rouge">X1</code> as below, where <code class="language-plaintext highlighter-rouge">H_ODD</code> is <code class="language-plaintext highlighter-rouge">true</code> if integer part of <code class="language-plaintext highlighter-rouge">H'</code> is <em>odd</em>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H_ODD = H'mod2 &gt;= 1
X0 = C * ( H_ODD ?     1 : F )
X1 = C * ( H_ODD ? (1-F) : 1 )
</code></pre></div></div>

<p>Adapting previous example again, the ordering is <code class="language-plaintext highlighter-rouge">(0, X1, X0)</code>, where:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>H_ODD = true
X0 = 0.56 * 1 = 0.56
X1 = 0.56 * ( 1 - 0.6 ) = 0.224
</code></pre></div></div>

<p>Since we now have a clear pattern, we can assign each value to indices that are calculated based on arithmetic. Here is a C implementation of this approach:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span>
 <span class="nf">hsv_to_rgb</span><span class="p">(</span> <span class="kt">double</span> <span class="k">const</span> <span class="o">*</span> <span class="k">const</span> <span class="n">hsv</span><span class="p">,</span> <span class="kt">double</span> <span class="o">*</span> <span class="k">const</span> <span class="n">rgb</span> <span class="p">)</span>
<span class="p">{</span>
    <span class="k">const</span> <span class="kt">double</span> <span class="n">h</span> <span class="o">=</span> <span class="p">(</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">0</span> <span class="p">]</span> <span class="o">-</span> <span class="n">floor</span><span class="p">(</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">0</span> <span class="p">]</span> <span class="p">)</span> <span class="p">)</span> <span class="o">*</span> <span class="mi">6</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">int</span> <span class="n">h_int</span> <span class="o">=</span> <span class="p">(</span> <span class="kt">int</span> <span class="p">)</span> <span class="n">h</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">double</span> <span class="n">h_frac</span> <span class="o">=</span> <span class="n">h</span> <span class="o">-</span> <span class="n">h_int</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">h_shr1</span> <span class="o">=</span> <span class="n">h_int</span> <span class="o">&gt;&gt;</span> <span class="mi">1</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">int</span> <span class="n">h_odd</span> <span class="o">=</span> <span class="n">h_int</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">double</span> <span class="n">chroma</span> <span class="o">=</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">1</span> <span class="p">]</span> <span class="o">*</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">2</span> <span class="p">];</span>
    <span class="k">const</span> <span class="kt">double</span> <span class="n">svf</span> <span class="o">=</span> <span class="n">chroma</span> <span class="o">*</span> <span class="n">h_frac</span><span class="p">;</span>
    <span class="n">rgb</span><span class="p">[</span> <span class="p">(</span> <span class="n">h_shr1</span> <span class="o">+</span> <span class="mi">0</span> <span class="p">)</span> <span class="o">%</span> <span class="mi">3</span> <span class="p">]</span> <span class="o">=</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">2</span> <span class="p">]</span> <span class="o">-</span> <span class="n">h_odd</span> <span class="o">*</span> <span class="n">svf</span><span class="p">;</span>
    <span class="n">rgb</span><span class="p">[</span> <span class="p">(</span> <span class="n">h_shr1</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">)</span> <span class="o">%</span> <span class="mi">3</span> <span class="p">]</span> <span class="o">=</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">2</span> <span class="p">]</span> <span class="o">-</span> <span class="o">!</span><span class="n">h_odd</span> <span class="o">*</span> <span class="p">(</span> <span class="n">chroma</span> <span class="o">-</span> <span class="n">svf</span> <span class="p">);</span>
    <span class="n">rgb</span><span class="p">[</span> <span class="p">(</span> <span class="n">h_shr1</span> <span class="o">+</span> <span class="mi">2</span> <span class="p">)</span> <span class="o">%</span> <span class="mi">3</span> <span class="p">]</span> <span class="o">=</span> <span class="n">hsv</span><span class="p">[</span> <span class="mi">2</span> <span class="p">]</span> <span class="o">-</span> <span class="n">chroma</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>When I did some naive benchmarking, I did observe better performance with this approach compared to the <code class="language-plaintext highlighter-rouge">switch</code> based implementation. However, I am pretty sure other popular HSV to RGB approaches will be faster than this. (I also haven’t really tested this implementation for edge cases.)</p>

<p>One alternative is actually <a href="https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative">documented in the same Wikipedia page</a>. But I haven’t spent much time to understand that algorithm yet. I might do that in a future post.</p>

<p>That’s all for today. Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="cg" /><summary type="html"><![CDATA[Exploring HSV to RGB conversion for fun.]]></summary></entry><entry><title type="html">Timesampled Attribute Support</title><link href="https://blog.kenanb.com/code/lisp/mopr/2024/02/15/mopr-timesampled-attribute-support.html" rel="alternate" type="text/html" title="Timesampled Attribute Support" /><published>2024-02-15T09:00:00+00:00</published><updated>2024-02-15T09:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/mopr/2024/02/15/mopr-timesampled-attribute-support</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/mopr/2024/02/15/mopr-timesampled-attribute-support.html"><![CDATA[<p>Mopr now has initial support for timesampled attributes.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>Short post today.</p>

<p>I wrote <a href="/code/lisp/2024/02/14/means-of-production.html">about <code class="language-plaintext highlighter-rouge">mopr</code></a> yesterday. I mentioned that <code class="language-plaintext highlighter-rouge">USDS</code> module supported generating attribute values for the <code class="language-plaintext highlighter-rouge">Default</code> timecode, but not for timesamples.</p>

<p>I added the initial support for timesamples today.</p>

<p>I had to write a mini C wrapper for <code class="language-plaintext highlighter-rouge">UsdTimeCode</code>, since that’s an object you need to pass as an argument while setting timesampled values on an attribute.</p>

<p>While at it, I also added support for authoring attributes of type <code class="language-plaintext highlighter-rouge">timecode</code>, which happens to be of cpp type <code class="language-plaintext highlighter-rouge">SdfTimeCode</code>. The underlying data is the same for both: a <code class="language-plaintext highlighter-rouge">double</code>. <code class="language-plaintext highlighter-rouge">UsdTimeCode</code> just encodes a couple sentinel values (<code class="language-plaintext highlighter-rouge">Default</code> and <code class="language-plaintext highlighter-rouge">EarliestTime</code>) as well.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><category term="mopr" /><summary type="html"><![CDATA[Mopr now has initial support for timesampled attributes.]]></summary></entry><entry><title type="html">Means of Production</title><link href="https://blog.kenanb.com/code/lisp/2024/02/14/means-of-production.html" rel="alternate" type="text/html" title="Means of Production" /><published>2024-02-14T10:00:00+00:00</published><updated>2024-02-14T10:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/14/means-of-production</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/14/means-of-production.html"><![CDATA[<p>I have been working on a personal framework for my OpenUSD related experiments, mainly in Lisp.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>I was trying to hit the first milestone in my latest project, called <code class="language-plaintext highlighter-rouge">mopr</code>, so I couldn’t write a post for the last few days.</p>

<p>I just open-sourced the code of this project, but <strong>it is heavily experimental, buggy, untested, unsafe, and completely undocumented. The experimental ideas I will describe in this post are similarly unsafe. So I really don’t recommend trying any of this.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup></strong> I am just sharing it as an intellectual activity.</p>

<p><a href="https://github.com/kenanb/mopr">The repository is here</a>. It is currently under a <a href="https://github.com/kenanb/mopr/blob/main/LICENSE">BSD-3-Clause license</a>.</p>

<p>The acronym <code class="language-plaintext highlighter-rouge">mopr</code> is based on a reference to the economics term: “<a href="https://en.wikipedia.org/wiki/Means_of_production">means of production</a>”. I found the name suitable, since I am using <code class="language-plaintext highlighter-rouge">mopr</code> for experimenting with visual production related ideas.</p>

<p>This is a monolithic personal framework for my own VFX related experiments. So its characteristics will evolve over time, and it will likely remain <strong>heavily experimental, buggy, untested, and unsafe</strong>.</p>

<h2 id="what-can-it-do">What Can It Do</h2>

<p>Not a lot of interesting things just yet. It has the foundations that allow me to do <a href="https://openusd.org/release/index.html">OpenUSD</a>-focused prototyping, mostly using <a href="https://en.wikipedia.org/wiki/Common_Lisp">Common Lisp</a>:</p>
<ul>
  <li>Very minimal and incomplete C and Lisp access to USD APIs like Layer, Stage, Prim.</li>
  <li>Support for generic data transfer from native Lisp arrays to USD’s <code class="language-plaintext highlighter-rouge">VtValue</code> containers.</li>
  <li>Boilerplate setup to allow integrating the code into OpenUSD plugins. This kind of integration is currently specific to Embeddable Common Lisp.</li>
</ul>

<p>But this effort already enabled one prototype, that I call USDS.</p>

<h3 id="usds---boring-parts">USDS - Boring Parts</h3>

<p>I do a lot of testing with USD content, and composition of content, usually to observe the outcome, confirm my intuition etc. I value being able to quickly prototype test data.</p>

<p>So the one actual feature I started implementing, is a declarative scene description language I call USDS, that allows me to populate a USD layer from native <a href="https://en.wikipedia.org/wiki/S-expression">S-Expression</a> (s-exp) forms, without explicitly calling USD APIs. The information stored is similar to <code class="language-plaintext highlighter-rouge">usda</code> format, but the representation allows symbolic manipulation. So it is more like what you would have if USDA was based on a generic serialization format.</p>

<p>I have support for scene graph tree building, and most attribute types. No metadata, relationship, or timecoded attribute support yet. I also have an extension that allows more concise syntax, but it comes with its own limitations, so I will skip that for now.</p>

<p><a href="https://github.com/kenanb/mopr/tree/main/src/data/test"><code class="language-plaintext highlighter-rouge">data/test</code> module</a> has some examples. <code class="language-plaintext highlighter-rouge">02.lisp</code> looks like this:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">((</span><span class="ss">:tree</span>
  <span class="p">(</span><span class="s">"hello"</span>
   <span class="p">(</span><span class="s">"world"</span><span class="p">)))</span>

 <span class="p">(</span><span class="ss">:prim</span> <span class="p">(</span><span class="s">"hello"</span><span class="p">)</span>
        <span class="p">(</span><span class="ss">:type</span> <span class="nv">Xform</span><span class="p">))</span>

 <span class="p">(</span><span class="ss">:prim</span> <span class="p">(</span><span class="s">"hello"</span> <span class="s">"world"</span><span class="p">)</span>
        <span class="p">(</span><span class="ss">:type</span> <span class="nv">Sphere</span><span class="p">)))</span>
</code></pre></div></div>

<p>When processed, this expression would produce usd that corresponds to <code class="language-plaintext highlighter-rouge">usda</code> below:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#usda 1.0

def Xform "hello"
{
    def Sphere "world"
    {
    }
}
</code></pre></div></div>

<p>Clearly, the <code class="language-plaintext highlighter-rouge">usda</code> form is more concise in this case. But I can directly manipulate/generate the s-exp form in Lisp.</p>

<p>One difference is, the USDS syntax separates the scene graph tree description (<code class="language-plaintext highlighter-rouge">:tree</code> forms) from the definition of prims (<code class="language-plaintext highlighter-rouge">:prim</code> forms), because I find it error-prone and tedious to write USD attributes inside 5 levels of nesting, when I write USDA by hand for testing.</p>

<p>I can also define “aliases” for prim paths. Here, <code class="language-plaintext highlighter-rouge">x</code> is an alias, that’s later used to refer to the prim instead of by path “<code class="language-plaintext highlighter-rouge">/b/d/e</code>”.</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">((</span><span class="ss">:tree</span>
  <span class="p">(</span><span class="s">"a"</span> <span class="ss">:spec</span> <span class="ss">:class</span><span class="p">)</span>
  <span class="p">(</span><span class="s">"b"</span>
   <span class="p">(</span><span class="s">"d"</span>
    <span class="p">(</span><span class="s">"e"</span> <span class="ss">:spec</span> <span class="ss">:over</span> <span class="ss">:alias</span> <span class="nv">x</span><span class="p">)))</span>
  <span class="p">(</span><span class="s">"c"</span><span class="p">))</span>

 <span class="p">(</span><span class="ss">:prim</span> <span class="nv">x</span>
        <span class="p">(</span><span class="ss">:type</span> <span class="nv">Sphere</span><span class="p">))</span>

 <span class="p">(</span><span class="ss">:prim</span> <span class="p">(</span><span class="s">"a"</span><span class="p">)))</span>
</code></pre></div></div>

<p>This corresponds to a layer that consists of prims at: <code class="language-plaintext highlighter-rouge">&lt;/a&gt;</code>, <code class="language-plaintext highlighter-rouge">&lt;/b&gt;</code>, <code class="language-plaintext highlighter-rouge">&lt;/b/d&gt;</code>, <code class="language-plaintext highlighter-rouge">&lt;/b/d/e&gt;</code>, and <code class="language-plaintext highlighter-rouge">&lt;/c&gt;</code>.</p>

<p>Also, multiple declarations targeting same entities is supported, which is useful when programmatically building parts of a prim or tree from independent functions.</p>

<h3 id="cooler-stuff">Cooler Stuff</h3>

<p>OK, let’s move on to slightly cooler stuff: I can register <code class="language-plaintext highlighter-rouge">callables</code> that I am able to trigger from within the USDS declarations.</p>

<p>Example: An expression like below will call the registered function <code class="language-plaintext highlighter-rouge">test-gen-cubes</code> with <code class="language-plaintext highlighter-rouge">30</code> as its only argument:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">((</span><span class="ss">:call</span> <span class="ss">:test-gen-cubes</span> <span class="mi">30</span><span class="p">))</span>
</code></pre></div></div>

<p>Obviously, <strong>what I am about to say would be a very unsafe thing to do</strong>, but if I were to then plug USDS into a file-format plugin, and opened the file that has the above form in usdview, I would see:
<img src="/assets/img/usdview-mopr-00.png" alt="USDS data displayed in usdview." width="740" /></p>

<p><strong>But again, this is a very bad idea.</strong> I only added support for callables to trigger calls from within a live programming context, where it is clear that some arbitrary execution might take place.</p>

<p>Anyway, <code class="language-plaintext highlighter-rouge">callables</code> are expected to be just usual Lisp functions that return USDS forms themselves, which then get processed normally. (<em>But there is no mechanism in-place to sandbox the function being called, or prevent side effects.</em>) <em>Conceptually</em>, the return value acts as a list that is <strong>spliced</strong> into the location of the <code class="language-plaintext highlighter-rouge">:call</code> form.</p>

<p>Example callable <code class="language-plaintext highlighter-rouge">test-gen-cubes</code> (called with arg <code class="language-plaintext highlighter-rouge">N</code>) produces a grid of <code class="language-plaintext highlighter-rouge">N</code>x<code class="language-plaintext highlighter-rouge">N</code> cubes, each looking like below:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def Cube "Prim_0002"
{
    double size = 0.5
    double3 xformOp:rotateXYZ = (0, 2, 2)
    float3 xformOp:translate = (0, 1, 0)
    uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]
}
</code></pre></div></div>

<p>Here is an example that mixes hardcoded data with function calls at different levels: <a href="https://github.com/kenanb/mopr/blob/c6bd7ff02fc83501ec5143278b27ba3b30070789/src/data/test/09_call.lisp">09_call.lisp</a></p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">((</span><span class="ss">:call</span> <span class="ss">:test-tree-gen</span><span class="p">)</span>

 <span class="p">(</span><span class="ss">:prim</span> <span class="ss">:x</span>
        <span class="p">(</span><span class="ss">:type</span> <span class="nv">Sphere</span><span class="p">)</span>
        <span class="p">(</span><span class="ss">:call</span> <span class="ss">:test-gen-xform-info</span>
               <span class="err">#</span><span class="nv">1A</span> <span class="p">(</span><span class="mi">10</span> <span class="mi">0</span> <span class="mi">100</span><span class="p">)</span>
               <span class="err">#</span><span class="nv">1A</span> <span class="p">(</span><span class="mi">33</span> <span class="mi">55</span> <span class="mi">4</span><span class="p">))</span>
        <span class="p">(</span><span class="ss">:prop</span> <span class="s">"radius"</span>
         <span class="ss">:double</span> <span class="err">#</span><span class="nv">0A</span> <span class="mf">5.0d0</span><span class="p">))</span>

 <span class="p">(</span><span class="ss">:call</span> <span class="ss">:test-gen-cubes</span> <span class="mi">2</span><span class="p">))</span>
</code></pre></div></div>

<p>This corresponds to the USDA file here: <a href="https://github.com/kenanb/mopr/blob/c6bd7ff02fc83501ec5143278b27ba3b30070789/src/data/test/09_call.usda">09_call.usda</a></p>

<p>In this last example, we have 3 <code class="language-plaintext highlighter-rouge">call</code> expressions. <code class="language-plaintext highlighter-rouge">test-gen-xform-info</code> is a “prim-level” call, and it takes 2 arguments, both are “one-dimensional arrays” (<code class="language-plaintext highlighter-rouge">#1A</code>).<sup id="fnref:4" role="doc-noteref"><a href="#fn:4" class="footnote" rel="footnote">2</a></sup></p>

<h2 id="architecture">Architecture</h2>

<p>The way I currently integrate with USD roughly looks like this:
<img src="/assets/img/mopr-ffi-diagram-00.png" alt="USD integration over FFI." width="740" /></p>

<p>The current set of key modules in repo are:<sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">3</a></sup></p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">wrap</code>: A very incomplete C API wrapper for some key OpenUSD modules, and minimal wrapper for miscellaneous classes.</li>
  <li><code class="language-plaintext highlighter-rouge">lisp</code>: Common Lisp based implementation of various features building on the <code class="language-plaintext highlighter-rouge">wrap</code> module. This defines an <a href="https://asdf.common-lisp.dev/">ASDF</a> system called <code class="language-plaintext highlighter-rouge">mopr</code>.</li>
</ul>

<p>These 2 key modules currently build a generic API that aims to be Common Lisp implementation agnostic. So far, that’s the case for the 2 Common Lisp implementations I am testing with: <a href="https://www.sbcl.org/">SBCL</a>, and <a href="https://ecl.common-lisp.dev/">ECL</a>.</p>

<p>I am hoping to split this part to its own respository, once the OpenUSD API coverage is good enough (and tested enough) to be independently useful. For now, it only exposes the minimal API the rest of the framework needs.</p>

<p><code class="language-plaintext highlighter-rouge">lisp</code> module mainly consists of submodules:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">ffi</code>: Common Lisp foreign-function-interface for the API defined on <code class="language-plaintext highlighter-rouge">wrap</code>. This is using the ubiquitous <a href="https://cffi.common-lisp.dev/">CFFI</a> system, and <a href="https://github.com/rpav/cl-autowrap">cl-autowrap</a> library.</li>
  <li><code class="language-plaintext highlighter-rouge">mopr</code>: An interface to interact with various USD concepts like the <code class="language-plaintext highlighter-rouge">VtValue</code> and <code class="language-plaintext highlighter-rouge">VtArray</code>, along with some <code class="language-plaintext highlighter-rouge">with-*</code> macros to implement RAII behaviour for foreign USD objects.</li>
  <li><code class="language-plaintext highlighter-rouge">plug</code>: Placeholder to make the lisp system itself pluggable. It currently only registers a few hardcoded <code class="language-plaintext highlighter-rouge">callables</code>, so that the <code class="language-plaintext highlighter-rouge">call</code> expressions in the USDS declarations can trigger them.</li>
  <li><code class="language-plaintext highlighter-rouge">usds</code>: This implements a <code class="language-plaintext highlighter-rouge">list</code> based declarative language to express scene description that can be used to populate an OpenUSD layer.</li>
</ul>

<p>The remaining <code class="language-plaintext highlighter-rouge">lisp</code> submodules are not interesting.<sup id="fnref:3" role="doc-noteref"><a href="#fn:3" class="footnote" rel="footnote">4</a></sup></p>

<p>On top of this, there are also some modules to allow testing this lisp-based interface in a practical fashion. Specifically, I currently use Embeddable Common Lisp based Linux-native builds of the Lisp module to integrate it into the OpenUSD runtime using USD’s own plugin system:</p>
<ul>
  <li>The <code class="language-plaintext highlighter-rouge">boot</code> module is built into a shared library that I use to initialize the <code class="language-plaintext highlighter-rouge">mopr</code> ECL modules. That becomes a dependency of the actual USD plugin library that will call into <code class="language-plaintext highlighter-rouge">mopr</code> lisp modules.</li>
  <li><code class="language-plaintext highlighter-rouge">plug</code> module has an empty example USD “file format plugin” that integrates the <code class="language-plaintext highlighter-rouge">boot</code> module, and triggers some test code implemented in Lisp. So it doesn’t really do anything useful.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">test</code> module implements some initial <a href="https://github.com/catchorg/Catch2.git"><code class="language-plaintext highlighter-rouge">Catch2</code></a> based testing. <code class="language-plaintext highlighter-rouge">data</code> module contains test files that I used to compare the <code class="language-plaintext highlighter-rouge">usds</code> forms to the reference USD ASCII format representation.</p>

<h2 id="why-common-lisp">Why Common Lisp</h2>

<p><a href="/code/lisp/2024/01/21/exploring-embeddable-common-lisp.html">I wrote about this a bit before</a>. Not for any critical reasons, but:</p>
<ul>
  <li>It is very suitable for the kind of flexible prototyping goals I have.</li>
  <li>It is a mature language ecosystem with some very cool properties like “homoiconicity”.</li>
  <li>Modern Lisp implementations find a good balance of dynamism and performance.</li>
</ul>

<h2 id="goals">Goals</h2>

<p>Here are a few things I am planning to do with this.</p>

<h3 id="more-posts">More Posts</h3>

<p>Now that I have something that produces visuals, I am planning to write a series of blog posts with example procedural scenes first. (<em>Even though this is not the most scalable (or resource-friendly) kind of proceduralism for scene content generation, it is proceduralism nevertheless.</em>)</p>

<p>I am also planning to write up a bit about how I currently handle foreign objects etc.</p>

<p>I will add metadata etc. support soon. And hopefully, the C wrapper coverage will progressively increase. I am also planning to introduce an actual plugin interface to Lisp side.</p>

<h3 id="threading">Threading</h3>

<p>So far, I spent no time to investigate how integrating CL-based computations into a USD plugin would work if Lisp gets called from multiple threads. I need to look into that.</p>

<p>I really don’t know if the OpenUSD-plugin - CommonLisp integration idea will hold well in practice.</p>

<p>If it does, I will likely move on to CL integration in other parts of USD, like in Hydra layer. Same fundamental data types are used on both layers, so I think it would be relatively straightforward to do similar interfacing in USD Hydra.</p>

<h3 id="data-mapping-and-ffi-improvements">Data Mapping and FFI Improvements</h3>

<p>Binary encoding of primitives is usually different between the Lisp world and the C/C++ world. So I currently don’t try to map or <code class="language-plaintext highlighter-rouge">memcpy</code> anything. I just iterate over the data blocks and let CFFI handle conversion. I didn’t worry about performance so far anyway. But specific optimizations might be possible, if the data passing the language boundary ends up being the bottleneck.</p>

<p>Also, note that I am not too experienced with FFIs. So there might be issues with my approach to bridging C++ to Lisp.</p>

<h3 id="other-implementations">Other Implementations</h3>

<p>Also, testing with other implementations: For now, I will continue focusing on ECL based integration. But I read that SBCL has early support for generating dynamic libraries. So I am planning to do some testing with that as well. Finally, once I am confident with the stability of various layers, I will return to investigating <a href="https://clasp-developers.github.io/">Clasp</a> integration.</p>

<p>And since the USDS declarative syntax is basically standard s-expressions, I might test integration with a couple of <a href="https://en.wikipedia.org/wiki/Scheme_(programming_language)">Scheme</a> implementations as well.</p>

<h3 id="sandboxed-callables">Sandboxed Callables</h3>

<p>I mentioned that it is sufficient for <code class="language-plaintext highlighter-rouge">callables</code> to be just pure functions that produce more USDS forms. So I would like to see if it would be possible to integrate with <a href="https://webassembly.org/">WebAssembly</a>, and use it <a href="https://webassembly.org/docs/security/">as a sandbox</a> for callables. Since WebAssembly has a text format that uses S-Expressions as well, there might be other synergy opportunities.</p>

<h3 id="other-plans">Other Plans</h3>

<p>I am hoping to make the <code class="language-plaintext highlighter-rouge">mopr</code> framework a testbed for a few other ideas I have been investigating:</p>
<ul>
  <li>I previously started looking into <a href="https://dwarfstd.org/">DWARF</a> Debugging Standard. I would like to see how I can utilize DWARF for interesting runtime features, rather than just debugging.</li>
  <li>SBCL has a really cool concept called <em>virtual operations</em> (VOPs). This is another thing I have been collecting notes on, and I want to see if I can make creative use of that.</li>
</ul>

<p>I am hoping to soon write about VOPs and DWARF anyway.</p>

<p>That’s all for today. I hope the post wasn’t too boring.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>See <a href="/about/">About</a> and <a href="https://github.com/kenanb/mopr/blob/main/LICENSE">project license</a> disclaimers. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:4" role="doc-endnote">
      <p>For the 1D case, I could have just written <code class="language-plaintext highlighter-rouge">#( ... )</code> instead of <code class="language-plaintext highlighter-rouge">#1A( ... )</code>. <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p>There are the <code class="language-plaintext highlighter-rouge">base</code> and <code class="language-plaintext highlighter-rouge">core</code> modules, which, despite the names, contains nothing interesting. <code class="language-plaintext highlighter-rouge">base</code> consists of small headers that are needed by many modules. <code class="language-plaintext highlighter-rouge">core</code> is a placeholder library for future functionality I expect to be implementing in C. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:3" role="doc-endnote">
      <p>I also define a <code class="language-plaintext highlighter-rouge">mopr-user</code> lisp package to be used for the interactions with this API. <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[I have been working on a personal framework for my OpenUSD related experiments, mainly in Lisp.]]></summary></entry><entry><title type="html">Chez Scheme and Gambit Scheme</title><link href="https://blog.kenanb.com/code/lisp/2024/02/08/chez-scheme-and-gambit-scheme.html" rel="alternate" type="text/html" title="Chez Scheme and Gambit Scheme" /><published>2024-02-08T01:00:00+00:00</published><updated>2024-02-08T01:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/08/chez-scheme-and-gambit-scheme</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/08/chez-scheme-and-gambit-scheme.html"><![CDATA[<p>Looking into current state of various Scheme implementations.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>This morning, I was updating my OS packages, and I realized <a href="https://www.scheme.com/">Chez Scheme</a> had its v10.0 release! For those unfamiliar, here is the description of Chez from <a href="https://en.wikipedia.org/wiki/Chez_Scheme">its Wikipedia page</a>:</p>
<blockquote>
  <p>Chez Scheme is a programming language, a dialect and implementation of the language Scheme which is a type of Lisp. It uses an incremental native-code compiler to produce native binary files for the x86 (IA-32, x86-64), PowerPC, and SPARC processor architectures.</p>
</blockquote>

<p>Links to Chez Scheme project page and source code are <a href="https://www.scheme.com/">available in its webpage</a>.</p>

<p>The release notes for v10.0.0 <a href="https://cisco.github.io/ChezScheme/release_notes/v10.0/release_notes.html">is available here</a>. I have not used Chez a lot, but I have always been interested. The direction and amount of improvements really got me excited to give it a try with my current project, which I will write about soon.</p>

<p>There are a lot of nice improvements, from introduction of a <em>portable bytecode</em> to <em>wrapper procedures</em> and foreign interface improvements. Apparently, the compiler now generates code that locally unboxes floats. Great! But also, support for more architectures:</p>

<blockquote>
  <p>AArch64 (64-bit Arm), RV64G (64-bit RISC-V), and LoongArch64 architectures are supported. Threads are supported on architectures with weak memory models while preserving the safety guarantee described in the documentation for variables and primitive datatypes.</p>
</blockquote>

<p>I read in forums that recently, <a href="https://en.wikipedia.org/wiki/Racket_(programming_language)">Racket</a> branch of Chez Scheme merged with the mainline Chez Scheme. Lisp dialects are not super mainstream nowadays, so this kind of consolidation is great to see.</p>

<p>Another scheme implementation I have always been interested is <a href="https://gambitscheme.org/">Gambit Scheme</a>. Gambit has a compiler that compiles to <code class="language-plaintext highlighter-rouge">C</code>. I realize Gambit’s foreign interface is written in a way to also support <code class="language-plaintext highlighter-rouge">new</code>/<code class="language-plaintext highlighter-rouge">delete</code> based resource management of <code class="language-plaintext highlighter-rouge">C++</code>. That got me curious regarding the <code class="language-plaintext highlighter-rouge">C++</code> interop experience in Gambit. Its <a href="https://en.wikipedia.org/wiki/Gambit_(Scheme_implementation)">wikipedia page</a> also mentions that software written in Gambit-C can contain <code class="language-plaintext highlighter-rouge">C++</code> and integrate with corresponding libraries.</p>

<p>I hope to soon try both implementations with some minimal FFI code and share my findings.</p>

<p>That’s all for today.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[Looking into current state of various Scheme implementations.]]></summary></entry><entry><title type="html">Common Lisp Standard Method Combination</title><link href="https://blog.kenanb.com/code/lisp/2024/02/07/common-lisp-method-combination.html" rel="alternate" type="text/html" title="Common Lisp Standard Method Combination" /><published>2024-02-07T01:00:00+00:00</published><updated>2024-02-07T01:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/07/common-lisp-method-combination</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/07/common-lisp-method-combination.html"><![CDATA[<p>Common Lisp Object System defines a flexible approach to method combination.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>Common Lisp has a very powerful OOP system, called CLOS (<a href="https://en.wikipedia.org/wiki/Common_Lisp_Object_System">Common Lisp Object System</a>). To be clear, I am specifically talking about expressive power, and flexibility. CLOS is not cheap in terms of performance. I assume it will be fast enough for many tasks, but I would not rely on CLOS as I can rely on OOP concepts of C++, if performance is very important.</p>

<p>One of the interesting aspects of the CLOS model is the emphasis on the functions. Methods are not owned by classes, but by “generic functions”. Again, this is not the kind of generics statically typed languages like C++ has. It is just dynamic method dispatch. It is not a compile-time polymorphism solution, which I really wish existed in CL.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup></p>

<p>I think decoupling methods from the classes they operate on empowers the programmer to reason about the design in a more flexible manner. At least that’s my memory of my CLOS experience. CLOS also privides a <a href="https://www.lispworks.com/documentation/HyperSpec/Body/07_ffb.htm"><em>standard method combination</em></a> that has the concept of “auxiliary methods”: <code class="language-plaintext highlighter-rouge">:before</code>, <code class="language-plaintext highlighter-rouge">:after</code>, and <code class="language-plaintext highlighter-rouge">:around</code>. So a call can automatically resolve to a well-ordered set of function calls. It is a good feature, if used wisely.</p>

<p>Wikipedia page of CLOS has <a href="https://en.wikipedia.org/wiki/Common_Lisp_Object_System#/media/File:Method-combination.png">this nice diagram</a> that visualizes the method application order defined by Standard Method Combination.</p>

<p>That’s all for today.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>I suspect “sufficiently smart compilers” might be trying to optimize method dispatch when it is safe, but CLOS also allows runtime modification of classes etc. So I am not sure how possible that is. I am aware of an interesting concept called <a href="https://github.com/marcoheisig/sealable-metaobjects">sealable metaobjects</a>, but I didn’t get a chance to try it yet. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[Common Lisp Object System defines a flexible approach to method combination.]]></summary></entry><entry><title type="html">One Year Since the Earthquake</title><link href="https://blog.kenanb.com/life/2024/02/06/one-year-since-earthquake.html" rel="alternate" type="text/html" title="One Year Since the Earthquake" /><published>2024-02-06T10:00:00+00:00</published><updated>2024-02-06T10:00:00+00:00</updated><id>https://blog.kenanb.com/life/2024/02/06/one-year-since-earthquake</id><content type="html" xml:base="https://blog.kenanb.com/life/2024/02/06/one-year-since-earthquake.html"><![CDATA[<p>A year ago, on 6 February 2023, Türkiye and Syria were hit by a devastating earthquake.</p>

<p>It has been one year since the 7.8 magnitude earthquake shook Türkiye and Syria. Description from the <a href="https://en.wikipedia.org/wiki/2023_Turkey%E2%80%93Syria_earthquakes">Wikipedia page</a>:</p>

<blockquote>
  <p>On 6 February 2023, at 04:17 TRT (01:17 UTC), a Mw 7.8 earthquake struck southern and central Turkey and northern and western Syria. The epicenter was 37 km (23 mi) west–northwest of Gaziantep.[2] The earthquake had a maximum Mercalli intensity of XII (Extreme) around the epicenter and in Antakya. It was followed by a Mw 7.7 earthquake at 13:24.[3] This earthquake was centered 95 km (59 mi) north-northeast from the first. There was widespread damage and tens of thousands of fatalities.</p>
</blockquote>

<p><strong>Confirmed death toll in Türkiye is over 50,000.</strong></p>

<p>Being Turkish, I have been following the events and announcements in Türkiye relating to the earthquake.</p>

<p>Hatay is the worst impacted city. A year after the event, many in Hatay are very angry.</p>

<p>There is anger towards the government. There is anger towards local authorities, including the mayor, who is a member of the main opposition party. Here is <a href="https://www.reuters.com/world/middle-east/anger-turkish-government-spills-over-earthquake-anniversary-vigil-2024-02-06/">a post in English</a> about the recent protests.</p>

<p>There is also 2024 Turkish local elections at the end of March. So there is obvious PR damage control, along with not-so-subtle political statements being made. Some of those statements leave me at a loss for words.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="life" /><summary type="html"><![CDATA[A year ago, on 6 February 2023, Türkiye and Syria were hit by a devastating earthquake.]]></summary></entry><entry><title type="html">Common Lisp Supplied-p Parameters</title><link href="https://blog.kenanb.com/code/lisp/2024/02/05/common-lisp-supplied-p-parameters.html" rel="alternate" type="text/html" title="Common Lisp Supplied-p Parameters" /><published>2024-02-05T09:00:00+00:00</published><updated>2024-02-05T09:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/05/common-lisp-supplied-p-parameters</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/05/common-lisp-supplied-p-parameters.html"><![CDATA[<p>In CL, you can check if the optional and keyword arguments are actually supplied.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>I made a brief intro to lambda lists (parameter lists) of CL in <a href="/code/lisp/2024/02/03/common-lisp-lambda-lists.html">a previous post</a>.</p>

<p>I wanted to mention another interesting feature of the lambda list of Common Lisp. We already mentioned that CL supports <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_dab.htm"><code class="language-plaintext highlighter-rouge">&amp;optional</code></a>, and <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_dad.htm"><code class="language-plaintext highlighter-rouge">&amp;key</code></a> parameters. It also allows both of these parameter groups to have default values.</p>

<p>Example:</p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">fn</span> <span class="p">(</span><span class="nv">a</span> <span class="nv">b</span> <span class="k">&amp;optional</span> <span class="p">(</span><span class="nv">c</span> <span class="mi">5</span><span class="p">))</span>
  <span class="p">(</span><span class="nb">*</span> <span class="nv">a</span> <span class="nv">b</span> <span class="nv">c</span><span class="p">))</span>
</code></pre></div></div>
<p>The optional parameter <code class="language-plaintext highlighter-rouge">c</code> has a default value of <code class="language-plaintext highlighter-rouge">5</code>.</p>

<p>Let’s try to call this:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">fn</span> <span class="mi">3</span> <span class="mi">4</span> <span class="mi">7</span><span class="p">)</span> <span class="c1">; = 84</span>
<span class="p">(</span><span class="nv">fn</span> <span class="mi">3</span> <span class="mi">4</span><span class="p">)</span>   <span class="c1">; = 60</span>
</code></pre></div></div>

<p>Now, the cool part. You can also check whether the caller actually supplied an optional parameter, or if the value defaulted.</p>

<p>In languages like python, people sometimes default to an intermediate value, like <code class="language-plaintext highlighter-rouge">None</code>, that’s not a sensible value for that specific parameter, just to be able to distinguish between defaulted value vs a caller-supplied value that happens to match the default.</p>

<p>In CL, you don’t need that. You can supply a variable name to be bound to <em>true</em> or <em>false</em>, depending on whether or not an argument was supplied for the parameter during call.</p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">fn</span> <span class="p">(</span><span class="k">&amp;optional</span> <span class="p">(</span><span class="nv">x</span> <span class="mi">0</span> <span class="nv">x-supplied-p</span><span class="p">))</span>
  <span class="p">(</span><span class="nb">format</span> <span class="no">t</span> <span class="s">"Value of x: ~a~%Caller supplied x: ~a"</span>
          <span class="nv">x</span>
          <span class="p">(</span><span class="k">if</span> <span class="nv">x-supplied-p</span> <span class="s">"YES"</span> <span class="s">"NO"</span><span class="p">)))</span>
</code></pre></div></div>

<p>Here is the output of various calls:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CL-USER&gt; (fn 5)
Value of x: 5
Caller supplied x: YES
NIL
CL-USER&gt; (fn 0)
Value of x: 0
Caller supplied x: YES
NIL
CL-USER&gt; (fn)
Value of x: 0
Caller supplied x: NO
NIL
</code></pre></div></div>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[In CL, you can check if the optional and keyword arguments are actually supplied.]]></summary></entry><entry><title type="html">Common Lisp AUX Variables</title><link href="https://blog.kenanb.com/code/lisp/2024/02/04/common-lisp-aux-variables.html" rel="alternate" type="text/html" title="Common Lisp AUX Variables" /><published>2024-02-04T09:00:00+00:00</published><updated>2024-02-04T09:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/04/common-lisp-aux-variables</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/04/common-lisp-aux-variables.html"><![CDATA[<p>AUX lambda list keyword allows defining variables in the function lambda list.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>I made a brief intro to lambda lists (parameter lists) of CL in <a href="/code/lisp/2024/02/03/common-lisp-lambda-lists.html">my previous post</a>.</p>

<p>The lambda list of Common Lisp has an interesting feature that I haven’t encountered in other languages. It is called an <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_dae.htm"><code class="language-plaintext highlighter-rouge">&amp;aux</code> variable</a>.</p>

<p>Basically, it allows you to define function variables in the parameter list. So it is not an actual parameter. You can’t provide an argument that will be bound to the auxiliary variable while calling the function. Rather, it is analogous to a variable binding that would be defined within the function body, using a <code class="language-plaintext highlighter-rouge">let*</code> form.</p>

<p>For reference: <a href="https://www.lispworks.com/documentation/lw70/CLHS/Body/s_let_l.htm"><code class="language-plaintext highlighter-rouge">let</code> and <code class="language-plaintext highlighter-rouge">let*</code> operators</a> allow creating new variable bindings with a scope. <code class="language-plaintext highlighter-rouge">let*</code> variant performs the bindings sequentially, so each binding can refer to previously defined variables.</p>

<p>Let’s start with a simple function definition that doesn’t have an auxiliary variable:</p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">fn</span> <span class="p">(</span><span class="nv">a</span> <span class="nv">b</span><span class="p">)</span>
  <span class="p">(</span><span class="nb">*</span> <span class="nv">a</span> <span class="nv">b</span><span class="p">))</span>
</code></pre></div></div>

<p>We just have a function <code class="language-plaintext highlighter-rouge">fn</code> that accepts parameters <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code>. It returns the result of multiplying <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code>. Calling <code class="language-plaintext highlighter-rouge">(fn 2 3)</code> would return <code class="language-plaintext highlighter-rouge">6</code>.</p>

<p>Let’s modify this to have an <code class="language-plaintext highlighter-rouge">&amp;aux</code> variable called <code class="language-plaintext highlighter-rouge">c</code>, bind it to <code class="language-plaintext highlighter-rouge">a + b</code>, and introduce <code class="language-plaintext highlighter-rouge">c</code> into the multiplication:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">fn</span> <span class="p">(</span><span class="nv">a</span> <span class="nv">b</span> <span class="k">&amp;aux</span> <span class="p">(</span><span class="nv">c</span> <span class="p">(</span><span class="nb">+</span> <span class="nv">a</span> <span class="nv">b</span><span class="p">)))</span>
  <span class="p">(</span><span class="nb">*</span> <span class="nv">a</span> <span class="nv">b</span> <span class="nv">c</span><span class="p">))</span>
</code></pre></div></div>

<p>And here is the corresponding function using the usual <code class="language-plaintext highlighter-rouge">let*</code> form instead:</p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">fn</span> <span class="p">(</span><span class="nv">a</span> <span class="nv">b</span><span class="p">)</span>
  <span class="p">(</span><span class="k">let*</span> <span class="p">((</span><span class="nv">c</span> <span class="p">(</span><span class="nb">+</span> <span class="nv">a</span> <span class="nv">b</span><span class="p">)))</span>
    <span class="p">(</span><span class="nb">*</span> <span class="nv">a</span> <span class="nv">b</span> <span class="nv">c</span><span class="p">)))</span>
</code></pre></div></div>

<p>As expected, <code class="language-plaintext highlighter-rouge">(fn 2 3)</code> will return <code class="language-plaintext highlighter-rouge">30</code> for both of these.</p>

<p>So why is <code class="language-plaintext highlighter-rouge">&amp;aux</code> useful?</p>

<p><code class="language-plaintext highlighter-rouge">&amp;aux</code> is not a very popular feature of the language. The <code class="language-plaintext highlighter-rouge">let*</code> form above is how you would usually see local variables like this get introduced. Most uses of <code class="language-plaintext highlighter-rouge">&amp;aux</code> are convenience, based on personal preference. For example, you can use it to reduce one level of indentation.</p>

<p>There is an <a href="https://groups.google.com/g/comp.lang.lisp/c/WGyjmda34LQ">old <code class="language-plaintext highlighter-rouge">comp.lang.lisp</code> discussion on <code class="language-plaintext highlighter-rouge">&amp;aux</code></a>, where people shared a few other interesting uses.</p>

<p>Examples of convenience uses:</p>

<ul>
  <li>Some use it for cases where they will possibly promote a local variable to a formal parameter later. That use allows the parameter “promotion” to happen without modifying the function body.</li>
  <li>Some people use &amp;aux variables to emphasize an important local variable, like the variable that’s populated in function body, and eventually becomes the return value.</li>
  <li>Some use it for variables that are directly derived from function arguments, like the <code class="language-plaintext highlighter-rouge">(c (+ a b))</code> example above. That makes the relationship obvious.</li>
</ul>

<p>Examples of more important usecases (these will only be clear to people who already know Common Lisp):</p>
<ul>
  <li>Non-trivial initialization of structure slots, <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_df.htm">which is also defined in the standard</a>.</li>
  <li>If a macro introduces lexical bindings, introducing it via a <code class="language-plaintext highlighter-rouge">let*</code> form will cause possible <em>declaration</em> forms in the macro call to be placed in the wrong position in macro expansion. An <code class="language-plaintext highlighter-rouge">&amp;aux</code> variable will avoid that.</li>
</ul>

<p>I like <code class="language-plaintext highlighter-rouge">&amp;aux</code>. I occasionally use it for each reason stated above.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[AUX lambda list keyword allows defining variables in the function lambda list.]]></summary></entry><entry><title type="html">Common Lisp Lambda Lists</title><link href="https://blog.kenanb.com/code/lisp/2024/02/03/common-lisp-lambda-lists.html" rel="alternate" type="text/html" title="Common Lisp Lambda Lists" /><published>2024-02-03T09:00:00+00:00</published><updated>2024-02-03T09:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/03/common-lisp-lambda-lists</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/03/common-lisp-lambda-lists.html"><![CDATA[<p>Brief and informal introduction to parameter lists of CL.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>Common Lisp parameter lists have some interesting features I haven’t encountered in other languages. But before I get to  those, I will start by introducing the usual argument passing styles in CL.</p>

<p>Let’s start with a simple function definition:</p>

<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defun</span> <span class="nv">mul</span> <span class="p">(</span><span class="nv">a</span> <span class="nv">b</span><span class="p">)</span>
  <span class="p">(</span><span class="nb">*</span> <span class="nv">a</span> <span class="nv">b</span><span class="p">))</span>
</code></pre></div></div>

<p>In CL, parameter lists are officially called <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/26_glo_l.htm#lambda_list">“lambda list”</a>. So <code class="language-plaintext highlighter-rouge">(a b)</code> is the lambda list here.</p>

<p>There are <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_d.htm">various types of lambda lists</a>. The one used by functions is called <a href="https://www.lispworks.com/documentation/lw50/CLHS/Body/03_da.htm">“ordinary lambda list”</a>. Macro definitions use an “extended lambda list”.</p>

<p>You have all the usual parameter styles that you would be familiar from languages like Python. You have <em>required</em>, <em>optional</em>, <em>keyword</em>, as well as a <em>rest</em> (catchall) style parameter. The way these are declared is slightly unconventional. The way they behave (especially the way combinations behave) is also different from other languages.</p>

<p>Each parameter declaration is called a “parameter specifier”. Specifiers of the same style are grouped together. There are “lambda list keywords” that describes the kind of each group.</p>

<p>Here is an example with optional positional parameters (<code class="language-plaintext highlighter-rouge">...</code> is where function body would go):</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                __ required parameters
               /               __ optional parameters
           ___/          _____/
(defun fn (a b &amp;optional c d e) ... )
                   \
                    \_ A lambda list keyword.
</code></pre></div></div>

<p>This can be called like:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span><span class="p">)</span>     <span class="c1">; c = nil, d = nil, e = nil</span>
<span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span><span class="p">)</span> <span class="c1">; c = 3, d = 4, e = nil</span>
</code></pre></div></div>

<p>So everything you declare before the first lambda-list keyword are required parameters.</p>

<p>Lambda list keywords start with ampersand character, like: <code class="language-plaintext highlighter-rouge">&amp;optional</code>.</p>

<p>Another example, this time using a <code class="language-plaintext highlighter-rouge">&amp;rest</code> parameter:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                __ required
               /          __ all other positional arguments
           ___/      ____/   gathered into a list
(defun fn (a b &amp;rest args) ... )
</code></pre></div></div>

<p>This can be called like:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span><span class="p">)</span>             <span class="c1">; args = nil</span>
<span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span><span class="p">)</span>           <span class="c1">; args = '(3)</span>
<span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span> <span class="mi">5</span> <span class="mi">6</span> <span class="mi">7</span> <span class="mi">8</span><span class="p">)</span> <span class="c1">; args = '(3 4 5 6 7 8)</span>
</code></pre></div></div>

<p>And the last one, using keyword parameters:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                __ required
               /        __ keyword arguments
           ___/     ___/
(defun fn (a b &amp;key c d) ... )
</code></pre></div></div>

<p>This can be called like:</p>
<div class="language-common-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span><span class="p">)</span>      <span class="c1">; c = nil , d = nil</span>
<span class="p">(</span><span class="nv">fn</span> <span class="mi">1</span> <span class="mi">2</span> <span class="ss">:d</span> <span class="mi">4</span><span class="p">)</span> <span class="c1">; c = nil , d = 4</span>
</code></pre></div></div>

<p>You can combine different groups but only a subset of combinations build an intuitive protocol.</p>

<p>I will continue describing some interesting aspects in future posts, but you can read a great description of details from the <a href="https://gigamonkeys.com/book/functions">functions section</a> of Practical Common Lisp.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[Brief and informal introduction to parameter lists of CL.]]></summary></entry><entry><title type="html">ECL Object Lifetime and Ownership</title><link href="https://blog.kenanb.com/code/lisp/2024/02/02/ecl-object-lifetime-and-ownership.html" rel="alternate" type="text/html" title="ECL Object Lifetime and Ownership" /><published>2024-02-02T09:00:00+00:00</published><updated>2024-02-02T09:00:00+00:00</updated><id>https://blog.kenanb.com/code/lisp/2024/02/02/ecl-object-lifetime-and-ownership</id><content type="html" xml:base="https://blog.kenanb.com/code/lisp/2024/02/02/ecl-object-lifetime-and-ownership.html"><![CDATA[<p>I am trying to build a mental model of object lifetimes in ECL.</p>

<p>[ <em>Check out all posts in “lisp” series <a href="/series/#lisp">here</a>.</em> ]</p>

<p>Another short post today.</p>

<p>I have been exploring <a href="https://en.wikipedia.org/wiki/Embeddable_Common_Lisp">Embeddable Common-Lisp</a> for a few weeks now. Here is my <a href="/code/lisp/2024/01/23/ecl-exploration-continued.html">previous ECL post</a>. I learned quite a lot since. I am now fairly familiar with:</p>
<ul>
  <li>the general C API,</li>
  <li>ECL specific Lisp API,</li>
  <li>some key sections of the C codebase,</li>
  <li>the primary means of communicating between the C/C++ world and the Lisp world.</li>
</ul>

<p>I also mentioned that I was trying to have a better grasp of the <a href="https://ecl.common-lisp.dev/static/files/manual/current-manual/Memory-Management.html#Memory-Management">memory management</a> aspect, which I started.</p>

<p>There is not much to say for objects that live purely in Lisp world.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup> Because it will just behave like what you would expect a garbage collected environment to behave.</p>

<p>However, the situation is different for <em>foreign objects</em>. Working with data across runtimes with different data models usually involves multiple layers of wrapper/proxy objects. So that already obfuscates things. On top of that, if the main memory management strategy of those runtimes are not similar, the topic of memory management and ownership becames a pretty complicated one to reason about.</p>

<p>I briefly talked about the <a href="/code/lisp/2024/01/23/ecl-exploration-continued.html#cl-object"><code class="language-plaintext highlighter-rouge">cl_object</code> type</a> in my previous ECL related post. This value either encodes an <em>immediate</em>, or a pointer to a <em>box</em> object. The box can be set to contain “foreign data”, in which case it will point to a foreign data block. Here are a few subtleties that requires accounting for in the mental model, if you aim to transfer data across:</p>
<ul>
  <li>There is a question of <em>foreign data lifetime and ownership</em>.</li>
  <li>There is a question of <em>wrapper object lifetime and ownership</em>.</li>
  <li>De-facto ownership expectations for the Lisp-&gt;C case is not quite the same as C-&gt;Lisp case. So there is a bit of asymmetry as well.</li>
  <li>Since the Lisp world utilizes garbage collection, there is the question of how references to allocations are tracked, and which memory regions are scanned for that.</li>
</ul>

<p>At this point, there are gaps in my understanding, so I will defer elaborating further to another post. But it is an interesting topic, so I am hoping to return later with some real-world examples.</p>

<p>Thanks for reading! If you find technical errors, please report in the blog’s <a href="https://github.com/kenanb/kenanb-blog/issues">Issues page</a>.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>That is, unless your usecase involves resource utilization concerns. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Kenan Bölükbaşı</name></author><category term="code" /><category term="lisp" /><summary type="html"><![CDATA[I am trying to build a mental model of object lifetimes in ECL.]]></summary></entry></feed>