void NatureBloom(SkinnedMesh mesh) { if (mesh.useBakeMesh) { var m = transform.localToWorldMatrix; for (int i = 0; i < mesh.vertexCount; i++) { Vector3 position = mesh.bakedVertices[i]; Vector3 normal = mesh.bakedNormals[i]; Quaternion q = Quaternion.LookRotation(mesh.normals[i], Vector3.up); Quaternion w = Quaternion.identity; w.SetEulerRotation(Mathf.PI / 2, 0, 0); Vector3 worldPt = transform.TransformPoint(position); instantiatedPrefab = Instantiate(instaMesh, worldPt, transform.rotation * q * w); // baseScale = instantiatedPrefab.transform.localScale; //instantiatedPrefab.transform.localScale = baseScale * startSize; } } else { for (int i = 0; i < mesh.vertexCount; i++) { Vector3 position = mesh.vertices[i]; Vector3 normal = mesh.normals[i]; Quaternion q = Quaternion.LookRotation(mesh.normals[i], Vector3.up); Quaternion w = Quaternion.identity; w.SetEulerRotation(Mathf.PI / 2, 0, 0); Vector3 worldPt = transform.TransformPoint(position); instantiatedPrefab = Instantiate(instaMesh, position, transform.rotation * q * w); //baseScale = instantiatedPrefab.transform.localScale; //instantiatedPrefab.transform.localScale = baseScale * startSize; } } }
/// <summary> /// Clones this instance. /// </summary> /// <returns>The cloned animated model data.</returns> public InternalSkinnedModel Clone() { var newModel = new InternalSkinnedModel(); newModel.graphics = this.graphics; newModel.BoundingBox = this.BoundingBox; for (int i = 0; i < this.Meshes.Count; i++) { SkinnedMesh currentMesh = this.Meshes[i]; SkinnedVertexBuffer currentBuffer = currentMesh.VertexBuffer as SkinnedVertexBuffer; var newVertices = new SkinnedVertex[currentMesh.NumVertices]; Array.Copy(currentBuffer.CpuVertices, newVertices, currentBuffer.CpuVertices.Length); var newBuffer = new SkinnedVertexBuffer(currentBuffer.VertexBufferFormat); newBuffer.SetData(newVertices, currentBuffer.VertexCount); var newIndexBuffer = new IndexBuffer(this.internalindices[i]); var newMesh = new SkinnedMesh( currentMesh.VertexOffset, currentMesh.NumVertices, currentMesh.IndexOffset, currentMesh.NumPrimitives, newBuffer, newIndexBuffer, PrimitiveType.TriangleList); newMesh.Name = currentMesh.Name; newModel.Meshes.Add(newMesh); this.graphics.BindIndexBuffer(newModel.Meshes[i].IndexBuffer); this.graphics.BindVertexBuffer(newModel.Meshes[i].VertexBuffer); } return(newModel); }
/// <summary> /// Try to get all root joints. /// </summary> public static List <SJoint> GetRootJoints(SkinnedMesh mesh) { List <SJoint> roots = new List <SJoint>(); List <SJoint> allJoints = mesh.GetAllJoints(); for (int i = 0; i < allJoints.Count; i++) { bool isRoot = true; SJoint testedJoint = allJoints[i]; for (int j = 0; j < allJoints.Count; j++) { SJoint testedJoint2 = allJoints[j]; for (int k = 0; k < testedJoint2.Children.Count; k++) { if (testedJoint.Equals(testedJoint2.Children[k])) { isRoot = false; } } } if (isRoot) { roots.Add(testedJoint); } } return(roots); }
private void LoadFromColladaSceneNode(ColladaSceneNodeBase node) { if (node.Type != ColladaSceneNodeBase.NodeType.Node && node.Type != ColladaSceneNodeBase.NodeType.Scene) { return; } // This is not correct. When using a skin there is an 'instance_controller' if (node.Instance_Geometry != null) { ColladaMesh mesh = node.Instance_Geometry; for (int iPart = 0; iPart < mesh.Parts.Count; iPart++) { ColladaMesh.PrimitiveList meshPart = mesh.Parts[iPart]; SkinnedMesh skinnedMesh = new SkinnedMesh(skinnedModel); Matrix objectMatrix = node.GetFullMatrix() * Matrix.CreateRotationX(-MathHelper.PiOver2); LoadMesh(skinnedMesh, mesh, meshPart, objectMatrix); skinnedModel.Meshes.Add(skinnedMesh); //model.FullData.ObjectMatrix = node.GetFullMatrix(); // TODO: this only counts when model is from max! //model.FullData.ObjectMatrix = model.FullData.ObjectMatrix * Matrix.CreateRotationX( -MathHelper.PiOver2 ); } } for (int iNode = 0; iNode < node.Nodes.Count; iNode++) { LoadFromColladaSceneNode(node.Nodes[iNode]); } }
/// <summary> /// Try to apply animation to model. /// </summary> public void Apply(SkinnedMesh skinnedMesh) { skinnedMesh.AnimationSpeed = animationSpeed; for (int i = 0; i < orientations.Count; i++) { SJoint joint = skinnedMesh.GetAllJoints()[i]; for (int j = 0; j < positions[i].Count; j++) { var poskey = skinnedMesh.AddPositionKey(joint); poskey.Position = positions[i][j]; poskey.Frame = positionsKeyframes[i][j]; } for (int j = 0; j < orientations[i].Count; j++) { var rotkey = skinnedMesh.AddRotationKey(joint); rotkey.Rotation = orientations[i][j]; rotkey.Frame = orientKeyframes[i][j]; } for (int j = 0; j < scales[i].Count; j++) { var scalekey = skinnedMesh.AddScaleKey(joint); scalekey.Scale = scales[i][j]; scalekey.Frame = scalesKeyframes[i][j]; } } }
/// <summary> /// Displays the centers of rotation using cubes /// </summary> /// <param name="mesh"></param> private void PlotCenters(SkinnedMesh mesh) { var centers = mesh.GetCentersOfRotation(); foreach (var position in centers) { Instantiate(dataPoint, position, Quaternion.identity); } }
/// <summary> /// Try to get joint by name. /// </summary> public static SJoint GetJointByName(SkinnedMesh mesh, string name) { int jointID = mesh.GetJointIndex(name); if (jointID == -1) { return(null); } return(mesh.GetAllJoints()[jointID]); }
/// <summary> /// Sets the material slot index to highlight. /// </summary> /// <param name="mesh">The mesh.</param> public void SetHighlight(SkinnedMesh mesh) { if (Window._skipEffectsGuiEvents) { return; } Window._highlightIndex = mesh?.MaterialSlotIndex ?? -1; Window.UpdateEffectsOnAsset(); UpdateEffectsOnUI(); }
void DrawVertices(SkinnedMesh mesh) { Color color = Color.green; var m = transform.localToWorldMatrix; for (int i = 0; i < mesh.vertexCount; i++) { Vector3 position = mesh.bakedVertices[i]; Vector3 normal = mesh.bakedNormals[i]; Debug.DrawLine(position, position + (normal * normalLength), color); } }
/// <summary> /// Sets the material slot index to the mesh. /// </summary> /// <param name="mesh">The mesh.</param> /// <param name="newSlotIndex">New index of the material slot to use.</param> public void SetMaterialSlot(SkinnedMesh mesh, int newSlotIndex) { if (Window._skipEffectsGuiEvents) { return; } mesh.MaterialSlotIndex = newSlotIndex == -1 ? 0 : newSlotIndex; Window.UpdateEffectsOnAsset(); UpdateEffectsOnUI(); Window.MarkAsEdited(); }
void Start() { // Initialize character mesh list int hierarchy_depth, skeleton_bone_count; var controllers = GPUSkinnedMeshComponent.PrepareControllers(characters, out hierarchy_depth, out skeleton_bone_count); // Initialize GPU Instancer this.m = new MeshInstancer(); this.m.Initialize(max_parent_depth: hierarchy_depth + 2, num_skeleton_bones: skeleton_bone_count, pathCount: 2); this.p = new PathArrayHelper(this.m); // Add all animations to GPU buffer this.m.SetAllAnimations(controllers); // Add all character mesh types to GPU Instancer foreach (var character in this.characters) { this.m.AddGPUSkinnedMeshType(character); } // Do stuff for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { var mesh = characters[Random.Range(0, characters.Count)]; var anim = mesh.anim.namedAnimations["walk"]; instances[i, j] = new SkinnedMesh(mesh, this.m); instances[i, j].mesh.position = new Vector3(i, 0, j); instances[i, j].SetRadius(1.75f); // set large enough radius so model doesnt get culled to early instances[i, j].Initialize(); instances[i, j].SetAnimation(anim, speed: 1.4f, start_time: Random.Range(0.0f, 1.0f)); // set animation var path = GetNewPath(); // create new path instances[i, j].mesh.SetPath(path, this.m); // assign path to instance paths[i, j] = path; instances[i, j].UpdateAll(); } } // For testing purposes.. do bone visualization of [0,0] model bones_unity = new GameObject[instances[0, 0].skeleton.data.Length]; for (int i = 0; i < bones_unity.Length; i++) { var obj = GameObject.CreatePrimitive(PrimitiveType.Cube); obj.name = "Calculated Bone Transform " + i.ToString(); bones_unity[i] = obj; } }
/// <summary> /// Try to apply skeleton to model. /// </summary> private void ApplySkeletonToModel(SkinnedMesh skinnedMesh) { // Create the bones for (int i = 0; i < meshSkeleton.nbBones; i++) { string boneName = meshSkeleton.names[i]; var joint = skinnedMesh.AddJoint(); joint.Name = boneName; } // Set the hierarchy for (int i = 0; i < meshSkeleton.nbBones; i++) { short parent = meshSkeleton.parentIdx[i]; if (parent != -1) // root { var parentJoint = CSkeleton.GetJointByName(skinnedMesh, meshSkeleton.names[parent]); if (parentJoint != null) { parentJoint.AddChildren(skinnedMesh.GetAllJoints()[i]); } } } // Set the transformations for (int i = 0; i < meshSkeleton.nbBones; i++) { string boneName = meshSkeleton.names[i]; var joint = CSkeleton.GetJointByName(skinnedMesh, boneName); if (joint == null) { continue; } joint.LocalMatrix = meshSkeleton.matrix[i]; joint.Animatedposition = meshSkeleton.positions[i]; joint.Animatedrotation = meshSkeleton.rotations[i]; joint.Animatedscale = meshSkeleton.scales[i]; } // Compute the global matrix List <SJoint> roots = CSkeleton.GetRootJoints(skinnedMesh); for (int i = 0; i < roots.Count; ++i) { CSkeleton.ComputeGlobal(skinnedMesh, roots[i]); } }
private void Serialize() { if (serializeMesh) { foreach (var renderer in this.animated.skinnedMeshRenderers) { var skinnedMesh = new SkinnedMesh(renderer.sharedMesh, renderer); skinnedMesh.Serialize(location); } } if (serializeAnimations) { foreach (var clip in this.animated.animationClips) { // editor binding var bindings = AnimationUtility.GetCurveBindings(clip); // animation: bone index + propertyName + curves var curves = new List <SerializedCurve>(); foreach (var binding in bindings) { // dont serialize root gameobject component animation curves if (binding.path.Equals("")) { continue; } AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, binding); SerializedCurve serialized = new SerializedCurve( this.animated.skeletonRoot.BoneIndexRecursive(binding.path), binding.propertyName, curve ); curves.Add(serialized); } System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(List <SerializedCurve>)); var path = Path.Combine(location, clip.name + ".curves"); var file = File.Create(path); writer.Serialize(file, curves); file.Close(); } } }
void update() { // randomly add/remove skinned mesh every frame for (int i = 0; i < 20; i++) { var x = r.Next() % N; var y = r.Next() % N; bool remove = !adding; var gpu_skinned_mesh = r.Next() % 2 == 1 ? model1 : model2; GPUAnimation.Animation anim = gpu_skinned_mesh.anim.animations[r.Next(1, gpu_skinned_mesh.anim.animations.Length)]; var mscale = gpu_skinned_mesh == model1 ? Model1Scale : Vector3.one; if (!this.skins[x, y].Initialized() && !remove) { var skin = new SkinnedMesh(gpu_skinned_mesh, this.m); skin.SetRadius(1.75f); skin.Initialize(); skin.mesh.position = new Vector3(x, this.y_offset, y); skin.mesh.scale = mscale; skin.SetAnimation(anim, speed: 0.1f + (float)r.NextDouble() * 2.0f, start_time: (float)r.NextDouble()); // create & assign path Path path = new Path(path_length: 4, m: this.m, use_constants: true); this.p.InitializePath(ref path); this.p.SetPathConstants(path, new Vector3(0, 1, 0), new Vector3(0, 0, 1), skin.mesh.rotation, skin.mesh.position); this.p.UpdatePath(ref path); skin.mesh.SetPath(path, this.m); skin.UpdateAll(); skins[x, y] = skin; paths[x, y] = path; } else if (this.skins[x, y].Initialized() && remove) { skins[x, y].Dispose(); this.p.DeletePath(ref paths[x, y]); } } // reset if adding time_seconds += Time.deltaTime; if (time_seconds > period) { adding = !adding; time_seconds = 0; } }
private void selectAnimationToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { node.DebugDataVisible = DebugSceneType.Off; SkinnedMesh sm = helper.applyAnimation(e.ClickedItem.Text, meshToAnimate); if (sm != null) { modelPosition = new Vector3Df(0.0f); modelAngle = new Vector3Df(0.0f); node.Mesh = sm; resetDebugViewMenu(); setMaterialsSettings(node); activeAnim = e.ClickedItem.Text; } }
/// <summary> /// Try to get real parent. /// </summary> public static SJoint GetRealParent(SkinnedMesh mesh, SJoint joint) { List <SJoint> allJoints = mesh.GetAllJoints(); for (int j = 0; j < allJoints.Count; j++) { SJoint testedJoint = allJoints[j]; for (int k = 0; k < testedJoint.Children.Count; k++) { if (joint == testedJoint.Children[k]) { return(testedJoint); } } } return(null); }
public void LoadMeshes() { //Dictionary<ColladaMaterial, EditorMaterial> materials = new Dictionary<ColladaMaterial, EditorMaterial>(); // Load all models from the scene. Each meshPart/primitivelist will become a seperate model //TODO: this does not work, now simply load every mesh found //LoadFromColladaSceneNode( colladaModel.Scene ); for (int i = 0; i < colladaModel.Meshes.Count; i++) { ColladaMesh colladaMesh = colladaModel.Meshes[i]; for (int j = 0; j < colladaMesh.Parts.Count; j++) { SkinnedMesh mesh = new SkinnedMesh(skinnedModel); skinnedModel.Meshes.Add(mesh); LoadMesh(mesh, colladaMesh, colladaMesh.Parts[j], Matrix.CreateRotationX(-MathHelper.PiOver2)); } } }
/// <summary> /// Try to compute global matrix. /// </summary> public static void ComputeGlobal(SkinnedMesh mesh, SJoint joint) { SJoint parent = GetRealParent(mesh, joint); if (parent != null) { joint.GlobalMatrix = parent.GlobalMatrix * joint.LocalMatrix; } else { joint.GlobalMatrix = joint.LocalMatrix; } for (int i = 0; i < joint.Children.Count; ++i) { ComputeGlobal(mesh, joint.Children[i]); } }
public void StartRecord() { if (isRecord) { return; } skinnedMesh = new SkinnedMesh(); SimpleMesh simpleMesh = new SimpleMesh(); //Vertices for (var i = 0; i < skinnedMeshRenderer.sharedMesh.vertices.Length; i++) { simpleMesh.Vertices.Add(new MeshInfomation.Vertex { X = skinnedMeshRenderer.sharedMesh.vertices[i].x, Y = skinnedMeshRenderer.sharedMesh.vertices[i].y, Z = skinnedMeshRenderer.sharedMesh.vertices[i].z }); } //UV for (var i = 0; i < skinnedMeshRenderer.sharedMesh.uv.Length; i++) { simpleMesh.UV.Add(new MeshInfomation.UV { X = skinnedMeshRenderer.sharedMesh.uv[i].x, Y = skinnedMeshRenderer.sharedMesh.uv[i].y }); } //Normals for (var i = 0; i < skinnedMeshRenderer.sharedMesh.normals.Length; i++) { simpleMesh.Normals.Add(new MeshInfomation.Normal { X = skinnedMeshRenderer.sharedMesh.normals[i].x, Y = skinnedMeshRenderer.sharedMesh.normals[i].y, Z = skinnedMeshRenderer.sharedMesh.normals[i].z }); } //Indices for (var i = 0; i < skinnedMeshRenderer.sharedMesh.GetIndices(0).Length; i++) { simpleMesh.Indices.Add(skinnedMeshRenderer.sharedMesh.GetIndices(0)[i]); } skinnedMesh.Mesh = simpleMesh; frameCount = 0; isRecord = true; }
public PlayerObject(PlayerIndex playerIndex, Color color, Vector3 pos, float initialYRot) { this.playerIndex = playerIndex; this.color = color; // initial transform this._position = pos; rotation = initialYRot; SetupLights(); mesh = new SkinnedMesh(); mesh.Model = AssetLoader.mdl_character; //Create a new Animation Player that will take the bone dictionaries as arguments allowing individual animation with upper and lower body upPlayer = new DurationBasedAnimator(mesh.SkinningData, mesh.SkinningData.AnimationClips["Take 001"], Animation_States.upperCharacterBones); lowPlayer = new DurationBasedAnimator(mesh.SkinningData, mesh.SkinningData.AnimationClips["Take 001"], Animation_States.lowerCharacterBonesandRoot); //Load the animations from the asset loader (these are in an Animation Package) upPlayer.AddAnimationPackage = AssetLoader.ani_character; upPlayer.StartClip(moving + shooting + weapon); lowPlayer.AddAnimationPackage = AssetLoader.ani_character; lowPlayer.StartClip(moving + weapon); UpdateAnimation(0); UpdateMajorTransforms(0); Globals.gameInstance.sceneGraph.Setup(mesh); modelReceipt = Globals.gameInstance.sceneGraph.Add(mesh); light1receipt = Globals.gameInstance.sceneGraph.Add(torchlight); light2receipt = Globals.gameInstance.sceneGraph.Add(haloemitlight); light3receipt = Globals.gameInstance.sceneGraph.Add(halolight); SetupWeapons(); SwitchWeapon(0); collisionRectangle = new RectangleF( _position.X - boundingBoxSize, _position.Y - boundingBoxSize, boundingBoxSize * 2, boundingBoxSize * 2 ); }
/// <summary> /// Helper method for storing data. This actually stores shader parameters. /// Note: This does not rreaally support material sharing among multiple models /// </summary> /// <param name="mat"></param> /// <returns></returns> private void LoadMeshMaterial(SkinnedMesh mesh, ColladaMaterial mat) { //MaterialName = mat.Name; mesh.Shader.AmbientColor = mat.Ambient.ToVector4(); mesh.Shader.DiffuseColor = mat.Diffuse.ToVector4(); mesh.Shader.SpecularColor = mat.Specular.ToVector4(); mesh.Shader.Shininess = mat.Shininess; if (mat.DiffuseTexture != null) { ;//mesh.Shader DiffuseTexture = mat.DiffuseTexture.GetFullFilename(); } mesh.Shader.DiffuseTextureRepeat = new Vector2(mat.DiffuseTextureRepeatU, mat.DiffuseTextureRepeatV); if (mat.NormalTexture != null) { ;// mesh.Shader NormalTexture = mat.NormalTexture.GetFullFilename(); } mesh.Shader.NormalTextureRepeat = new Vector2(mat.NormalTextureRepeatU, mat.NormalTextureRepeatV); }
private void exportToolStripMenuItem_Click(object sender, EventArgs e) { using (var sf = new SaveFileDialog()) { sf.Filter = "Irrlicht mesh | *.irrm | Collada mesh | *.coll | STL Mesh | *.stl | OBJ Mesh | *.obj | PLY Mesh | *.ply | B3D Mesh | *.b3d | FBX Mesh | *.fbx"; if (sf.ShowDialog() == DialogResult.OK) { MeshWriterType mwt = 0; switch (Path.GetExtension(sf.FileName).Trim()) { case ".irrm": mwt = MeshWriterType.IrrMesh; break; case ".coll": mwt = MeshWriterType.Collada; break; case ".obj": mwt = MeshWriterType.Obj; break; case ".stl": mwt = MeshWriterType.Stl; break; case ".ply": mwt = MeshWriterType.Ply; break; case ".b3d": mwt = MeshWriterType.B3d; break; case ".fbx": mwt = MeshWriterType.Fbx; break; default: MessageBox.Show(this, "Wrong file format selected, choose correct file format!", "WolvenKit", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var mw = smgr.CreateMeshWriter(mwt); AnimatedMesh sm = mesh; SkinnedMesh s = null; if (meshToAnimate != null) { sm = meshToAnimate; } if (!string.IsNullOrEmpty(activeAnim)) { s = helper.applyAnimation(activeAnim, meshToAnimate); if (s != null) { sm = s; } } if (mw.WriteMesh(dev.FileSystem.CreateWriteFile(sf.FileName), sm, MeshWriterFlag.None)) { MessageBox.Show(this, "Sucessfully wrote file!", "WolvenKit", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(this, "Failed to write file!", "WolvenKit", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (sm != null) { sm.Drop(); } if (mw != null) { mw.Drop(); } if (s != null) { s.Drop(); } } } }
private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; //DeviceSettings settings = e.Argument as DeviceSettings; // create irrlicht device using provided settings if (panelRenderWindow.IsDisposed) { throw new Exception("Form closed!"); } DeviceSettings s = new DeviceSettings( IntPtr.Zero, DriverType.Direct3D9, 0, //antialias new Color(100, 101, 140), false); if (panelRenderWindow.InvokeRequired) { panelRenderWindow.Invoke(new MethodInvoker(delegate { s.WindowID = panelRenderWindow.Handle; })); } dev = IrrlichtDevice.CreateDevice(s); if (dev == null) { throw new NullReferenceException("Could not create device for engine!"); } dev.OnEvent += new IrrlichtDevice.EventHandler(this.device_OnEvent); dev.Logger.LogLevel = LogLevel.Warning; drv = dev.VideoDriver; smgr = dev.SceneManager; gui = dev.GUIEnvironment; _ = smgr.FileSystem.AddFileArchive(activeMod.FileDirectory); smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true); smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true); // added by vl if (meshFile != null && meshFile.Length > 0) { mesh = smgr.GetMesh(meshFile); } if (mesh == null) { throw new Exception("Failed to load mesh."); } mesh.Grab(); smgr.MeshManipulator.RecalculateNormals(mesh); meshLoaded = true; float scaleMul = 1.0f; node = smgr.AddAnimatedMeshSceneNode(mesh); helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper(); // hacked to gat witcher3 loader if (node != null && meshLoaded) { node.Scale = new Vector3Df(3.0f); node.SetMaterialFlag(MaterialFlag.Lighting, false); scaleMul = node.BoundingBox.Radius / 4; if (!string.IsNullOrEmpty(rigFile)) { meshToAnimate = helper.loadRig(rigFile, mesh); if (meshToAnimate == null) { throw new Exception("Failed to load rig."); } else { meshToAnimate.Grab(); rigLoaded = true; Logger.LogString("Rig loaded!", Logtype.Success); node.Mesh = meshToAnimate; } } if (!string.IsNullOrEmpty(animFile) && rigLoaded) { animList = helper.loadAnimation(animFile, meshToAnimate); if (animList.Count > 0) { animLoaded = true; Logger.LogString($"{animList.Count} animations loaded! Select animation to play", Logtype.Success); } else { Logger.LogString("No animations loaded!", Logtype.Important); } } setMaterialsSettings(node); } var camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0)); camera.NearValue = 0.001f; camera.FOV = 45.0f * 3.14f / 180.0f; var animText = activeAnim; var mAnimText = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70)); var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60)); var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50)); var fpsText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40)); var infoText = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height)); mAnimText.OverrideColor = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255); mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0); viewPort = drv.ViewPort; var lineMat = new Material { Lighting = false }; while (dev.Run()) { drv.ViewPort = viewPort; drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, s.BackColor); node.Position = modelPosition; node.Rotation = modelAngle; //update info box mPositionText.Text = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}"; mRotationText.Text = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}"; fpsText.Text = $"FPS: {drv.FPS}"; smgr.DrawAll(); gui.DrawAll(); // draw xyz axis right bottom drv.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height); drv.SetMaterial(lineMat); var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle); drv.SetTransform(TransformationState.World, matrix); matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue); drv.SetTransform(TransformationState.Projection, matrix); matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0)); drv.SetTransform(TransformationState.View, matrix); drv.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.SolidGreen); drv.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.SolidBlue); drv.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.SolidRed); drv.EndScene(); // if we requested to stop, we close the device if (worker.CancellationPending) { dev.Close(); } } // drop device dev.Drop(); }
/// <summary> /// Loads this class with data from a stream. /// </summary> /// <param name="graphicsDevice">The graphicsDevice device.</param> /// <param name="stream">The stream that contains the model data.</param> public void Load(GraphicsDevice graphicsDevice, Stream stream) { this.graphics = graphicsDevice; using (var reader = new BinaryReader(stream)) { this.internalindices = new List <ushort[]>(); this.BoundingBox.Min = reader.ReadVector3(); this.BoundingBox.Max = reader.ReadVector3(); this.BoundingBoxBoneIndex = reader.ReadInt32(); int numMeshes = reader.ReadInt32(); for (int i = 0; i < numMeshes; i++) { string meshName = reader.ReadString(); reader.ReadInt32(); // mesh count for (int j = 0; j < 1; j++) { ////bool usesTangent = false; int vertexOffset = reader.ReadInt32(); int numVertices = reader.ReadInt32(); int startIndex = reader.ReadInt32(); int primitiveCount = reader.ReadInt32(); reader.ReadInt32(); // vertex stride int numVertexElements = reader.ReadInt32(); var properties = new VertexElementProperties[numVertexElements]; for (int k = 0; k < numVertexElements; k++) { properties[k].Offset = reader.ReadInt32(); properties[k].Format = (VertexElementFormat)reader.ReadInt32(); properties[k].Usage = (VertexElementUsage)reader.ReadInt32(); properties[k].UsageIndex = reader.ReadInt32(); } reader.ReadInt32(); // bufferSize var bufferData = new SkinnedVertex[numVertices]; for (int k = 0; k < numVertices; k++) { foreach (VertexElementProperties property in properties) { switch (property.Usage) { case VertexElementUsage.Position: bufferData[k].Position = reader.ReadVector3(); break; case VertexElementUsage.TextureCoordinate: bufferData[k].TexCoord = reader.ReadVector2(); break; case VertexElementUsage.Normal: bufferData[k].Normal = reader.ReadVector3(); break; case VertexElementUsage.BlendIndices: bufferData[k].BlendIndices = reader.ReadByte4(); break; case VertexElementUsage.BlendWeight: bufferData[k].BlendWeights = reader.ReadVector2(); break; case VertexElementUsage.Tangent: bufferData[k].Tangent = reader.ReadVector3(); break; case VertexElementUsage.Binormal: bufferData[k].Binormal = reader.ReadVector3(); break; } } } int indexSize = reader.ReadInt32(); var indices = new ushort[indexSize]; for (int k = 0; k < indexSize; k++) { indices[k] = reader.ReadUInt16(); } this.internalindices.Add(indices); var newSkinnedBuffer = new SkinnedVertexBuffer(SkinnedVertex.VertexFormat); newSkinnedBuffer.SetData(bufferData, numVertices); var mesh = new SkinnedMesh( vertexOffset, numVertices, startIndex, primitiveCount, newSkinnedBuffer, new IndexBuffer(indices), PrimitiveType.TriangleList); mesh.Name = meshName; this.Meshes.Add(mesh); } } } }
/// <summary> /// Draws the animated model. /// </summary> /// <param name="gameTime">The elapsed game time.</param> /// <remarks> /// This method will only be called if all the following points are true: /// <list type="bullet"> /// <item> /// <description>The entity passes a frustrum culling test.</description> /// </item> /// <item> /// <description>The parent of the owner <see cref="Entity" /> of the <see cref="Drawable" /> cascades its visibility to its children and it is visible.</description> /// </item> /// <item> /// <description>The <see cref="Drawable" /> is active.</description> /// </item> /// <item> /// <description>The owner <see cref="Entity" /> of the <see cref="Drawable" /> is active and visible.</description> /// </item> /// </list> /// </remarks> public override void Draw(TimeSpan gameTime) { if (this.lastModelId != this.skinnedModel.GetHashCode()) { this.meshMaterials = new Material[this.skinnedModel.Meshes.Count]; this.updateVertexBuffer = new bool[this.skinnedModel.Meshes.Count]; this.lastModelId = this.skinnedModel.GetHashCode(); } if (this.LODEnabled) { this.passUpdate--; if (this.passUpdate <= 0) { float distanceToCamera = Vector3.Distance(this.Transform.Position, this.RenderManager.CurrentDrawingCamera3D.Position); float amount = (distanceToCamera - this.lodMinDistance) / this.lodDiffDistance; if (amount > 1) { amount = 1; } if (amount < 0) { amount = 0; } this.passUpdate = (int)(amount * Quality); this.updateLod = true; } } float zOrder = Vector3.DistanceSquared(this.RenderManager.CurrentDrawingCamera3D.Position, this.Transform.Position); bool needsUpdate = (!LowPerformance && this.lastKeyFrame != this.Animation.Frame && this.updateLod) && this.lastAnimTime != this.Animation.TotalAnimTime; this.lastAnimTime = this.Animation.TotalAnimTime; if (needsUpdate) { this.UpdateTransforms(); } for (int i = 0; i < this.skinnedModel.Meshes.Count; i++) { Material currentMaterial; SkinnedMesh currentMesh = this.skinnedModel.Meshes[i]; this.updateVertexBuffer[i] |= needsUpdate; if (this.MaterialMap.Materials.ContainsKey(currentMesh.Name)) { currentMaterial = this.MaterialMap.Materials[currentMesh.Name]; } else { currentMaterial = this.MaterialMap.DefaultMaterial; } this.meshMaterials[i] = currentMaterial; if (currentMaterial != null) { if (this.updateVertexBuffer[i]) { currentMesh.SetBones(this.skinTransforms, true); this.GraphicsDevice.BindVertexBuffer(currentMesh.VertexBuffer); this.updateVertexBuffer[i] = false; } currentMesh.ZOrder = zOrder; this.GraphicsDevice.UnsetBuffers(); Matrix transform = this.Transform.WorldTransform; this.RenderManager.DrawMesh(currentMesh, currentMaterial, ref transform, false); this.GraphicsDevice.UnsetBuffers(); } } if (this.LODEnabled) { this.updateLod = false; } this.lastKeyFrame = this.Animation.Frame; }
void Start() { SkinnedMesh mesh = GetComponent <SkinnedMesh>(); mesh.OnResultsReady += DrawVertices; }
// Use this for initialization void Start() { SkinnedMesh mesh = GetComponent <SkinnedMesh>(); mesh.OnResultsReady += NatureBloom; }
private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; DeviceSettings settings = e.Argument as DeviceSettings; // create irrlicht device using provided settings IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings); if (dev == null) { throw new Exception("Failed to create Irrlicht device."); } dev.Logger.LogLevel = LogLevel.Warning; VideoDriver drv = dev.VideoDriver; SceneManager smgr = dev.SceneManager; smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Mod/Bundle"); smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Raw/Mod/TextureCache"); smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true); smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true); // setup a simple 3d scene //CameraSceneNode cam = smgr.AddCameraSceneNode(); //cam.Target = new Vector3Df(0); // added by vl AnimatedMesh mesh = smgr.GetMesh("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/models/animals/cat/model/t_01__cat.w2mesh"); if (mesh == null) { throw new Exception("Failed to load mesh."); } smgr.MeshManipulator.RecalculateNormals(mesh); List <String> animList = null; float scaleMul = 1.0f; AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(mesh); MeshLoaderHelper helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper(); if (node != null) { scaleMul = node.BoundingBox.Radius / 4; node.Scale = new Vector3Df(3.0f); node.SetMaterialFlag(MaterialFlag.Lighting, false); SkinnedMesh sm = helper.loadRig("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/base_entities/cat_base/cat_base.w2rig", mesh); if (sm == null) { throw new Exception("Failed to load rig."); } animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", sm); if (animList.Count > 0) { AnimatedMesh am = helper.applyAnimation(animList[0], sm); node.Mesh = am; } //scaleSkeleton(sm, 3.0f); //sm.SkinMesh(); mesh.Drop(); sm.Drop(); setMaterialsSettings(node); /* * animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", node); * if (animList.Count > 0) * { * helper.applyAnimation(animList[0]); * } */ } var camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0) ); camera.NearValue = 0.001f; camera.FOV = 45.0f * 3.14f / 180.0f; node.DebugDataVisible ^= DebugSceneType.BBox | DebugSceneType.Skeleton; node.Position = new Vector3Df(0.0f); /* * SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f); * cam.AddAnimator(anim); * anim.Drop(); * * SceneNode cube = smgr.AddCubeSceneNode(20); * cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp")); * cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg")); * cube.SetMaterialFlag(MaterialFlag.Lighting, false); * cube.SetMaterialType(MaterialType.Reflection2Layer); */ if (settings.BackColor == null) { smgr.AddSkyBoxSceneNode( "../../media/irrlicht2_up.jpg", "../../media/irrlicht2_dn.jpg", "../../media/irrlicht2_lf.jpg", "../../media/irrlicht2_rt.jpg", "../../media/irrlicht2_ft.jpg", "../../media/irrlicht2_bk.jpg"); } dev.GUIEnvironment.AddImage( drv.GetTexture("../../media/lime_logo_alpha.png"), new Vector2Di(30, 0)); // draw all int lastFPS = -1; while (dev.Run()) { if (settings.BackColor == null) { // indeed, we do not need to spend time on cleaning color buffer if we use skybox drv.BeginScene(ClearBufferFlag.Depth); } else { drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, settings.BackColor); } smgr.DrawAll(); dev.GUIEnvironment.DrawAll(); drv.EndScene(); int fps = drv.FPS; if (lastFPS != fps) { // report progress using common BackgroundWorker' method // note: we cannot do just labelRenderingStatus.Text = "...", // because we are running another thread worker.ReportProgress(fps, drv.Name); lastFPS = fps; } // if we requested to stop, we close the device if (worker.CancellationPending) { dev.Close(); } } // drop device dev.Drop(); }
/// <summary> /// Try to apply skeleton to model. /// </summary> public void Apply(SkinnedMesh skinnedMesh) { // Create the bones for (int i = 0; i < meshSkeleton.nbBones; i++) { string boneName = meshSkeleton.names[i]; if (skinnedMesh.GetJointIndex(boneName) == -1) { var joint = skinnedMesh.AddJoint(); joint.Name = boneName; } } // Set the hierarchy for (int i = 0; i < meshSkeleton.nbBones; i++) { short parent = meshSkeleton.parentIdx[i]; if (parent != -1) // root { var parentJoint = RenderSkeleton.GetJointByName(skinnedMesh, meshSkeleton.names[parent]); if (parentJoint != null) { parentJoint.AddChildren(skinnedMesh.GetAllJoints()[i]); } } } // Set the transformations for (int i = 0; i < meshSkeleton.nbBones; i++) { string boneName = meshSkeleton.names[i]; var joint = RenderSkeleton.GetJointByName(skinnedMesh, boneName); if (joint == null) { continue; } joint.LocalMatrix = meshSkeleton.matrix[i]; joint.Animatedposition = meshSkeleton.positions[i]; joint.Animatedrotation = meshSkeleton.rotations[i]; joint.Animatedscale = meshSkeleton.scales[i]; } // Compute the global matrix List <SJoint> roots = RenderSkeleton.GetRootJoints(skinnedMesh); for (int i = 0; i < roots.Count; ++i) { RenderSkeleton.ComputeGlobal(skinnedMesh, roots[i]); } // The matrix of the bones for (int i = 0; i < CData.boneData.nbBones; i++) { var jointIdx = skinnedMesh.GetJointIndex(CData.boneData.jointNames[i]); if (jointIdx == -1) { continue; //if the mesh bone is not in the animation rig (ie. dynamic) } SJoint joint = skinnedMesh.GetAllJoints()[jointIdx]; Matrix matrix = CData.boneData.boneMatrices[i]; Vector3Df position = matrix.Translation; Matrix invRot = matrix.GetInverse(); //invRot.rotateVect(position); Vector3Df rotation = invRot.GetRotationDegrees(invRot.Scale); //rotation = core::vector3df(0, 0, 0); position = -position; Vector3Df scale = matrix.Scale; if (joint != null) { // Build GlobalMatrix: Matrix positionMatrix = new Matrix(); positionMatrix.Translation = position; Matrix scaleMatrix = new Matrix(); scaleMatrix.Scale = scale; Matrix rotationMatrix = new Matrix(); rotationMatrix.SetRotationRadians(rotation * CommonData.PI_OVER_180); //joint.GlobalMatrix = scaleMatrix * rotationMatrix * positionMatrix; //joint.LocalMatrix = joint.GlobalMatrix; //joint.Animatedposition = joint.LocalMatrix.Translation; //joint.Animatedrotation = new Quaternion(joint.LocalMatrix.GetRotationDegrees(joint.LocalMatrix.Scale)).MakeInverse(); //joint.Animatedscale = joint.LocalMatrix.Scale; var bone = new W3_DataCache.BoneEntry(); bone.name = joint.Name; bone.offsetMatrix = matrix; CData.w3_DataCache.bones.Add(bone); } } // Apply skin for (int i = 0; i < CData.w3_DataCache.vertices.Count; i++) { var entry = CData.w3_DataCache.vertices[i]; // Check if it's a valid entry if (entry.boneId >= CData.w3_DataCache.bones.Count || entry.meshBufferId >= skinnedMesh.MeshBufferCount || entry.vertexId >= skinnedMesh.GetMeshBuffer(entry.meshBufferId).VertexCount) { // Console.WriteLine("Fail to skin : the vertex entry is not valid."); continue; } int jointID = skinnedMesh.GetJointIndex(CData.w3_DataCache.bones[(int)entry.boneId].name); if (jointID == -1) { // Console.WriteLine("Fail to skin : joint not found." ); continue; } SJoint joint = skinnedMesh.GetAllJoints()[jointID]; SWeight weight = skinnedMesh.AddWeight(joint); weight.BufferId = entry.meshBufferId; weight.VertexId = entry.vertexId; weight.Strength = entry.strength; } // Add weights /*for (int i = 0; i < w3_DataCache.vertices.Count; i++) * { * uint boneId = w3_DataCache.vertices[i].boneId; * ushort bufferId = w3_DataCache.vertices[i].meshBufferId; * uint vertexId = w3_DataCache.vertices[i].vertexId; * float fweight = w3_DataCache.vertices[i].strength; * * if (boneId >= skinnedMesh.GetAllJoints().Count) // If bone doesnt exist * continue; * * SJoint joint = skinnedMesh.GetAllJoints()[(int)boneId]; * * SWeight w = skinnedMesh.AddWeight(joint); * w.BufferId = bufferId; * w.Strength = fweight; * w.VertexId = vertexId; * }*/ }
/// <summary> /// The irrlicht thread for rendering. /// </summary> private void StartIrr() { try { IrrlichtCreationParameters irrparam = new IrrlichtCreationParameters(); if (irrlichtPanel.IsDisposed) { throw new Exception("Form closed!"); } if (irrlichtPanel.InvokeRequired) { irrlichtPanel.Invoke(new MethodInvoker(delegate { irrparam.WindowID = irrlichtPanel.Handle; })); } irrparam.DriverType = DriverType.Direct3D9; irrparam.BitsPerPixel = 16; device = IrrlichtDevice.CreateDevice(irrparam); if (device == null) { throw new NullReferenceException("Could not create device for engine!"); } driver = device.VideoDriver; smgr = device.SceneManager; gui = device.GUIEnvironment; var animText = ""; if (Animations.AnimationNames.Count > 0) { animText = "Animation: " + Animations.AnimationNames[selectedAnimIdx].Key; } var mAnimText = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70)); var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60)); var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50)); var fpsText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40)); var infoText = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height)); mAnimText.OverrideColor = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255); mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0); SkinnedMesh skinnedMesh = smgr.CreateSkinnedMesh(); foreach (var meshBuffer in cdata.staticMesh.MeshBuffers) { skinnedMesh.AddMeshBuffer(meshBuffer); } smgr.MeshManipulator.RecalculateNormals(skinnedMesh); if (RigFile != null) { rig.Apply(skinnedMesh); if (AnimFile != null) { anims.Apply(skinnedMesh); } } skinnedMesh.SetDirty(HardwareBufferType.VertexAndIndex); skinnedMesh.FinalizeMeshPopulation(); AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(skinnedMesh); if (node == null) { throw new Exception("Could not load file!"); } node.Scale = new Vector3Df(3.0f); node.SetMaterialFlag(MaterialFlag.Lighting, false); SetMaterials(driver, node); CameraSceneNode camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0)); camera.NearValue = 0.001f; camera.FOV = 45 * CommonData.PI_OVER_180; scaleMul = node.BoundingBox.Radius / 4; var viewPort = driver.ViewPort; var lineMat = new Material(); lineMat.Lighting = false; while (device.Run()) { driver.ViewPort = viewPort; driver.BeginScene(ClearBufferFlag.All, new Color(100, 101, 140)); node.Position = modelPosition; node.Rotation = modelAngle; node.DebugDataVisible = DebugSceneType.Skeleton | DebugSceneType.BBox; mPositionText.Text = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}"; mRotationText.Text = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}"; fpsText.Text = $"FPS: {driver.FPS}"; smgr.DrawAll(); gui.DrawAll(); driver.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height); //driver.ClearBuffers(ClearBufferFlag.None); driver.SetMaterial(lineMat); var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle); driver.SetTransform(TransformationState.World, matrix); matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue); driver.SetTransform(TransformationState.Projection, matrix); matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0)); driver.SetTransform(TransformationState.View, matrix); driver.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.OpaqueGreen); driver.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.OpaqueBlue); driver.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.OpaqueRed); driver.EndScene(); } device.Drop(); } catch (ThreadAbortException) { } catch (NullReferenceException) { } catch (Exception ex) { if (!this.IsDisposed) { MessageBox.Show(ex.Message); //this.Invoke(new MethodInvoker(delegate { this.Close(); })); } } }