LoginSignup
5
2

More than 5 years have passed since last update.

Perspectiveで簡単WPF3Dモデリング!4

Posted at

ではいよいよ、球体を描画しましょう。MainWindow.csに以下のコードを追加してください。

public static Spherical3D CreateSphereModel(Point3D centerPoint, SolidColorBrush brush = null, double radius = 1)
{
    var sphere = new Spherical3D() { Material = new DiffuseMaterial(brush != null ? brush : Brushes.Red) };
    sphere = TranslateSphere(sphere, centerPoint, radius);
    return sphere;
}

// Translate sphere to specified position and size
public static Spherical3D TranslateSphere(Spherical3D sphere, Point3D centerPoint, double radius = 1)
{
    var tgroup = sphere.Transform as Transform3DGroup;
    if (tgroup == null)
    {
        tgroup = new Transform3DGroup();
        tgroup.Children.Add(new ScaleTransform3D(radius, radius, radius));
        var tt3D = new TranslateTransform3D(centerPoint.X, centerPoint.Y, centerPoint.Z);
        tgroup.Children.Add(tt3D);
    }
    else
    {
        var tt3D = tgroup.Children[1] as TranslateTransform3D;
        tt3D.OffsetX = centerPoint.X;
        tt3D.OffsetY = centerPoint.Y;
        tt3D.OffsetZ = centerPoint.Z;
        tgroup.Children[1] = tt3D;
    }
    sphere.Transform = tgroup;
    return sphere;
}

まず、CreateSphereModelメソッドでは、Perspectiveライブラリから、Spherical3Dクラスを呼び出します。しかし、このクラスは少々使い勝手が悪く、座標の指定や球体の半径などを決めることができません。そこで、TranslateSphereメソッドを用意します。
TranslateSphereメソッドでは、Spherical3Dインスタンスの座標やサイズを設定します。WPF2Dに慣れている方は、Controlの移動の際に、TranslateTransformなどを用いたことがあるかと思いますが、それの3Dバージョンだとお考えください。WPFの場合、すべてのControlにはTranformプロパティが備わっています。このTransformプロパティを変更することによって、Controlの形の変換をすべて行うことができます。
他のモデルも同様の方法で座標、サイズ、角度の変更が可能ですので、参考になれば幸いです。

MainWindow.csを以下のように変更します。

public MainWindow()
{
    InitializeComponent();
    axis3DViewport.Children.Add(new XyzAxis3D() { Length = 4, Radius = 0.03 });
    //var triangle = CreateTriangleModel(new Point3D(0, 1, 0), new Point3D(0, 0, 1), new Point3D(1, 0, 0), Brushes.Red);
    //var plane = CreatePlane(new Point3D(0, 1, 1), new Point3D(0, 0, 1), new Point3D(1, 0, 0), new Point3D(1, 1, 0), Brushes.Blue);
    //var cube = CreateCubeModel(new Point3D(0, 0, 0), 2, 1, 3, Brushes.Yellow);
    var sphere = CreateSphereModel(new Point3D(0, 0, 0), Brushes.Purple, 2);
    axis3DViewport.Children.Add(sphere);
}

Spherical3Dは、直接ViewPort3DのChildrenに追加できるところに注意して下さい。この親和性の高さがPerspectiveライブラリの魅力の一つだと僕は感じています。
実行結果は以下のようになります。

キャプチャ.PNG

5
2
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
5
2