This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Vector swizzles in D

By: a guest on Mar 20th, 2012  |  syntax: D  |  size: 1.52 KB  |  views: 129  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. module main;
  2.  
  3. import std.stdio;
  4. import std.process;
  5. import std.conv;
  6.  
  7. private immutable (char[][]) elementNames = [['x', 'y', 'z', 'w'], ['r', 'g', 'b', 'a'], ['s', 't', 'p', 'q']];
  8.  
  9. int main(string[] argv) {
  10.         alias Vec!4 Vec4;
  11.  
  12.         Vec4 v = Vec4(1, 2, 3, 4);
  13.  
  14.         writeln(v.bgra); // Prints Vec!(4)([3, 2, 1, 4])
  15.         writeln(v.rg); // Prints Vec!(2)([1, 2])
  16.  
  17.         return 0;
  18. }
  19.  
  20. struct Vec(size_t size) {
  21.         alias size Size;
  22.  
  23.         mixin(generateConstructor(Size));
  24.  
  25.         mixin(generateProperties(Size));
  26.  
  27.         auto opDispatch(string s)() {
  28.                 mixin(generateSwizzle(s));
  29.         }
  30.  
  31.         float v[Size];
  32. }
  33.  
  34. private string generateConstructor(size_t size) {
  35.         string constructorParams;
  36.         string constructorBody;
  37.  
  38.         foreach(i; 0..size) {
  39.                 string paramName = "v" ~ to!string(i);
  40.                 constructorParams ~= "float " ~ paramName ~ "=0,";
  41.                 constructorBody ~= "v[" ~ to!string(i) ~ "] = " ~ paramName ~ ";";
  42.         }
  43.  
  44.         return "this(" ~ constructorParams[0..$-1] ~ "){" ~ constructorBody ~ "}";
  45. }
  46.  
  47. private string generateProperties(size_t size) {
  48.         string props;
  49.  
  50.         foreach(names; elementNames) {
  51.                 foreach(i, name; names[0..size]) {
  52.                         props ~= "@property float " ~ name ~ "() const { return v[" ~ to!string(i) ~ "]; }";
  53.                         props ~= "@property void " ~ name ~ "(float f) { v[" ~ to!string(i) ~ "] = f; }";
  54.                 }
  55.         }
  56.  
  57.         return props;
  58. }
  59.  
  60. private string generateSwizzle(string elements) {
  61.         string swizzleImpl = "return Vec!" ~ to!string(elements.length) ~ "(";
  62.  
  63.         foreach(e; elements) {
  64.                 swizzleImpl ~= e ~ ",";
  65.         }
  66.  
  67.         return swizzleImpl[0..$-1] ~ ");";
  68. }
clone this paste RAW Paste Data