2019-04-04

How to make 2D Game that fit multiple resolution in Unity

There's a lot of screen resolution out there, how to make our UI objects (canvas) fit all resolution? One of the easiest solution is to envelope the canvas with borders, here's how you do it:

  1. Create a canvas object
  2. Set the Canvas Scaler to Scale with Screen Size
  3. Set the Reference Resolution to for example: 1080 x 800
  4. Set the Screen Match Mode to Match with Or Height
  5. Set the match to 1 if your current screen width is smaller, 0 if height is smaller
  6. Create an Image as background inside the Canvas
  7. Add Aspect Ratio Fitter script
  8. Set the Aspect Mode to Fit in Parent (so the UI anchor can be anywhere)
  9. Set the Aspect Ratio to 1080/800 = 1.35

Now you can add any UI elements inside the background Image.

Last piece is add this piece of script on the canvas' Awake method:

var canvasScaler = GetComponent<CanvasScaler>();
var ratio = Screen.height / (float) Screen.width;
var rr = canvasScaler.referenceResolution;
canvasScaler.matchWidthOrHeight = (ratio < rr.x / rr.y) ? 1 : 0;

This would ensure that the scaling/aspect ratio works correctly across any screen resolutions. There would be border on top-bottom if screen is taller than aspect ratio, and there would be border on left-right if screen is wider than aspect ratio.



2019-03-18

New Promising Programming Language: V

Found out that there's a new programming language called V (2019). At glance it's like combination of Go and Rust. Seems really promising, has really fast compilation speed.
  • No global state
  • No null
  • No undefined values
  • Option types
  • Generics
  • Immutability by default
  • Partially pure functions
  • Hot Code Reload
  • REPL
  • C/C++ converter
  • Native cross platform UI library
  • Run Everywhere
But no compiler yet (but there's already software built with it), wait until May 2019. I hope it hype :3
Here's a bit negative review about V.



Pony (2012) also share similar belief (like Rust and Erlang/Elixir combined):
  • Pony is type safe
  • Pony is memory safe
  • Exception-Safe
  • Data-race Free
  • Deadlock-Free
  • Native Code
  • Compatible with C
  • Garbage Collected
  • and many more
Zig (2017) hopefully will succeed C
  • Integration with C without binding, can compile C
  • Cross compile
  • Generics
  • Error handling and Stacktrace by default
  • Compile-time reflection and compile-time code execution
  • Simple build system
Crystal (2014), not giving similar spirit, but hey it's faster Ruby :3

And don't forget this interesting fib benchmark.

2019-02-01

Free Digital Painting Software

What are our options?
Raster
Vector
  • Inkscape, supports: Windows, Mac, Linux
  • Gravit, supports: Windows, Mac, Linux, Web
  • Synfig, supports: Windows, Mac, Linux
  • Karbon, supports: Windows, Mac, Linux, BSD
  • Vectr, supports: Web
Misc Tools
Bonus: Video Editing
Bonus: 3D Anime Character Creator
Bonus: Audio Editing

Since I don't like GIMP, i wont put it here. For animating check this very useful site

An image from Critical Reikan for more reference:

No photo description available.

2019-01-10

CockroachDB 2.1.3 Benchmark

Redoing the old benchmark on my office's Mac, I have installed cockroachdb on Mac using
brew install cockroach

Start the server
cockroach start --insecure --listen-addr=localhost  

Create the database
cockroach sql --insecure
CREATE DATABASE test3;
GRANT ALL ON DATABASE test3 TO test3;
 

And do the benchmark:

alias time='/usr/local/bin/gtime -f "\nCPU: %Us\tReal: %es\tRAM: %MKB"'


time go run cockroach.go lib.go

INSERT: 1.653080201s (0.17 ms/op)
UPDATE: 1.947936008s (0.19 ms/op)

SELECT: 1m44.425784366s (1.60 ms/op: 65096)


CPU: 43.20s Real: 108.71s RAM: 89072KB

The benchmark performed on i7-4770HQ, 16GB RAM, SSD harddisk, with OSX Mojave 10.14.2 under Go 1.11. Conclusion: the result is really impressive :3 Great job CockroachDB Team.

2018-11-01

Hex to C# Colors Converter

This is C# version for https://openglcolor.mpeters.me that I've been using a lot lately. Paste your colors one per line using RRGGBB or RGB format, with or without hash/pound sign (#).


The result will appear here (Ctrl/Cmd+A, Ctrl/Cmd+C to copy paste):

Techempower Framework Benchmark Round 17

The new result is up, as usual the most important thing is database update benchmark


Top rankers for this time is Rust, Java, C, C#, Go, and C++, the rest has some error or ranked lower than that. Here's some result of multiple queries benchmark:


2018-09-13

String Associative Array Benchmark 2

Redoing old string associative benchmark (3 years ago) but now on Macbook Pro MJLQ2, here's the result:

alias time='/usr/local/bin/gtime -f "\nCPU: %Us\tReal: %es\tRAM: %MKB"'

$ java -version
java version "1.8.0_172"
Java(TM) SE Runtime Environment (build 1.8.0_172-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.172-b11, mixed mode)
$ time javac hash_map.java
CPU: 1.22s Real: 0.60s RAM: 67540KB
$ time java hash_map
6009354 6009348 611297
36186112 159701682 23370001
CPU: 274.83s Real: 53.47s RAM: 3946268KB

$ go version
go version go1.10.2 darwin/amd64

$ go build map.go
CPU: 0.09s Real: 0.14s RAM: 16160KB
$ time ./map
6009354 6009348 611297
36186112 159701682 23370001
CPU: 29.55s Real: 22.12s RAM: 2425316KB

$ dart --version
Dart VM version: 2.0.0 (Fri Aug 3 10:53:23 2018 +0200) on "macos_x64"

$ time dart ./map.dart
6009354 6009348 611297
36186112 159701682 23370001
CPU: 59.29s Real: 60.08s RAM: 1763952KB

$ node --version
v10.10.0
$ time node object.js # ERROR: TOO SLOW
^CCommand terminated by signal 2 
CPU: 855.68s Real: 763.40s RAM: 1517576KB

$ php -version
PHP 7.1.16 (cli) (built: Mar 31 2018 02:59:59) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
$ time php -d memory_limit=4G assoc.php
6009354 6009348 611297
36186112 159701682 23370001
CPU: 26.76s Real: 27.89s RAM: 1297824KB

$ mcs --version
Mono C# compiler version 5.10.1.0
$ time mcs dictionary.cs
CPU: 0.21s Real: 0.32s RAM: 42564KB
$ time mono ./dictionary.exe
6009354 6009348 611297
36186112 159701682 23370001
CPU: 33.69s Real: 33.64s RAM: 1609576KB

$ ruby --version
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin17]
$ time ruby hash.rb
time ruby hash.rb
6009354 6009348 611297
36186112 159701682 23370001
CPU: 100.57s Real: 103.63s RAM: 3012148KB

$ jruby --version
jruby 9.2.0.0 (2.5.0) 2018-05-24 81156a8 Java HotSpot(TM) 64-Bit Server VM 25.172-b11 on 1.8.0_172-b11 +jit [darwin-x86_64]
$ time jruby hash.rb # ERROR: TOO MEMORY CONSUMING
Error: Your application used more memory than the automatic cap of 3641MB.
Specify -J-Xmx####M to increase it (#### = cap size in MB).
Specify -w for full java.lang.OutOfMemoryError: GC overhead limit exceeded stack trace
Command exited with non-zero status 1
CPU: 1616.55s Real: 257.91s RAM: 4439172KB

$ python3 --versionPython 3.7.0
$ time python3 dictionary.py
6009354 6009348 611297
36186112 159701682 23370001
CPU: 117.59s Real: 121.63s RAM: 3923812KB

$ pypy --version
Python 2.7.13 (ab0b9caf307db6592905a80b8faffd69b39005b8, Jun 24 2018, 08:19:27)[PyPy 6.0.0 with GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.2)]
$ time pypy dictionary.py
(6009354, 6009348, 611297)
(36186112, 159701682, 23370001)
CPU: 28.82s Real: 31.55s RAM: 3993764KB

$ lua -v
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
$ time lua table.lua
6009354 6009348 611297
36186112 159701682 23370001
CPU: 89.05s Real: 91.35s RAM: 2523332KB

$ luajit -v
LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/
$ time luajit table.lua # ERROR: CANNOT ALLOC MEMORY
PANIC: unprotected error in call to Lua API (not enough memory)
Command exited with non-zero status 1CPU: 30.57s Real: 31.56s RAM: 1132648KB

This time PHP7 became the best performing programming language implementation, also the least memory consumption (I'm amazed with what they did in version 7). And as usual LuaJIT limited to 1-2GB so they failed, NodeJS too slow, and I'm unwilling to wait more than 10 minutes, so I terminate the app, JRuby hogging RAM too much.


LanguageVersionCompile DurationCompile RAMRuntime DurationRuntime RAM2015's Duration2015's RAMDuration ImprovRAM Improv
C#5.10.1.00.3242,56433.641,609,57640.981,690,22417.91%4.77%
Dart2.0.060.081,763,952133.352,538,22054.95%30.50%
Go1.10.20.1416,16022.122,425,31624.102,748,7848.22%11.77%
Java1.8.0_1720.6067,54053.473,946,268103.544,119,38848.36%4.20%
Lua5.3.591.352,523,332101.733,079,33610.20%18.06%
PHP7.1.1627.891,297,824failedfailed
Pypy6.0.031.553,993,76479.874,034,95660.50%1.02%
Python33.7.0121.633,923,812157.714,335,56822.88%9.50%
Ruby2.3.7p456103.633,012,148107.913,031,8723.97%0.65%

2018-07-01

Introduction to gitflow

GitFlow is one way to manage git repository, where master branch forked into develop branch, and each person will create their own branch when they develop a feature, merged back to develop branch. See this video for the detailed explanation. Also this cheatsheet for the comparison between git-flow command and normal git command.

When you are using Gitflow without git-flow program, you will have to type this long git commands:


Or you can use Git GUIs.

2018-06-12

Costajob HTTP Benchmark

Learning about Pony, a new (at least for me) programming language that designed to be elixir-python-golang like (imho), got me to this page:


It's interesting to see the memory usage of those language-framework, also Crystal, despite inability to utilize multicore still could perform as good as Golang's default muxer (which is not the best).

2018-06-01

Hybrid ECS in Unity

Previously we tried the Pure ECS to create a Pong animation, this article will show example snippet of how to use Hybrid ECS. With hybrid ECS we can use normal game object to act as the entity. What you need to do is:
  • create a prefab, 
  • drag-and-drop your custom Component script (MonoBehavior, not a struct that inherited from IComponentData, so must be exactly one class per file) to the prefab, 
  • then add the GameObjectEntity script to the prefab. 
  • Next, you can instantiate the prefab as usual. 
  • Use a class inherited from ComponentSystem to manipulate the values of those components.
To create a System that uses those GameObjectEntity, you can use injected property or method:

class SomeSystem1 : ComponentSystem {
  ComponentGroup group;
  protected override void OnUpdate() {
    if(group == null || group.CalculateLength() < 1) {
      group = GetComponentGroup(typeof(Direction2D), typeof(Coord2D), typeof(Health)); // must be cached as data member    }
    var dirs = group.GetComponentArray<Coord2D>(); 
    // do something with it, 
    // note that if you want to use Job/Schedule, 
    // you must use [Inject]
  }
}

class SomeSystem2 : ComponentSystem {
  struct Data {

    public GameObjectArray gameObjects;
    public ComponentArray<Position2D> Positions; 
    public ComponentArray<Heading2D> Headings;
    public ComponentArray<Health> Healths;
  }
  [Inject] Data data;
  protected override void OnUpdate() {
    // do something with data.*
    // inherit from JobComponentSystem 
    // if you want to use Job/Schedule
    // also read this
  }
}

One of the biggest benefit of using Hybrid ECS than Pure ECS is that you don't have to wait/implement missing component/system (Animation for example) that not yet implemented by Unity to make stuff works correctly.

This is the example the difference between creating hybrid ECS way and standard/normal way (btw this is not using a correct composition of component, just minimal conversion between those two):


Difference between prefab in Hybrid ECS way and in normal way:


Example code for the system:


For more info, see this slide Unity ECS Intro

Update 2019-05-07: see this video for better understanding how to use DOTS (the ECS new name on unity 2019)

2018-05-10

Rendering Sprite using ECS and JobSystem in Unity

Old style Unity programming, known for slow performance when number of GameObjects grows, that can be solved by managing the update call ourself. Object pooling known to be used to minimize GC overhead (that can cause stutter). ECS (Entity Component System), is a architectural pattern, known best for simplifying a complex system, that popularized and mostly used in Games. In ECS, composition are preferred than inheritance (like Golang :3 yay).
  • Component is a structure that consist of one or more computable element, for example: Position, Sprite, Velocity, Input, AI, etc. 
  • Entity is collection of Components, for example: 
    • Player (consist of Position, Velocity, Sprite, Input), 
    • Enemy (consist of Position, Velocity, Sprite, AI), 
    • Tree/Pillar (consist of Position, Sprite), etc.
  • System is a function that process components in a batch, for example: 
    • Movement (uses Position, Velocity),
    • Render (uses Position, Sprite),
    • PlayerControl (uses Player.Velocity, Input)
    • Bot (uses Enemy.Velocity, Player.Position)
In Unity, the latest stable version (2018.1.0, 2018-05-02) at the time of this article written have built in support for ECS. The benefit of using built-in ECS is the new Job System (utilizing multi-core and cache-friendly, automatic scheduling, prevent race condition) and Burst Compiler that able to utilize SIMD. There's another alternative for ECS that known long time ago if you don't want to use Unity's, such as Entitas framework (which has best documentation among others), Artemis (C# version), Leopotam, and EgoECS.

To use the Unity ECS, there's two method that can be used:
  • Hybrid, to create hybrid ECS, all you need to do is add an EntityGameObject script on the prefab.
  • Pure, you must create an entity manually.
To start any type of ECS project, all you must do is edit Packages/manifest.json, update to something like this:

{
    "dependencies": {
        "com.unity.incrementalcompiler": "0.0.38", 
        "com.unity.entities": "0.0.12-preview.1"
    }, 
    "registry": "https://staging-packages.unity.com", 
    "testables": [
        "com.unity.collections", 
        "com.unity.entities", 
        "com.unity.jobs"
    ]
}

Then you must go to Edit > Project Settings > Player, Other Settings, Scripting Runtime Version to 4.x. Also it's better to use il2cpp than Mono for the scripting backend.
To start a pure ECS, first you must decompose all Component to structs, for example:


Then start create the bootstrap code (one that spawns the entity):


Then create a system to manipulate the values:


Add the GameBootstrap to the main camera or the canvas (don't forget to add the canvas). Set these values on your Unity:
  • Main camera > projection to "perspective"
  • Canvas 
    • Canvas Scaler reference resolution to 800 x 600 (or whatever you like)
    • Screen match ratio to 0.5
    • X rotation to 90, render mode to "screen space - camera"
    • Drag your main camera to the "Render Camera"
  • Create a directory "Resources/" inside "Assets/" and add a ball.png image with transparency, in my case I used 600x600 image.
  • Install or git clone SpriteInstanceRenderer component to render the sprite using ECS. This component requires TransformMatrix, Heading2D and Position/Position2D component to render the sprite.
That's it, now you have created a simple pong animation with ECS, it would show something like this (I add a text on each corner to make sure the coordinate system is right):



To debug the entities, since it would not shown on the Hierarchy panel, click the Window > Entity Debugger. It would show something like this:


When you click one of the entity, you watch the current component values on Inspector panel, like this:


An the core utilization on the profiler:



2018-03-07

Cross Platform Mobile App Development

There's some new alternative for near native performance out there today:

  1. Flutter Beta1 (Dart),
    pros: developed by Google, hot reload
    cons: the Dart programming language have a bit awkward syntax, standard library a bit incomplete compared to other programming languages
  2. NativeScript Vue or Vue-Native (Javascript)
    pros: no angular :3, Javascript!
    cons: Javascript! very early
  3. GoMatcha (Go)
    pros: Go!
    cons: very early

Sorry but i didn't intend to add ReactNative, personal reason: the error message is too freakin ugly. Also there are some others like Unity3D (for games, inefficient =battery-drain if you use it for static UIs), Xamarin (.NET), Scade (Swift), CodenameOne (Java), Kotlin/Native (Kotlin), Qt (C++), LiveCode (Transcript) and others (especially game engines like: Marmalade with C++/Lua, Corona with Lua) and of course you can choose other Hybrid or HTML5-based ones.

Update 2019-05-07: https://wails.app/ (not native, it's Golang + Javascript)
Update 2020-01-22: SvelteNative, FuseOpen
Update 2020-01-29: UnoPlatform

2018-02-15

TechEmpower Framework Benchmark Round 15

As usual, the only one matters are data updates and multiple queries.

Top ranker languages are C, C++, Java, C#, Dart, Python, Go, Perl, Scala, Javascript.


Top ranker language for multiple queries: Dart, Java, C++, C, Kotlin, Rust, Ur, Go.

Dart seems to be getting more and more popularity, since a framework for cross platform mobile app: Flutter is very usable.

2017-11-07

Elixir/Erlang better than Go, really?

The microbenchmark result for spawning short-lived concurrent process:

# Go 1.8.0
$ go build test.go ; for k in 5 50 500 5000 50000 500000; do echo -n $k; time ./test $k > /dev/null; done

5
CPU: 0.00s      Real: 0.00s     RAM: 2080KB
50
CPU: 0.06s      Real: 0.01s     RAM: 3048KB
500
CPU: 0.61s      Real: 0.12s     RAM: 7760KB
5K
CPU: 6.02s      Real: 1.23s     RAM: 17712KB # 17 MB
50K
CPU: 62.30s     Real: 12.53s    RAM: 207720KB # 207 MB

500K # this is 10x more! 
CPU: 649.47s    Real: 131.53s   RAM: 3008180KB # 3 GB

# Elixir 1.4.2 (erts-8.2.2)
$ for k in 5 50 500 5000 50000 ; do echo -n $k; time elixir --erl "+P 90000000" test.exs $k > /dev/null; done

5
CPU: 0.53s      Real: 0.50s     RAM: 842384KB # 842 MB
50
CPU: 1.50s      Real: 0.62s     RAM: 934276KB # 934 MB
500
CPU: 11.92s     Real: 2.53s     RAM: 1675872KB # 1.6 GB
5K
CPU: 122.65s    Real: 20.20s    RAM: 4336116KB # 4.3 GB
50K 
CPU: 1288.65s   Real: 209.66s   RAM: 6573560KB # 6.5 GB

You can find the code here. In terms of performance and memory usage, it's not really, but you can argue about anything else.

2017-07-31

Tricks to be Motivated

Recently I being so much unmotivated with my work, and I think I know the reason, but anyway, these are the generic things to get things done:

  1. Buy a pen, and small notebook, seriously! Make a TODO list, break into very small things to be done in a day
  2. Have enough sugar and sleep, lack of sleep/concentration/focus is bad, as bad as alcohol addiction
  3. Do your tasks first before doing unimportant tasks (facebook, tweeting, watching movies, etc), make those unimportant things as reward
  4. Do not imagine yourself reaching the success, probably better imagining if you are fail and be afraid of it
  5. Your willpower is unlimited, and can be strengthened by doing more things that requires willpower, as willpower is contagious
  6. Surround yourself with people with same goals, or at least watch motivational people that work hard to reach their goals/dreams, be envious!
  7. Forgive yourself, guilt makes you want instant gratification that produces more guilt
  8. Do less decision, always go for option A, be courageous, set simple rules
  9. Walk/start first, motivation will comes later
I think that's it, these article summarized from videos about motivation and willpower I found on youtube.





2017-06-14

Cross Platform Game Development

So I was looking for cross-platform game development, found some that are good for Indie game dev development, such as V-Play that uses QML (I like Qt), but the review for the games it produced is quite bad (crashes a lot), so I look another one and found Cocos2D-JS (that has been merged to Cocos2D-X at 2016). To start the development, visit the download page, and choose the full one. Start any web server on that directory.

Need more resource? You can watch this awesome youtube playlist (2014 but still quite relevant), or see the website (warning: mostly broken link) or github for more reference.

Or you might want to try, comparison:
Actually I want to write this page as Cocos2D tutorial, but for my current project I need engine that can run under a WebView component, so here's the alternative:
I think QiCiEngine (built on top Phaser.io which built on top PixiJS) is quite awesome, lot's of examples, too bad that WebGL that used by Pixi must use Android Lolipop. There's some people that review those engines (see the recommended videos next ot that video). Also you may want to see TileD to help you edit the stages.

2017-06-01

Alternatives for Web and Mobile App in single codebase

If you are a one-man-army.. um I mean full-stack dev, you'll need to reuse most code as much as possible, a single codebase for all platform instead of rewrite everything in programming language best suited for that platform, that is C++/Java for Android, Swift/Obj-C for iOS, and Javascript for Web.

Other than the popular ReactNative (with react-native-web) and NativeScript (with angular-part that can be reused), there are ReactXP (Microsoft), is a fork of ReactNative (Facebook), with some extras: TypeScript (future proposed ES7 with better tooling), single codebase for all common platform: Android, iOS, Web, and Windows.
To use them, you should clone their repository, and use the provided Hello World.

git clone https://github.com/microsoft/reactxp
cp -r reactxp/samples/hello-world rxp1
cd rxp1
npm install
npm run web-watch # or rn-watch for mobile

Open index.html using browser, preferably use a web server instead of file:// protocol. Install ReactDevTools for better debugging experience. The directories should show something like this:

├── android
│   ├── app
│   ├── build.gradle
│   ├── gradle
│   ├── gradle.properties
│   ├── gradlew
│   ├── gradlew.bat
│   ├── keystores
│   └── settings.gradle
├── index.android.js
├── index.html # <-- the main code for web
├── index.ios.js
├── ios
│   ├── RXPHelloWorld
│   ├── RXPHelloWorldTests
│   └── RXPHelloWorld.xcodeproj
├── node_modules
├── package.json
├── README.md
├── src # <-- your common source code / components here
│   ├── App.tsx 
│   ├── index.tsx
│   ├── ToggleSwitch.tsx
│   └── typings
├── tsconfig.json
└── webpack.config.ts

Now you can edit the App.tsx and start digging, but probably you'll need to wait around end of this year, until it has more features.

Next are the Cordova-based (that would be slower than native since it's browser based, also user on the older devices that has buggy 1 probably need to install last version of CrossWalk), there are:
And there are new one similar to ReactNative that supported by Alibaba (internet giant from China), called Weex that can be used with VueJS, and recently joined Apache Foundation.

Haven't tried them all, but..
  • by skimming the specs and the docs (that i prefer ones that not focusing on mobile-only), 
  • and since I dislike Angular (sorry Google), 
  • not really into React (and whatever state management libraries available: Flux, AltJS, Redux, MobX, Cerebral), 
  • prefer to use RiotJS > VueJS (since I think they take the good parts of Angular and React)
  • not really like write in Typescript (but I like using libraries that written in Typescript ^^ because parameter info/object-property checking is quite helpful on development), 
I think the most prospect is Weex (hey it's native) and Quasar Framework (really cool built in components).

Btw have you heard PWA (youtube)?

Note: this article written in 26th April 2017, scheduled to be published at 1st June 2017, probably things have change since then.

Github Stat Apr 2017 Watch Star Fork
ReactNative 2.9 47.5 11.0
Weex 1.9 14.0 1.9
Ionic 1.7 29.2 7.4
NativeScript 0.6 10.0 0.7
Framework7 0.5 9.5 2.0
OnsenUI 0.2 4.6 0.6
ReactXP 0.2 4.4 0.2
IncubatorWeex 0.1 2.2 0.3
Quasar 0.1 1.9 0.1
Phonon 0.0 0.3 0.0
React 4.4 65.3 12.1
Angular 4.4 55.5 27.7
Vue 2.9 51.5 6.89
Riot 0.4 11.8 0.9
Mithril 0.3 7.5 0.6

Also note that I didn't include other cross platform mobile-only development alternative or ones that specialized for gaming or must-pay, such as Xamarin/Unity3D, Cocos2D, RemObject's Silver, etc