demo008.odin 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. import "core:fmt.odin"
  2. import "core:strconv.odin"
  3. import "core:mem.odin"
  4. import "core:bits.odin"
  5. import "core:hash.odin"
  6. import "core:math.odin"
  7. import "core:math/rand.odin"
  8. import "core:os.odin"
  9. import "core:raw.odin"
  10. import "core:sort.odin"
  11. import "core:strings.odin"
  12. import "core:types.odin"
  13. import "core:utf16.odin"
  14. import "core:utf8.odin"
  15. // File scope `when` statements
  16. when ODIN_OS == "windows" {
  17. import "core:atomics.odin"
  18. import "core:thread.odin"
  19. import win32 "core:sys/windows.odin"
  20. }
  21. @(link_name="general_stuff")
  22. general_stuff :: proc() {
  23. fmt.println("# general_stuff");
  24. { // `do` for inline statements 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. _ = (^f32)(ptr);
  41. // ^f32(ptr) == ^(f32(ptr))
  42. _ = cast(^f32)ptr;
  43. _ = (^f32)(ptr)^;
  44. _ = (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(f);
  60. fmt.println(x, b);
  61. fmt.println(expand_to_tuple(f));
  62. }
  63. {
  64. // .. half-closed range
  65. // .. open range
  66. for in 0..2 {} // 0, 1
  67. for in 0..2 {} // 0, 1, 2
  68. }
  69. { // Multiple sized booleans
  70. x0: bool; // default
  71. x1: b8 = true;
  72. x2: b16 = false;
  73. x3: b32 = true;
  74. x4: b64 = false;
  75. fmt.printf("x1: %T = %v;\n", x1, x1);
  76. fmt.printf("x2: %T = %v;\n", x2, x2);
  77. fmt.printf("x3: %T = %v;\n", x3, x3);
  78. fmt.printf("x4: %T = %v;\n", x4, x4);
  79. // Having specific sized booleans is very useful when dealing with foreign code
  80. // and to enforce specific alignment for a boolean, especially within a struct
  81. }
  82. { // `distinct` types
  83. // Originally, all type declarations would create a distinct type unless #type_alias was present.
  84. // Now the behaviour has been reversed. All type declarations create a type alias unless `distinct` is present.
  85. // If the type expression is `struct`, `union`, `enum`, or `proc`, the types will always been distinct.
  86. Int32 :: i32;
  87. #assert(Int32 == i32);
  88. My_Int32 :: distinct i32;
  89. #assert(My_Int32 != i32);
  90. My_Struct :: struct{x: int};
  91. #assert(My_Struct != struct{x: int});
  92. }
  93. }
  94. default_struct_values :: proc() {
  95. fmt.println("# default_struct_values");
  96. {
  97. Vector3 :: struct {
  98. x: f32,
  99. y: f32,
  100. z: f32,
  101. }
  102. v: Vector3;
  103. fmt.println(v);
  104. }
  105. {
  106. // Default values must be constants
  107. Vector3 :: struct {
  108. x: f32 = 1,
  109. y: f32 = 4,
  110. z: f32 = 9,
  111. }
  112. v: Vector3;
  113. fmt.println(v);
  114. v = Vector3{};
  115. fmt.println(v);
  116. // Uses the same semantics as a default values in a procedure
  117. v = Vector3{137};
  118. fmt.println(v);
  119. v = Vector3{z = 137};
  120. fmt.println(v);
  121. }
  122. {
  123. Vector3 :: struct {
  124. x := 1.0,
  125. y := 4.0,
  126. z := 9.0,
  127. }
  128. stack_default: Vector3;
  129. stack_literal := Vector3{};
  130. heap_one := new(Vector3); defer free(heap_one);
  131. heap_two := new_clone(Vector3{}); defer free(heap_two);
  132. fmt.println("stack_default - ", stack_default);
  133. fmt.println("stack_literal - ", stack_literal);
  134. fmt.println("heap_one - ", heap_one^);
  135. fmt.println("heap_two - ", heap_two^);
  136. N :: 4;
  137. stack_array: [N]Vector3;
  138. heap_array := new([N]Vector3); defer free(heap_array);
  139. heap_slice := make([]Vector3, N); defer free(heap_slice);
  140. fmt.println("stack_array[1] - ", stack_array[1]);
  141. fmt.println("heap_array[1] - ", heap_array[1]);
  142. fmt.println("heap_slice[1] - ", heap_slice[1]);
  143. }
  144. }
  145. union_type :: proc() {
  146. fmt.println("\n# union_type");
  147. {
  148. val: union{int, bool};
  149. val = 137;
  150. if i, ok := val.(int); ok {
  151. fmt.println(i);
  152. }
  153. val = true;
  154. fmt.println(val);
  155. val = nil;
  156. switch v in val {
  157. case int: fmt.println("int", v);
  158. case bool: fmt.println("bool", v);
  159. case: fmt.println("nil");
  160. }
  161. }
  162. {
  163. // There is a duality between `any` and `union`
  164. // An `any` has a pointer to the data and allows for any type (open)
  165. // A `union` has as binary blob to store the data and allows only certain types (closed)
  166. // The following code is with `any` but has the same syntax
  167. val: any;
  168. val = 137;
  169. if i, ok := val.(int); ok {
  170. fmt.println(i);
  171. }
  172. val = true;
  173. fmt.println(val);
  174. val = nil;
  175. switch v in val {
  176. case int: fmt.println("int", v);
  177. case bool: fmt.println("bool", v);
  178. case: fmt.println("nil");
  179. }
  180. }
  181. Vector3 :: struct {x, y, z: f32};
  182. Quaternion :: struct {x, y, z: f32, w: f32 = 1};
  183. // More realistic examples
  184. {
  185. // NOTE(bill): For the above basic examples, you may not have any
  186. // particular use for it. However, my main use for them is not for these
  187. // simple cases. My main use is for hierarchical types. Many prefer
  188. // subtyping, embedding the base data into the derived types. Below is
  189. // an example of this for a basic game Entity.
  190. Entity :: struct {
  191. id: u64,
  192. name: string,
  193. position: Vector3,
  194. orientation: Quaternion,
  195. derived: any,
  196. }
  197. Frog :: struct {
  198. using entity: Entity,
  199. jump_height: f32,
  200. }
  201. Monster :: struct {
  202. using entity: Entity,
  203. is_robot: bool,
  204. is_zombie: bool,
  205. }
  206. // See `parametric_polymorphism` procedure for details
  207. new_entity :: proc(T: type) -> ^Entity {
  208. t := new(T);
  209. t.derived = t^;
  210. return t;
  211. }
  212. entity := new_entity(Monster);
  213. switch e in entity.derived {
  214. case Frog:
  215. fmt.println("Ribbit");
  216. case Monster:
  217. if e.is_robot do fmt.println("Robotic");
  218. if e.is_zombie do fmt.println("Grrrr!");
  219. }
  220. }
  221. {
  222. // NOTE(bill): A union can be used to achieve something similar. Instead
  223. // of embedding the base data into the derived types, the derived data
  224. // in embedded into the base type. Below is the same example of the
  225. // basic game Entity but using an union.
  226. Entity :: struct {
  227. id: u64,
  228. name: string,
  229. position: Vector3,
  230. orientation: Quaternion,
  231. derived: union {Frog, Monster},
  232. }
  233. Frog :: struct {
  234. using entity: ^Entity,
  235. jump_height: f32,
  236. }
  237. Monster :: struct {
  238. using entity: ^Entity,
  239. is_robot: bool,
  240. is_zombie: bool,
  241. }
  242. // See `parametric_polymorphism` procedure for details
  243. new_entity :: proc(T: type) -> ^Entity {
  244. t := new(Entity);
  245. t.derived = T{entity = t};
  246. return t;
  247. }
  248. entity := new_entity(Monster);
  249. switch e in entity.derived {
  250. case Frog:
  251. fmt.println("Ribbit");
  252. case Monster:
  253. if e.is_robot do fmt.println("Robotic");
  254. if e.is_zombie do fmt.println("Grrrr!");
  255. }
  256. // NOTE(bill): As you can see, the usage code has not changed, only its
  257. // memory layout. Both approaches have their own advantages but they can
  258. // be used together to achieve different results. The subtyping approach
  259. // can allow for a greater control of the memory layout and memory
  260. // allocation, e.g. storing the derivatives together. However, this is
  261. // also its disadvantage. You must either preallocate arrays for each
  262. // derivative separation (which can be easily missed) or preallocate a
  263. // bunch of "raw" memory; determining the maximum size of the derived
  264. // types would require the aid of metaprogramming. Unions solve this
  265. // particular problem as the data is stored with the base data.
  266. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  267. // It should be noted that the union approach can have the same memory
  268. // layout as the any and with the same type restrictions by using a
  269. // pointer type for the derivatives.
  270. /*
  271. Entity :: struct {
  272. ..
  273. derived: union{^Frog, ^Monster},
  274. }
  275. Frog :: struct {
  276. using entity: Entity,
  277. ..
  278. }
  279. Monster :: struct {
  280. using entity: Entity,
  281. ..
  282. }
  283. new_entity :: proc(T: type) -> ^Entity {
  284. t := new(T);
  285. t.derived = t;
  286. return t;
  287. }
  288. */
  289. }
  290. }
  291. parametric_polymorphism :: proc() {
  292. fmt.println("# parametric_polymorphism");
  293. print_value :: proc(value: $T) {
  294. fmt.printf("print_value: %T %v\n", value, value);
  295. }
  296. v1: int = 1;
  297. v2: f32 = 2.1;
  298. v3: f64 = 3.14;
  299. v4: string = "message";
  300. print_value(v1);
  301. print_value(v2);
  302. print_value(v3);
  303. print_value(v4);
  304. fmt.println();
  305. add :: proc(p, q: $T) -> T {
  306. x: T = p + q;
  307. return x;
  308. }
  309. a := add(3, 4);
  310. fmt.printf("a: %T = %v\n", a, a);
  311. b := add(3.2, 4.3);
  312. fmt.printf("b: %T = %v\n", b, b);
  313. // This is how `new` is implemented
  314. alloc_type :: proc(T: type) -> ^T {
  315. t := cast(^T)alloc(size_of(T), align_of(T));
  316. t^ = T{}; // Use default initialization value
  317. return t;
  318. }
  319. copy_slice :: proc(dst, src: []$T) -> int {
  320. return mem.copy(&dst[0], &src[0], n*size_of(T));
  321. }
  322. double_params :: proc(a: $A, b: $B) -> A {
  323. return a + A(b);
  324. }
  325. fmt.println(double_params(12, 1.345));
  326. { // Polymorphic Types and Type Specialization
  327. Table_Slot :: struct(Key, Value: type) {
  328. occupied: bool,
  329. hash: u32,
  330. key: Key,
  331. value: Value,
  332. }
  333. TABLE_SIZE_MIN :: 32;
  334. Table :: struct(Key, Value: type) {
  335. count: int,
  336. allocator: Allocator,
  337. slots: []Table_Slot(Key, Value),
  338. }
  339. // Only allow types that are specializations of a (polymorphic) slice
  340. make_slice :: proc(T: type/[]$E, len: int) -> T {
  341. return make(T, len);
  342. }
  343. // Only allow types that are specializations of `Table`
  344. allocate :: proc(table: ^$T/Table, capacity: int) {
  345. c := context;
  346. if table.allocator.procedure != nil do c.allocator = table.allocator;
  347. context <- c {
  348. table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
  349. }
  350. }
  351. expand :: proc(table: ^$T/Table) {
  352. c := context;
  353. if table.allocator.procedure != nil do c.allocator = table.allocator;
  354. context <- c {
  355. old_slots := table.slots;
  356. cap := max(2*len(table.slots), TABLE_SIZE_MIN);
  357. allocate(table, cap);
  358. for s in old_slots do if s.occupied {
  359. put(table, s.key, s.value);
  360. }
  361. free(old_slots);
  362. }
  363. }
  364. // Polymorphic determination of a polymorphic struct
  365. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  366. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  367. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  368. index := find_index(table, key, hash);
  369. if index < 0 {
  370. if f64(table.count) >= 0.75*f64(len(table.slots)) {
  371. expand(table);
  372. }
  373. assert(table.count <= len(table.slots));
  374. hash := get_hash(key);
  375. index = int(hash % u32(len(table.slots)));
  376. for table.slots[index].occupied {
  377. if index += 1; index >= len(table.slots) {
  378. index = 0;
  379. }
  380. }
  381. table.count += 1;
  382. }
  383. slot := &table.slots[index];
  384. slot.occupied = true;
  385. slot.hash = hash;
  386. slot.key = key;
  387. slot.value = value;
  388. }
  389. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  390. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  391. hash := get_hash(key);
  392. index := find_index(table, key, hash);
  393. if index < 0 {
  394. return Value{}, false;
  395. }
  396. return table.slots[index].value, true;
  397. }
  398. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  399. if len(table.slots) <= 0 do return -1;
  400. index := int(hash % u32(len(table.slots)));
  401. for table.slots[index].occupied {
  402. if table.slots[index].hash == hash {
  403. if table.slots[index].key == key {
  404. return index;
  405. }
  406. }
  407. if index += 1; index >= len(table.slots) {
  408. index = 0;
  409. }
  410. }
  411. return -1;
  412. }
  413. get_hash :: proc(s: string) -> u32 { // fnv32a
  414. h: u32 = 0x811c9dc5;
  415. for i in 0..len(s) {
  416. h = (h ~ u32(s[i])) * 0x01000193;
  417. }
  418. return h;
  419. }
  420. table: Table(string, int);
  421. for i in 0..36 do put(&table, "Hellope", i);
  422. for i in 0..42 do put(&table, "World!", i);
  423. found, _ := find(&table, "Hellope");
  424. fmt.printf("`found` is %v\n", found);
  425. found, _ = find(&table, "World!");
  426. fmt.printf("`found` is %v\n", found);
  427. // I would not personally design a hash table like this in production
  428. // but this is a nice basic example
  429. // A better approach would either use a `u64` or equivalent for the key
  430. // and let the user specify the hashing function or make the user store
  431. // the hashing procedure with the table
  432. }
  433. }
  434. prefix_table := [?]string{
  435. "White",
  436. "Red",
  437. "Green",
  438. "Blue",
  439. "Octarine",
  440. "Black",
  441. };
  442. threading_example :: proc() {
  443. when ODIN_OS == "windows" {
  444. fmt.println("# threading_example");
  445. unordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
  446. __bounds_check_error_loc(loc, index, len(array));
  447. array[index] = array[len(array)-1];
  448. pop(array);
  449. }
  450. ordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
  451. __bounds_check_error_loc(loc, index, len(array));
  452. copy(array[index..], array[index+1..]);
  453. pop(array);
  454. }
  455. worker_proc :: proc(t: ^thread.Thread) -> int {
  456. for iteration in 1..5 {
  457. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  458. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  459. // win32.sleep(1);
  460. }
  461. return 0;
  462. }
  463. threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
  464. defer free(threads);
  465. for in prefix_table {
  466. if t := thread.create(worker_proc); t != nil {
  467. t.init_context = context;
  468. t.use_init_context = true;
  469. t.user_index = len(threads);
  470. append(&threads, t);
  471. thread.start(t);
  472. }
  473. }
  474. for len(threads) > 0 {
  475. for i := 0; i < len(threads); /**/ {
  476. if t := threads[i]; thread.is_done(t) {
  477. fmt.printf("Thread %d is done\n", t.user_index);
  478. thread.destroy(t);
  479. ordered_remove(&threads, i);
  480. } else {
  481. i += 1;
  482. }
  483. }
  484. }
  485. }
  486. }
  487. array_programming :: proc() {
  488. fmt.println("# array_programming");
  489. {
  490. a := [3]f32{1, 2, 3};
  491. b := [3]f32{5, 6, 7};
  492. c := a * b;
  493. d := a + b;
  494. e := 1 + (c - d) / 2;
  495. fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
  496. }
  497. {
  498. a := [3]f32{1, 2, 3};
  499. b := swizzle(a, 2, 1, 0);
  500. assert(b == [3]f32{3, 2, 1});
  501. c := swizzle(a, 0, 0);
  502. assert(c == [2]f32{1, 1});
  503. assert(c == 1);
  504. }
  505. {
  506. Vector3 :: distinct [3]f32;
  507. a := Vector3{1, 2, 3};
  508. b := Vector3{5, 6, 7};
  509. c := (a * b)/2 + 1;
  510. d := c.x + c.y + c.z;
  511. fmt.printf("%.1f\n", d); // 22.0
  512. cross :: proc(a, b: Vector3) -> Vector3 {
  513. i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
  514. j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
  515. return i - j;
  516. }
  517. blah :: proc(a: Vector3) -> f32 {
  518. return a.x + a.y + a.z;
  519. }
  520. x := cross(a, b);
  521. fmt.println(x);
  522. fmt.println(blah(x));
  523. }
  524. }
  525. using println in import "core:fmt.odin"
  526. using_in :: proc() {
  527. fmt.println("# using in");
  528. using print in fmt;
  529. println("Hellope1");
  530. print("Hellope2\n");
  531. Foo :: struct {
  532. x, y: int,
  533. b: bool,
  534. }
  535. f: Foo;
  536. f.x, f.y = 123, 321;
  537. println(f);
  538. using x, y in f;
  539. x, y = 456, 654;
  540. println(f);
  541. }
  542. named_proc_return_parameters :: proc() {
  543. fmt.println("# named proc return parameters");
  544. foo0 :: proc() -> int {
  545. return 123;
  546. }
  547. foo1 :: proc() -> (a: int) {
  548. a = 123;
  549. return;
  550. }
  551. foo2 :: proc() -> (a, b: int) {
  552. // Named return values act like variables within the scope
  553. a = 321;
  554. b = 567;
  555. return b, a;
  556. }
  557. fmt.println("foo0 =", foo0()); // 123
  558. fmt.println("foo1 =", foo1()); // 123
  559. fmt.println("foo2 =", foo2()); // 567 321
  560. }
  561. enum_export :: proc() {
  562. fmt.println("# enum #export");
  563. Foo :: enum #export {A, B, C};
  564. f0 := A;
  565. f1 := B;
  566. f2 := C;
  567. fmt.println(f0, f1, f2);
  568. }
  569. explicit_procedure_overloading :: proc() {
  570. fmt.println("# explicit procedure overloading");
  571. add_ints :: proc(a, b: int) -> int {
  572. x := a + b;
  573. fmt.println("add_ints", x);
  574. return x;
  575. }
  576. add_floats :: proc(a, b: f32) -> f32 {
  577. x := a + b;
  578. fmt.println("add_floats", x);
  579. return x;
  580. }
  581. add_numbers :: proc(a: int, b: f32, c: u8) -> int {
  582. x := int(a) + int(b) + int(c);
  583. fmt.println("add_numbers", x);
  584. return x;
  585. }
  586. add :: proc[add_ints, add_floats, add_numbers];
  587. add(int(1), int(2));
  588. add(f32(1), f32(2));
  589. add(int(1), f32(2), u8(3));
  590. add(1, 2); // untyped ints coerce to int tighter than f32
  591. add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
  592. add(1, 2, 3); // three parameters
  593. // Ambiguous answers
  594. // add(1.0, 2);
  595. // add(1, 2.0);
  596. }
  597. complete_switch :: proc() {
  598. fmt.println("# complete_switch");
  599. { // enum
  600. Foo :: enum #export {
  601. A,
  602. B,
  603. C,
  604. D,
  605. }
  606. b := Foo.B;
  607. f := Foo.A;
  608. #complete switch f {
  609. case A: fmt.println("A");
  610. case B: fmt.println("B");
  611. case C: fmt.println("C");
  612. case D: fmt.println("D");
  613. case: fmt.println("?");
  614. }
  615. }
  616. { // union
  617. Foo :: union {int, bool};
  618. f: Foo = 123;
  619. #complete switch in f {
  620. case int: fmt.println("int");
  621. case bool: fmt.println("bool");
  622. case:
  623. }
  624. }
  625. }
  626. main :: proc() {
  627. when true {
  628. general_stuff();
  629. default_struct_values();
  630. union_type();
  631. parametric_polymorphism();
  632. threading_example();
  633. array_programming();
  634. using_in();
  635. named_proc_return_parameters();
  636. enum_export();
  637. explicit_procedure_overloading();
  638. complete_switch();
  639. }
  640. }