demo.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import (
  2. "fmt.odin";
  3. "strconv.odin";
  4. "mem.odin";
  5. "thread.odin" when ODIN_OS == "windows";
  6. win32 "sys/windows.odin" when ODIN_OS == "windows";
  7. /*
  8. "atomics.odin";
  9. "bits.odin";
  10. "hash.odin";
  11. "math.odin";
  12. "opengl.odin";
  13. "os.odin";
  14. "raw.odin";
  15. "sort.odin";
  16. "strings.odin";
  17. "sync.odin";
  18. "types.odin";
  19. "utf8.odin";
  20. "utf16.odin";
  21. */
  22. )
  23. general_stuff :: proc() {
  24. { // `do` for inline statmes rather than block
  25. foo :: proc() do fmt.println("Foo!");
  26. if false do foo();
  27. for false do foo();
  28. when false do foo();
  29. if false do foo();
  30. else do foo();
  31. }
  32. { // Removal of `++` and `--` (again)
  33. x: int;
  34. x += 1;
  35. x -= 1;
  36. }
  37. { // Casting syntaxes
  38. i := i32(137);
  39. ptr := &i;
  40. fp1 := (^f32)(ptr);
  41. // ^f32(ptr) == ^(f32(ptr))
  42. fp2 := cast(^f32)ptr;
  43. f1 := (^f32)(ptr)^;
  44. f2 := (cast(^f32)ptr)^;
  45. // Questions: Should there be two ways to do it?
  46. }
  47. /*
  48. * Remove *_val_of built-in procedures
  49. * size_of, align_of, offset_of
  50. * type_of, type_info_of
  51. */
  52. { // `expand_to_tuple` built-in procedure
  53. Foo :: struct {
  54. x: int;
  55. b: bool;
  56. }
  57. f := Foo{137, true};
  58. x, b := expand_to_tuple(f);
  59. fmt.println(x, b);
  60. fmt.println(expand_to_tuple(f));
  61. }
  62. {
  63. // .. half-closed range
  64. // ... open range
  65. for in 0..2 {} // 0, 1
  66. for in 0...2 {} // 0, 1, 2
  67. }
  68. }
  69. nested_struct_declarations :: proc() {
  70. {
  71. FooInteger :: int;
  72. Foo :: struct {
  73. i: FooInteger;
  74. };
  75. f := Foo{FooInteger(137)};
  76. }
  77. {
  78. Foo :: struct {
  79. Integer :: int;
  80. i: Integer;
  81. }
  82. f := Foo{Foo.Integer(137)};
  83. }
  84. }
  85. default_struct_values :: proc() {
  86. {
  87. Vector3 :: struct {
  88. x: f32;
  89. y: f32;
  90. z: f32;
  91. }
  92. v: Vector3;
  93. fmt.println(v);
  94. }
  95. {
  96. // Default values must be constants
  97. Vector3 :: struct {
  98. x: f32 = 1;
  99. y: f32 = 4;
  100. z: f32 = 9;
  101. }
  102. v: Vector3;
  103. fmt.println(v);
  104. v = Vector3{};
  105. fmt.println(v);
  106. // Uses the same semantics as a default values in a procedure
  107. v = Vector3{137};
  108. fmt.println(v);
  109. v = Vector3{z = 137};
  110. fmt.println(v);
  111. }
  112. {
  113. Vector3 :: struct {
  114. x := 1.0;
  115. y := 4.0;
  116. z := 9.0;
  117. }
  118. stack_default: Vector3;
  119. stack_literal := Vector3{};
  120. heap_one := new(Vector3); defer free(heap_one);
  121. heap_two := new_clone(Vector3{}); defer free(heap_two);
  122. fmt.println("stack_default - ", stack_default);
  123. fmt.println("stack_literal - ", stack_literal);
  124. fmt.println("heap_one - ", heap_one^);
  125. fmt.println("heap_two - ", heap_two^);
  126. N :: 4;
  127. stack_array: [N]Vector3;
  128. heap_array := new([N]Vector3); defer free(heap_array);
  129. heap_slice := make([]Vector3, N); defer free(heap_slice);
  130. fmt.println("stack_array[1] - ", stack_array[1]);
  131. fmt.println("heap_array[1] - ", heap_array[1]);
  132. fmt.println("heap_slice[1] - ", heap_slice[1]);
  133. }
  134. }
  135. union_type :: proc() {
  136. {
  137. val: union{int, bool};
  138. val = 137;
  139. if i, ok := val.(int); ok {
  140. fmt.println(i);
  141. }
  142. val = true;
  143. fmt.println(val);
  144. val = nil;
  145. match v in val {
  146. case int: fmt.println("int", v);
  147. case bool: fmt.println("bool", v);
  148. case: fmt.println("nil");
  149. }
  150. }
  151. {
  152. // There is a duality between `any` and `union`
  153. // An `any` has a pointer to the data and allows for any type (open)
  154. // A `union` has as binary blob to store the data and allows only certain types (closed)
  155. // The following code is with `any` but has the same syntax
  156. val: any;
  157. val = 137;
  158. if i, ok := val.(int); ok {
  159. fmt.println(i);
  160. }
  161. val = true;
  162. fmt.println(val);
  163. val = nil;
  164. match v in val {
  165. case int: fmt.println("int", v);
  166. case bool: fmt.println("bool", v);
  167. case: fmt.println("nil");
  168. }
  169. }
  170. Vector3 :: struct {
  171. x, y, z: f32;
  172. };
  173. Quaternion :: struct {
  174. x, y, z: f32;
  175. w: f32 = 1;
  176. };
  177. // More realistic examples
  178. {
  179. // NOTE(bill): For the above basic examples, you may not have any
  180. // particular use for it. However, my main use for them is not for these
  181. // simple cases. My main use is for hierarchical types. Many prefer
  182. // subtyping, embedding the base data into the derived types. Below is
  183. // an example of this for a basic game Entity.
  184. Entity :: struct {
  185. id: u64;
  186. name: string;
  187. position: Vector3;
  188. orientation: Quaternion;
  189. derived: any;
  190. }
  191. Frog :: struct {
  192. using entity: Entity;
  193. jump_height: f32;
  194. }
  195. Monster :: struct {
  196. using entity: Entity;
  197. is_robot: bool;
  198. is_zombie: bool;
  199. }
  200. // See `parametric_polymorphism` procedure for details
  201. new_entity :: proc(T: type) -> ^Entity {
  202. t := new(T);
  203. t.derived = t^;
  204. return t;
  205. }
  206. entity := new_entity(Monster);
  207. match e in entity.derived {
  208. case Frog:
  209. fmt.println("Ribbit");
  210. case Monster:
  211. if e.is_robot do fmt.println("Robotic");
  212. if e.is_zombie do fmt.println("Grrrr!");
  213. }
  214. }
  215. {
  216. // NOTE(bill): A union can be used to achieve something similar. Instead
  217. // of embedding the base data into the derived types, the derived data
  218. // in embedded into the base type. Below is the same example of the
  219. // basic game Entity but using an union.
  220. Entity :: struct {
  221. id: u64;
  222. name: string;
  223. position: Vector3;
  224. orientation: Quaternion;
  225. derived: union {Frog, Monster};
  226. }
  227. Frog :: struct {
  228. using entity: ^Entity;
  229. jump_height: f32;
  230. }
  231. Monster :: struct {
  232. using entity: ^Entity;
  233. is_robot: bool;
  234. is_zombie: bool;
  235. }
  236. // See `parametric_polymorphism` procedure for details
  237. new_entity :: proc(T: type) -> ^Entity {
  238. t := new(Entity);
  239. t.derived = T{entity = t};
  240. return t;
  241. }
  242. entity := new_entity(Monster);
  243. match e in entity.derived {
  244. case Frog:
  245. fmt.println("Ribbit");
  246. case Monster:
  247. if e.is_robot do fmt.println("Robotic");
  248. if e.is_zombie do fmt.println("Grrrr!");
  249. }
  250. // NOTE(bill): As you can see, the usage code has not changed, only its
  251. // memory layout. Both approaches have their own advantages but they can
  252. // be used together to achieve different results. The subtyping approach
  253. // can allow for a greater control of the memory layout and memory
  254. // allocation, e.g. storing the derivatives together. However, this is
  255. // also its disadvantage. You must either preallocate arrays for each
  256. // derivative separation (which can be easily missed) or preallocate a
  257. // bunch of "raw" memory; determining the maximum size of the derived
  258. // types would require the aid of metaprogramming. Unions solve this
  259. // particular problem as the data is stored with the base data.
  260. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  261. // It should be noted that the union approach can have the same memory
  262. // layout as the any and with the same type restrictions by using a
  263. // pointer type for the derivatives.
  264. /*
  265. Entity :: struct {
  266. ...
  267. derived: union{^Frog, ^Monster};
  268. }
  269. Frog :: struct {
  270. using entity: Entity;
  271. ...
  272. }
  273. Monster :: struct {
  274. using entity: Entity;
  275. ...
  276. }
  277. new_entity :: proc(T: type) -> ^Entity {
  278. t := new(T);
  279. t.derived = t;
  280. return t;
  281. }
  282. */
  283. }
  284. }
  285. parametric_polymorphism :: proc() {
  286. print_value :: proc(value: $T) {
  287. fmt.printf("print_value: %T %v\n", value, value);
  288. }
  289. v1: int = 1;
  290. v2: f32 = 2.1;
  291. v3: f64 = 3.14;
  292. v4: string = "message";
  293. print_value(v1);
  294. print_value(v2);
  295. print_value(v3);
  296. print_value(v4);
  297. fmt.println();
  298. add :: proc(p, q: $T) -> T {
  299. x: T = p + q;
  300. return x;
  301. }
  302. a := add(3, 4);
  303. fmt.printf("a: %T = %v\n", a, a);
  304. b := add(3.2, 4.3);
  305. fmt.printf("b: %T = %v\n", b, b);
  306. // This is how `new` is implemented
  307. alloc_type :: proc(T: type) -> ^T {
  308. t := cast(^T)alloc(size_of(T), align_of(T));
  309. t^ = T{}; // Use default initialization value
  310. return t;
  311. }
  312. copy :: proc(dst, src: []$T) -> int {
  313. n := min(len(dst), len(src));
  314. if n > 0 {
  315. mem.copy(&dst[0], &src[0], n*size_of(T));
  316. }
  317. return n;
  318. }
  319. double_params :: proc(a: $A, b: $B) -> A {
  320. return a + A(b);
  321. }
  322. fmt.println(double_params(12, 1.345));
  323. { // Polymorphic Types and Type Specialization
  324. Table :: struct(Key, Value: type) {
  325. Slot :: struct {
  326. occupied: bool;
  327. hash: u32;
  328. key: Key;
  329. value: Value;
  330. }
  331. SIZE_MIN :: 32;
  332. count: int;
  333. allocator: Allocator;
  334. slots: []Slot;
  335. }
  336. // Only allow types that are specializations of a (polymorphic) slice
  337. make_slice :: proc(T: type/[]$E, len: int) -> T {
  338. return make(T, len);
  339. }
  340. // Only allow types that are specializations of `Table`
  341. allocate :: proc(table: ^$T/Table, capacity: int) {
  342. c := context;
  343. if table.allocator.procedure != nil do c.allocator = table.allocator;
  344. push_context c {
  345. table.slots = make_slice([]T.Slot, max(capacity, T.SIZE_MIN));
  346. }
  347. }
  348. expand :: proc(table: ^$T/Table) {
  349. c := context;
  350. if table.allocator.procedure != nil do c.allocator = table.allocator;
  351. push_context c {
  352. old_slots := table.slots;
  353. cap := max(2*cap(table.slots), T.SIZE_MIN);
  354. allocate(table, cap);
  355. for s in old_slots do if s.occupied {
  356. put(table, s.key, s.value);
  357. }
  358. free(old_slots);
  359. }
  360. }
  361. // Polymorphic determination of a polymorphic struct
  362. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  363. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  364. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  365. index := find_index(table, key, hash);
  366. if index < 0 {
  367. if f64(table.count) >= 0.75*f64(cap(table.slots)) {
  368. expand(table);
  369. }
  370. assert(table.count <= cap(table.slots));
  371. hash := get_hash(key);
  372. index = int(hash % u32(cap(table.slots)));
  373. for table.slots[index].occupied {
  374. if index += 1; index >= cap(table.slots) {
  375. index = 0;
  376. }
  377. }
  378. table.count += 1;
  379. }
  380. slot := &table.slots[index];
  381. slot.occupied = true;
  382. slot.hash = hash;
  383. slot.key = key;
  384. slot.value = value;
  385. }
  386. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  387. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  388. hash := get_hash(key);
  389. index := find_index(table, key, hash);
  390. if index < 0 {
  391. return Value{}, false;
  392. }
  393. return table.slots[index].value, true;
  394. }
  395. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  396. if cap(table.slots) <= 0 do return -1;
  397. index := int(hash % u32(cap(table.slots)));
  398. for table.slots[index].occupied {
  399. if table.slots[index].hash == hash {
  400. if table.slots[index].key == key {
  401. return index;
  402. }
  403. }
  404. if index += 1; index >= cap(table.slots) {
  405. index = 0;
  406. }
  407. }
  408. return -1;
  409. }
  410. get_hash :: proc(s: string) -> u32 { // fnv32a
  411. h: u32 = 0x811c9dc5;
  412. for i in 0..len(s) {
  413. h = (h ~ u32(s[i])) * 0x01000193;
  414. }
  415. return h;
  416. }
  417. table: Table(string, int);
  418. for i in 0..36 do put(&table, "Hellope", i);
  419. for i in 0..42 do put(&table, "World!", i);
  420. found, _ := find(&table, "Hellope");
  421. fmt.printf("`found` is %v\n", found);
  422. found, _ = find(&table, "World!");
  423. fmt.printf("`found` is %v\n", found);
  424. // I would not personally design a hash table like this in production
  425. // but this is a nice basic example
  426. // A better approach would either use a `u64` or equivalent for the key
  427. // and let the user specify the hashing function or make the user store
  428. // the hashing procedure with the table
  429. }
  430. }
  431. prefix_table := [...]string{
  432. "White",
  433. "Red",
  434. "Green",
  435. "Blue",
  436. "Octarine",
  437. "Black",
  438. };
  439. threading_example :: proc() {
  440. when ODIN_OS == "windows" {
  441. unordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
  442. __bounds_check_error_loc(loc, index, len(array));
  443. array[index] = array[len(array)-1];
  444. pop(array);
  445. }
  446. ordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
  447. __bounds_check_error_loc(loc, index, len(array));
  448. copy(array[index..], array[index+1..]);
  449. pop(array);
  450. }
  451. worker_proc :: proc(t: ^thread.Thread) -> int {
  452. for iteration in 1...5 {
  453. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  454. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  455. win32.sleep(1);
  456. }
  457. return 0;
  458. }
  459. threads := make([]^thread.Thread, 0, len(prefix_table));
  460. defer free(threads);
  461. for i in 0..len(prefix_table) {
  462. if t := thread.create(worker_proc); t != nil {
  463. t.init_context = context;
  464. t.use_init_context = true;
  465. t.user_index = len(threads);
  466. append(&threads, t);
  467. thread.start(t);
  468. }
  469. }
  470. for len(threads) > 0 {
  471. for i := 0; i < len(threads); {
  472. if t := threads[i]; thread.is_done(t) {
  473. fmt.printf("Thread %d is done\n", t.user_index);
  474. thread.destroy(t);
  475. ordered_remove(&threads, i);
  476. } else {
  477. i += 1;
  478. }
  479. }
  480. }
  481. }
  482. }
  483. main :: proc() {
  484. when false {
  485. if true {
  486. fmt.println("\ngeneral_stuff:"); general_stuff();
  487. fmt.println("\nnested_struct_declarations:"); nested_struct_declarations();
  488. fmt.println("\ndefault_struct_values:"); default_struct_values();
  489. fmt.println("\nunion_type:"); union_type();
  490. fmt.println("\nparametric_polymorphism:"); parametric_polymorphism();
  491. }
  492. fmt.println("\nthreading_example:"); threading_example();
  493. }
  494. }