Away3D TypeScriptではじめる3次元表現

第16回 炎の照り返しのアニメーションと床の反射を調整する

この記事を読むのに必要な時間:およそ 16.5 分

第11回から前回の第15回素材に凹凸と反射の強弱を与える─⁠─法線マップとスペキュラマップまでつくってきたAnimating particles simulating fireをお題としたパーティクルによる炎の表現は,いよいよ仕上げにかかる。炎のアニメーションや床への照り返しなどに細かな手を加えたい。

炎の照り返しを少しずつ拡げる

まずは,いわれないと気づかないかもしれない細かなアニメーションからだ。炎の照り返しを床にアニメーションとして加えた。その始まりで,炎のパーティクルは次第に大きくなるのに,照り返しのアニメーションはいきなり範囲が広い図1)⁠これをパーティクルと同じように,少しずつ拡げるようにしたい。

図1 燃え始めた炎の照り返しがいきなり大きい

図1 燃え始めた炎の照り返しがいきなり大きい

もっとも,炎が照り返す光のアニメーションは,前から手を加えるつもりでいた。炎のアニメーションを扱うクラス(FireObject)のコンストラクタに定めたプロパティのひとつ(strength)がこれまでまったく使われていない。実は,このプロパティが照り返しの光の強さを示す。

function FireObject(mesh, animator) {
  this.strength = 0;

}

炎の照り返しのアニメーションを行うメソッド(animateLight())で,つぎのように前述プロパティ(strength)の値を増してゆき,それを光のLightBase.diffuseLightBase.specularプロパティの値に反映させればよい。もちろん,炎のアニメーションを扱うオブジェクト(fireObject)がもつ光(light)のこれらのプロパティ値は以下のとおり,はじめに0に定めておく。

FireObject.prototype.animateLight = function(fallOff, radius, addition) {

  if (this.strength < 1) {
    this.strength += 0.05;
  }

  // light.diffuse = light.specular = 1 + addition;
  light.diffuse = light.specular = this.strength + addition; 

};
function startFire(eventObject) {

  var fireObject = fireObjects[count - 1];

  var light = new PointLight();

  light.diffuse = 0;
  light.specular = 0; 

  fireObject.light = light;

}

以上の修正を施したスクリプトは,炎のアニメーションを扱うクラス(FireObject)とパーティクルのアニメーション全体を組み立てるJavaScriptコードに分けて以下に掲げたコード1およびコード2)⁠これで,炎が照り返す光も,炎のパーティクルと同じように,少しずつ広がってゆく。

コード1 炎のアニメーションを扱うクラス

function FireObject(mesh, animator) {
  this.strength = 0;
  this.mesh = mesh;
  this.animator = animator;
}
FireObject.prototype.startAnimation = function() {
  this.animator.start();
};
FireObject.prototype.animateLight = function(fallOff, radius, addition) {
  var light = this.light;
  if (light) {
    if (this.strength < 1) {
      this.strength += 0.05;
    }
    light.fallOff = fallOff;
    light.radius = radius;
    light.diffuse = light.specular = this.strength + addition;
  }
};

コード2 パーティクルのアニメーション全体を組み立てる

var BlendMode = require("awayjs-core/lib/data/BlendMode");
var LoaderEvent = require("awayjs-core/lib/events/LoaderEvent");
var TimerEvent = require("awayjs-core/lib/events/TimerEvent");
var ColorTransform = require("awayjs-core/lib/geom/ColorTransform");
var Vector3D = require("awayjs-core/lib/geom/Vector3D");
var AssetLibrary = require("awayjs-core/lib/library/AssetLibrary");
var URLRequest = require("awayjs-core/lib/net/URLRequest");
var RequestAnimationFrame = require("awayjs-core/lib/utils/RequestAnimationFrame");
var Timer = require("awayjs-core/lib/utils/Timer");
var View = require("awayjs-display/lib/containers/View");
var DirectionalLight = require("awayjs-display/lib/entities/DirectionalLight");
var Mesh = require("awayjs-display/lib/entities/Mesh");
var PointLight = require("awayjs-display/lib/entities/PointLight");
var StaticLightPicker = require("awayjs-display/lib/materials/lightpickers/StaticLightPicker");
var PrimitivePlanePrefab = require("awayjs-display/lib/prefabs/PrimitivePlanePrefab");
var ParticleAnimationSet = require("awayjs-renderergl/lib/animators/ParticleAnimationSet");
var ParticleAnimator = require("awayjs-renderergl/lib/animators/ParticleAnimator");
var ParticlePropertiesMode = require("awayjs-renderergl/lib/animators/data/ParticlePropertiesMode");
var ParticleBillboardNode = require("awayjs-renderergl/lib/animators/nodes/ParticleBillboardNode");
var ParticleScaleNode = require("awayjs-renderergl/lib/animators/nodes/ParticleScaleNode");
var ParticleVelocityNode = require("awayjs-renderergl/lib/animators/nodes/ParticleVelocityNode");
var ParticleColorNode = require("awayjs-renderergl/lib/animators/nodes/ParticleColorNode");
var DefaultRenderer = require("awayjs-renderergl/lib/DefaultRenderer");
var MethodMaterial = require("awayjs-methodmaterials/lib/MethodMaterial");
var MethodRendererPool = require("awayjs-methodmaterials/lib/pool/MethodRendererPool");
var MethodMaterialMode = require("awayjs-methodmaterials/lib/MethodMaterialMode");
var HoverController = require("awayjs-display/lib/controllers/HoverController");
var ParticleGeometryHelper = require("awayjs-renderergl/lib/utils/ParticleGeometryHelper");
var view;
var plane;
var cameraController;
var lightPicker;
var timer;
var planeDiffuse = "assets/floor_diffuse.jpg";
var imageNormal = "assets/floor_normal.jpg";
var imageSpecular = "assets/floor_specular.jpg";
var imageParticle = "assets/blue.png";
var lastMouseX;
var lastMouseY;
var lastPanAngle;
var lastTiltAngle;
var fireObjects;
var particleMaterial;
function initialize() {
  var directionalLight = createDirectionalLight(0.25, 0xFFFFFF);
  view = createView(240, 180, 0x0);
  var scene = view.scene;
  lightPicker = new StaticLightPicker([directionalLight]);
  plane = createPlane(800, 800, lightPicker, -20, 2.5);
  fireObjects = createParticles(3, 500, 300, 5, scene);
  scene.addChild(plane);
  cameraController = setupCameraController(view.camera, 1000, 0, 90, 45, 20);
  loadAsset(planeDiffuse);
  loadAsset(imageNormal);
  loadAsset(imageSpecular);
  loadAsset(imageParticle);
  document.onmousedown = startDrag;
  timer = new RequestAnimationFrame(render);
  timer.start();
  var fireTimer = new Timer(1000, fireObjects.length);
  fireTimer.addEventListener(TimerEvent.TIMER, startFire);
  fireTimer.start();
}
function createView(width, height, backgroundColor) {
  var defaultRenderer = new DefaultRenderer(MethodRendererPool);
  var view = new View(defaultRenderer);
  view.width = width;
  view.height = height;
  view.backgroundColor = backgroundColor;
  return view;
}
function createPlane(width, height, light, y, specular) {
  var material = new MethodMaterial();
  var plane = new PrimitivePlanePrefab(width, height).getNewObject();
  material.mode = MethodMaterialMode.MULTI_PASS;
  plane.material = material;
  material.lightPicker = light;
  material.specular = specular;
  plane.y = y;
  return plane;
}
function createParticles(numFires, numParticles, radius, y, scene) {
  var GLOBAL = ParticlePropertiesMode.GLOBAL;
  var startColor = new ColorTransform(0, 0, 0, 1, 0xFF, 0x33, 0x01);
  var endColor = new ColorTransform(0, 0, 0, 1, 0x99);
  var animations = [
    new ParticleBillboardNode(),
    new ParticleScaleNode(GLOBAL, false, false, 2.5, 0.5),
    new ParticleVelocityNode(GLOBAL, new Vector3D(0, 80, 0)),
    new ParticleColorNode(GLOBAL, true, true, false, false, startColor, endColor),
    new ParticleVelocityNode(ParticlePropertiesMode.LOCAL_STATIC)
  ];
  var animationSet = getParticleAnimationSet(animations, initParticle);
  var primitive = new PrimitivePlanePrefab(10, 10, 1, 1, false);
  var geometry = primitive.geometry;
  var material = particleMaterial = new MethodMaterial();
  var geometrySet = [];
  material.blendMode = BlendMode.ADD;
  for (var i = 0; i < numParticles; i++) {
    geometrySet[i] = geometry;
  }
  var fireObjects = getFireObjects(geometrySet, numFires, material, animationSet, radius, y, scene);
  return fireObjects;
}
function getFireObjects(geometrySet, numFires, material, animationSet, radius, y, scene) {
  var fireObjects = [];
  var particleGeometry = ParticleGeometryHelper.generateGeometry(geometrySet);
  var anglePerFire = Math.PI * 2 / numFires;
  for (var i = 0; i < numFires; i++) {
    var mesh = createAnimationParticle(particleGeometry, material, animationSet, fireObjects);
    var angle = i * anglePerFire;
    mesh.x = radius * Math.sin(angle);
    mesh.z = radius * Math.cos(angle);
    mesh.y = y;
    scene.addChild(mesh);
  }
  return fireObjects;
}
function getParticleAnimationSet(animations, initParticleFunc) {
  var animationSet = new ParticleAnimationSet(true, true);
  var count = animations.length;
  for (var i = 0; i < count; i++) {
    animationSet.addAnimation(animations[i]);
  }
  animationSet.initParticleFunc = initParticleFunc;
  return animationSet;
}
function createAnimationParticle(particleGeometry, material, animationSet, fireObjects) {
  var mesh = new Mesh(particleGeometry, material);
  var animator = new ParticleAnimator(animationSet);
  mesh.animator = animator;
  fireObjects.push(new FireObject(mesh, animator));
  return mesh;
}
function initParticle(prop) {
  var PIx2 = Math.PI * 2;
  var radian0 = Math.random() * PIx2;
  var radian1 = Math.random() * PIx2;
  var velocityVector = getVector3D(15, radian0, radian1);
  prop.startTime = Math.random() * 5;
  prop.duration = Math.random() * 4 + 0.1;
  prop[ParticleVelocityNode.VELOCITY_VECTOR3D] = velocityVector;
}
function getVector3D(radius, angleXY, angleXZ) {
  var sinXY = Math.sin(angleXY);
  var cosXY = Math.cos(angleXY);
  var sinXZ = Math.sin(angleXZ);
  var cosXZ = Math.cos(angleXZ);
  var vector = new Vector3D(radius * cosXY * cosXZ, radius * cosXY * sinXZ, radius * sinXY);
  return vector;
}
function startFire(eventObject) {
  var fireTimer = eventObject.target;
  var count = fireTimer.currentCount;
  var fireObject = fireObjects[count - 1];
  var lights = lightPicker.lights;
  var light = new PointLight();
  fireObject.startAnimation();
  light.color = 0xFF3301;
  light.diffuse = 0;
  light.specular = 0;
  light.transform.position = fireObject.mesh.transform.position;
  fireObject.light = light;
  lights.push(light);
  lightPicker.lights = lights;
  if (count >= fireTimer.repeatCount) {
    fireTimer.removeEventListener(TimerEvent.TIMER, startFire);
  }
}
function createDirectionalLight(ambient, color) {
  var light = new DirectionalLight();
  light.ambient = ambient;
  light.color = color;
  return light;
}
function setupCameraController(camera, distance, minTiltAngle, maxTiltAngle, panAngle, tiltAngle) {
  var cameraController = new HoverController(camera);
  cameraController.distance = distance;
  cameraController.minTiltAngle = minTiltAngle;
  cameraController.maxTiltAngle = maxTiltAngle;
  cameraController.panAngle = panAngle;
  cameraController.tiltAngle = tiltAngle;
  return cameraController;
}
function loadAsset(url) {
  AssetLibrary.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
  AssetLibrary.load(new URLRequest(url));
}
function onResourceComplete(eventObject) {
  var assets = eventObject.assets;
  var material;
  var count = assets.length;
  var url = eventObject.url;
  for (var i = 0; i < count; i++) {
    var asset = assets[i];
    switch (url) {
      case (planeDiffuse):
        material = plane.material;
        material.texture = asset;
        break;
      case (imageNormal):
        material = plane.material;
        material.normalMap = asset;
        break;
      case (imageSpecular):
        material = plane.material;
        material.specularMap = asset;
        break;
      case (imageParticle):
        particleMaterial.texture = asset;
        break;
    }
  }
}
function render(timeStamp) {
  var count = fireObjects.length;
  for (var i = 0; i < count; i++) {
    var fireObject = fireObjects[i];
    fireObject.animateLight(380 + Math.random() * 100, 200 + Math.random() * 100, Math.random());
  }
  view.render();
}
function startDrag(eventObject) {
  lastMouseX = eventObject.clientX;
  lastMouseY = eventObject.clientY;
  lastPanAngle = cameraController.panAngle;
  lastTiltAngle = cameraController.tiltAngle;
  document.onmousemove = drag;
  document.onmouseup = stopDrag;
}
function drag(eventObject) {
  cameraController.panAngle = 0.5 * (eventObject.clientX - lastMouseX) + lastPanAngle;
  cameraController.tiltAngle = 0.3 * (eventObject.clientY - lastMouseY) + lastTiltAngle;
}
function stopDrag(eventObject) {
  document.onmousemove = null;
  document.onmouseup = null;
}

著者プロフィール

野中文雄(のなかふみお)

ソフトウェアトレーナー,テクニカルライター,オーサリングエンジニア。上智大学法学部卒,慶応義塾大学大学院経営管理研究科修士課程修了(MBA)。独立系パソコン販売会社で,総務・人事,企画,外資系企業担当営業などに携わる。その後,マルチメディアコンテンツ制作会社に転職。ソフトウェアトレーニング,コンテンツ制作などの業務を担当する。2001年11月に独立。Web制作者に向けた情報発信プロジェクトF-siteにも参加する。株式会社ロクナナ取締役(非常勤)。

URLhttp://www.FumioNonaka.com/

著書

コメント

コメントの記入