Exemplo n.º 1
0
        //①Overrides Form.OnLoad method
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e); //You should call base.Load(e); at first line of this method when you override OnLoad method.

            //Use OpenFileDialog
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "pmx model file(*.pmx)|*.pmx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //Load model when ShowDialog result is DialogResult.OK


                //②Load Model
                MMDModel model = MMDModelWithPhysics.OpenLoad(ofd.FileName, RenderContext);//MMDModel MMDModelWithPhysics.OpenLoad(string fileName,RenderContext);
                //When you want to disable physics calclation,you can do that by using the static method below.
                //MMDModel model=MMDModel.OpenLoad(ofd.FileName, RenderContext);
                //RenderContext contains device data,direct2D device data..and so on using for rendering 3DCG world. If the class  extends RenderForm,you can use this field as RenderContext.
                //The method or classes rendering something sometimes require this value.

                //③Add model to world.
                WorldSpace.AddResource(model);
                //WorldSpace manages the models added to world. If you add a drawable obeject to WorldSpace,the object will be rendered.
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// ファイルにMMDモデルを書きだす
        /// </summary>
        /// <param name="filename">書きだすファイル名</param>
        /// <param name="model">モデルオブジェクト</param>
        /// <param name="scale">スケーリング値</param>
        public static void Write(string filename, MMDModel model, float scale = 1f)
        {
            //フルパス取得
            filename = Path.GetFullPath(filename);
            //ファイルリーダー
            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                BinaryWriter writer = new BinaryWriter(fs);

                //マジック文字列
                writer.Write(MMDModel1.encoder.GetBytes("Pmd"));
                //バージョン
                writer.Write(model.Version);
                //中身の書きだし
                try
                {
                    model.Write(writer, scale);
                }
                catch (NullReferenceException e)
                {
                    throw new ArgumentNullException("modelの中の変数がnull", e);
                }
                fs.Close();
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// デフォルトコンストラクタ
 /// </summary>
 /// <param name="rigid">MMD剛体データ</param>
 /// <param name="Model">MMDモデルデータ</param>
 public MMDMotionState(MMDRigid rigid, MMDModel Model)
 {
     UserData = null;
     m_rigid = rigid;
     //初期の姿勢を計算
     Matrix startTransform;
     if (!string.IsNullOrEmpty(rigid.RelatedBoneName))
         startTransform = Model.BoneManager[rigid.RelatedBoneName].GlobalTransform;
     else
     {
         if (Model.BoneManager.IndexOf("センター") >= 0)
             startTransform = Model.BoneManager[Model.BoneManager.IndexOf("センター")].GlobalTransform;
         else
             startTransform = Matrix.Identity;
     }
     //ボーンと剛体とのズレを計算
     Matrix RigidBias = CreateRigidBias(rigid);
     //初期姿勢を計算
     startTransform = RigidBias * startTransform * Model.Transform;
     //初期の姿勢をMotionStateに設定
     btTransform startTrans;
     MMDXMath.TobtTransform(ref startTransform, out startTrans);
     
         
     m_graphicsWorldTrans = startTrans;
     m_centerOfMassOffset = btTransform.Identity;
     m_startWorldTrans = startTrans;
     //これからの計算ように確保
     m_rigidBias = RigidBias;
     RelatedBoneName =  rigid.RelatedBoneName;
     m_model = Model;
 }
Exemplo n.º 4
0
 static void OnLoadReferenceModel( string path )
 {
     var refLoader = new PMXLoader(
        path
     );
     RefModel = refLoader.MMDModel;
 }
Exemplo n.º 5
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ScreenContext.CameraMotionProvider = new BasicCameraControllerMotionProvider(this, this);
            BasicGrid grid = new BasicGrid();

            grid.Load(RenderContext);
            WorldSpace.AddResource(grid);
            bulletPhysics = new BulletPhysics(new Vector3(0, -9.8f, 0f));
            ground        = bulletPhysics.CreatePlane(0, Matrix.Identity);
            ball_Model    = MMDModel.OpenLoad("1.pmx", RenderContext);
            ball_Model2   = MMDModel.OpenLoad("1.pmx", RenderContext);
            RigidBodyData data = ball_Model.Model.RigidBodyList.RigidBodies[0];

            ball  = bulletPhysics.CreateSphere(data.Size.X, Matrix.Translation(-15, 12f, 0), 1f, 1f, 0f);
            ball2 = bulletPhysics.CreateSphere(data.Size.X, Matrix.Translation(15, 12f, 0), 1f, 1f, 0f);

            rigid2model = GetModelWorldFromRigid();

            WorldSpace.AddResource(ball_Model);
            WorldSpace.AddResource(ball_Model2);
            CreateWalls();
            ball.ApplyCentralImpulse(new Vector3(2, 0.01f, 0f));
            ball2.ApplyCentralImpulse(new Vector3(-2, 0, 0));
            brush  = SpriteBatch.CreateSolidColorBrush(Color.Brown);
            format = SpriteBatch.CreateTextformat("Meiriyo", 30);
            format.Format.ParagraphAlignment = ParagraphAlignment.Center;
            format.Format.TextAlignment      = TextAlignment.Center;
            timer1.Start();
        }
Exemplo n.º 6
0
        public bool BeginCapture(MMDModel target, HitResult hit)
        {
            // save local and world frames
            rotateFrameL = target.GetGameObjectFrame(CoordSpace.ObjectCoords);
            rotateFrameW = target.GetGameObjectFrame(CoordSpace.WorldCoords);
            rotateAxisW  = rotateFrameW.GetAxis(nRotationAxis);

            // save angle of hitpos in 2D plane perp to rotateAxis, so we can find delta-angle later
            Vector3f vWorldHitPos = hit.HitPosition;
            Vector3f dv           = vWorldHitPos - rotateFrameW.Origin;
            int      iX           = (nRotationAxis + 1) % 3;
            int      iY           = (nRotationAxis + 2) % 3;
            float    fX           = Vector3f.Dot(dv, rotateFrameW.GetAxis(iX));
            float    fY           = Vector3f.Dot(dv, rotateFrameW.GetAxis(iY));

            fRotateStartAngle = (float)Math.Atan2(fY, fX);

            // construct plane we will ray-intersect with in UpdateCapture()
            raycastFrame = new Frame3f(vWorldHitPos, rotateAxisW);
            if (EnableSnapping)
            {
                //enable_circle_indicator(true);
            }

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// ファイルにMMDモデルを書きだす
        /// </summary>
        /// <param name="filename">書きだすファイル名</param>
        /// <param name="model">モデルオブジェクト</param>
        /// <param name="scale">スケーリング値</param>
        public static void Write(string filename, MMDModel model, float scale = 1f)
        {
            //フルパス取得
            filename = Path.GetFullPath(filename);
            //ファイルリーダー
            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                BinaryWriter writer = new BinaryWriter(fs);

                //マジック文字列
                writer.Write(MMDModel1.encoder.GetBytes("Pmd"));
                //バージョン
                writer.Write(model.Version);
                //中身の書きだし
                try
                {
                    model.Write(writer, scale);
                }
                catch (NullReferenceException e)
                {
                    throw new ArgumentNullException("modelの中の変数がnull", e);
                }
                fs.Close();
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="rigids">剛体情報</param>
        /// <param name="joints">関節情報</param>
        /// <param name="model">モデル情報</param>
        public PhysicsManager(MMDRigid[] rigids, MMDJoint[] joints, MMDModel model)
        {
            List<RigidBody> rbodies = new List<RigidBody>();
            List<Generic6DofSpringConstraint> dofjoints = new List<Generic6DofSpringConstraint>();
            motionState = new List<MMDMotionState>();
            List<short> groups = new List<short>();
            List<short> masks = new List<short>();
            //剛体の作成
            for (int i = 0; i < rigids.Length; i++)
            {
                MMDMotionState mstate;
                short group;
                rbodies.Add(CreateRigidBody(rigids[i], model, out group, out mstate));
                motionState.Add(mstate);
                groups.Add(group);
                masks.Add((short)rigids[i].GroupTarget);
            }
            //ジョイント(拘束)の作成
            for (int i = 0; i < joints.Length; i++)
            {
                RigidBody phisic0 = rbodies[(int)joints[i].RigidBodyA];
                RigidBody phisic1 = rbodies[(int)joints[i].RigidBodyB];
                dofjoints.Add(CreateJoint(phisic0, phisic1, joints[i], model));
            }

            Rigids = new ReadOnlyCollection<RigidBody>(rbodies);
            this.groups = groups.ToArray();
            this.masks = masks.ToArray();
            Joints = new ReadOnlyCollection<Generic6DofSpringConstraint>(dofjoints);
            bSetup = true;
            //イベントをフック
            PhysicsThreadManager.Instanse.Synchronize += new Action(Update);
            PhysicsThreadManager.Instanse.DropFrame += new Action<int>(DropFrame);
        }
Exemplo n.º 9
0
        public static void Main( string[] args )
        {

            if ( !SharpDevice.IsDirectX11Supported( ) )
            {
                MessageBox.Show( "DirectX11 Not Supported" );
                return;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "pmx|*.pmx";
            if ( openFileDialog.ShowDialog( ) == DialogResult.OK )
            {
                string V = openFileDialog.FileName;
                //PMXLoader.WriteTestCSV( V );
                LoadedFromDialog = new PMXLoader( V );
                Model = LoadedFromDialog.MMDModel;
                MorphViewer = new VertMorphViewer( Model.Morphs );
                Model.BindMorphProp( MorphViewer.BarValues );
                MorphViewer.Show( );
                ModForm = new BlenderModifier.SphereModForm( LoadedFromDialog);
                ModForm.OnLoadReferenceModel = OnLoadReferenceModel;
                NormalStart( );
            }

        }
Exemplo n.º 10
0
 public static void XMLTest()
 {
     foreach (var i in Selection.objects)
     {
         string path = AssetDatabase.GetAssetPath(i.GetInstanceID());
         path = Application.dataPath.Remove(Application.dataPath.Length - 6) + path;
         var a = MMDModel.GetMMDModel(path);
     }
 }
Exemplo n.º 11
0
        public bool EndCapture(MMDModel target)
        {
            if (EnableSnapping)
            {
                //enable_circle_indicator(false);
                //enable_snap_indicator(false);
            }

            return(true);
        }
 public ActionResult Edit(MMDModel <SecurityRole, SecurityForm, SecurityRoleAccess> pModel)
 {
     if (oRoleAccessBLL.SaveList(pModel.DetailList))
     {
         return(RedirectToAction("IndexRoleForms", new { pRoleCode = pModel.Master1.RoleCode, pApplicationCode = pModel.Master2.ApplicationCode }));
     }
     else
     {
         return(HttpNotFound());
     }
 }
Exemplo n.º 13
0
 public ActionResult Edit(MMDModel <SecurityUser, SecurityForm, SecurityUserAccess> pModel)
 {
     if (oUserAccessBLL.SaveList(pModel.DetailList))
     {
         return(RedirectToAction("IndexUserForms", new { pUserCode = pModel.Master1.UserCode, pApplicationCode = pModel.Master2.ApplicationCode, pFormCode = pModel.Master2.FormCode }));
     }
     else
     {
         return(HttpNotFound());
     }
 }
Exemplo n.º 14
0
        private RigidBody CreateRigidBody(MMDRigid rigid, MMDModel Model,out short group, out MMDMotionState motionStateStart)
        {
            CollisionShape collision;
            RigidBody body;
            //衝突スキンの作成
            switch (rigid.ShapeType)
            {
                case 0:
                    collision = new SphereShape(rigid.ShapeWidth);
                    break;
                case 1:
                    collision = new BoxShape(new btVector3(rigid.ShapeWidth, rigid.ShapeHeight, rigid.ShapeDepth));
                    break;
                case 2:
                    collision = new CapsuleShape(rigid.ShapeWidth, rigid.ShapeHeight);
                    break;
                default:
                    throw new NotImplementedException("不明な剛体タイプ");
            }


            motionStateStart = new MMDMotionState(rigid, Model);

            btVector3 localInertia = btVector3.Zero;
            //イナーシャの計算
            if (rigid.Type != 0)
                collision.calculateLocalInertia(rigid.Weight, out localInertia);


            //剛体を作成
            body = new RigidBody((rigid.Type != 0 ? rigid.Weight : 0), motionStateStart, collision, localInertia);
            //ダンピング値、摩擦、Restitutionをセット
            body.setDamping(rigid.LinerDamping, rigid.AngularDamping);
            body.Friction = rigid.Friction;
            body.Restitution = rigid.Restitution;

            //ボーン追従型はKinematicにする
            if (rigid.Type == 0)
            {
                body.ActivationState |= ActivationStateFlags.DISABLE_DEACTIVATION;
                body.CollisionFlags = CollisionFlags.CF_KINEMATIC_OBJECT;
                if (!string.IsNullOrEmpty(rigid.RelatedBoneName))
                    Model.BoneManager[rigid.RelatedBoneName].IsPhysics = false;
            }
            else
            {//物理演算型はボーンのフラグをオンにする
                if (!string.IsNullOrEmpty(rigid.RelatedBoneName))
                    Model.BoneManager[rigid.RelatedBoneName].IsPhysics = true;
            }
            //グループのフラグをセット
            group = (short)Math.Pow(2, rigid.GroupIndex);

            return body;
        }
Exemplo n.º 15
0
 public LatticeDef(MMDModel model, int[] divs = null)
 {
     if (divs == null)
     {
         divs = new int[3] {
             3, 3, 3
         };
     }
     UVW = divs;
     Start(model);
     //LatticeData は BKE_lattice_resize, init_latt_deform で初期化されている
 }
Exemplo n.º 16
0
 // ビリヤード台の剛体を作る
 private void CreateBilliardRigids(MMDModel model)
 {
     foreach (RigidBodyData rigidBody in model.Model.RigidBodyList.RigidBodies)
     {
         Matrix trans = Matrix.Translation(rigidBody.Position);
         Matrix rot   = Matrix.RotationYawPitchRoll(rigidBody.Rotation[1], rigidBody.Rotation[0],
                                                    rigidBody.Rotation[2]);
         bulletPhysics.CreateBox(rigidBody.Size.X, rigidBody.Size.Y, rigidBody.Size.Z, rot * trans, 0,
                                 1, 0, 0, 0);
     }
     models[0].Transformer.Position = new Vector3(0, 0, 0);
     models[0].Transformer.Rotation = Quaternion.Identity;
 }
Exemplo n.º 17
0
        /// <summary>
        /// ファイルからMMDモデルを読み込む
        /// </summary>
        /// <param name="filename">MMDモデルファイル</param>
        /// <param name="coordinate">変換先座標系</param>
        /// <param name="scale">スケーリング値</param>
        /// <returns>MMDモデルオブジェクト</returns>
        ///  <remarks>MMDの座標系は右手座標系です</remarks>
        public static MMDModel Read(string filename, CoordinateType coordinate, float scale = 1f)
        {
            //フルパス取得
            filename = Path.GetFullPath(filename);
            //ファイルチェック
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("MMDモデルファイル:" + filename + "が見つかりません");
            }
            //戻り値用変数
            MMDModel result = null;

            //ファイルリーダー
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                BinaryReader reader = new BinaryReader(fs);
                //マジック文字列
                string magic = MMDModel1.encoder.GetString(reader.ReadBytes(3));
                if (magic != "Pmd")
                {
                    throw new FileLoadException("MMDモデルファイルではありません");
                }
                //バージョン
                float version = BitConverter.ToSingle(reader.ReadBytes(4), 0);
                if (OriginalObjects.ContainsKey(version) &&
                    OriginalObjects[version].BaseType == typeof(MMDModel))
                {//このバージョンで使用し、利用可能型
                    result = (MMDModel)OriginalObjects[version].InvokeMember(null, System.Reflection.BindingFlags.CreateInstance, null, null, null);
                }
                else
                {
                    if (version == 1.0)
                    {
                        result = new MMDModel1();
                    }
                    else
                    {
                        throw new FileLoadException("version=" + version.ToString() + "モデルは対応していません");
                    }
                }
                result.Read(reader, coordinate, scale);
                if (fs.Length != fs.Position)
                {
                    Console.WriteLine("警告:ファイル末尾以降に不明データ?");
                }
                fs.Close();
            }
            return(result);
        }
Exemplo n.º 18
0
        //GET: /User/Details/5
        public ActionResult IndexUserForms(string pUserCode, string pApplicationCode)
        {
            MMDModel <SecurityUser, SecurityApplication, SecurityForm> vModel = new MMDModel <SecurityUser, SecurityApplication, SecurityForm>();

            vModel.Master1    = oUserBLL.GetByCode(pUserCode);
            vModel.Master2    = oApplicationBLL.GetByCode(pApplicationCode);
            vModel.DetailList = oFormBLL.GetByApplicationCode(vModel.Master2.ApplicationCode).ToList();

            if (vModel.Master1 == null || vModel.Master2 == null)
            {
                return(HttpNotFound());
            }

            return(View(vModel));
        }
Exemplo n.º 19
0
        // 球の剛体を作る
        private void CreateSphereRigid(MMDModel model, Vector3 rigid_position)
        {
            RigidBodyData rigidBody    = model.Model.RigidBodyList.RigidBodies[0];
            float         radius       = rigidBody.Size.X;
            float         mass         = rigidBody.Mass;
            float         restitution  = 1; //rigidBody.Repulsion;
            float         friction     = 0; //rigidBody.Friction;
            float         linear_damp  = 0; // rigidBody.MoveAttenuation;
            float         angular_damp = rigidBody.RotationAttenuation;
            Matrix        world        = Matrix.Translation(rigid_position);
            ConvexShape   shape;

            balls.Add(bulletPhysics.CreateSphere(radius, world, mass, restitution, friction, linear_damp, angular_damp));
            count++;
        }
Exemplo n.º 20
0
        //GET: /User/Details/5
        public ActionResult Edit(string pUserCode, string pApplicationCode, string pFormCode)
        {
            MMDModel <SecurityUser, SecurityForm, SecurityUserAccess> pModel = new MMDModel <SecurityUser, SecurityForm, SecurityUserAccess>();

            pModel.Master1    = oUserBLL.GetByCode(pUserCode);
            pModel.Master2    = oFormBLL.GetByCode(pApplicationCode, pFormCode);
            pModel.DetailList = oUserAccessBLL.GetByUserAppForm(pModel.Master1, pModel.Master2);

            if (pModel.Master1 == null)
            {
                return(HttpNotFound());
            }

            return(View(pModel));
        }
Exemplo n.º 21
0
 public static Frame3f GetGameObjectFrame(this MMDModel go, CoordSpace eSpace)
 {
     if (eSpace == CoordSpace.WorldCoords)
     {
         return(new Frame3f(go.Position, go.Rotation));
     }
     else if (eSpace == CoordSpace.ObjectCoords)
     {
         //return new Frame3f(go.transform.localPosition, go.transform.localRotation);
         //Util.DebugWrite("ObjectCoords" + go.Rotation.ToString( ) );
         return(new Frame3f(go.Position, go.Rotation));
     }
     else
     {
         throw new ArgumentException("not possible without refernce to scene!");
     }
 }
Exemplo n.º 22
0
    void Start(MMDModel model)
    {
        mesh = model;//GetComponent<MeshFilter>().mesh;

        keytype = KEYType.KEY_BSPLINE;
        overts  = mesh.OrigVertice;
        verts   = mesh.Vertice;
        int len = verts.Length;

        nverts = new Vertex[len];
        NotifyChanged( );
        init_latt_deform( );
        lattice_deform_vertsFull( );
        topind = LatticeData.FirstIndex(l => SamePos(l.Value.Position, new Vector3(0, 1, 0)));
#if INTERPOLATION
        interp = new Interpolation.Elastic(2, 10, 7, 1);
#endif
    }
Exemplo n.º 23
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "pmx model file(*.pmx)|*.pmx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                MMDModel model = MMDModelWithPhysics.OpenLoad(ofd.FileName, RenderContext);

                //OpenFileDialog to select vmd motion file
                OpenFileDialog ofd2 = new OpenFileDialog();
                ofd2.Filter = "vmd motion file(*.vmd)|*.vmd";
                if (ofd2.ShowDialog() == DialogResult.OK)
                {
                    //①Load motion file
                    IMotionProvider motion = model.MotionManager.AddMotionFromFile(ofd2.FileName, true);
                    //You should add your motion file to the model you wanting to apply.
                    //IMotionProvider AddMotionFromFile(string fileName,bool ignoreParentBone);
                    //If you set true in secound argument to the method above,MMF will ignore root bones motion.
                    //For instance,you want to walk by your code and motion with motion file,motion file might move model coordinate.
                    //When MMF ignore parent bone,MMF will not move model coordinate by motion.

                    //②Apply motion to your PMX model
                    model.MotionManager.ApplyMotion(motion, 0, ActionAfterMotion.Replay);
                    //Secound argument:
                    //Start frame number
                    //Third argument:
                    //What MMF should do when motion playing is finished.
                    //If you want MMF to do nothing when motion playing is finished,you should set ActionAfterMotion.Nothing in third argument.

                    //Extra
                    //(1) How to stop motion?
                    //You can stop motion by using the code below.
                    //model.MotionManager.StopMotion();
                    //(2) What frame number is it playing?
                    //You can get form model.MotionManager.CurrentFrame.
                }
                WorldSpace.AddResource(model);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        ///     コンストラクタ
        /// </summary>
        /// <param name="renderContext">レンダーコンテキスト</param>
        public Billiard(RenderContext renderContext)
        {
            CreateBallRayout();
            Vector3 gravity = new Vector3(0, -9.8f * 2.5f, 0);

            bulletPhysics = new BulletPhysics(gravity);

            MMDModel model = MMDModel.OpenLoad("../../res/ビリヤード台.pmx", renderContext);

            models.Add(model);
            CreateBilliardRigids(model);

            for (int i = 0; i < ballRayout.Count; ++i)
            {
                model = MMDModel.OpenLoad("../../res/" + (i + 1) + ".pmx", renderContext);
                models.Add(model);
                CreateSphereRigid(model, ballRayout[i]);
            }
            transferMatrixFromRigidToModel = GetTransferMatrixFromRigidToModel();
        }
Exemplo n.º 25
0
        public bool BeginCapture(MMDModel target, HitResult hit)
        {
            // save local and world frames
            translateFrameL = target.GetGameObjectFrame(CoordSpace.ObjectCoords);
            translateFrameW = target.GetGameObjectFrame(CoordSpace.WorldCoords);
            translateAxisW  = translateFrameW.GetAxis(nTranslationAxis);

            // save t-value of closest point on translation axis, so we can find delta-t
            Vector3 vWorldHitPos = hit.HitPosition;

            fTranslateStartT = ClosestPointOnLineT(
                translateFrameW.Origin, translateAxisW, vWorldHitPos);

            // construct plane we will ray-intersect with in UpdateCapture()
            Vector3 makeUp       = Vector3.Cross(Platform.Program.Camera.Forward, translateAxisW).GetNormalized( );
            Vector3 vPlaneNormal = Vector3.Cross(makeUp, translateAxisW).GetNormalized( );

            raycastFrame = new Frame3f(vWorldHitPos, vPlaneNormal);

            return(true);
        }
Exemplo n.º 26
0
        private void Form1_Load(object sender, EventArgs e)
        {
            panel.Initialize();
            panel.RenderContext.CameraMotionProvider = new BasicCameraControllerMotionProvider(panel, this);
            panel.Dock = DockStyle.Fill;
            Controls.Add(panel);
            var grid = new NormalGrid();

            grid.Visiblity = true;
            grid.Load(panel.RenderContext);
            panel.RenderContext.AddResource(grid);
            const int Nball  = 20;              // 球の数
            var       models = new List <MMDModel>();

            for (int i = 0; i < Nball; ++i)
            {
                models.Add(MMDModel.OpenLoad("../../res/1.pmx", panel.RenderContext));
                panel.RenderContext.AddResource(models[i]);
            }
            freeFall = new FreeFall(models);
        }
Exemplo n.º 27
0
        public bool UpdateCapture(MMDModel target, RayWrap worldRay)
        {
            int normalAxis = 2;

            if (nTranslationAxis == 2)
            {
                normalAxis = 1;
            }
            // ray-hit with plane that contains translation axis
            var planeHitOpt = raycastFrame.RayPlaneIntersection(worldRay.From, worldRay.Dir, normalAxis);

            if (!planeHitOpt.HasValue)
            {
                return(false);
            }
            Vector3 planeHit = planeHitOpt.Value;

            // figure out new T-value along axis, then our translation update is delta-t
            float fNewT   = ClosestPointOnLineT(translateFrameW.Origin, translateAxisW, planeHit);
            float fDeltaT = (fNewT - fTranslateStartT);

            fDeltaT *= TranslationScaleF( );
            if (DeltaDistanceConstraintF != null)
            {
                fDeltaT = DeltaDistanceConstraintF(translateFrameL, nTranslationAxis, fDeltaT);
            }

            // construct new frame translated along axis (in local space)
            Frame3f newFrame = translateFrameL;

            newFrame.Origin += fDeltaT * translateFrameL.GetAxis(nTranslationAxis);

            // update target
            //target.SetLocalFrame (newFrame, CoordSpace.ObjectCoords);
            target.Position = newFrame.Origin;
            return(true);
        }
Exemplo n.º 28
0
    async static void OnPostprocessAllAssets(string[] relativePaths, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        foreach (string relativePath in relativePaths)
        {
            if (relativePath.EndsWith(PMXExtension))
            {
                string inputFileAbsolutePath         = Application.dataPath + relativePath.TrimStart(AssetFolderName.ToCharArray());
                string inputFileName                 = Path.GetFileName(inputFileAbsolutePath);
                string inputFileNameWithoutExtension = inputFileName.TrimEnd(PMXExtension.ToCharArray());
                string inputFolderAbsolutePath       = Path.GetDirectoryName(inputFileAbsolutePath);
                string inputFolderRelativePath       = Path.GetDirectoryName(relativePath);
                string outputFolderAbsolutePath      = inputFolderAbsolutePath + outputFolderName + SanitizeFolderName(inputFileNameWithoutExtension) + "/";
                string outputFolderRelativePath      = inputFolderRelativePath + outputFolderName + SanitizeFolderName(inputFileNameWithoutExtension) + "/";
                string outputFileAbsolutePath        = outputFolderAbsolutePath + inputFileNameWithoutExtension + PrefabExtension;

                Transform model = await PMXModelLoader.LoadPMXModel(inputFileAbsolutePath, false);

                if (model == null)
                {
                    UnityEngine.Debug.Log("読み込みに問題がありました");
                    UnityEngine.Debug.Log(inputFileAbsolutePath);
                    continue;
                }

                if (!Directory.Exists(outputFolderAbsolutePath))
                {
                    Directory.CreateDirectory(outputFolderAbsolutePath);
                }

                string meshFolderAbsolutePath = outputFolderAbsolutePath + MeshFolderName;
                if (!Directory.Exists(meshFolderAbsolutePath))
                {
                    Directory.CreateDirectory(meshFolderAbsolutePath);
                }

                string avatarFolderAbsolutePath = outputFolderAbsolutePath + AvatarFolderName;
                if (!Directory.Exists(avatarFolderAbsolutePath))
                {
                    Directory.CreateDirectory(avatarFolderAbsolutePath);
                }

                string texturesFolderPath = outputFolderAbsolutePath + TexturesFolderName;
                if (!Directory.Exists(texturesFolderPath))
                {
                    Directory.CreateDirectory(texturesFolderPath);
                }

                string materialsFolderPath = outputFolderAbsolutePath + MaterialsFolderName;
                if (!Directory.Exists(materialsFolderPath))
                {
                    Directory.CreateDirectory(materialsFolderPath);
                }

                Mesh mesh = model.GetComponent <MMDModel>().Mesh;
                if (mesh != null)
                {
                    AssetDatabase.CreateAsset(mesh, outputFolderRelativePath + MeshFolderName + mesh.name + MeshExtension);
                }

                Animator animator = model.GetComponent <Animator>();
                if (animator != null)
                {
                    Avatar avatar = animator.avatar;
                    if (avatar != null)
                    {
                        AssetDatabase.CreateAsset(avatar, outputFolderRelativePath + AvatarFolderName + avatar.name + AvatarExtension);
                    }
                }

                foreach (Material material in model.GetComponent <MMDModel>().SkinnedMeshRenderer.sharedMaterials)
                {
                    if (material != null && material.mainTexture != null)
                    {
                        string textureAbsolutePath = texturesFolderPath + material.mainTexture.name + PNGExtension;
                        string textureRelativePath = outputFolderRelativePath + TexturesFolderName + material.mainTexture.name + PNGExtension;
                        using (FileStream fileStream = new FileStream(textureAbsolutePath, FileMode.Create))
                            using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
                            {
                                binaryWriter.Write((material.mainTexture as Texture2D).EncodeToPNG());
                            }
                        AssetDatabase.Refresh();
                        material.mainTexture = AssetDatabase.LoadAssetAtPath <Texture>(textureRelativePath);
                    }

                    if (material != null)
                    {
                        AssetDatabase.CreateAsset(material, outputFolderRelativePath + MaterialsFolderName + material.name + MaterialExtension);
                    }
                }

                MMDModel mmdModel = model.GetComponent <MMDModel>();
                mmdModel.ShowModel();

#if UNITY_EDITOR
                GameObject.DestroyImmediate(mmdModel);
#else
                GameObject.Destroy(mmdModel);
#endif

                PrefabUtility.SaveAsPrefabAsset(model.gameObject, outputFolderRelativePath + model.name + PrefabExtension);

#if UNITY_EDITOR
                GameObject.DestroyImmediate(model.gameObject);
#else
                GameObject.Destroy(model.gameObject);
#endif
            }
        }
    }
Exemplo n.º 29
0
    public async static Task <Transform> LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController, Transform parent, bool autoShowModel = true)
    {
        if (!File.Exists(path))
        {
            UnityEngine.Debug.Log(path);
            UnityEngine.Debug.Log("与えられたパスにファイルが存在ません");
            return(null);
        }

        MMDModel mmdModel = null;

        try
        {
            mmdModel = await MMDModel.ImportModel(path, autoShowModel);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Log(ex.Message);
            return(null);
        }

        if (mmdModel == null)
        {
            return(null);
        }

        try
        {
            AvatarMaker avaterMaker = mmdModel.gameObject.AddComponent <AvatarMaker>();
            avaterMaker.Prepare(mmdModel, runtimeAnimatorController);
            await avaterMaker.MakeAvatar();

#if UNITY_EDITOR
            GameObject.DestroyImmediate(avaterMaker);
#else
            GameObject.Destroy(avaterMaker);
#endif
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Log("アバターの作成に失敗しました");
            UnityEngine.Debug.Log(path);

            AvatarMaker avaterMaker = mmdModel.gameObject.GetComponent <AvatarMaker>();

#if UNITY_EDITOR
            if (avaterMaker != null)
            {
                GameObject.DestroyImmediate(avaterMaker);
            }
#else
            if (avaterMaker != null)
            {
                GameObject.Destroy(avaterMaker);
            }
#endif

            mmdModel.transform.parent        = parent;
            mmdModel.transform.localPosition = Vector3.zero;
            mmdModel.transform.localRotation = Quaternion.identity;

            return(mmdModel.transform);
        }

        mmdModel.transform.parent        = parent;
        mmdModel.transform.localPosition = Vector3.zero;
        mmdModel.transform.localRotation = Quaternion.identity;

        return(mmdModel.transform);
    }
Exemplo n.º 30
0
 public bool EndCapture(MMDModel target)
 {
     return(true);
 }
Exemplo n.º 31
0
        public bool UpdateCapture(MMDModel target, RayWrap worldRay)
        {
            int normalAxis = 2;

            if (nRotationAxis == 2)
            {
                normalAxis = 1;
            }

            // ray-hit with plane perpendicular to rotateAxisW
            var planeHitWOpt = raycastFrame.RayPlaneIntersection(worldRay.From, worldRay.Dir, normalAxis);

            if (!planeHitWOpt.HasValue)
            {
                return(false);
            }
            var planeHitW = planeHitWOpt.Value;

            // find angle of hitpos in 2D plane perp to rotateAxis, and compute delta-angle
            Vector3f dv = planeHitW - rotateFrameW.Origin;
            int      iX = (nRotationAxis + 1) % 3;
            int      iY = (nRotationAxis + 2) % 3;
            float    fX = Vector3.Dot(dv, rotateFrameW.GetAxis(iX));
            float    fY = Vector3.Dot(dv, rotateFrameW.GetAxis(iY));

            Util.DebugWrite("dv " + dv.ToString( ));
            Util.DebugWrite("planeHitW " + planeHitW.ToString( ));
            Util.DebugWrite("rotateFrameW " + rotateFrameW.Origin.ToString( ));

            float fNewAngle = (float)Math.Atan2(fY, fX);

            //if ( AbsoluteAngleConstraintF != null )
            //	fNewAngle = AbsoluteAngleConstraintF( rotateFrameL , nRotationAxis , fNewAngle );

            float fDeltaAngle = (fNewAngle - fRotateStartAngle);

            //if (DeltaAngleConstraintF != null)
            //    fDeltaAngle = DeltaAngleConstraintF(rotateFrameL, nRotationAxis, fDeltaAngle);

            Util.DebugWrite("fDeltaAngle " + fDeltaAngle);

            fDeltaAngle *= 0.03f;

            bool on_snap = false;

            if (EnableSnapping)
            {
                //double dist = (planeHitW - rotateFrameW.Origin).Length();
                //on_snap = Math.Abs(dist - gizmoRadiusW) < gizmoRadiusW * 0.15f;
                //if (on_snap)
                //    fDeltaAngle = (float)Snapping.SnapToIncrement(fDeltaAngle, SnapIncrementDeg * MathUtil.Deg2Radf);
                //enable_snap_indicator(true);
                //update_snap_indicator(-fDeltaAngle, on_snap);
            }

            // 軸を中心に回るターゲットのための新しいフレームを作る
            Vector3f   rotateAxisL = rotateFrameL.GetAxis(nRotationAxis);
            Quaternion q           = Quaternion.RotationAxis(rotateAxisL, fDeltaAngle.Deg());
            Frame3f    newFrame    = rotateFrameL;

            newFrame.Rotation = q * newFrame.Rotation;                          // order matters here!

            // update target
            target.SetLocalFrame(newFrame, CoordSpace.ObjectCoords);

            if (EnableSnapping)
            {
                //update_circle_indicator(on_snap);
            }

            return(true);
        }
Exemplo n.º 32
0
 public static void SetLocalFrame(this MMDModel go, Frame3f frame, CoordSpace eSpace)
 {
     go.Position = frame.Origin;
     go.Rotation = frame.Rotation;
 }
Exemplo n.º 33
0
        private Generic6DofSpringConstraint CreateJoint(RigidBody body0, RigidBody body1, MMDJoint joint, MMDModel model)
        {
            Matrix frameInA, frameInB;
            btTransform btFrameInA, btFrameInB;
            Matrix jointPos =MMDXMath.CreateMatrixFromYawPitchRoll(joint.Rotation[1], joint.Rotation[0], joint.Rotation[2])
                * MMDXMath.CreateTranslationMatrix(joint.Position[0], joint.Position[1], joint.Position[2]);
            if (body0.MotionState != null)
            {
                MMDMotionState motionState = (MMDMotionState)body0.MotionState;
                frameInA = MMDXMath.ToMatrix(motionState.GraphicsWorldTrans);
            }
            else
                throw new NotImplementedException("来るハズないのだが");
            frameInA = jointPos * model.Transform * Matrix.Invert(frameInA);
            if (body1.MotionState != null)
            {
                MMDMotionState motionState = (MMDMotionState)body1.MotionState;
                frameInB = MMDXMath.ToMatrix(motionState.GraphicsWorldTrans);
            }
            else
                throw new NotImplementedException("来るハズないのだが");
            frameInB = jointPos * model.Transform * Matrix.Invert(frameInB);
            //frameInB = jointPos * Matrix.Invert(MMDMath.ConvertToMatrix(body1.GetWorldTransformSmart()));
            MMDXMath.TobtTransform(ref frameInA, out btFrameInA);
            MMDXMath.TobtTransform(ref frameInB, out btFrameInB);

            Generic6DofSpringConstraint mConstPoint = new Generic6DofSpringConstraint(body0, body1, btFrameInA, btFrameInB, true);

            //G6Dof設定用変数の準備
            mConstPoint.setLinearLowerLimit(new btVector3(joint.ConstrainPosition1));
            mConstPoint.setLinearUpperLimit(new btVector3(joint.ConstrainPosition2));
            mConstPoint.setAngularLowerLimit(new btVector3(joint.ConstrainRotation1));
            mConstPoint.setAngularUpperLimit(new btVector3(joint.ConstrainRotation2));
            System.Diagnostics.Debug.WriteLine(joint.Name);
            for(int i=0;i<3;i++)
                System.Diagnostics.Debug.WriteLine(joint.ConstrainPosition1[i]);
            for (int i = 0; i < 3; i++)
                System.Diagnostics.Debug.WriteLine(joint.ConstrainPosition2[i]);
            for (int i = 0; i < 3; i++)
                System.Diagnostics.Debug.WriteLine(joint.ConstrainRotation1[i]);
            for (int i = 0; i < 3; i++)
                System.Diagnostics.Debug.WriteLine(joint.ConstrainRotation2[i]);

            for (int i = 0; i < 3; i++)
            {
                mConstPoint.setStiffness(i, joint.SpringPosition[i]);
                mConstPoint.enableSpring(i, true);
                mConstPoint.setStiffness(i + 3, joint.SpringRotation[i]);
                mConstPoint.enableSpring(i + 3, true);
            }
            mConstPoint.calculateTransforms();
            mConstPoint.setEquilibriumPoint();

            return mConstPoint;
        }
Exemplo n.º 34
0
    //lattice_deform_vertsから呼ばれる,notested done
    void init_latt_deform()
    {
        MMDModel  ob = null;
        Matrix4x4 latmat;
        Matrix4x4 imat;

        if (ob == null)
        {
            //デフォームスペースの行列
            latmat = latma.Inverted();
            //デフォーム配列に戻す
            imat = latmat.Inverted();
        }
        //今のところここに入るパターンが無い
        else
        {
            imat = latma.Inverted( );
            //latmat = imat * myself;
            latmat = Matrix4x4.Identity;
            //imat = latmat.inverse;
        }

        //BPoint bp;//頂点だけ参照している、lattice
        int           id       = 0;
        var           ffu      = fu;
        var           ffv      = fv;
        var           ffw      = fw;
        List <Vertex> vertices = new List <Vertex>( );

        for (int w = 0; w < UVW[2]; w++, fw += dw)
        {
            for (int v = 0; v < UVW[1]; v++, fv += dv)
            {
                for (int u = 0; u < UVW[0]; u++,
                     //bp++, co += 3, fp += 3,
                     fu += du)
                {
                    //coはlattice座標 fpは初期fu,fv,fwで引かれて0になる
                    Vertex value = LatticeData[id].Value;

#if true
                    value.Position = (mul_mat3_m4_v3(imat,  value.Position));
                    vertices.Add(value);
#else
                    Vector3 pos = value.Position - new Vector3(fu, fv, fw);
                    //latmatをかけて行列を戻す
                    value.Position = (mul_mat3_m4_v3(imat,  pos));
                    vertices.Add(value);
                    // ちゃんと変更
                    RelativeLattice[id] = new LatticeType(value);
                    // 常に相対になりたい
                    //                                                  0 0 0 -> -1 -1 -1
                    //RelativeLattice[ id ].ToReactivePropertyAsSynchronized( x => x.Value ,
                    //	convert :x => x + value ,convertBack: x => x - value );
#endif
                    id++;
                }
                fu = ffu;
            }
            fv = ffv;
        }
        fw = ffw;

        RelativeLattice = LatticeData.Select(
            (lat, i) => lat.Select(
                // x => x.Value , convert:
                x => LatticeData[i].Value - vertices[i]
                //, convertBack: x => vertices[ i ] - LatticeData[i].Value)
                ).ToReactiveProperty()).ToArray();
        latma = latmat;
    }