public override void Draw(Graphics g, double deltaTime) { base.Draw(g, deltaTime); Vector2 sub = Size * MMWMath.Lerp(0.95f, 1.0f, rate); var pos = WorldLocation + (Size - sub) * 0.5f; var add = (SelectedPanel == this ? 0.15f : 0.0f); var r = MMWMath.Lerp(0.75f, 1.0f, rate); r += Connected ? 0.3f : 0.0f; Drawer.DrawTextureScaled(texImage, pos.X, pos.Y, sub.X, sub.Y, new Color4(backColor.R * r, backColor.G * r + add, backColor.B * r, 1.0f)); if (texIcon != null && texIcon.Loaded) { var iconSize = texIcon.Size.ToVector2(); iconSize = new Vector2(64.0f); var iconPos = WorldLocation + (Size - iconSize) * 0.5f; Drawer.DrawTextureScaled(texIcon, iconPos.X, WorldLocation.Y + 24.0f, iconSize.X, iconSize.Y, Color4.White); } var size = g.MeasureString(Info.WorldName, DefaultFont); g.DrawString(Info.WorldName, DefaultFont, Brushes.White, WorldLocation.X + (Size.X - size.Width) * 0.5f, WorldLocation.Y + (Size.Y - size.Height) * 0.5f + 24.0f); size = g.MeasureString(Info.HostName, DefaultFontS); g.DrawString(Info.HostName, DefaultFontS, Brushes.LightGray, WorldLocation.X + (Size.X - size.Width) * 0.5f, WorldLocation.Y + (Size.Y - size.Height) * 0.5f + 48.0f); Icons.DrawConnection(g, WorldLocation.X + Size.X - 50.0f, WorldLocation.Y + 20.0f, 20.0f, 20.0f, Connected ? 2 : 0); }
protected override void Update(double deltaTime) { base.Update(deltaTime); showtime -= deltaTime; var l = logs.Count - 1; for (var i = l; i > (l - 30) && i >= 0; i--) { logs[i].position.X = MMWMath.Lerp(logs[i].position.X, 8.0f, MMWMath.Saturate((float)deltaTime * 12.0f)); } if (Input.Ctrl && Input.IsKeyDown(OpenTK.Input.Key.Down)) { Scroll -= (float)deltaTime * ScrollSpeed; showtime = ShowTime; } else if (Input.Ctrl && Input.IsKeyDown(OpenTK.Input.Key.Up)) { Scroll += (float)deltaTime * ScrollSpeed; showtime = ShowTime; } var max = logs.Sum(log => log.tex.Size.Height + Interval) + 8.0f - Size.Y; if (max < 0.0f) { max = 0.0f; } Scroll = MMWMath.Clamp(Scroll, 0.0f, max); }
protected override void OnReceivedMessage(string message, params object[] args) { if (message == "hud show") { Show(); } else if (message == "hud hide") { Hide(); } else if (message == "enable hotbar") { Enabled = true; } else if (message == "disable hotbar") { Enabled = false; } else if (message == "show dialog") { Enabled = false; Hide(); } else if (message == "close dialog") { Enabled = true; Show(); } else if (message == "set selected item index") { userData.ItemSelectIndex = MMWMath.Clamp((int)args[0], 0, userData.MaxHotbatItemCount - 1); } }
protected override void Draw(double deltaTime, Camera camera) { if (!Visible) { return; } var d = new Vector4(Transform.WorldPosition + new Vector3(0.0f, RenderHeight, 0.0f), 1.0f) * camera.View; if (d.Z > 0.0f) { return; } var vps = camera.ViewProjection * MatrixHelper.CreateScreen(MMW.RenderResolution.ToVector2()); var v = new Vector4(0.0f, RenderHeight, 0.0f, 1.0f) * Transform.WorldTransform * vps; var pos = v.Xy / v.W; var scale = MMWMath.Clamp(Math.Abs(2.0f / -d.Z), 0.01f, 1.0f); pos -= fix; var col = new Color4(1.0f, 1.0f, 1.0f, MMWMath.Clamp(1.0f - (-d.Z / 100.0f), 0.0f, 1.0f)); var g = Drawer.GetGraphics(); g.DrawString(GameObject.Name, font, Brushes.Black, pos.X + 2, pos.Y + 1); g.DrawString(GameObject.Name, font, brush, pos.X, pos.Y); Drawer.IsGraphicsUsed = true; //Drawer.DrawTexturePixeledAlignment(tex, ContentAlignment.TopLeft, pos.X, pos.Y, col, 0.0f, scale, 200 - (int)(-d.Z), true); }
protected override void Update(double deltaTime) { if (!completed && rate == 1.0f && asyncFunc == null) { var res = syncFunc(asyncResult); mes.mes = ""; LoadCompleted(this, res); syncFunc = null; completed = true; } else if (!completed && rate >= 0.0f && rate < 1.0f) { rate += (float)deltaTime; rate = MMWMath.Clamp(rate, 0.0f, 1.0f); if (rate == 1.0f && asyncFunc != null) { Task.Factory.StartNew(() => { asyncResult = asyncFunc(mes); asyncFunc = null; }); } } else if (completed && rate > 0.0f) { rate -= (float)deltaTime; rate = MMWMath.Clamp(rate, 0.0f, 1.0f); if (rate == 0.0f) { completed = false; rate = -1.0f; } } }
protected override void Update(double deltaTime) { transition += (trans ? -1.0f : 1.0f) * (float)deltaTime * 5.0f; transition = MMWMath.Saturate(transition); transit.Update(deltaTime); if (AcceptInput && !trans) { input.Update(deltaTime); controls.ForEach(c => c.Update(null, deltaTime)); if (input.IsBack) { MMW.GetAsset <Sound>("back").Play(); trans = true; transit.Target = new Vector2(-MMW.ClientSize.Width * 2.0f, 0.0f); GameObject.AddComponent <TitleScript>(); } } if (trans && transition < 0.01f) { Destroy(); } }
protected override void Update(double deltaTime) { base.Update(deltaTime); //rate = MMWMath.Lerp(rate, 1.0f, (float)deltaTime * 10.0f); transition += (trans ? -1.0f : 1.0f) * (float)deltaTime * 5.0f; transition = MMWMath.Saturate(transition); transit.Update(deltaTime); if (AcceptInput && !trans) { controls.ForEach(c => c.Update(null, deltaTime)); //input.Update(deltaTime); //if (input.IsDown || input.IsUp) rate = 0.0f; /* * if (state == State.ModeSelect) * { * if (input.IsDown) * { * modeSelectIndex = MMWMath.Repeat(modeSelectIndex + 1, 0, 3); * soundSelect.Play(); * } * else if (input.IsUp) * { * modeSelectIndex = MMWMath.Repeat(modeSelectIndex - 1, 0, 3); * soundSelect.Play(); * } * else if (input.IsSelect) * { * soundClick.Play(); * if (modeSelectIndex == (int)ModeSelect.PlayOffline) * { * trans = true; * GameObject.AddComponent<PlayerSelectScript>(); * * } * else if (modeSelectIndex == (int)ModeSelect.PlayOnline) * { * trans = true; * GameObject.AddComponent<ServerSelectScript>(); * } * } * } * else if (state == State.Option) * { * * } */ } if (trans && transition < 0.01f) { Destroy(); } }
public void NextSelect() { if (Tabs == null) { return; } if (Tabs[TabIndex].Items == null || Tabs[TabIndex].Items.Length == 0) { return; } SelectIndex = MMWMath.Repeat(SelectIndex + 1, 0, Tabs[TabIndex].Items.Length - 1); }
public void PrevTab() { if (Tabs == null) { return; } TabIndex = MMWMath.Repeat(TabIndex - 1, 0, 1); if (Tabs[TabIndex].Items == null || Tabs[TabIndex].Items.Length == 0) { return; } SelectIndex = MMWMath.Clamp(SelectIndex, 0, Tabs[TabIndex].Items.Length - 1); }
public override void Update(Graphics g, double deltaTime) { base.Update(g, deltaTime); if (IsMouseOn || SelectedPanel == this) { rate = MMWMath.Lerp(rate, 1.0f, (float)deltaTime * 6.0f); } else { rate = MMWMath.Lerp(rate, 0.0f, (float)deltaTime * 6.0f); } }
public override void Update(Graphics g, double deltaTime) { base.Update(g, deltaTime); if (IsMouseOn) { rate = MMWMath.Lerp(rate, 1.0f, (float)deltaTime * 10.0f); } else { rate = 0.0f; } }
protected override void Update(double deltaTime) { if (Input.IsKeyPressed(Key.Number1) && 0 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 0; } if (Input.IsKeyPressed(Key.Number2) && 1 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 1; } if (Input.IsKeyPressed(Key.Number3) && 2 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 2; } if (Input.IsKeyPressed(Key.Number4) && 3 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 3; } if (Input.IsKeyPressed(Key.Number5) && 4 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 4; } if (Input.IsKeyPressed(Key.Number6) && 5 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 5; } if (Input.IsKeyPressed(Key.Number7) && 6 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 6; } if (Input.IsKeyPressed(Key.Number8) && 7 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 7; } if (Input.IsKeyPressed(Key.Number9) && 8 < userData.MaxHotbatItemCount) { userData.ItemSelectIndex = 8; } if (Input.MouseWheel > 0) { userData.ItemSelectIndex = MMWMath.Repeat(userData.ItemSelectIndex + 1, 0, userData.MaxHotbatItemCount - 1); } if (Input.MouseWheel < 0) { userData.ItemSelectIndex = MMWMath.Repeat(userData.ItemSelectIndex - 1, 0, userData.MaxHotbatItemCount - 1); } }
public override void Update(Graphics g, double deltaTime) { base.Update(g, deltaTime); if (IsMouseOn && Input.MouseWheel != 0) { targetHeight -= Input.MouseWheel * 100.0f; targetHeight = MMWMath.Clamp(targetHeight, -((panels.Count - 1) / 2) * 180.0f, 0.0f); } dummy.LocalLocation = new Vector2(dummy.LocalLocation.X, MMWMath.Lerp(dummy.LocalLocation.Y, targetHeight, (float)deltaTime * 6.0f)); foreach (var p in panels) { p.Update(g, deltaTime); } }
protected override void Update(double deltaTime) { if (Pause) { return; } var dist = (Transform.WorldPosition - MMW.MainCamera.Transform.WorldPosition).Length; var interval = dist / (300.0 * Priority); if (interval > 0.2) { interval = 0.2; } time += deltaTime; frame += deltaTime * Speed; if (time >= interval) { time -= interval; Animator.Frame = MMWMath.Repeat((float)(frame * 30.0), 0.0f, maxframe); } if (setdelay > 0.0) { delay -= deltaTime; if (delay < 0.0) { delay = 0.0; } var rate = (float)(delay / setdelay); if (prevAnimName != null) { Animator.SetRate(prevAnimName, rate); } Animator.SetRate(animName, 1.0f - rate); if (delay == 0.0) { prevAnimName = animName; setdelay = 0.0; } } }
public override void Draw(Graphics g, double deltaTime) { var s = g.MeasureString(Text, Font); var l = GetLocation(s.Width, s.Height, Alignment); var pos = new Vector2(l.X + WorldLocation.X, l.Y + WorldLocation.Y); g.DrawString(Text, Font, Brush, pos.X, pos.Y); g.DrawLine(pen, pos.X, pos.Y + s.Height, MMWMath.Lerp(pos.X, pos.X + s.Width, rate), pos.Y + s.Height); if (rate > 0.0f) { Drawer.DrawTexturePixeledAlignment( texStar, ContentAlignment.TopLeft, MMWMath.Lerp(pos.X, pos.X + s.Width, rate) - texStar.Size.Width * 0.5f, pos.Y + s.Height - texStar.Size.Height * 0.5f, Color4.White, -(float)MMW.TotalElapsedTime * 2.0f, 1.0f / 32.0f); } }
protected override void Update(double deltaTime) { if (dof == null || !dof.Enabled) { return; } if (focusedObj == null) { dof.Focus = MMWMath.Approach(dof.Focus, 1.6f, (float)deltaTime * 5.0f); //dof.NearBias = MMWMath.Approach(dof.NearBias, 24.0f, (float)deltaTime * 10.0f); dof.FarBias = MMWMath.Approach(dof.FarBias, 0.0f, (float)deltaTime * 1.5f); dof.FarRadiusMax = MMWMath.Approach(dof.FarRadiusMax, 12.0f, (float)deltaTime * 12.0f); } else if (cameraType == "first person") { dof.Focus = MMWMath.Approach(dof.Focus, ray.distance, (float)deltaTime * 5.0f); //dof.NearBias = MMWMath.Approach(dof.NearBias, 12.0f, (float)deltaTime * 10.0f); dof.FarBias = MMWMath.Approach(dof.FarBias, Math.Min(0.5f / ray.distance, 2.0f), (float)deltaTime * 0.25f); dof.FarRadiusMax = MMWMath.Approach(dof.FarRadiusMax, Math.Min(12.0f / ray.distance, 24.0f), (float)deltaTime * 12.0f); } }
public ImportedObject[] Import(string path, ImportType type) { ImportedObject obj = new ImportedObject() { Result = Result.Failed, Type = ImportedObjectType.Model, Path = path, }; PmdImportResult res; { var importer = new PmdModelImporter.PmdModelImporter(); res = importer.Import(path, type == ImportType.Full); if (res == null || res.result != PmdImportResult.Result.Success) { return(new ImportedObject[] { obj }); } } var pmd = res.pmd; obj.Result = Result.Success; obj.Name = pmd.Header.Name; obj.Version = pmd.Header.Version.ToString(); obj.Description = pmd.Header.Comment; if (type == ImportType.OverviewOnly) { obj.Result = Result.Success; return(new ImportedObject[] { obj }); } // texture var texturePathes = new List <string>(); var textures = new List <Texture2D>(); // material var materials = new List <Material>(); for (var i = 0; i < pmd.MaterialList.MaterialNum; i++) { var mat = pmd.MaterialList.Materials[i]; var m = new Material(); m.AddParam("albedo", "Albedo", mat.DiffuseColor.ToColor4(mat.Alpha)); //m.AddParam("specular", "Specular", mat.SpecularColor.ToColor4()); //m.AddParam("shininess", "Shininess", mat.SpecularPower); m.AddParam("emissive", "Emissive", new Color4(0, 0, 0, 0)); // m.AddParam("ambient", "Ambient", mat.AmbientColor.ToColor4()); m.AddParam("roughness", "Roughness", 1.0f - MMWMath.Clamp(mat.SpecularPower / 32.0f, 0.0f, 1.0f)); m.AddParam("metallic", "Metallic", mat.SpecularPower > 14.0f ? 1.0f : 0.0f); m.AddParam("reflectance", "Reflectance", 0.0f); //m.AddParam("f0", "F0", (mat.SpecularColor + new Vector3(0.15f, 0.15f, 0.15f)).ToColor4()); //m.AddParam("f0", "F0", mat.SpecularColor.ToColor4()); if (!string.IsNullOrEmpty(mat.TextureFileName)) { mat.TextureFileName = Path.GetDirectoryName(path) + "\\" + mat.TextureFileName; if (File.Exists(mat.TextureFileName)) { Texture2D difMap = null; var index = texturePathes.IndexOf(mat.TextureFileName); if (index == -1) { Bitmap bitmap = null; try { bitmap = (Bitmap)Image.FromFile(mat.TextureFileName); } catch { var ext = Path.GetExtension(mat.TextureFileName).ToLower(); if (ext == ".tga") { using (FileStream fs = new FileStream(mat.TextureFileName, FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs)) { var tga = new TgaLib.TgaImage(br); bitmap = tga.GetBitmap().ToBitmap(PixelFormat.Format32bppPArgb); } } } } difMap = new Texture2D(bitmap, Path.GetFileNameWithoutExtension(mat.TextureFileName), false); difMap.UseMipmap = true; difMap.WrapMode = OpenTK.Graphics.OpenGL4.TextureWrapMode.Repeat; difMap.MinFilter = OpenTK.Graphics.OpenGL4.TextureMinFilter.LinearMipmapLinear; textures.Add(difMap); texturePathes.Add(mat.TextureFileName); } else { difMap = textures[index]; } m.AddParam("albedoMap", "AlbedoMap", difMap); } } else { m.AddParam <Texture2D>("albedoMap", "AlbedoMap", null); } m.AddParam <Texture2D>("specularMap", "SpecularMap", null); m.AddParam <Texture2D>("normalMap", "NormalMap", null); m.AddParam <Texture2D>("physicalMap", "PhysicalMap", null); materials.Add(m); } obj.Materials = materials.ToArray(); obj.Textures = textures.ToArray(); // mesh var mesh = new Mesh(pmd.Header.Name); { mesh.Vertices = new OpenTK.Vector3[pmd.VertexList.VertexNum]; mesh.UVs = new OpenTK.Vector2[pmd.VertexList.VertexNum]; mesh.Normals = new OpenTK.Vector3[pmd.VertexList.VertexNum]; mesh.BoneWeights = new BoneWeight[pmd.VertexList.VertexNum]; for (var i = 0; i < pmd.VertexList.VertexNum; i++) { var vert = pmd.VertexList.Vertices[i]; var v = vert.Position.ToVec3() * ImportScale; mesh.Vertices[i] = v; mesh.Vertices[i].Z *= -1.0f; mesh.UVs[i] = vert.UV.ToVec2(); mesh.Normals[i] = vert.Normal.ToVec3(); mesh.Normals[i].Z *= -1.0f; mesh.BoneWeights[i].boneIndex0 = vert.BoneIndex0; mesh.BoneWeights[i].boneIndex1 = vert.BoneIndex1; if (mesh.BoneWeights[i].boneIndex1 == 0) { mesh.BoneWeights[i].boneIndex1 = -1; } mesh.BoneWeights[i].boneIndex2 = -1; mesh.BoneWeights[i].boneIndex3 = -1; mesh.BoneWeights[i].weight0 = 1.0f - vert.Weight; mesh.BoneWeights[i].weight1 = vert.Weight; } var offset = 0; for (var i = 0; i < pmd.MaterialList.MaterialNum; i++) { var mat = pmd.MaterialList.Materials[i]; var indices = new int[mat.FaceVertNum]; for (var j = 0; j < mat.FaceVertNum / 3; j++) { indices[j * 3 + 0] = pmd.FaceList.Indices[offset++]; indices[j * 3 + 1] = pmd.FaceList.Indices[offset++]; indices[j * 3 + 2] = pmd.FaceList.Indices[offset++]; } if (mat.FaceVertNum > 0) { mesh.SetIndices(i, indices, OpenTK.Graphics.OpenGL4.BeginMode.Triangles); } } } obj.Meshes = new Mesh[] { mesh }; // bone if (pmd.BoneList != null && pmd.BoneList.BoneNum > 0) { obj.Bones = CreateBones(pmd.BoneList.Bones); BindBones(obj.Bones, pmd.BoneList.Bones, pmd.IKList.IKs); } // morph if (pmd.MorphList != null && pmd.MorphList.MorphNum > 0) { obj.Morphs = new Morph[pmd.MorphList.MorphNum]; for (var i = 0; i < pmd.MorphList.MorphNum; i++) { obj.Morphs[i] = new Morph(); var m = pmd.MorphList.Morphs[i]; obj.Morphs[i].Name = m.Name; obj.Morphs[i].Vertices = new VertexMorph[m.SkinVertCount]; for (var j = 0; j < m.SkinVertCount; j++) { obj.Morphs[i].Vertices[j] = new VertexMorph(); obj.Morphs[i].Vertices[j].Index = (int)m.Data[j].Index; obj.Morphs[i].Vertices[j].Offset = m.Data[j].Offset.ToVec3(true) * ImportScale; } } } return(new ImportedObject[] { obj }); }
protected override void Update(double deltaTime) { if (Input.MouseWheel > 0) { Distance *= 1.1f; } if (Input.MouseWheel < 0) { Distance *= 0.9f; } MMW.MainCamera.Near = Distance * 0.01f; MMW.MainCamera.Far = Distance * 1000.0f; var delta = Vector2.Zero; if (Input.IsButtonDown(OpenTK.Input.MouseButton.Middle)) { var d = Input.MouseDelta; if (d != Vector2.Zero) { var up = Vector3.TransformVector(Vector3.UnitY, Matrix4.CreateRotationX(height)); up = Vector3.TransformVector(up, Matrix4.CreateRotationY(-rotate)); var zz = (MMW.MainCamera.Target - MMW.MainCamera.Transform.Position).Normalized(); Vector3 x, y; y = up; x = Vector3.Cross(y, zz); y *= d.Y * Distance * 0.002f; x *= d.X * Distance * 0.002f; Target += y + x; } } else if (Input.IsButtonDown(OpenTK.Input.MouseButton.Right)) { delta = Input.MouseDelta; } Rotate += delta.X * 0.01f; Height += delta.Y * 0.01f; Height = MMWMath.Clamp(Height, -1.5f, 1.5f); rotate = MMWMath.Lerp(rotate, Rotate, (float)deltaTime * 30.0f); height = MMWMath.Lerp(height, Height, (float)deltaTime * 30.0f); Vector3 v; v.X = (float)(Math.Sin(rotate) * Math.Cos(height)); v.Z = (float)(-Math.Cos(rotate) * Math.Cos(height)); v.Y = (float)Math.Sin(height); v *= Distance; var dir = -v; v += Target; MMW.MainCamera.Transform.Position = v; MMW.MainCamera.Target = Target; MMW.DirectionalLight.Direction = dir; }
protected override void Update(double deltaTime) { if (time > 0.0) { time -= deltaTime; } if (time < 0.0 && totalCoin < maxCoin) { time += userData.CoinSpownTime; var r = Util.RandomInt(0, 100); var coin = cupperCoin; if (r >= 90) { coin = silverCoin; } else if (r == 99) { coin = goldCoin; } RayTestResult res = null; int test = 5; while (test > 0) { var x = MMWMath.Lerp(bounds.Min.X, bounds.Max.X, Util.RandomFloat()); var z = MMWMath.Lerp(bounds.Min.Z, bounds.Max.Z, Util.RandomFloat()); var pos = new Vector4(x, 0.0f, z, 1.0f) * Transform.WorldTransform; var rays = Bullet.RayTest(new Vector3(pos.X, 100.0f, pos.Z), new Vector3(pos.X, -50.0f, pos.Z)); if (rays.Count > 0 && rays[0].GameObject.Tags.Contains("world")) { res = rays[0]; break; } test--; } if (res != null) { var go = new NwWalkerGameObject() { CreateDate = DateTime.Now.ToString(), CreatorName = MMW.GetAsset <UserData>().UserName, Hash = Util.CreateHash(12), Name = "coin", ObjectHash = coin.Hash, Position = (res.Position + Vector3.UnitY * 0.2f).ToVec3f(), Rotation = new Vector3f(), Scale = new Vector3f(1, 1, 1), SessionID = MMW.GetAsset <UserData>().SessionID, UserID = MMW.GetAsset <UserData>().UserID, }; MMW.FindGameComponent <WalkerScript>().PutGameObject(go, false); totalCoin++; } } }
protected override void Update(double deltaTime) { base.Update(deltaTime); transition += (trans ? -1.0f : 1.0f) * (float)deltaTime * 5.0f; transition = MMWMath.Saturate(transition); transit.Update(deltaTime); if (AcceptInput && !trans) { input.Update(deltaTime); if (input.IsRight) { tabCtr.NextTab(); } else if (input.IsLeft) { tabCtr.PrevTab(); } else if (input.IsDown) { tabCtr.NextSelect(); } else if (input.IsUp) { tabCtr.PrevSelect(); } else if (input.IsBack) { trans = true; transit.Target = new Vector2(-MMW.ClientSize.Width * 2.0f, 0.0f); GameObject.AddComponent <PlayerSelectScript>(); } else if (input.IsSelect && tabCtr.SelectedObject != null) { SelectedStage = (ImportedObject)tabCtr.SelectedObject; MMW.GetAsset <GameData>().Stage = SelectedStage; trans = true; transit.Target = new Vector2(-MMW.ClientSize.Width * 2.0f, 0.0f); var loadScript = MMW.FindGameComponent <LoadingScript>(); loadScript.StartLoading(null, (args) => { var data = MMW.GetAsset <GameData>(); // プレイヤ var player = GameObjectFactory.CreateMeshObject(data.Player.Path, data.SkinShader); //player.Layer = 20; player.AddComponent <SetNameScript>(); player.Tags.Add("player"); var motions = Array.FindAll(load.PresetObjects, o => o.Type == ImportedObjectType.Motion && o.Property != null); if (motions.Length > 0) { var animator = player.AddComponent <ComputeAnimator>(); var mr = player.GetComponent <MeshRenderer>(); animator.Bones = mr.Bones; foreach (var m in motions) { var impo = MMW.GetSupportedImporter(m.Path); var mo = impo.Import(m.Path, Importers.ImportType.Full)[0]; animator.AddMotion(mo.Name, mo.Motions[0]); } animator.SetRate("nekomimi_mikuv2", 1.0f); player.AddComponent <AnimationController>(); } // テストライト { var pl = player.AddComponent <PointLight>(); pl.Intensity = 1.0f; pl.Radius = 4.0f; pl.Color = Color4.White; } { var c = player.AddComponent <CapsuleCollider>(0.3f, 1.0f); c.Position.Y = 0.8f; var rb = player.AddComponent <RigidBody>(); rb.Mass = 50.0f; rb.FreezeRotation = true; rb.DisableDeactivation = true; rb.LinearDamping = 0.3f; rb.LinearVelocityLimitXZ = 2.0f; rb.Friction = 0.95f; player.UpdateAction += (s, ev) => { player.Transform.Rotate.Y += Input.MouseDelta.X * 0.0025f; MMW.MainCamera.Transform.Rotate.X += Input.MouseDelta.Y * 0.0025f; MMW.MainCamera.Transform.Rotate.X = MathHelper.Clamp(MMW.MainCamera.Transform.Rotate.X, -1.0f, 1.0f); var front = player.Transform.WorldDirectionZ; var left = player.Transform.WorldDirectionX; var speed = (float)ev.deltaTime * 2.0f; var deltaDir = Vector3.Zero; if (Input.IsKeyDown(Key.W)) { deltaDir += front; } if (Input.IsKeyDown(Key.S)) { deltaDir -= front; } if (Input.IsKeyDown(Key.A)) { deltaDir += left; } if (Input.IsKeyDown(Key.D)) { deltaDir -= left; } if (deltaDir != Vector3.Zero) { deltaDir.Normalize(); //rb.ApplyImpulse(deltaDir * speed * 80.0f); player.Transform.Position += deltaDir * speed; } if (Input.IsKeyPressed(Key.Space)) { rb.ApplyImpulse(Vector3.UnitY * 36.0f); } player.Transform.UpdatePhysicalTransform(); var cam = MMW.MainCamera; var pos = cam.Transform.WorldPosition; //var vel = (cam.Transform.Position - prevPos) * (float)deltaTime; var dirv = cam.Transform.WorldDirectionZ; var ori = new float[] { dirv.X, dirv.Y, dirv.Z, cam.Up.X, cam.Up.Y, cam.Up.Z }; AL.Listener(OpenTK.Audio.OpenAL.ALListener3f.Position, ref pos); //AL.Listener(OpenTK.Audio.OpenAL.ALListener3f.Velocity, ref vel); AL.Listener(OpenTK.Audio.OpenAL.ALListenerfv.Orientation, ref ori); }; MMW.MainCamera.ShadowMapping = true; MMW.MainCamera.Transform.Parent = player.Transform; MMW.MainCamera.GameObject.UpdateAction += (s, ev) => { if (Input.IsKeyDown(Key.ShiftLeft)) { MMW.MainCamera.Transform.Position = new Vector3(-0.5f, 1.5f, -0.5f); } else { MMW.MainCamera.Transform.Position = new Vector3(0.0f, 1.5f, -1.3f); } //MMW.DirectionalLight.Transform.Rotate.Y += (float)ev.deltaTime * 0.01f; }; } // ステージ var stage = GameObjectFactory.CreateStage(data.Stage.Path, data.Shader); stage.Tags.Add("stage"); { var sCol = stage.GetComponent <PhysicalGameComponent>(); sCol.Collide += SCol_Collide; } MMW.RegistGameObject(player); MMW.RegistGameObject(stage); for (var i = 0; i < 1; i++) { var tsts = GameObjectFactory.CreateMeshObject(data.Player.Path, data.SkinShader); tsts.Tags.Add("test"); //tsts.Layer = 20; tsts.AddComponent <SetNameScript>(); tsts.Transform.Position.Z = (i + 1) * 1.0f; var c = tsts.AddComponent <CapsuleCollider>(0.3f, 1.0f); c.Position.Y = 0.8f; var rb = tsts.AddComponent <RigidBody>(); rb.Mass = 50.0f; rb.FreezeRotation = true; rb.DisableDeactivation = true; rb.LinearDamping = 0.3f; var animator = tsts.AddComponent <ComputeAnimator>(); var mr = tsts.GetComponent <MeshRenderer>(); animator.Bones = mr.Bones; foreach (var m in motions) { var impo = MMW.GetSupportedImporter(m.Path); var mo = impo.Import(m.Path, Importers.ImportType.Full)[0]; animator.AddMotion(mo.Name, mo.Motions[0]); } animator.SetRate("nekomimi_mikuv2", 1.0f); var s = i + 1; var ac = tsts.AddComponent <AnimationController>(); ac.Speed = i * 0.25; var sound = new Sound("C:/Users/yoshihiro/Downloads/dbg2.wav"); sound.Load(); var sc = tsts.AddComponent <SoundController>(); sc.Sounds.Add("test", sound); sc.Play("test", 1.0f); tsts.UpdateAction += (se, e) => { tsts.Transform.Position = new Vector3((float)Math.Sin(MMW.TotalElapsedTime * 4.0) * 4.0f, 0.0f, (float)Math.Cos(MMW.TotalElapsedTime * 4.0) * 4.0f); }; MMW.RegistGameObject(tsts); } var effs = MMW.MainCamera.GameObject.GetComponents <ImageEffect>(); foreach (var eff in effs) { eff.Enabled = true; } MMW.GlobalAmbient = new Color4(0.2f, 0.18f, 0.16f, 0.0f); MMW.DirectionalLight.Intensity = 6.0f; MMW.IBLIntensity = 0.0f; return(true); }); loadScript.LoadCompleted += Load_LoadCompleted; } } if (trans && transition < 0.01f) { Destroy(); } }
public ImportedObject[] Import(string path, ImportType type) { ImportedObject obj = new ImportedObject() { Result = Result.Failed, Type = ImportedObjectType.Model, Path = path, }; PmxImportResult res; { var importer = new PmxModelImporter.PmxModelImporter(); res = importer.Import(path, type == ImportType.Full); if (res == null || res.result != PmxImportResult.Result.Success) { return(new ImportedObject[] { obj }); } } var pmx = res.pmx; obj.Result = Result.Success; obj.Name = pmx.ModelInfo.ModelName; obj.Version = pmx.Header.Version.ToString(); obj.Description = pmx.ModelInfo.Comment; if (type == ImportType.OverviewOnly) { obj.Result = Result.Success; return(new ImportedObject[] { obj }); } // texture var textures = new Texture2D[pmx.TextureList.TextureNum]; for (var i = 0; i < pmx.TextureList.TextureNum; i++) { var texname = pmx.TextureList.Textures[i]; if (string.IsNullOrEmpty(texname)) { continue; } var texPath = Path.GetDirectoryName(path) + "\\" + texname; if (!File.Exists(texPath)) { continue; } Texture2D difMap = null; Bitmap bitmap = null; try { bitmap = (Bitmap)Image.FromFile(texPath); } catch { var ext = Path.GetExtension(texPath).ToLower(); if (ext == ".tga") { using (FileStream fs = new FileStream(texPath, FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs)) { var tga = new TgaLib.TgaImage(br); bitmap = tga.GetBitmap().ToBitmap(PixelFormat.Format32bppArgb); } } } } difMap = new Texture2D(bitmap, Path.GetFileNameWithoutExtension(texPath), false); difMap.UseMipmap = true; difMap.WrapMode = OpenTK.Graphics.OpenGL4.TextureWrapMode.Repeat; difMap.MinFilter = OpenTK.Graphics.OpenGL4.TextureMinFilter.LinearMipmapLinear; textures[i] = difMap; } obj.Textures = textures; // material var materials = new List <Material>(); var colliders = new List <int>(); for (var i = 0; i < pmx.MaterialList.MaterialNum; i++) { var mat = pmx.MaterialList.Materials[i]; // 当たり判定用マテリアル if (mat.Name.Contains("collider")) { colliders.Add(i); } var m = new Material(mat.Name); m.AddParam("albedo", "Albedo", mat.Diffuse.ToColor4()); //m.AddParam("specular", "Specular", mat.Specular.ToColor4()); //m.AddParam("shininess", "Shininess", mat.SpecularPower); m.AddParam("emissive", "Emissive", new Color4(0, 0, 0, 0)); //m.AddParam("ambient", "Ambient", mat.Ambient.ToColor4()); m.AddParam("roughness", "Roughness", 1.0f - MMWMath.Clamp(mat.SpecularPower / 32.0f, 0.0f, 1.0f)); m.AddParam("metallic", "Metallic", mat.SpecularPower > 14.0f ? 1.0f : 0.0f); m.AddParam("reflectance", "Reflectance", 0.0f); //m.AddParam("f0", "F0", (mat.Specular + new Vector3(0.15f, 0.15f, 0.15f)).ToColor4()); //m.AddParam("f0", "F0", mat.Specular.ToColor4()); if (mat.AlbedoMapIndex != -1) { m.AddParam("albedoMap", "AlbedoMap", textures[mat.AlbedoMapIndex]); } else { m.AddParam <Texture2D>("albedoMap", "AlbedoMap", null); } m.AddParam <Texture2D>("specularMap", "SpecularMap", null); m.AddParam <Texture2D>("normalMap", "NormalMap", null); m.AddParam <Texture2D>("physicalMap", "PhysicalMap", null); materials.Add(m); } obj.Materials = materials.ToArray(); // mesh var mesh = new Mesh(pmx.ModelInfo.ModelName); var collideMesh = new Mesh("collider"); { mesh.Vertices = new OpenTK.Vector3[pmx.VertexList.VertexNum]; mesh.UVs = new OpenTK.Vector2[pmx.VertexList.VertexNum]; mesh.Normals = new OpenTK.Vector3[pmx.VertexList.VertexNum]; mesh.BoneWeights = new BoneWeight[pmx.VertexList.VertexNum]; // 追加UV for (var i = 0; i < pmx.Header.AddUVCound; i++) { if (i == 0) { mesh.UV1s = new OpenTK.Vector4[pmx.VertexList.VertexNum]; } if (i == 1) { mesh.UV2s = new OpenTK.Vector4[pmx.VertexList.VertexNum]; } if (i == 2) { mesh.UV3s = new OpenTK.Vector4[pmx.VertexList.VertexNum]; } if (i == 3) { mesh.UV4s = new OpenTK.Vector4[pmx.VertexList.VertexNum]; } } for (var i = 0; i < pmx.VertexList.VertexNum; i++) { var vert = pmx.VertexList.Vertices[i]; var v = vert.Position.ToVec3(true) * ImportScale; mesh.Vertices[i] = v; mesh.UVs[i] = vert.UV.ToVec2(); mesh.Normals[i] = vert.Normal.ToVec3(true); for (var j = 0; j < pmx.Header.AddUVCound; j++) { if (j == 0) { mesh.UV1s[i] = vert.UV1.ToVec4(); } if (j == 1) { mesh.UV2s[i] = vert.UV2.ToVec4(); } if (j == 2) { mesh.UV3s[i] = vert.UV3.ToVec4(); } if (j == 3) { mesh.UV4s[i] = vert.UV4.ToVec4(); } } mesh.BoneWeights[i].boneIndex0 = vert.BoneIndex0; mesh.BoneWeights[i].boneIndex1 = vert.BoneIndex1; mesh.BoneWeights[i].boneIndex2 = vert.BoneIndex2; mesh.BoneWeights[i].boneIndex3 = vert.BoneIndex3; mesh.BoneWeights[i].weight0 = vert.Weight0; mesh.BoneWeights[i].weight1 = vert.Weight1; mesh.BoneWeights[i].weight2 = vert.Weight2; mesh.BoneWeights[i].weight3 = vert.Weight3; } collideMesh.Vertices = mesh.Vertices; var offset = 0; for (var i = 0; i < pmx.MaterialList.MaterialNum; i++) { var mat = pmx.MaterialList.Materials[i]; var indices = new int[mat.FaceVertNum]; for (var j = 0; j < mat.FaceVertNum / 3; j++) { indices[j * 3 + 0] = pmx.FaceList.Faces[offset++]; indices[j * 3 + 1] = pmx.FaceList.Faces[offset++]; indices[j * 3 + 2] = pmx.FaceList.Faces[offset++]; } if (mat.FaceVertNum > 0) { if (colliders.Exists((c) => c == i)) { collideMesh.SetIndices(i, indices, OpenTK.Graphics.OpenGL4.BeginMode.Triangles); } else { mesh.SetIndices(i, indices, OpenTK.Graphics.OpenGL4.BeginMode.Triangles); } } } } var meshes = new List <Mesh>(); meshes.Add(mesh); if (collideMesh.SubMeshCount > 0) { meshes.Add(collideMesh); } obj.Meshes = meshes.ToArray(); // bone if (pmx.BoneList != null && pmx.BoneList.BoneNum > 0) { obj.Bones = CreateBones(pmx.BoneList.Bones); BindBones(obj.Bones, pmx.BoneList.Bones); } // morphs var morphs = new List <Morph>(); // 頂点モーフ var vs = CreateVertexMorphs(pmx.MorphList.VertexList); if (vs != null) { morphs.AddRange(vs); } // ボーンモーフ var bs = CreateBoneMorphs(pmx.MorphList.BoneList); if (bs != null) { morphs.AddRange(bs); } obj.Morphs = morphs.ToArray(); return(new ImportedObject[] { obj }); }
protected override void Update(double deltaTime) { base.Update(deltaTime); var cam = MMW.MainCamera; var prevPos = cam.Transform.Position; if (CameraType == "third person") { GameObject.GetComponent <MeshRenderer>().Visible = true; MMW.MainCamera.FoV = 1.2f; var center = Target != null ? Target.WorldPosition : Vector3.Zero; targetRot -= Input.MouseDelta.X * 0.005f; targetHeight += Input.MouseDelta.Y * 0.005f; targetHeight = MMWMath.Clamp(targetHeight, -MathHelper.PiOver6, MathHelper.PiOver2 - 0.3f); rot = MMWMath.Lerp(rot, targetRot, (float)deltaTime * 16.0f); height = MMWMath.Lerp(height, targetHeight, (float)deltaTime * 16.0f); Vector3.Lerp(ref target, ref center, (float)deltaTime * 6.0f, out target); var y = Math.Sin(height); var x = Math.Cos(height) * Math.Sin(rot); var z = Math.Cos(height) * Math.Cos(rot); var dx = (float)Math.Sin(MMW.TotalElapsedTime * 0.5); var dy = (float)Math.Cos(MMW.TotalElapsedTime * 0.7); var dz = (float)Math.Cos(MMW.TotalElapsedTime * 0.3); var pos = new Vector3((float)x, (float)y, (float)z) * Distance; pos += target; var rays = Physics.Bullet.RayTest(target, Vector3.Lerp(target, pos, 1.1f), GameObject); if (rays.Count > 0) { var l = rays.Min(r => r.Rate); var ray = rays.Find(r => r.Rate == l); if (ray != null) { pos = Vector3.Lerp(target, ray.Position, 0.9f); } } var nx = Noise.Fbm((float)MMW.TotalElapsedTime * 0.15f * NoiseSpeed, 3) * 0.01f; var ny = Noise.Fbm((float)MMW.TotalElapsedTime * 0.1f * NoiseSpeed, 4) * 0.01f; var nz = Noise.Fbm((float)MMW.TotalElapsedTime * 0.05f * NoiseSpeed, 5) * 0.01f; var rt = new Vector3(nx, ny, nz) * NoiseIntensity * 7.0f; var rp = new Vector3(ny, nz, nx) * NoiseIntensity * 4.0f; cam.Up = Matrix3.CreateRotationZ(nx * NoiseIntensity * 2.0f) * Vector3.UnitY; cam.Target = target + rt; cam.Transform.Position = pos + rp; } else if (CameraType == "first person") { GameObject.GetComponent <MeshRenderer>().Visible = false; MMW.MainCamera.FoV = 1.4f; Transform.Rotate.Y += Input.MouseDelta.X * 0.005f; var t = new Vector4(pi.Character.EyePosition, 1.0f) * Transform.WorldTransform; cam.Transform.Position = t.Xyz; fpHeight -= Input.MouseDelta.Y * 0.005f; fpHeight = MMWMath.Clamp(fpHeight, -MathHelper.PiOver2 + 0.1f, MathHelper.PiOver2 - 0.1f); var dir = ct.WorldDirectionZ; dir *= (float)Math.Cos(fpHeight); dir.Y += (float)Math.Sin(fpHeight); var target = dir + t.Xyz; Vector3.Lerp(ref nowDir, ref target, (float)deltaTime * 30.0f, out nowDir); cam.Target = nowDir; } }
protected override void Update(double deltaTime) { base.Update(deltaTime); transition += (trans ? -1.0f : 1.0f) * (float)deltaTime * 5.0f; transition = MMWMath.Saturate(transition); transit.Update(deltaTime); if (AcceptInput && !trans) { input.Update(deltaTime); var prev = tabCtr.SelectedObject; if (input.IsRight) { tabCtr.NextTab(); if (prev != tabCtr.SelectedObject) { MMW.DestroyGameObject(player); player = null; } } else if (input.IsLeft) { tabCtr.PrevTab(); if (prev != tabCtr.SelectedObject) { MMW.DestroyGameObject(player); player = null; } } else if (input.IsDown) { tabCtr.NextSelect(); if (prev != tabCtr.SelectedObject) { MMW.DestroyGameObject(player); player = null; } } else if (input.IsUp) { tabCtr.PrevSelect(); if (prev != tabCtr.SelectedObject) { MMW.DestroyGameObject(player); player = null; } } else if (input.IsBack) { if (player != null) { MMW.DestroyGameObject(player); } trans = true; transit.Target = new Vector2(-MMW.ClientSize.Width * 2.0f, 0.0f); GameObject.AddComponent <TitleScript>(); } else if (input.IsSelect && player != null) { MMW.DestroyGameObject(player); SelectedPlayer = (ImportedObject)tabCtr.SelectedObject; MMW.GetAsset <GameData>().Player = SelectedPlayer; trans = true; transit.Target = new Vector2(-MMW.ClientSize.Width * 2.0f, 0.0f); GameObject.AddComponent <StageSelectScript>(); } } if (trans && transition < 0.01f) { Destroy(); } if (player == null && tabCtr.SelectedObject != null) { var path = ((ImportedObject)tabCtr.SelectedObject).Path; var go = GameObjectFactory.CreateMeshObject(path, MMW.GetAsset <GameData>().SkinShader); //go.Layer = 1; go.Transform.Rotate.Y = -2.8f; go.UpdateAction += (s, e) => { //go.Transform.Rotate.Y += (float)e.deltaTime * 0.5f; }; // Test: モーションを取得 var motions = Array.FindAll(load.PresetObjects, o => o.Type == ImportedObjectType.Motion && o.Property != null); if (motions.Length > 0) { var animator = go.AddComponent <ComputeAnimator>(); var mr = go.GetComponent <MeshRenderer>(); animator.Bones = mr.Bones; foreach (var m in motions) { var impo = MMW.GetSupportedImporter(m.Path); var mo = impo.Import(m.Path, Importers.ImportType.Full)[0]; animator.AddMotion(mo.Name, mo.Motions[0]); } //animator.SetRate("secret", 1.0f); animator.SetRate("nekomimi_mikuv2", 1.0f); animator.Frame = 0.0f; go.AddComponent <AnimationController>(); //go.UpdateAction += (se, e) => //{ //animator.Frame = MMWMath.Repeat(animator.Frame + ((float)e.deltaTime * 30.0f), 0.0f, 5000.0f); //if (Input.IsKeyDown(Key.Right)) animator.AddRate("nekomimi_mikuv2", (float)e.deltaTime, 0.0f, 1.0f); //if (Input.IsKeyDown(Key.Left)) animator.AddRate("nekomimi_mikuv2", -(float)e.deltaTime, 0.0f, 1.0f); //if (Input.IsKeyDown(Key.Right)) go.Transform.Rotate.Y += (float)e.deltaTime; //if (Input.IsKeyDown(Key.Left)) go.Transform.Rotate.Y -= (float)e.deltaTime; //}; } MMW.RegistGameObject(go); player = go; } }
protected override void Update(double deltaTime) { var cam = MMW.MainCamera; var d = cam.Transform.WorldPosition - cam.Target; d.Y = 0.0f; d.Normalize(); var dirZ = d; var dirX = dirZ * Matrix3.CreateRotationY(MathHelper.PiOver2); var deltaDir = Vector3.Zero; if (Input.IsKeyDown(Key.W)) { deltaDir -= dirZ; } if (Input.IsKeyDown(Key.S)) { deltaDir += dirZ; } if (Input.IsKeyDown(Key.A)) { deltaDir -= dirX; } if (Input.IsKeyDown(Key.D)) { deltaDir += dirX; } if (deltaDir != Vector3.Zero) { deltaDir.Normalize(); var move = deltaDir * (float)deltaTime * 6.0f; Velocity += move; var length = Velocity.Length; if (length > 2.5f) { length = 2.5f; } Velocity = Velocity.Normalized() * length; Transform.Position += Velocity * (float)deltaTime; //rb.ApplyForce(deltaDir * (float)deltaTime * 12.5f * rb.Mass * 50.0f); userData.TotalMoveDistance += (Velocity * (float)deltaTime).Length; if (CameraType == "third person") { var dot = -(Vector3.Dot(Transform.WorldDirectionZ, deltaDir) - 1.0f) * 0.5f * MathHelper.Pi; var cross = Vector3.Cross(Transform.WorldDirectionZ, deltaDir); var r = MMWMath.Clamp(dot, 0.0f, (float)deltaTime * 8.0f); if (cross.Y > 0.0f) { Transform.Rotate.Y -= r; } else { Transform.Rotate.Y += r; } } } else { var length = Velocity.Length; length -= (float)deltaTime * 5.0f; if (length <= 0.0f) { Velocity = Vector3.Zero; } else { Velocity = Velocity.Normalized() * length; } Transform.Position += Velocity * (float)deltaTime; } if (Input.IsKeyPressed(Key.Space)) { var wp = Transform.WorldPosition; var rays = Bullet.RayTest(wp + Vector3.UnitY * 0.1f, wp - Vector3.UnitY * 0.2f, GameObject); if (rays.Count > 0) { rb.ApplyImpulse(Vector3.UnitY * 4.5f * rb.Mass); userData.TotalJumpCount++; } } Transform.UpdatePhysicalTransform(); }
public override void CalcTransform() { if (bones == null) { return; } // 計算済みの場合は何もしない if (!dataChanged) { return; } for (var i = 0; i < TransformSize; i++) { bmvs[i].Init(); } Array.Copy(transforms, oldTransforms, transforms.Length); // morph if (morpher != null) { foreach (var m in motionDic.Values) { if (m.Rate == 0.0f) { continue; } foreach (var sm in m.Motion.SkinMotions.Values) { if (!morpher.HasMorph(sm.MorphName)) { continue; } var values = GetKeyAndRate(sm.Keys, 0.0f); if (values.Item3 == -1.0f) { continue; } var w = MMWMath.Lerp(values.Item1.Value, values.Item2.Value, values.Item3); morpher.SetRate(sm.MorphName, w); } } var bms = morpher.GetBoneTransforms(); foreach (var bm in bms) { bmvs[bm.Index].location = bm.Location; bmvs[bm.Index].rotation = bm.Rotation; } } // bone foreach (var m in motionDic.Values) { if (m.Rate == 0.0f) { continue; } foreach (var bm in m.Motion.BoneMotions.Values) { int index; if (!indexDic.TryGetValue(bm.BoneName, out index)) { continue; } var values = GetKeyAndRate(bm.Keys, BoneMotionValue.Identity); if (values.Item3 == -1.0f) { continue; } BoneMotionValue bmv; BoneMotionValue.Lerp(ref values.Item1.Value, ref values.Item2.Value, values.Item3, out bmv); bmv *= m.Rate; if (bmvs[index] == BoneMotionValue.Identity) { bmvs[index] = bmv; } else { bmvs[index] += bmv; } } } // update transform for (var i = 0; i < boneTranses.Length; i++) { BoneTransforms[i].Position = initBoneTransforms[i].ExtractTranslation() + bmvs[i].location; BoneTransforms[i].Rotation = bmvs[i].rotation * userRotations[i]; BoneTransforms[i].Scale = bmvs[i].scale * userScales[i]; } // TODO: IKボーン変形 var iks = Array.FindAll(bones, b => b.BoneType == "IK"); if (iks.Length > 0) { foreach (var ik in iks) { if (bmvs[ik.Index].location == Vector3.Zero) { continue; } var ts = new List <FastTransform>(); for (var i = ik.IKLinks.Length - 1; i >= 0; i--) { ts.Add(BoneTransforms[ik.IKLinks[i].Bone.Index]); } ts.Add(BoneTransforms[ik.IKTarget.Index]); ts.Reverse(); var target = BoneTransforms[ik.Index].WorldPosition; // loop回数繰り返す var loop = 0; var end = ik.IKLoop / 3; for (loop = 0; loop < end; loop++) { for (var c = 1; c < ts.Count; c++) { var t = ts[c]; var tPos = t.WorldPosition; var pt = ts[0]; //内積, 外積を求める var v = (pt.WorldPosition - tPos).Normalized(); var vt = (target - tPos).Normalized(); var dot = Vector3.Dot(v, vt); if (dot < 1.0f) { // 角度を求める var rot = (float)Math.Acos(dot); var cross = Vector3.Cross(v, vt); // 制限角度以上ならclamp if (rot > ik.IKRotLimit) { rot = ik.IKRotLimit; } // 姿勢を変形 var r = Quaternion.FromAxisAngle(cross, rot); t.Rotation *= r; if (ik.IKLinks[c - 1].LimitAngle) { var euler = t.Rotation.ToEuler(); //var p = BoneTransforms[ik.IKLinks[c - 1].Bone.Index].WorldTransform.ExtractRotation(); //if (loop == 0 && ik.Name == "右足IK") Console.WriteLine(p); var l = ik.IKLinks[c - 1].LowerLimitAngle; var u = ik.IKLinks[c - 1].UpperLimitAngle; euler = Vector3.Clamp(euler, l, u); t.Rotation = euler.ToQuaternion(); } } } var length = (ts[0].WorldPosition - target).Length; if (length < 0.02f) { break; } } ts.RemoveAt(0); for (var i = 0; i < ik.IKLinks.Length; i++) { var idx = ik.IKLinks[i].Bone.Index; bmvs[idx].rotation = ts[i].Rotation; } } } for (var i = 0; i < boneTranses.Length; i++) { if (bmvs[i] == BoneMotionValue.Identity) { boneTranses[i] = Matrix4.Identity; } else { boneTranses[i] = bmvs[i].CreateTransform(); } } // FKボーンを確定 { var iden = Matrix4.Identity; var all = Array.FindAll(bones, b => b.Parent == null); for (var i = all.Length - 1; i >= 0; i--) { ConfirmTransforms(all[i], ref iden); } } dataChanged = false; }
public ImportedObject[] Import(string path, ImportType type) { var obj = new ImportedObject() { Result = Result.Failed, Type = ImportedObjectType.Model, Path = path, }; var importer = new MqoModelImporter.MqoModelImporter(); var res = importer.Import(path, type == ImportType.Full); if (res == null || res.result != MqoModelImporter.MqoImportResult.Result.Success) { return(new ImportedObject[] { obj }); } var mqo = res.mqo; obj.Name = Path.GetFileNameWithoutExtension(path); obj.Version = mqo.Version.ToString(); if (type == ImportType.OverviewOnly) { obj.Result = Result.Success; return(new ImportedObject[] { obj }); } #region Material // material var materials = new List <Material>(); var textures = new List <Texture2D>(); var texturePaths = new List <string>(); foreach (var m in mqo.Materials) { var mat = new Material(m.Name); mat.AddParam("albedo", "Albedo", new OpenTK.Graphics.Color4(m.Color.R * m.Diffuse, m.Color.G * m.Diffuse, m.Color.B * m.Diffuse, m.Color.A)); //mat.AddParam("specular", "Specular", new OpenTK.Graphics.Color4(m.Specular, m.Specular, m.Specular, 1.0f)); //mat.AddParam("shininess", "Shininess", m.SpecularPower); //mat.AddParam("reflect", "Reflect", m.Reflect); //mat.AddParam("refract", "Refract", m.Refract); //mat.AddParam("ambient", "Ambient", new OpenTK.Graphics.Color4(m.Ambient, m.Ambient, m.Ambient, 1.0f)); mat.AddParam("emissive", "Emissive", new OpenTK.Graphics.Color4(m.Emissive, m.Emissive, m.Emissive, 0.0f)); mat.AddParam("roughness", "Roughness", 1.0f - MMWMath.Clamp(m.SpecularPower / 32.0f, 0.0f, 1.0f)); mat.AddParam("metallic", "Metallic", m.SpecularPower > 14.0f ? 1.0f : 0.0f); mat.AddParam("reflectance", "Reflectance", m.Reflect); //m.AddParam("f0", "F0", (mat.SpecularColor + new Vector3(0.15f, 0.15f, 0.15f)).ToColor4()); //mat.AddParam("f0", "F0", new OpenTK.Graphics.Color4(m.Specular, m.Specular, m.Specular, 1.0f)); Texture2D difMap = null; if (!string.IsNullOrEmpty(m.TextureFullpath) && File.Exists(m.TextureFullpath)) { var index = texturePaths.IndexOf(m.TextureFullpath); if (index == -1) { var bitmap = (Bitmap)Image.FromFile(m.TextureFullpath); difMap = new Texture2D(bitmap, Path.GetFileNameWithoutExtension(m.TextureFullpath)); difMap.UseMipmap = true; difMap.WrapMode = OpenTK.Graphics.OpenGL4.TextureWrapMode.Repeat; difMap.MinFilter = OpenTK.Graphics.OpenGL4.TextureMinFilter.LinearMipmapLinear; textures.Add(difMap); texturePaths.Add(m.TextureFullpath); } else { difMap = textures[index]; } mat.AddParam("albedoMap", "AlbedoMap", difMap); } else { mat.AddParam <Texture2D>("albedoMap", "AlbedoMap", null); } mat.AddParam <Texture2D>("specularMap", "SpecularMap", null); mat.AddParam <Texture2D>("normalMap", "NormalMap", null); mat.AddParam <Texture2D>("physicalMap", "PhysicalMap", null); Texture2D bumpMap = null; if (!string.IsNullOrEmpty(m.BumpMapFullpath) && File.Exists(m.BumpMapFullpath)) { var index = texturePaths.IndexOf(m.BumpMapFullpath); if (index == -1) { var bitmap = (Bitmap)Image.FromFile(m.BumpMapFullpath); bumpMap = new Texture2D(bitmap, Path.GetFileNameWithoutExtension(m.BumpMapFullpath)); bumpMap.WrapMode = OpenTK.Graphics.OpenGL4.TextureWrapMode.Repeat; textures.Add(difMap); texturePaths.Add(m.BumpMapFullpath); } else { difMap = textures[index]; } mat.AddParam("bumpMap", "BumpMap", bumpMap); } Texture2D alphaMap = null; if (!string.IsNullOrEmpty(m.AlphaMapFullpath) && File.Exists(m.AlphaMapFullpath)) { var index = texturePaths.IndexOf(m.AlphaMapFullpath); if (index == -1) { var bitmap = (Bitmap)Image.FromFile(m.AlphaMapFullpath); alphaMap = new Texture2D(bitmap, Path.GetFileNameWithoutExtension(m.AlphaMapFullpath)); alphaMap.WrapMode = OpenTK.Graphics.OpenGL4.TextureWrapMode.Repeat; textures.Add(difMap); texturePaths.Add(m.AlphaMapFullpath); } else { alphaMap = textures[index]; } mat.AddParam("alphaMap", "AlphaMap", alphaMap); } materials.Add(mat); } obj.Materials = materials.ToArray(); obj.Textures = textures.ToArray(); #endregion if (!CombineMeshes) { // mesh var meshes = new List <Mesh>(); foreach (var o in mqo.Objects) { // vertices var vertices = new List <OpenTK.Vector3>(); for (int i = 0; i < o.Vertices.Length; i++) { vertices.Add(new OpenTK.Vector3(o.Vertices[i].X, o.Vertices[i].Y, o.Vertices[i].Z)); } // indices var matNum = mqo.Materials.Length; var indicesList = new List <int> [matNum]; var subs = new List <SubMesh>(); // init for (int i = 0; i < matNum; i++) { indicesList[i] = new List <int>(); subs.Add(new SubMesh()); subs[i].materialIndex = i; subs[i].mode = BeginMode.Triangles; } // uvs var uvs = new List <OpenTK.Vector2>(); for (int i = 0; i < o.Vertices.Length; i++) { uvs.Add(new OpenTK.Vector2(-1.0f, -1.0f)); } // face foreach (var face in o.Faces) { var matIndex = face.MaterialIndex; var offset = indicesList[matIndex].Count; indicesList[matIndex].Add(face.Indices[0]); indicesList[matIndex].Add(face.Indices[1]); indicesList[matIndex].Add(face.Indices[2]); if (face.UVs != null) { for (var i = 0; i < 3; i++) { var faceIndex = face.Indices[i]; var newUV = new OpenTK.Vector2(face.UVs[i].X, face.UVs[i].Y); if (CombineTextures) { while (newUV.X < 0.0f) { newUV.X += 1.0f; } while (newUV.Y < 0.0f) { newUV.Y += 1.0f; } while (newUV.X >= 1.0f) { newUV.X -= 1.0f; } while (newUV.Y >= 1.0f) { newUV.Y -= 1.0f; } } if (uvs[faceIndex].X == -1.0f && uvs[faceIndex].Y == -1.0f) { uvs[faceIndex] = newUV; } else { // UVがかぶったら新しい頂点を追加 var newIndex = vertices.Count; vertices.Add(vertices[faceIndex]); indicesList[matIndex][offset + i] = newIndex; uvs.Add(newUV); } } } } for (int i = 0; i < matNum; i++) { subs[i].indices = indicesList[i].ToArray(); } subs.RemoveAll((s) => s.indices.Length == 0); var mesh = new Mesh(o.Name) { Vertices = vertices.ToArray(), UVs = uvs.ToArray(), }; mesh.subMeshes = subs; meshes.Add(mesh); } obj.Meshes = meshes.ToArray(); } else { // mesh var meshes = new List <Mesh>(); // vertices var vertices = new List <OpenTK.Vector3>(); var uvs = new List <OpenTK.Vector2>(); foreach (var o in mqo.Objects) { var vertexOffset = vertices.Count; for (int i = 0; i < o.Vertices.Length; i++) { vertices.Add(new OpenTK.Vector3(o.Vertices[i].X, o.Vertices[i].Y, o.Vertices[i].Z)); uvs.Add(new OpenTK.Vector2(-1.0f, -1.0f)); } // indices var matNum = mqo.Materials.Length; var indicesList = new List <int> [matNum]; var subs = new List <SubMesh>(); // init for (int i = 0; i < matNum; i++) { indicesList[i] = new List <int>(); subs.Add(new SubMesh()); subs[i].materialIndex = i; subs[i].mode = BeginMode.Triangles; } // face foreach (var face in o.Faces) { var matIndex = face.MaterialIndex; var offset = indicesList[matIndex].Count; indicesList[matIndex].Add(vertexOffset + face.Indices[0]); indicesList[matIndex].Add(vertexOffset + face.Indices[1]); indicesList[matIndex].Add(vertexOffset + face.Indices[2]); if (face.UVs != null) { for (var i = 0; i < 3; i++) { var faceIndex = vertexOffset + face.Indices[i]; var newUV = new OpenTK.Vector2(face.UVs[i].X, face.UVs[i].Y); if (CombineTextures) { while (newUV.X < 0.0f) { newUV.X += 1.0f; } while (newUV.Y < 0.0f) { newUV.Y += 1.0f; } while (newUV.X >= 1.0f) { newUV.X -= 1.0f; } while (newUV.Y >= 1.0f) { newUV.Y -= 1.0f; } } if (uvs[faceIndex].X == -1.0f && uvs[faceIndex].Y == -1.0f) { uvs[faceIndex] = newUV; } else { // UVがかぶったら新しい頂点を追加 var newIndex = vertices.Count; vertices.Add(vertices[faceIndex]); indicesList[matIndex][offset + i] = newIndex; uvs.Add(newUV); } } } } for (int i = 0; i < matNum; i++) { subs[i].indices = indicesList[i].ToArray(); } subs.RemoveAll((s) => s.indices.Length == 0); var m = new Mesh(o.Name) { Vertices = vertices.ToArray(), UVs = uvs.ToArray(), }; m.subMeshes = subs; meshes.Add(m); } obj.Meshes = meshes.ToArray(); // メッシュを一つにまとめる { var mesh = new Mesh(obj.Name); mesh.Vertices = vertices.ToArray(); mesh.UVs = uvs.ToArray(); var indicesList = new List <int> [materials.Count]; for (var i = 0; i < materials.Count; i++) { indicesList[i] = new List <int>(); } foreach (var m in obj.Meshes) { foreach (var sub in m.subMeshes) { indicesList[sub.materialIndex].AddRange(sub.indices); } } for (var i = 0; i < indicesList.Length; i++) { if (indicesList[i].Count == 0) { continue; } mesh.SetIndices(i, indicesList[i].ToArray(), BeginMode.Triangles); } obj.Meshes = new Mesh[] { mesh }; } } // テクスチャを一つにまとめる if (CombineTextures) { var gridCount = 1; while (gridCount * gridCount < textures.Count) { gridCount++; } var bitmaps = new Bitmap[textures.Count]; for (var i = 0; i < bitmaps.Length; i++) { bitmaps[i] = textures[i].SrcBitmap; } var bitmap = BitmapHelper.CombineBitmaps(bitmaps, gridCount); obj.Textures = new Texture2D[] { new Texture2D(bitmap) { WrapMode = TextureWrapMode.Repeat, } }; // 全メッシュのUVを補正する foreach (var mesh in obj.Meshes) { foreach (var sub in mesh.subMeshes) { var mat = materials[sub.materialIndex]; if (!mat.HasParam <Texture2D>("albedoMap")) { continue; } var tex = mat.GetParam <Texture2D>("albedoMap"); var texIndex = textures.IndexOf(tex); var x = texIndex % gridCount; var y = texIndex / gridCount; foreach (var index in sub.indices) { var uv = mesh.UVs[index] / gridCount; uv += (new OpenTK.Vector2(x, y) / gridCount); mesh.UVs[index] = uv; } } } foreach (var mat in obj.Materials) { if (mat.HasParam <Texture2D>("albedoMap")) { mat.SetParam("albedoMap", obj.Textures[0]); } } } // マテリアルを一つにまとめる if (CombineMaterials) { // パラメータが被っているマテリアルを1つにまとめる var mats = new List <Material>(); var indexTable = new int[materials.Count]; for (var i = 0; i < materials.Count; i++) { var diffuse = materials[i].GetParam <OpenTK.Graphics.Color4>("albedo"); //var specular = materials[i].GetParam<OpenTK.Graphics.Color4>("specular"); //var shininess = materials[i].GetParam<float>("shininess"); //var reflect = materials[i].GetParam<float>("reflect"); //var refract = materials[i].GetParam<float>("refract"); //var ambient = materials[i].GetParam<float>("ambient"); var emissive = materials[i].GetParam <float>("emissive"); var difMap = materials[i].GetParam <Texture2D>("albedoMap"); var alphaMap = materials[i].GetParam <Texture2D>("alphaMap"); var bumpMap = materials[i].GetParam <Texture2D>("bumpMap"); var m = mats.Find((mat) => { bool same = true; same = same && diffuse == mat.GetParam <OpenTK.Graphics.Color4>("albedo"); //same = same && specular == mat.GetParam<OpenTK.Graphics.Color4>("specular"); //same = same && shininess == mat.GetParam<float>("shininess"); //same = same && reflect == mat.GetParam<float>("reflect"); //same = same && refract == mat.GetParam<float>("refract"); //same = same && ambient == mat.GetParam<float>("ambient"); same = same && emissive == mat.GetParam <float>("emissive"); if (difMap == null) { same = same && mat.GetParam <Texture2D>("albedoMap") == null; } else { same = same && difMap == mat.GetParam <Texture2D>("albedoMap"); } if (alphaMap == null) { same = same && mat.GetParam <Texture2D>("alphaMap") == null; } else { same = same && alphaMap == mat.GetParam <Texture2D>("alphaMap"); } if (bumpMap == null) { same = same && mat.GetParam <Texture2D>("bumpMap") == null; } else { same = same && bumpMap == mat.GetParam <Texture2D>("bumpMap"); } return(same); }); if (m != null) { indexTable[i] = mats.IndexOf(m); } else { mats.Add(materials[i]); indexTable[i] = mats.Count - 1; } } foreach (var mesh in obj.Meshes) { foreach (var sub in mesh.subMeshes) { sub.materialIndex = indexTable[sub.materialIndex]; } } obj.Materials = mats.ToArray(); } if (CombineMeshes && CombineMaterials) { var indices = new List <int> [materials.Count]; foreach (var sub in obj.Meshes[0].subMeshes) { if (indices[sub.materialIndex] == null) { indices[sub.materialIndex] = new List <int>(); } indices[sub.materialIndex].AddRange(sub.indices); } obj.Meshes[0].subMeshes.Clear(); for (var i = 0; i < materials.Count; i++) { if (indices[i] == null) { continue; } obj.Meshes[0].SetIndices(i, indices[i].ToArray(), BeginMode.Triangles); } } return(new ImportedObject[] { obj }); }
private void SetControlParameters(NwObject obj) { // textures textures.AddRange(obj.Texture2Ds); // general textBox_name.Text = obj.Name; textBox_version.Text = obj.Version; textBox_desc.Text = obj.Description; textBox_editor.Text = obj.Editor; textBox_url.Text = obj.EditorURL; textBox_tags.Text = obj.Tags; if (obj.Thumbnail != null) { pictureBox_thumbnail.Image = Util.ToBitmap(obj.Thumbnail.Image); } else { pictureBox_thumbnail.Image = null; } // item comboBox_itemType.SelectedItem = obj.ItemType; numericUpDown_price.Value = MMWMath.Clamp((int)obj.ItemPrice, 0, 1000); checkBox_itemConsume.Checked = obj.ItemConsume; numericUpDown_maxStack.Value = MMWMath.Clamp(obj.MaxStack, 1, 99); checkBox_itemSync.Checked = obj.Sync; checkBox_itemPurchasable.Checked = obj.Purchasable; // materials listBox_material.DisplayMember = "Name"; foreach (var mat in obj.Materials) { listBox_material.Items.Add(mat); } listBox_material.SelectedIndex = 0; // physics if (obj.CollisionShape is NwCollisionCapsule) { radioButton_capsule.Checked = true; } else if (obj.CollisionShape is NwCollisionCylinder) { radioButton_cylinder.Checked = true; } else if (obj.CollisionShape is NwCollisionBox) { radioButton_box.Checked = true; } else if (obj.CollisionShape is NwCollisionSphere) { radioButton_sphere.Checked = true; } else if (obj.CollisionShape is NwCollisionMesh) { radioButton_mesh.Checked = true; } checkBox_isRigidBody.Checked = obj.PhysicalMaterial.IsRigidBody; if (obj.PhysicalMaterial.IsRigidBody) { numericUpDown_mass.Value = (decimal)obj.PhysicalMaterial.Mass; checkBox_freezePosition.Checked = obj.PhysicalMaterial.FreezePosition; checkBox_freezeRotation.Checked = obj.PhysicalMaterial.FreezeRotation; checkBox_kinematic.Checked = obj.PhysicalMaterial.Kinematic; checkBox_disableDeactivation.Checked = obj.PhysicalMaterial.DisableDeactivation; slider_friction.Value = obj.PhysicalMaterial.Friction; slider_rollingFriction.Value = obj.PhysicalMaterial.RollingFriction; slider_restitution.Value = obj.PhysicalMaterial.Restitution; slider_linearDamping.Value = obj.PhysicalMaterial.LinearDamping; slider_angulerDamping.Value = obj.PhysicalMaterial.AngulerDamping; } // motions foreach (var m in obj.Motions) { var i = dataGridView_motion.Rows.Add(m.Key, m.Name); dataGridView_motion.Rows[i].Tag = m; } // morphs // sounds foreach (var s in obj.Sounds) { var i = dataGridView_sound.Rows.Add(); var row = dataGridView_sound.Rows[i]; row.Cells[0].Value = s.Name; var path = System.Environment.CurrentDirectory + "/tempsound_" + Util.CreateHash(); File.WriteAllBytes(path, s.Data); var afd = new AudioFileReader(path); var waveOut = new WaveOut(); waveOut.Init(afd); row.Tag = new Tuple <AudioFileReader, WaveOut, byte[], string>(afd, waveOut, s.Data, s.Format); } // scripts foreach (var s in obj.Scripts) { var asm = Assembly.Load(s.Assembly); var type = asm.GetExportedTypes().Where(t => t.IsSubclassOf(typeof(GameObjectScript))).ToArray()[0]; var inst = asm.CreateInstance(type.FullName) as GameObjectScript; listBox_scripts.Items.Add(new ScriptInfo() { Assembly = s.Assembly, Script = inst, }); } // property var idx = 0; foreach (var p in obj.Properties) { idx = dataGridView_property.Rows.Add(1); dataGridView_property[0, idx].Value = p.Key; dataGridView_property[1, idx].Value = p.Value; } }