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

Last change on this file since 13032 was 13032, checked in by gkronber, 4 years ago

#1966:

  • removed unused using
  • added/updated license headers
File size: 11.8 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 SharpDX;
24using SharpDX.Toolkit;     
25using SharpDX.Toolkit.Graphics;
26using SharpDX.Toolkit.Input;
27
28using ButtonStateDX = SharpDX.Toolkit.Input.ButtonState;
29using SharpDX.Direct3D11;
30
31namespace PackingPlanVisualizations {
32  public class PackingGame : Game {
33
34
35    #region Global Private Variables   
36    private GraphicsDeviceManager graphicsDeviceManager;
37    private PackingPlan3D control;
38    private Matrix worldMatrix;
39    private Matrix viewMatrix;
40    private Matrix projectionMatrix;
41    private float zoom = 50;
42    private int selectedItemIndex = -1;
43
44    private BasicEffect basicEffect;     
45    private Color backgroundColor { get; set; }
46
47    private CenteredContainer container;   
48    private MouseManager Mouse;
49    #endregion Global Private Variables     
50
51    protected override void Dispose(bool disposeManagedResources) {
52      control.disposedByGame = true;
53      base.Dispose(disposeManagedResources);
54      control.disposedByGame = false;
55    }
56
57
58    public PackingGame(PackingPlan3D control)
59      : base() {
60        this.control = control;
61      graphicsDeviceManager = new GraphicsDeviceManager(this);
62      graphicsDeviceManager.PreferMultiSampling = true;
63      graphicsDeviceManager.PreparingDeviceSettings += 
64        (object sender, PreparingDeviceSettingsEventArgs e) => {           
65          e.GraphicsDeviceInformation.PresentationParameters.MultiSampleCount = MSAALevel.X4;
66          return;
67        };
68      var controlColor = Color.White;//System.Drawing.SystemColors.Control;
69      backgroundColor = new Color (controlColor.R,controlColor.G, controlColor.B, controlColor.A);
70
71      Mouse = new MouseManager(this);
72    }
73
74    public void SetSize(int width, int height) {
75
76      graphicsDeviceManager.PreferredBackBufferHeight = height;
77      graphicsDeviceManager.PreferredBackBufferWidth = width;
78    }
79
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 = Mouse.GetState();
105      Console.WriteLine("Initial bounds:" + Window.ClientBounds);
106      this.Window.IsMouseVisible = true;
107      //this.Window.ClientSizeChanged += (a, b) => {
108      //  Console.WriteLine("Resized..");
109      //  this.Tick();
110      //};
111    }
112    private void initializeWorld() {
113      #region Matrix-Initialization
114      worldMatrix = Matrix.Identity;
115
116      viewMatrix = Matrix.LookAtLH(
117          new Vector3(0, 10, zoom),
118          Vector3.Zero,
119          Vector3.UnitY);
120
121      projectionMatrix = Matrix.PerspectiveFovLH(
122          (float)Math.PI / 6.0f,
123          (float)GraphicsDevice.BackBuffer.Width /
124          (float)GraphicsDevice.BackBuffer.Height,
125          1.0f, 1000.0f);
126      #endregion Matrix-Initialization
127
128      #region Effect and Color
129      //Effect initialization
130      basicEffect = new BasicEffect(GraphicsDevice);
131      basicEffect.World = worldMatrix;
132      basicEffect.View = viewMatrix;
133      basicEffect.Projection = projectionMatrix;
134
135      //Primitive color
136      basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
137      basicEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
138      basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
139      basicEffect.SpecularPower = 5.0f;
140      basicEffect.Alpha = 1.0f;
141      basicEffect.VertexColorEnabled = true;
142      #endregion Effect-World and Color
143
144      #region World lighting
145      basicEffect.LightingEnabled = true;
146
147      basicEffect.PreferPerPixelLighting = true;
148
149      if (basicEffect.LightingEnabled) {
150        basicEffect.DirectionalLight0.Enabled = true; // enable each light individually
151        if (basicEffect.DirectionalLight0.Enabled) {
152          // x direction
153          basicEffect.DirectionalLight0.DiffuseColor = new Vector3(1, 1, 1); // range is 0 to 1
154          basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-1, 0, 0));
155          // points from the light to the origin of the scene
156          basicEffect.DirectionalLight0.SpecularColor = Vector3.One;
157        }
158
159        basicEffect.DirectionalLight1.Enabled = true;
160        if (basicEffect.DirectionalLight1.Enabled) {
161          // y direction
162          basicEffect.DirectionalLight1.DiffuseColor = new Vector3(1, 1, 1);
163          basicEffect.DirectionalLight1.Direction = Vector3.Normalize(new Vector3(0, -1, 0));
164          basicEffect.DirectionalLight1.SpecularColor = Vector3.One;
165        }
166
167        basicEffect.DirectionalLight2.Enabled = true;
168        if (basicEffect.DirectionalLight2.Enabled) {
169          // z direction
170          basicEffect.DirectionalLight2.DiffuseColor = new Vector3(1, 1, 1);
171          basicEffect.DirectionalLight2.Direction = Vector3.Normalize(new Vector3(0, 0, -1));
172          basicEffect.DirectionalLight2.SpecularColor = Vector3.One;
173        }
174      }
175      #endregion World lighting
176
177      #region Transparency
178
179      //basicEffect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
180      //basicEffect.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
181      //basicEffect.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;   
182
183      BlendStateDescription blendStateDescription = new SharpDX.Direct3D11.BlendStateDescription();
184      blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
185      blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
186      blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
187      blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
188      blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
189      blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
190      blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
191      blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
192      SharpDX.Toolkit.Graphics.BlendState blendState = SharpDX.Toolkit.Graphics.BlendState.New(GraphicsDevice, blendStateDescription);
193      GraphicsDevice.SetBlendState(blendState);
194
195      #endregion
196    }
197
198
199    protected override void LoadContent() {
200
201    }
202
203    protected override void Draw(GameTime gameTime) {
204      GraphicsDevice.Clear(backgroundColor);
205
206      worldMatrix = 
207        Matrix.RotationY(MathUtil.DegreesToRadians(-currentViewAngle.X / 4)) *
208        Matrix.RotationX(MathUtil.DegreesToRadians(currentViewAngle.Y / 4));
209      basicEffect.World = worldMatrix;
210
211      viewMatrix = Matrix.LookAtLH(
212          new Vector3(0, zoom, zoom),
213          Vector3.Zero,
214          Vector3.UnitY);
215      basicEffect.View = viewMatrix;
216
217      foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) {
218        pass.Apply();
219
220        if (container != null) {
221          if (container.PackingItems.Count == 0)
222            container.Container.RenderShapeTrianglesAndLines(GraphicsDevice);
223          else {
224            container.Container.RenderShapeLines(GraphicsDevice, new Color(0, 0, 0));
225            var selectedItem = container.PackingItems.Find(x => x.ShapeID == selectedItemIndex);
226            foreach (BasicCuboidShape item in container.PackingItems) {
227              if (selectedItem == null || selectedItemIndex == item.ShapeID) {
228                item.RenderShapeLines(GraphicsDevice);
229                item.RenderShapeTriangles(GraphicsDevice);
230              } else
231                item.RenderShapeLines(GraphicsDevice, new Color(0,0,0));
232            }
233          }
234        }
235      }
236
237      base.Draw(gameTime);       
238    }
239
240
241
242
243
244
245    protected override void Update(GameTime gameTime) {
246      computeMouseHandling();                                     
247      base.Update(gameTime);
248    }
249    #region Mouse-Handling Variables
250    private MouseState previousMouseState;
251    private Vector2 mousePositionOnBtnDown;
252    private Vector2 viewAngleOnBtnRelease;
253    private Vector2 currentViewAngle = new Vector2(0, 0);
254    #endregion Mouse-Handling Variables
255    private void computeMouseHandling() {
256      MouseState mouseState = Mouse.GetState();
257
258      computeLeftMouseBtnHandling(mouseState);
259      computeMouseWheelHandling(mouseState);
260
261      previousMouseState = mouseState;
262    }
263    private void computeLeftMouseBtnHandling(MouseState mouseState) {
264      //Left btn released
265      if (mouseState.Left.Equals(ButtonStateDX.Released) && mouseState.Left.Equals(previousMouseState.Left)) {
266        //Console.WriteLine("Released");
267      }
268
269      //Left btn pressed
270      else if (mouseState.Left.Equals(ButtonStateDX.Pressed) && mouseState.Left.Equals(previousMouseState.Left)) {
271        currentViewAngle = new Vector2(
272          viewAngleOnBtnRelease.X + mouseState.X - mousePositionOnBtnDown.X,
273          viewAngleOnBtnRelease.Y + mouseState.Y - mousePositionOnBtnDown.Y);
274
275        //angle += 0.5f;
276        //Console.WriteLine("Pressed");
277        //Console.WriteLine(currentViewAngle.ToString());
278      }
279
280      //Left btn freshly pressed ==> ONLICK-EVENT
281      else if (mouseState.Left.Equals(ButtonStateDX.Pressed) && !previousMouseState.Left.Equals(ButtonStateDX.Pressed)) {
282        Console.WriteLine("OnClick");
283        PackingPlan3D native = (PackingPlan3D)Window.NativeWindow;
284        Console.WriteLine("Window: " + Window.ClientBounds.ToString());
285        Console.WriteLine("native: " + native.ClientSize.ToString());
286        Console.WriteLine("native.parent: " + native.Parent.ClientSize.ToString());
287
288        Console.WriteLine(native.ParentForm.ToString());
289        Console.WriteLine(Window.Name);
290        Console.WriteLine(this.IsActive);
291        mousePositionOnBtnDown = new Vector2(mouseState.X, mouseState.Y);
292      }
293
294      //Left btn freshly released ==> ONRELEASE-EVENT
295      else if (mouseState.Left.Equals(ButtonStateDX.Released) && !previousMouseState.Left.Equals(ButtonStateDX.Released)) {
296        Console.WriteLine("OnRelease");
297        viewAngleOnBtnRelease = currentViewAngle;
298      }
299    }
300    private void computeMouseWheelHandling(MouseState mouseState) {
301      int prev = previousMouseState.WheelDelta;
302      int curr = mouseState.WheelDelta;
303      if (curr < prev && zoom > 1) {
304        zoom++;
305        Console.WriteLine(zoom);
306      } else if (curr > prev && zoom < 300) {
307        zoom--;
308        Console.WriteLine(zoom);
309      }
310    }
311
312  }
313}
Note: See TracBrowser for help on using the repository browser.