Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.BinPacking/PackingPlanVisualizations/3D/PackingGame.cs @ 13530

Last change on this file since 13530 was 13530, checked in by gkronber, 8 years ago

#1966 final commit of changes to game before deleting the whole visualization plugin

File size: 10.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Joseph Helm and Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Drawing.Printing;
24using System.Windows.Forms;
25using SharpDX;
26using SharpDX.Direct3D11;
27using SharpDX.Toolkit;
28using SharpDX.Toolkit.Graphics;
29using SharpDX.Toolkit.Input;
30
31using ButtonStateDX = SharpDX.Toolkit.Input.ButtonState;
32
33
34namespace PackingPlanVisualizations {
35  public class PackingGame : Game {
36
37
38    #region Global Private Variables
39    private GraphicsDeviceManager graphicsDeviceManager;
40    private PackingPlan3D control;
41    private Matrix worldMatrix;
42    private Matrix viewMatrix;
43    private Matrix projectionMatrix;
44    private float zoom = 50;
45    private int selectedItemIndex = -1;
46
47    private BasicEffect basicEffect;
48    private Color backgroundColor { get; set; }
49
50    private CenteredContainer container;
51    private MouseManager mouseManager;
52    #endregion Global Private Variables
53
54    protected override void Dispose(bool disposeManagedResources) {
55      control.disposedByGame = true;
56      base.Dispose(disposeManagedResources);
57      control.disposedByGame = false;
58    }
59
60
61    public PackingGame(PackingPlan3D control)
62      : base() {
63      this.control = control;
64      graphicsDeviceManager = new GraphicsDeviceManager(this);
65      graphicsDeviceManager.PreferMultiSampling = true;
66      graphicsDeviceManager.PreparingDeviceSettings +=
67        (object sender, PreparingDeviceSettingsEventArgs e) => {
68          e.GraphicsDeviceInformation.PresentationParameters.MultiSampleCount = MSAALevel.X4;
69          return;
70        };
71      var controlColor = Color.White;
72      backgroundColor = new Color(controlColor.R, controlColor.G, controlColor.B, controlColor.A);
73
74      mouseManager = new MouseManager(this);
75    }
76
77    public void SetSize(int width, int height) {
78      graphicsDeviceManager.PreferredBackBufferHeight = height;
79      graphicsDeviceManager.PreferredBackBufferWidth = width;
80    }
81
82    public void InitializeContainer(BasicCuboidShape containerShape) {
83      container = new CenteredContainer(containerShape);
84    }
85    public void InitializeContainer(float width, float height, float depth) {
86      InitializeContainer(new BasicCuboidShape(new Vector3(width, height, depth), -1));
87    }
88
89    public void AddItemToContainer(float width, float height, float depth, float x, float y, float z, int index, int material) {
90      container.AddPackingItem(new Vector3(width, height, depth), new Vector3(x, y, z), index, material);
91    }
92
93    public void SelectItem(int itemIndex) {
94      selectedItemIndex = itemIndex;
95    }
96    public void UnselectItem() {
97      selectedItemIndex = -1;
98    }
99
100
101    protected override void Initialize() {
102      base.Initialize();
103      InitializeWorld();
104      previousMouseState = mouseManager.GetState();
105      this.Window.IsMouseVisible = true;
106    }
107    private void InitializeWorld() {
108      #region Matrix-Initialization
109      worldMatrix = Matrix.Identity;
110
111      viewMatrix = Matrix.LookAtLH(
112          new Vector3(0, 10, zoom),
113          Vector3.Zero,
114          Vector3.UnitY);
115
116      projectionMatrix = Matrix.PerspectiveFovLH(
117          (float)Math.PI / 6.0f,
118          (float)GraphicsDevice.BackBuffer.Width /
119          (float)GraphicsDevice.BackBuffer.Height,
120          1.0f, 1000.0f);
121      #endregion Matrix-Initialization
122
123      #region Effect and Color
124      //Effect initialization
125      basicEffect = new BasicEffect(GraphicsDevice);
126      basicEffect.World = worldMatrix;
127      basicEffect.View = viewMatrix;
128      basicEffect.Projection = projectionMatrix;
129
130      //Primitive color
131      basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
132      basicEffect.DiffuseColor = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
133      basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
134      basicEffect.SpecularPower = 5.0f;
135      basicEffect.Alpha = 1.0f;
136      basicEffect.VertexColorEnabled = true;
137      #endregion Effect-World and Color
138
139      #region World lighting
140      basicEffect.LightingEnabled = true;
141
142      basicEffect.PreferPerPixelLighting = true;
143
144      if (basicEffect.LightingEnabled) {
145        basicEffect.DirectionalLight0.Enabled = true; // enable each light individually
146        if (basicEffect.DirectionalLight0.Enabled) {
147          // x direction
148          basicEffect.DirectionalLight0.DiffuseColor = new Vector3(1, 1, 1); // range is 0 to 1
149          basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-1, 0, 0));
150          // points from the light to the origin of the scene
151          basicEffect.DirectionalLight0.SpecularColor = Vector3.One;
152        }
153
154        basicEffect.DirectionalLight1.Enabled = true;
155        if (basicEffect.DirectionalLight1.Enabled) {
156          // y direction
157          basicEffect.DirectionalLight1.DiffuseColor = new Vector3(1, 1, 1);
158          basicEffect.DirectionalLight1.Direction = Vector3.Normalize(new Vector3(0, -1, 0));
159          basicEffect.DirectionalLight1.SpecularColor = Vector3.One;
160        }
161
162        basicEffect.DirectionalLight2.Enabled = true;
163        if (basicEffect.DirectionalLight2.Enabled) {
164          // z direction
165          basicEffect.DirectionalLight2.DiffuseColor = new Vector3(1, 1, 1);
166          basicEffect.DirectionalLight2.Direction = Vector3.Normalize(new Vector3(0, 0, -1));
167          basicEffect.DirectionalLight2.SpecularColor = Vector3.One;
168        }
169      }
170      #endregion World lighting
171
172      #region Transparency
173
174      BlendStateDescription blendStateDescription = new SharpDX.Direct3D11.BlendStateDescription();
175      blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
176      blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
177      blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
178      blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
179      blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
180      blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
181      blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
182      blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
183      SharpDX.Toolkit.Graphics.BlendState blendState = SharpDX.Toolkit.Graphics.BlendState.New(GraphicsDevice, blendStateDescription);
184      GraphicsDevice.SetBlendState(blendState);
185
186      #endregion
187    }
188
189    protected override void Draw(GameTime gameTime) {
190      GraphicsDevice.Clear(backgroundColor);
191
192      worldMatrix =
193        Matrix.RotationY(MathUtil.DegreesToRadians(-currentViewAngle.X * control.Width / 4)) *
194        Matrix.RotationX(MathUtil.DegreesToRadians(currentViewAngle.Y * control.Height / 4));
195      basicEffect.World = worldMatrix;
196
197      viewMatrix = Matrix.LookAtLH(
198          new Vector3(0, zoom, zoom),
199          Vector3.Zero,
200          Vector3.UnitY);
201      basicEffect.View = viewMatrix;
202
203      foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) {
204        pass.Apply();
205
206        if (container != null) {
207          if (container.PackingItems.Count == 0)
208            container.Container.RenderShapeTrianglesAndLines(GraphicsDevice);
209          else {
210            container.Container.RenderShapeLines(GraphicsDevice, new Color(0, 0, 0));
211            var selectedItem = container.PackingItems.Find(x => x.ShapeID == selectedItemIndex);
212            foreach (BasicCuboidShape item in container.PackingItems) {
213              if (selectedItem == null || selectedItemIndex == item.ShapeID) {
214                item.RenderShapeLines(GraphicsDevice);
215                item.RenderShapeTriangles(GraphicsDevice);
216              } else
217                item.RenderShapeLines(GraphicsDevice, new Color(0, 0, 0));
218            }
219          }
220        }
221      }
222
223      base.Draw(gameTime);
224    }
225
226    protected override void Update(GameTime gameTime) {
227      ComputeMouseHandling();
228      base.Update(gameTime);
229    }
230
231    #region Mouse-Handling Variables
232    private MouseState previousMouseState;
233    private Vector2 mousePositionOnBtnDown;
234    private Vector2 viewAngleOnBtnRelease;
235    private Vector2 currentViewAngle = new Vector2(0, 0);
236    #endregion Mouse-Handling Variables
237
238    private void ComputeMouseHandling() {
239      MouseState mouseState = mouseManager.GetState();
240      ComputeLeftMouseBtnHandling(mouseState);
241      ComputeMouseWheelHandling(mouseState);
242
243      previousMouseState = mouseState;
244    }
245    private void ComputeLeftMouseBtnHandling(MouseState mouseState) {
246      //Left btn pressed
247      if (mouseState.LeftButton.Down && (previousMouseState.LeftButton.Pressed || previousMouseState.LeftButton.Down)) {
248        currentViewAngle = new Vector2(
249          viewAngleOnBtnRelease.X + mouseState.X - mousePositionOnBtnDown.X,
250          viewAngleOnBtnRelease.Y + mouseState.Y - mousePositionOnBtnDown.Y);
251      }
252
253      //Left btn freshly pressed ==> ONLICK-EVENT
254      else if (mouseState.LeftButton.Pressed && !(previousMouseState.LeftButton.Pressed || previousMouseState.LeftButton.Down)) {
255        mousePositionOnBtnDown = new Vector2(mouseState.X, mouseState.Y);
256      }
257
258      //Left btn freshly released ==> ONRELEASE-EVENT
259      else if (mouseState.LeftButton.Released && !previousMouseState.LeftButton.Released) {
260        viewAngleOnBtnRelease = currentViewAngle;
261      }
262    }
263    private void ComputeMouseWheelHandling(MouseState mouseState) {
264      int curr = mouseState.WheelDelta;
265      if (curr < 0 && zoom > 1) {
266        zoom++;
267      } else if (curr > 0 && zoom < 300) {
268        zoom--;
269      }
270    }
271
272  }
273}
Note: See TracBrowser for help on using the repository browser.