1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【未検証】three.jsのGeometryをJSONとして保存し、読み込む

1
Last updated at Posted at 2016-04-15

前提

課題

three.js の Geometry を、外部JSONとして保存して、再利用化したい。

問題

  • GeometryのJSON化はどうすればいいのか
  • JSON化したものをどう保存するのか
  • JSON化したものをどう読み込むのか

手法

GeometryのJSON化はどうすればいいのか

普通にtoJSONを呼ぶだけ

var geom = new THREE.BoxGeometry(1,1,1);
var json = geom.toJSON();

ただしこの方法では、JSON化はできても「読み込む手段」がない。それについては、下記「JSON化したものをどう読み込むのか」参照

JSON化したものをどう保存するのか

外部保存するので、そもそものコードをNode.jsで書く必要がある

$ npm init
$ npm install three --save-dev
var THREE = require('three');
var fs = require('fs');

var geom = new THREE.BoxGeometry(1,1,1);
var json = geom.toJSON();
fs.writeFile('geom.json', JSON.stringify(json));

実はJSON.stringifyが、引数のtoJSONを自動で呼ぶっぽいので、あらかじめtoJSONをしておく必要はないっぽい

JSON化したものをどう読み込むのか

three.jsには、単純にGeometryをJSON化しただけのものを読み込む手段がないっぽい。なので、 __Geometryを一旦BufferGeometryに変換__し、JSON化する

// 書き出し側: node.js
var THREE = require('three');
var fs = require('fs');

var geom = new THREE.BoxGeometry(1,1,1);
var buffer_geom = new THREE.BufferGeometry().fromGeometry( geom );
var json = buffer_geom.toJSON();
fs.writeFile('geom.json', JSON.stringify(json));
// 読み込み側: ブラウザ【未検証】
var loader = new THREE.BufferGeometryLoader();
loader.load('geom.json', function(persed_geom){
  // 適当にmesh作る
});

【未検証】とは

実際に動くコードは書いたけど、上記のようなシンプルなコードではないので、上記コードそのものを動かして検証したわけではない。後日検証して、問題があるようなら修正する。
ちなみに、俺はgeom.jsonの中身が複数のBufferGeometryのJSONによる配列だったので、下記のようなコードになってる。

$.ajax({
  url: 'geoms.json', // BufferGeometryの配列
  success: function(geoms_json){
    var loader = new THREE.BufferGeometryLoader();
    $.each( geoms_json, function(i, geom_json){
      ver buffer_geom = loader.parse( geom_json );
      ver geom = new THREE.Geometry().fromBufferGeometry( buffer_geom );
    });
  });
});
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?