2017年12月4日月曜日

About Dart x SDL on Mac

Dart の Native Extensions を利用して、 SDL を用いたマルチプラットフォームのゲーム開発環境を作れるか検証してみた。


結論からいくと、 「Mac 上で動作する SDL x Dart の アプリは動作させることが難しいよ」 と言うことです。 Windowsはできる。

ただ、時間をかければできるかなぁとも思いました。
※ Dartはゴリゴリ開発されているものなので、近い未来には、変わっているかもしれません。


# Dart とは

Serverサイド や SmartPhone で動作する VM をもち、 Browser上で動作する JavaScriptを出力できる 凄い奴です。
https://www.dartlang.org/


# Native Extensions とは

コマンドライン向けのVMから、 Shared Library と連携して、Nativeの機能をDartから叩くのに使用します。

https://www.dartlang.org/articles/dart-vm/native-extensions

# SDL とは

クロスプラットフォームの Low level のライブラリーです。 audio, keyboard, mouse, joystick, graphics hardware を扱うことができます。

ゲームを作成するのに必要な機能がサポートされており、スマフォの環境も含めて、ほとんどの環境で動作します。


# 試したこと


## Dart と SDLを組み合わせて、 Dartで書いたゲームをありとあらゆる PFで動作させることができないか?


Dart と SDLを組み合わせて、 Dartで書いたゲームをありとあらゆる PFで動作させることができないか? と考えました。

Dartには、 async-await がサポートされていたりして、 ロジックが書きやすいです。ゲームスクリプトとか、 Dartがあればあればいらないじゃん。 Dartがゲーム用のスクリプトといって問題ないくらい。気軽にロジックがかけるではないか..


## Dart


#### MAC で

https://github.com/kyorohiro/dart.sdltest

```
git clone https://github.com/kyorohiro/dart.sdltest
cd dart.sdltest
cd doc_sdl2
ninja -f build.osx.ninja
cd ..
sh build.sh
dart main.dart
```


#### Windows で


https://github.com/kyorohiro/dart.sdltest.vc

```
git clone https://github.com/kyorohiro/dart.sdltest.vc
cd dart.sdltest.vc
start Project3.sln
...
Debugモードでビルド.....
...
cd ..
git clone https://github.com/kyorohiro/dart.sdltest
cd dart.sdltest
copy {ビルドしたDLLとLib と SDL関連のDLL} ./
dart main.dart
```

# どうなったか?

Windowsでは、期待通りに動作します。
つまり、Dart で SDLアプリを作れます。



しかし、MACでは以下のようなエラーがでます。

とすると、 WARNING: nextEventMatchingMask should only be called from the Main Thread! This will throw an exception in the future.
と警告がでてそれ以上何もできません。

Mac では UI 関連のイベントは、 MainThreadで処理しなくてはならないからです。



# もしも macで Dart x SDLを実現したいなら

DartVM に手を入れて MainThread を、制御できるようにする。
DartVM と プロセスを分けて、MainThreadを描画ように利用する。
などなど。

Flutter のコードを見ると、 DartVM を組み込んで アレコレしているので、
参考にしたり、 そのまま利用したりすると良いかもしれません




2017年9月26日火曜日

Bake tiny calc app at antlr3 and Clang with emscripten

ゲームスクリプトを設計しようかと考えた。
文字で書かれた文章を構造化して、書かれた事を実行する。
ANTLR を 使う事にした。
Emscripteで利用するまでについて、解説します。



結論から

ANTLR3 (http://www.antlr3.org/)を利用します。ANTLR4は、C言語がなさげ、CPPはあります!!

ANTLR3 で 生成した Parser と Lexer は、 emscriptenようにビルドしましょう。
少しだけ変更します。以下の通り

電卓を作りました。参考までにどうぞ


コンパイラーコンパイラー

文字で書かれた文章を構造化するのに、Lexer と Parser を作るのがトレンドです。
Lexerで単語を分割する。Parserで分割した単語を木構造化するといった感じです。

こう書くと難しそうですが、いたって簡単です。
文章を構造化するとは、プログラマー的には、文章を関数化するという事です。
これを、念頭に読んでください

「xxx は yyy が zzz です。」を構造化してみましょう。

関数で木構造を表現する

void sentence() {
  xxx();
  printf("は");
  yyy();
  printf("が");
  zzz();
  printf("です。");
}

void xxx() {
  printf("私");
}

void yyy() {
  printf("ポテチ");
}

void zzz() {
  printf("すき");
}

こんな感じで出かけます。 xxx() yyy() zzz()を、自分好みに書き換えれば、
構造化の完成です。
今回の場合だと、「私はポテチが好きです」と表示されるはずです。


関数で構造解析木をつくる

xxx() yyy() zzz() の部分に何が入るかを、解析するのが、Parserです。

void  sentence(char *src) {
  src = xxx(src+1);
  if(src[0] !="は") {
    return; // failed to parse
  }
  src = yyy(src+1);
  if(src[0] == "が") {
    return; // failed to parse
  }
  src = zzz(src+1);
  if(src[0] != "で" || src[0] != "す") {
    return; // failed to parse
  }

}

char* xxx(char *src) {
  char data[100] = 0;
  for(int i=0;;i++) {
    if(src[i] == 'は') {
      return src+i;
    }else {
      data[i] = src[i];
    }
  }
}

char* yyy(char *src) {
  char data[100] = 0;
  for(int i=0;;i++) {
    if(src[i] == 'が') {
      return src+i;
    }else {
      data[i] = src[i];
    } 
  }
}

char* zzz(char *src) {
  char data[100] = 0;
  for(int i=0;;i++) {
    if(src[i] == 'で') {
      return src+i;
    }else {
      data[i] = src[i];
    }  
  }
}


こんな感じです。書くのが大変ですね。

コンパイラーコンパイラーが、かわりにやってくれる

この、大変な作業を、BNF形式で記述すれば自動で生成してくれるのが、
コンパイラーコンパイラーと言われるものです。

今回は、ANTLR(http://www.antlr.org/)を利用しました。


ANTLRについて

C言語は、ANTLR3をつかう

antlr4だと、C++ようはあるのですが、C言語用がありません。


Emscriptenようには、ビルドする

このコードを、自分でビルドします。少しだけ変更が必要でした、
ninja build できるようにしたものを、以下に起きました。


Java版は生成されるのに、C言語版はWarningがでる

```

warning(24):  template error: context [/outputFile /parser] 1:1 could not pass through undefined attribute filterMode
warning(24):  template error: context [/outputFile /parser /genericParser /_sub45 /ruleAttributeScopeFuncMacro] 1:4 no such property or can't access: null.attributes
warning(24):  template error: context [/outputFile /parser /genericParser /_sub45 /ruleAttributeScopeFuncMacro] 1:4 no such property or can't access: null.attributes
```
これは、でても問題ないそうです..

出力するParserの言語のしていは、グラマーファイルに書く


こんな感じ

PS

電卓のサンプルを起きました。

参考までにどうぞ。


REF BOOK




2017年9月24日日曜日

Layer For GL and SDL1 and SDL2 on html5 and Mac and Windows



私は、今、特殊なゲーム用のライブラリーを作成しているのだが、
SDL1 SDL2 html5 mingw osx で、発生する差異を吸収するレイヤーを作成することにした。
https://github.com/kyorohiro/capp

今の所、Image、Sound、TTF、GL が使えます。
徐々に、ビルド環境の構築方法や、イベントの対応などの機能が増えていくはずです..



Purpose

C言語だと、IfDef で、差異を吸収するわけだが、
このコードのあちこちであると、管理が面倒になるので、
それらを、cappライブラリーにまとめることにしたのだ。
https://github.com/kyorohiro/capp


cappライブラリーを作成する前に、もっと短いコードで確認してもいて
それは、以下にあります。
https://github.com/kyorohiro/doc_sdl2


MINGWについては、過去記事を参考にして、GLEWライブラリを生成してください。
http://kyorohiro.blogspot.jp/2017/09/build-sdl-x-mingw-x-opengl-s.html




...

おわり








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html




2017年9月22日金曜日

Build SDL x MinGW x opengl 's application 2017y9m22day



MinGW x SDL x OpenGL で アレコレしよう。
まずは、環境の構築をする必要があります。
ただ、このタイミングでは、素直に環境構築ができませんでした。
解説します。


結論から : GLEWは自前でビルド

glew を自分でビルドする必要があります。
また、glContextを生成した後で、glewを初期化する。

- mingwでビルドできるようにした、glew
  https://github.com/kyorohiro/glew_mingw
- SDL2 x GL のビルドファイル(ninja build)とソース
  https://github.com/kyorohiro/doc_sdl2

あとは、他Platformと変わりません


GLEWのビルド

http://glew.sourceforge.net/ で配布されている windows用の libは、
Visual Studio 用のようです。 ※確証はありません

なので、自分でビルドする必要があります。
mingw用のビルド方法のREADMEがあるので、その通りにやれば良いのですが、
パッチを充て必要があります。


fprintf () が見つからないといわれる

原因が standard ライブラリーを、リンクしないように GCC のOptionが指定されているからです。

にあるパッチを充てればビルドできます。

msys上で、mingw32-make をしてくださいhttp://www.mingw.org/wiki/getting_started



glContextを生成した後で、glewを初期化する。

glewを初期化しないとシグセグで落ちます。
ただ、初期化するタイミングは、glContextを生成した後のようです。※確証はありません。
なので、SDL_Render を用いた Bufferの更新とかは使えなくなります。たぶん、
かわりに、SDL_GL_SwapWindow を使うことになるかと



...

おわり


Build Option、source code は、 check following
- mingwでビルドできるようにした、glew
  https://github.com/kyorohiro/glew_mingw
- SDL2 x GL のビルドファイル(ninja build)とソース
  https://github.com/kyorohiro/doc_sdl2





.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html




.





2017年9月15日金曜日

About GL Texture with SDL1 and SDL2 x Emscripten and Desktop



SDL と OpenGL と Emscriptenを利用して Desktop とBrowser向けのゲームを作ろう。
で、Textureの扱いを、考える。

1-8枚の off-screen image を持っておく。シーンごとに、この off-screen imageに転送する。で、使い回す方法を取る事にした。


それはなぜか?
あと、Emscriptenで上手く動作しない使い方があったので、まとめます。
※ 2017y 9m 14d



Textureとは

ゲームで使う画像の事です。テキストデータの表示も画像です。SDLでは、SDL_Surfaceとして抽象化されています。

GLで利用する際は、この画像データをハードに転送してから利用します。
基本的、ハードに転送した画像しか使えません。

一度に転送できる画像の数や容量には制限があるので、
賢く使う必要があります。


Off-screen image

ここでは、画面に直接表示しないImageという意味で使います。 私のPCはGLで一度に処理できる画像の数は、8枚でした。16284x16384 のPixelの画像を扱えるようです。

なので、複数枚の小さな画像は、前もって一つにまとめておく必要があります。


SDLでのOff-screen imageの作り方


SDL_CreateRGBSurface() を利用します。
使い方は以下を参考にしてください。
SDL_BlitSurface() で、画像化したデータを追加できます。

https://github.com/kyorohiro/doc_sdl1/tree/master/sdl1_gl_textureFromRGBSurface

https://github.com/kyorohiro/doc_sdl2/tree/master/sdl1_gl_textureFromRGBSurface


SDL1 SDL2 Emscripten の差異

本題です。この記事を書いている時点では、以下のような事情があります。
- Emscripten x SDL1 だと、オフスクリーンImageに対する、SDL_BitSurface に失敗します。
- Desktop x SDL1 だと、SDL_SetAlpha(textSurface, 0, SDL_ALPHA_TRANSPARENT); をしてあげないと、透過色がある場合は、完全にすけてしまい、何も書き込まれません。※ SDL_BlitSurfaceを利用する場合


---> 解決方法
- SDL1 x Emscriptenの場合は手動で画像データを転送する。CPUでもGPUのどちらでも良いと思う。具体的には、以下のような感じで書きました。


 {
      char* m = image->pixels;
      char* n = textSurface->pixels;
      // for argb888 format 
      for(int i=0;i<textSurface->w;i++) {
        for(int j=0;j<textSurface->h;j++) {
          int mt = 4*(j*image->w + i);
          int nt = 4*(j*textSurface->w   + i);
            m[mt+0] = n[nt+0];
            m[mt+1] = n[nt+1];
            m[mt+2] = n[nt+2];
            m[mt+3] = n[nt+3];
        }
      }  
  }

SDL_Surfaceのpixelデータに直接書き込む

- SDL1 x デスクトップ  の時は、忘れずに、SDL_SetAlpha()をしてあげる。



おわり!!

.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html




.





2017年9月13日水曜日

For WebGL, hybrid SDL1 and SDL2 with emscripten



SDL v1と v2 の両方を利用したライブラリーにしようという事は前回話したとおり
Which SDL1 or SDL2 with emscripten

そこそこ動作するようになってきた。
https://github.com/kyorohiro/cgame/tree/master/examples





SDL1 と SDL2 の違い

大きな違いはなかった。 https://wiki.libsdl.org/MigrationGuide の通り。
基本は、初期化方法と、画面の更新方法が違うくらい。

SDL1 と SDL2 の差異、Html5用と、デスクトップ用の違いは、 https://github.com/kyorohiro/cgame/tree/master/app で吸収したので
興味のある方はどうぞ。

ちなみに、SDL_ttf と SDL_image と SDL_mixer の APIは同じでした。


ビルド方法のノウハウ

ビルド方法のノウハウは、Ninjaファイルを参照してください。
ninja -f build.gcc.ninja でビルドできます。




TODO

kyorohiro/cgame版のWebGLで、三角形を表示するコードです。
Html5用、デスクトップ用にビルドできます。



#include <stdio.h>
#include "app/capp.h"
#include "core/ccore.h"


int fps;
int frgShader;
int verShader;
int program;

GLfloat vertexBufferData[] = {
  0.0f, 0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f,
  0.5f, -0.5f, 0.0f
};

GLshort indexData[] = {
  0,1,2
};

void _onInit(CObject* context, CObject* args) {
  printf("## onInit\r\n");
  CApp* appObj = (CApp*)context;

  glEnable(GL_DEPTH_TEST);
  glViewport(0, 0, appObj->width, appObj->height);
  glClearColor(1.0, 0.7, 0.7, 1.0);//rgba
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  //

  CTry {
    frgShader = cglu_loadShader(GL_FRAGMENT_SHADER,
      "void main() {\n"
      "  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
      "}\n");
    verShader = cglu_loadShader(GL_VERTEX_SHADER,
      "attribute vec4 position;\n"
      "void main() {\n"
      "  gl_Position = position;\n"
      "}\n");
  } CCatch {
    printf("## ERROR\r\n");
    return;
  }

  program = glCreateProgram();
  glAttachShader(program, frgShader);
  glAttachShader(program, verShader);
  glLinkProgram(program);

}

void _onDisplay(CObject* context, CObject* args) {
  CApp* appObj = (CApp*)context;

  //
  // setup buffer
  GLuint vertexBuffer;
  GLuint indexBuffer;
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  glGenBuffers(1, &vertexBuffer);
  glGenBuffers(1, &indexBuffer);

  glUseProgram(program);
  int positionLoc = glGetAttribLocation(program, "position");

  //
  // connect buffer
  glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*3, vertexBufferData, GL_STATIC_DRAW);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLshort)*3, indexData, GL_STATIC_DRAW);

  glEnableVertexAttribArray(positionLoc);
  glVertexAttribPointer(positionLoc, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)0);

  //
  // draw
  glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0);

  //
  // release buffer
  glDeleteBuffers(1, &vertexBuffer);
  glDeleteBuffers(1, &indexBuffer);

  if(fps != appObj->fps) {
    fps = appObj->fps;
    printf("fps:%d;\r\n",fps);
  }

  capp_flushBuffers(appObj);
  //capp_postRedisplay(appObj);
}

int main(int argc, char** argv) {
  printf("capp sample\r\n");
  CApp* appObj = createCApp(300, 300);
  capp_addDisplayEventListener(appObj, (CObject*)appObj, _onDisplay);
  capp_addInitEventListener(appObj,  (CObject*)appObj, _onInit);
  capp_run(appObj);
  return 0;
}

https://github.com/kyorohiro/cgame/tree/master/examples/app_002_gl


余計なコードがなくなってきてる気がしませんか。
まだまだ、改良の余地ありかな..

REF

http://kripken.github.io/emscripten-site/



おわり!!

.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html




.


Create window at SDL1 and Emscripten

SDL1と Emscripten で、Windowsを表示する


//
// Create Window
//
#include <SDL.h>
#include <stdio.h>

int main( int argc, char* args[] )
{
  SDL_Init( SDL_INIT_EVERYTHING );
  SDL_Surface* screen = NULL;
  screen = SDL_SetVideoMode( 640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF );
  SDL_WM_SetCaption( "title", 0 );
  SDL_Flip( screen );
#ifdef PLATFORM_EMCC
#else
  SDL_Event event;
  int isQuit = 0;
  while(isQuit == 0) {
    if (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        isQuit = 1;
      }
    }
  }
  SDL_Quit();
#endif
  return 0;
}

で、Window作成できた。



おわり!!






----
作成中のコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html




2017年9月8日金曜日

Which SDL1 or SDL2 with emscripten





Emscripten と OpenGLを使ってゲームを作ろうと思いたって、
まずは、SDL2の基本的な使い方を試していた。

しかし、今の所は、SDL 1系 の方が、良いと思いました。
SDL2があるのに、SDL1 を選ぶのはなぜか?


# 2017y 9m7d

SDL と SDL2 が、ちゃんぽんのゲームライブラリーを作ろう

素の OpenGL の APIを直接いじるのは、大変なので、欲しい機能を抽象化してライブラリー化する事にしました。

SDL2をベースに作成しています。ただ、これを、ブラウザー用には「SDL1」、Windows OSX用には「SDL2」を利用する形にしたいと結論しました。

なぜに?


SDLはコンピューターゲーム用のハードに近い部分のライブラリ

SDLは、音やグラフィック、マウスイベント、タッチイベントなどを、扱う事ができるC言語のライブラリです。 
Android、 iOS、 Windows、 Mac、 Browser上で動作します。

このライブラリーを利用して書けば、作成したアプリやゲームが、ありとあらゆるPFで動作するようになります。


Emscriptenを使えば、SDLがブラウザーで動作する

EmscriptenはLLVMでバイトコードを、ブラウザーで動作できるようするライブラリーです。

Clangを利用すれば、LLVM用のバイトコードをC言語で作れますから、
SDL系 x C系 のアプリを ブラウザーで動作させる事ができます。


SDL2は、最新のSDL


SDLの最新版が、SDL2.x 系です。 SDL1.2.x から、大幅に変更されました。
VideoAPI、new Sprite 2dGmae, Touch Event, IMF, Mobile PF対応
などなど、様々な機能を追加されました。



kyorohiro/cgame のブラウザー向け、SDL1 を使う事にした。

kyorohiro/cgameのブラウザー向けは、SDL1を使う事にしました。

SDL2 系だと、現在(2017y 9m7d) 一部使えない機能があったのと、
SDL2系を使った時に生成される Javascriptのサイズが大きかったからです。


以下に作成したものおきます。

画像の表示、オーディオ化の再生、OpenGL、タッチイベント、マウスイベント、
の取得等、SDL1とSDL2で書いたコードです。
Emscripten と、OSXと、Windows(MinGW)で動作します。


a. SDL1系の方が2系よりも軽い

だいたい、SDL2系だと、1.2〜3.4 MBくらいのJavaScripteを出力します。
ただ、SDL1系だと、120kbから300KBくらいです。
めちゃくちゃ軽いです。


b. SDL2系で SDL_mixerが思い通りに動作しない

SDL_mixerの初期化に失敗しました。SDL_Mixierが使えないと
音の再生が面倒です。

c. SDL1系でも、タッチイベントが使える

Emscriptenでは、SDL1系でもFinger Event を取得できます。
スマートフォンのユーザー向けには、タッチイベントをサポートしたいですよね!!


という事で、kyorohiroの選択は、 browser用には、SDL1系、それ以外はSDL2系 で進める事にしました。


おわり!!

.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html


.







2017年9月1日金曜日

Scratch と C言語ようゲームライブラリ


C言語用のゲームライブラリを作成する事にした。
https://github.com/kyorohiro/cgame

C++ベースのゲームライブラリがあるが、C言語で書かれたものが、なさげだった。

きっかけ

C言語の入門書を書こうと思いたった。
どのように、解説するのが良いだろうか。入門書をいくつか読んでみた。

だいたいの本は文法を紹介したり。コマンドラインを想定した標準APIを使ったりしていた。
しかし、それは、私が望むものではなかった。


Scratch

皆さんは。Scratch(https://scratch.mit.edu/) をご存知だろうか。
Scratchは、GUI のBlockを利用してゲームやアート作品を作るためのツールです。
膨大な数の作品が公開されています。


この作品を作成した子供達は、はたして、文法などを学んだのだろうか?
そんな事はしていない。
右へ動けというBlockを配置すると、Scratch猫が右に動く。
左へ動けというBlockを配置すると、Scratch猫が左に動く。
そういった、素朴な操作を繰り返す事で、
自然、高度な作品を作り上げるようになるのだ。


プログラマー的な発想

詳細は知らなくても、プログラマー的な発想があれば、プログラムが書ける。

世の中には無数のプログラムが存在しています。
プログラマーは複数の言語を利用します。

プログラマーは新しい言語を使えるようになるために、
何度も学習を繰り返します。

しかし、ほとんどの場合は以前に学んだ言語の「xxx」は、新しい言語の「yyy」と同じだな。と理解しなおだけです。

どうように、プムログラムを書く際の、構造の組み方、抽象化の仕方は、引き続き再利用します。


逆から学ぶ

そこで、文法からでなく、実際に動くプログラムを操作する事で、プログラマー的な思考を学習する事ができないか。

で、実験してみたくなりました。
https://github.com/kyorohiro/cgame の作成を開始しました。





おわり!!

.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html


.















Created a gitbook plugin for emscripten application

emscripten で書いたアプリをgitbookに追加したかった。
が、なかったので作成した。

https://github.com/kyorohiro/gitbook-plugin-emscripten


Gitbookとは

https://www.gitbook.com
電子書籍を作成して公開できるWebサービスです。
Markdownで記述して、それを、Webページ、PDF、EBook への公開ができます。


Gitbook plugin 

gitbook で利用できる Markdown でアレコレ記述します。
ただ、このMarkdownは、表現力が乏しいです。
https://en.wikipedia.org/wiki/Markdown

独自の表現を追加できるように、Plugin機能がサボートされています。
自分専用のタグを追加したり。文書を書き換えたりすることが出来ます。


Emscripten 

C/C++ などで作成したアプリを、プラウザー上で動作させる事ができます。
https://github.com/kripken/emscripten

何ができるのだろう? という方は以下をみていただくとよいでしょう。
https://github.com/kripken/emscripten/wiki/Porting-Examples-and-Demos


C言語は最古の言語の一つで、Linuxなどは、C言語で書かれています。
古くからある言語なので、さまざまなライブラリーがC言語で作成されました。
これらを利用する事ができます。

作成したPlugin

{% emscripten js="test.js", mem="test.html.js" %}{% endemscripten %}
と記述する事で、作成したEmscriptenアプリをGitbookページに追加する事ができます。


ロードする間ページ遷移ができないので、その辺りが改善する必要があるかな








2017年8月31日木曜日

SDL2 x Emscripten x Windows で Ninja Build する際に注意点

今回はmakeの代わりに、Ninja Build を利用ていましす。


cc = emcc
cmd = cmd /c
objExt = bc
appExt = html
objLib = bc
sep = /

rule obj
 command = ${cmd} ${cc} -c $in -o $out -IC:\mingw_dev_lib\include\SDL2 -DPLATFORM_EMCC
rule exe
 command = ${cmd} ${cc} $in -o $out -s USE_SDL=2

subninja event${sep}build.ninja
subninja createWindow${sep}build.ninja

Windowsで、 emscripten の build.ninja ファイルを書く際は command に  "cmd /c "を入れないとビルドに失敗します。





おわり!!

.








------

試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html


.







Create window at SDL2 and Emscripten

SDL2 と Emscripten を使い始めた。
まずは、Windowsを表示するところから。

//
// Create Window
//
#include <SDL.h>
#include <stdio.h>

int main( int argc, char* args[] )
{
  SDL_Init( SDL_INIT_VIDEO );
  SDL_Window* window;
  SDL_Renderer* renderer;
  SDL_CreateWindowAndRenderer(600, 400, 0, &window, &renderer);

  SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255);
  SDL_RenderClear(renderer);

  SDL_RenderPresent(renderer);

  SDL_Delay( 2000 );
  SDL_DestroyWindow( window );
  SDL_Quit();
  return 0;
}

で、Window作成できた。



おわり!!

.








------
試したコード
https://github.com/kyorohiro/sdl2_doc
This codes can build for windows and mac and html5 on windows and mac

作成中のライブラリー
https://github.com/kyorohiro/cgame

ことはじめ
https://kyorohiro.blogspot.jp/2017/09/which-use-sdl1-or-sdl2-at-emscripten.html


.



2017年2月15日水曜日

Dart x WebDriver Capture webpage

クローラーを作る。
ただ、最近だJavaScriptが動的にデータを読み込むパターンがあるので、
WebDriverを利用して、実際にウェブブラウザーを利用する必要がある。

Dartで試してみた。

Install

brew install selenium-server-standalone
brew install chromedriver

Run

1. Run chromedriver
> chromedriver

2. Write code and capture


import 'package:webdriver/core.dart' as wcore;
import 'package:webdriver/io.dart' as wio;
import 'dart:async';
import 'dart:io' as io;


main() async {
  var uri = Uri.parse('http://127.0.0.1:9515');
  wcore.WebDriver driver = await wio.createDriver(uri: uri);
  await driver.get('http://firefirestyle.net');
  await new Future.delayed(new Duration(seconds: 2));
  wcore.WebElement elm = await driver.activeElement;
  print("${await elm.text}");
  io.File f = new io.File("./out.jpg");
  await f.writeAsBytes(await driver.captureScreenshotAsList());
}
http://firefirestyle.net/




参考

http://qiita.com/isyumi_net/items/49a7e60fed6b39377e6a

2017年2月14日火曜日

Dart x WebGL Spring Mesh

XX-CAKE!(https://www21.atwiki.jp/xxcake/)の影響を受けて、Spring機能付きのMeshを作ってみた。

https://firefirestyle.github.io/nonno/v0_0_1/index.html


とりあえず、バネ機能付のMeshを生成する部分までのコードを書いてみた。
https://github.com/kyorohiro/nonno

実際に書いて動かしてみると、これをぷるんぷるん動画作成に利用するのは、
発想がすごいよなぁ。

真似したくなる。
応用も利くし。
便利


作り込むか決めてない。
Spring Mesh の計算はGPGPU にで書けないか試してみたくはある。

PS
今の所、Dartiumのgl.readPixcel()が不調なので、
WebGLをTextureを利用して、GPGPU化する場合は、
dart2jsを通して、Chromeで確認する必要がある。

まぁ、Dart Dev Compiler  待ちですね。




2017年2月8日水曜日

Dart x AngularDart x GAE x Go で ウェブページを作ってみた

AngularDart x GAE x Go  で ウェブページを作ってみました

http://firefirestyle.net/



Twitterでログインして、投稿ができます。タグ検索をサポートしています。
機能不足ですが、今週中くらいには、現在の提供している
機能で未実装の部分は実装する予定。

ただ、投稿サイトの機能は、外して、http://k07.me の方のみにするかも

フォロー機能、タイムライン機能、メッセージ機能は
k07meには、今年の前半中には
実装する予定です。

ノウハウはあるので

Source
https://github.com/firefirestyle/engine-v01-app
https://github.com/firefirestyle/engine-v01

2017年2月2日木曜日

お金が尽きた (My money has run out)



日雇いのプログラマーになりたい人が、
ココにいますよ〜〜
(* ̄0 ̄*)ノ

A person who wants to be a day-haired programmer,
I am here here ~ ~
(* ̄0 ̄*)ノ

今なら、言値で働きますよ〜
If it is now, I will work with your asking price ~

たぶん
maybe

2017年1月30日月曜日

Dart x WebBluetooth x BLE Peripheral Simulator x Eddystone 's memo (1)

WebBluetoothについて、BLEの学習も兼ねて、アレコレ遊んでみます。
Dartを利用します。

型があるので、保管機能を利用することができます。Crt+Space するだけで、何ができるのかが判断できて便利です。

欠点としては、Dartium のWebBluetoothへの対応が微妙なの事です。dart:jsで変換しないと、動作確認ができません。しかし、Dart DDC対応が完了すれば、この問題もなくなります。なので、今だけの問題といえるでしょう。



# Batteryサービスから、残量を取得してみる

とりあえず、Web Bluetooth x Dart で、HelloWorldをしてみる。

BLE Peripheral Simulator(https://github.com/WebBluetoothCG/ble-test-peripheral-android) は、Web Bluetooth の通信の実験相手をしてくれます。
とっても便利です。
ソースも公開されていますから、中身を見ながら、理解を深める事ができます。

BLE Peripheral Simulator の Batteryサービスから、バッテリー残量を取得して見ましょう。
※ BLE Peripheral Simulator は、GooglePlay からダウンロードできます。
https://play.google.com/store/apps/details?id=io.github.webbluetoothcg.bletestperipheral
※ chrome://flags よりWeb Bluetoothを有効にしてください。

===

Source
https://github.com/firefirestyle/ebook_webbluetooth_with_dart/tree/master/memo/test/hello

import 'package:angular2/core.dart';
import 'dart:html' as html;
import 'bt.dart' as b;
import 'dart:typed_data';


@Component(selector: 'my-app',
    template: """
    <h1>Hello {{name}}</h1>
    <div>
    <div *ngFor='let v of logs'>{{v}}</div>
    </div>
    <button (click)='onClick()'>Click</button>
    """
)
class AppComponent {
  var name = 'Angular';
  List<String> logs = [];

  log(String l) {
    print(l);
    logs.add(l);
  }

  onClick() async {
    b.Bluetooth bluetooth = b.getBluetooth();
    b.BluetoothDevice device = await bluetooth.requestDevice({ "filters": [{ "services": ['battery_service']}]});
    log("name : ${device.name}");
    log("id : ${device.id}");

    b.BluetoothRemoteGATTServer server = await device.gatt.connect();
    log("server.connected : ${server.connected}");

    b.BluetoothRemoteGATTService service = await server.getPrimaryService('battery_service');
    log("service.isPrimary : ${service.isPrimary}");
    log("service.uuid : ${service.uuid}");

    b.BluetoothRemoteGATTCharacteristic chara = await service.getCharacteristic('battery_level');
    log("service.uuid : ${chara.uuid}");

    ByteData buffer = await chara.readValue();
    log("service.value : ${buffer}");
    log("service.value : ${buffer.lengthInBytes}");
    log("service.value : ${buffer.buffer.asUint8List()}");
  }
}

===

参考

Web Bluetooth Draft Community Group Report, 27 January 2017


Implementation Status


LeScanは、これから
https://github.com/WebBluetoothCG/web-bluetooth/pull/239
https://webbluetoothcg.github.io/web-bluetooth/scanning.html



PS

個人的に、ネタを集めて、WebBluetoothについて、まとめる予定
たぶん以下で



2017年1月29日日曜日

AngularDart で Pinterestっぽい、Layout を試して見た。

Angular Dart で Pinterestっぽい、Design を試して見ました。
https://github.com/firefirestyle/ebook_windstyle_markdown/tree/master/angular/tiny-dynamicblock



隙間なく、四角形を詰めていくデモです。

コンストラクターで ElementRef を取得できる事がわかれば
簡単に書けますね!!

コード

main.dart

import 'package:angular2/platform/browser.dart';
import 'package:angular2/core.dart';
import 'dart:async';
import 'dart:html' as html;
import 'dynablock.dart' as dyna;
import 'dart:math';

main() {
  bootstrap(AppComponent);
}

class DynamicItemParam {
  int w;
  int h;

  DynamicItemParam() {
    Random rnd = new Random();
    w = rnd.nextInt(100) + 50;
    h = rnd.nextInt(200) + 100;
  }
}

@Component(
  selector: 'dynamicitem',
  template: """
  xxx
  """,
)
class DynamicItem implements OnInit {
  @Input()
  DynamicComponent parent;

  @Input()
  int width = 100;

  @Input()
  int height = 200;

  final ElementRef element;

  DynamicItem(this.element) {
    (element.nativeElement as html.Element).style.width = "${width}px";
    (element.nativeElement as html.Element).style.height = "${height}px";
    (element.nativeElement as html.Element).style.color = "#FF00";
    (element.nativeElement as html.Element).style.padding = "0px";
    (element.nativeElement as html.Element).style.margin = "0px";
    (element.nativeElement as html.Element).style.backgroundColor = 'yellow';
    (element.nativeElement as html.Element).style.display = 'inline-block';
    (element.nativeElement as html.Element).style.border =
    "medium solid #333333";
  }

  ngOnInit() {
    print("xx1 ${element.nativeElement}");
    (element.nativeElement as html.Element).style.width = "${width}px";
    (element.nativeElement as html.Element).style.height = "${height}px";
    if (parent != null) {
      parent.append(this);
    }
  }
}


@Component(
  selector: 'markdown-component',
  directives: const [DynamicItem],
  template: """
  <div #markdowncontent>
    <dynamicitem  *ngFor='let c of contents' [parent]='own' [width]='c.w' [height]='c.h' ></dynamicitem>
  </div>
  """,
)
class DynamicComponent implements OnInit {
  @Input()
  List<DynamicItemParam> contents;
  List<DynamicItem> items = [];

  html.Element _contentElement;
  dyna.DynaBlockCore dynaCore = new dyna.DynaBlockCore();


  final ElementRef element;
  DynamicComponent own;

  DynamicComponent(this.element) {
    var elm = element.nativeElement;
    elm.style.position = "absolute";
    own = this;
  }

  @ViewChild('markdowncontent')
  set main(ElementRef elementRef) {
    _contentElement = elementRef.nativeElement;
    print("${elementRef} ${elementRef.nativeElement}");
    _contentElement.onChange.listen((e) {
      print("-a");
    });
  }

  append(DynamicItem ap) {
    print("XXS");
    var elm = ap.element.nativeElement;
    int margineW = 10;
    int margineH = 10;
    dyna.FreeSpaceInfo info = dynaCore.addBlock(
        ap.width + margineW, ap.height + margineH);
    elm.style.position = "absolute";
    elm.style.left = "${info.xs}px";
    elm.style.top = "${info.y}px";
  }

  ngOnInit() {
  }
}

@Component(
    selector: 'my-app',
    directives: const [DynamicComponent],
    template: """
    <markdown-component [contents]='contents'></markdown-component>
  """
)
class AppComponent implements OnInit {
  List<DynamicItemParam> contents = [
    new DynamicItemParam(),
    new DynamicItemParam(),
    new DynamicItemParam(),
    new DynamicItemParam(),
  ];

  ngOnInit() async {
    for (int i = 0; i < 10; i++) {
      contents.add(new DynamicItemParam());
      await new Future.delayed(new Duration(milliseconds: 500));
    }
  }
}


四角形を埋め尽くすアルゴ

https://github.com/firefirestyle/ebook_windstyle_markdown/blob/master/angular/tiny-dynamicblock/app/web/dynablock.dart


2017年1月28日土曜日

火の型 Scratchでプログラム入門 固定レイアウト版 おまけ010-012はFIXしたと見なす

三角関数(1) 万有引力をシミュレーションしてみよう
https://firebook.firefirestyle.net/presents010.html



三角関数(2) 角度を指定して移動しよう
https://firebook.firefirestyle.net/presents011.html



三角関数(3) 万有引力をシミュレーションしてみよう
https://firebook.firefirestyle.net/presents012.html



以降はGitbookを参照してください。
https://www.gitbook.com/book/kyorohiro/firestyle/details
100pageくらいあります。

AngularDart で Markdownを利用してみる

AngularDart で Markdownを利用してみた。
"#" と、@ViewChild を利用の仕方を覚えた!!

https://github.com/firefirestyle/ebook_windstyle_markdown/tree/master/angular/tiny-markdown

import 'package:angular2/platform/browser.dart';
import 'package:angular2/core.dart';
import 'dart:async';
import 'dart:html' as html;
import 'package:markdown/markdown.dart' as mark;

main() {
  bootstrap(AppComponent);
}


@Component(
  selector: 'markdown-component',
  template: """
  <div #markdowncontent></div>
  """,
)
class MarkdownComponent implements OnInit {
  @Input()
  String content;

  html.Element _contentElement;

  @ViewChild('markdowncontent')
  set main(ElementRef elementRef) {
    _contentElement = elementRef.nativeElement;
  }

  ngOnInit() {
    _contentElement.children.clear();
    _contentElement.children.add(new html.Element.html(
        """<div>${mark.markdownToHtml(content)}</div>""",
        treeSanitizer: html.NodeTreeSanitizer.trusted)
    );
    print(">> ${content}");
  }
}

@Component(
    selector: 'my-app',
    directives: const [MarkdownComponent],
    template: """
    <markdown-component [content]='content'></markdown-component>
  """
)
class AppComponent {
  String content = """
# H1
aasasdfa;lklasdf
  """;
}



mbedtls dart の 開発を始めた web wasm ffi io flutter

C言語 で開発した機能を、Dart をターゲットとして、Web でも サーバーでも、そして Flutter  でも使えるようにしたい。 そこで、mbedtls の 暗号化の部分を Dart 向けのPackageを作りながら、 実現方法を試行錯誤する事にした。 dart...