Project

General

Profile

Download (20.7 KB) Statistics
| Branch: | Revision:

distorted-objectlib / src / main / java / org / distorted / objectlib / json / JsonWriter.java @ 7aae846c

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.objectlib.json;
21

    
22
import java.io.BufferedWriter;
23
import java.io.FileOutputStream;
24
import java.io.IOException;
25
import java.io.OutputStreamWriter;
26
import java.nio.charset.StandardCharsets;
27

    
28
import org.distorted.objectlib.helpers.ObjectFaceShape;
29
import org.distorted.objectlib.helpers.ObjectSignature;
30
import org.json.JSONArray;
31
import org.json.JSONException;
32
import org.json.JSONObject;
33

    
34
import org.distorted.library.type.Static3D;
35
import org.distorted.library.type.Static4D;
36

    
37
import org.distorted.objectlib.helpers.ObjectShape;
38
import org.distorted.objectlib.helpers.ObjectSticker;
39
import org.distorted.objectlib.scrambling.ScrambleState;
40
import org.distorted.objectlib.main.TwistyObject;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
public class JsonWriter
45
{
46
  public static final int VERSION_OBJECT_MAJOR = 4;
47
  public static final int VERSION_OBJECT_MINOR = 0;
48
  public static final int VERSION_EXTRAS_MAJOR = 1;
49
  public static final int VERSION_EXTRAS_MINOR = 0;
50

    
51
  private static JsonWriter mThis;
52
  private static int mNumCubitFaces;
53

    
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55

    
56
  private JsonWriter()
57
    {
58

    
59
    }
60

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

    
63
  private JSONArray generateCubits(TwistyObject object) throws JSONException
64
    {
65
    JSONArray array = new JSONArray();
66

    
67
    int[] numLayers     = object.getNumLayers();
68
    float[][] positions = object.getCubitPositions(numLayers);
69
    int numCubits       = positions.length;
70

    
71
    for(int c=0; c<numCubits; c++)
72
      {
73
      JSONObject cubit = new JSONObject();
74
      Static4D rotQuat = object.getCubitQuats(c,numLayers);
75
      int variant      = object.getCubitVariant(c,numLayers);
76
      int type         = object.getCubitType(c);
77
      float[] offset   = object.getCubitOffset(c);
78

    
79
      JSONArray pos = new JSONArray();
80
      int numPos = positions[c].length;
81
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
82
      cubit.put("centers", pos);
83
      cubit.put("qx", rotQuat.get0() );
84
      cubit.put("qy", rotQuat.get1() );
85
      cubit.put("qz", rotQuat.get2() );
86
      cubit.put("qw", rotQuat.get3() );
87
      cubit.put("variant", variant );
88
      cubit.put("type", type);
89
      cubit.put("offsetX", offset[0]);
90
      cubit.put("offsetY", offset[1]);
91
      cubit.put("offsetZ", offset[2]);
92

    
93
      JSONArray colors = new JSONArray();
94

    
95
      for(int f=0; f<mNumCubitFaces; f++)
96
        {
97
        int cubColor = object.getCubitFaceMap(c,f);
98
        colors.put(cubColor);
99
        }
100
      cubit.put("colors",colors);
101

    
102
      array.put(cubit);
103
      }
104

    
105
    return array;
106
    }
107

    
108
///////////////////////////////////////////////////////////////////////////////////////////////////
109

    
110
  private JSONArray generateCorners(float[][] corners) throws JSONException
111
    {
112
    JSONArray array = new JSONArray();
113

    
114
    for(float[] c : corners)
115
      {
116
      JSONObject corner = new JSONObject();
117
      corner.put("strength", c[0]);
118
      corner.put("radius"  , c[1]);
119
      array.put(corner);
120
      }
121

    
122
    return array;
123
    }
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126

    
127
  private JSONArray generateCenters(float[][] centers) throws JSONException
128
    {
129
    JSONArray array = new JSONArray();
130

    
131
    for(float[] c : centers)
132
      {
133
      JSONObject center = new JSONObject();
134
      center.put("x", c[0]);
135
      center.put("y", c[1]);
136
      center.put("z", c[2]);
137
      array.put(center);
138
      }
139

    
140
    return array;
141
    }
142

    
143
///////////////////////////////////////////////////////////////////////////////////////////////////
144

    
145
  private JSONArray generateBands(float[][] bands) throws JSONException
146
    {
147
    JSONArray array = new JSONArray();
148

    
149
    for (float[] b : bands)
150
      {
151
      JSONObject band = new JSONObject();
152
      band.put("height"          , b[0]);
153
      band.put("angle"           , b[1]);
154
      band.put("distanceToCenter", b[2]);
155
      band.put("distanceToFlat"  , b[3]);
156
      band.put("numOfBands"      , b[4]);
157
      band.put("extraI"          , b[5]);
158
      band.put("extraJ"          , b[6]);
159
      array.put(band);
160
      }
161

    
162
    return array;
163
    }
164

    
165
///////////////////////////////////////////////////////////////////////////////////////////////////
166

    
167
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int cubit, int[] numLayers) throws JSONException
168
    {
169
    JSONArray array = new JSONArray();
170
    int numFaces = vertIndices.length;
171
    int variant = object.getCubitVariant(cubit,numLayers);
172

    
173
    for(int i=0; i<numFaces; i++)
174
      {
175
      JSONObject face = new JSONObject();
176
      face.put("bandIndex", bandIndices[i]);
177

    
178
      int sticker = object.getVariantFaceColor(variant,i);
179
      face.put("sticker",sticker);
180

    
181
      JSONArray vertArr = new JSONArray();
182
      int numV = vertIndices[i].length;
183
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
184
      face.put("vertexIndices",vertArr);
185

    
186
      array.put(face);
187
      }
188

    
189
    return array;
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

    
194
  private JSONArray generateVertices(float[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
195
    {
196
    JSONArray array = new JSONArray();
197
    int numVertices = vertices.length;
198

    
199
    for(int j=0; j<numVertices; j++)
200
      {
201
      JSONObject vert = new JSONObject();
202
      vert.put("x", vertices[j][0]);
203
      vert.put("y", vertices[j][1]);
204
      vert.put("z", vertices[j][2]);
205
      vert.put("cornerIndex", cornerIndices[j]);
206
      vert.put("centerIndex", centerIndices[j]);
207
      array.put(vert);
208
      }
209

    
210
    return array;
211
    }
212

    
213
///////////////////////////////////////////////////////////////////////////////////////////////////
214

    
215
  private JSONObject generateConvexity(float[] convexity) throws JSONException
216
    {
217
    JSONObject object = new JSONObject();
218
    object.put("x", convexity[0]);
219
    object.put("y", convexity[1]);
220
    object.put("z", convexity[2]);
221
    return object;
222
    }
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225

    
226
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
227
    {
228
    for(int i=0; i<numCubits; i++)
229
      {
230
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
231
      }
232

    
233
    return -1;
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

    
238
  private JSONArray generateShapes(TwistyObject object) throws JSONException
239
    {
240
    JSONArray shapes = new JSONArray();
241

    
242
    int[] numLayers = object.getNumLayers();
243
    int numVariants = object.getNumCubitVariants(numLayers);
244
    float[][] positions = object.getCubitPositions(numLayers);
245
    int numCubits = positions.length;
246
    mNumCubitFaces = 0;
247

    
248
    for(int i=0; i<numVariants; i++)
249
      {
250
      JSONObject shapeObj = new JSONObject();
251

    
252
      ObjectShape shape = object.getObjectShape(i);
253
      ObjectFaceShape face = object.getObjectFaceShape(i);
254

    
255
      float[] convexity  = face.getConvexityCenter();
256
      float[][] vertices = shape.getVertices();
257
      int[][] vertIndices= shape.getVertIndices();
258
      float[][] bands    = face.getBands();
259
      int[] bandIndices  = face.getBandIndices();
260
      float[][] corners  = face.getCorners();
261
      int[] cornerIndices= face.getCornerIndices();
262
      float[][] centers  = face.getCenters();
263
      int[] centerIndices= face.getCenterIndices();
264

    
265
      int num = vertIndices.length;
266
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
267

    
268
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
269

    
270
      if( convexity!=null )
271
        {
272
        JSONObject convObj = generateConvexity(convexity);
273
        shapeObj.put("convexity", convObj);
274
        }
275

    
276
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
277
      shapeObj.put("vertices", verticesArr);
278
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,cubit,numLayers);
279
      shapeObj.put("faces", facesArr);
280
      JSONArray bandsArr = generateBands(bands);
281
      shapeObj.put("bands", bandsArr);
282

    
283
      if( corners!=null )
284
        {
285
        JSONArray cornerArr = generateCorners(corners);
286
        shapeObj.put("cornerPush", cornerArr);
287
        }
288

    
289
      if( centers!=null )
290
        {
291
        JSONArray centerArr = generateCenters(centers);
292
        shapeObj.put("centerPush", centerArr);
293
        }
294

    
295
      shapes.put(shapeObj);
296
      }
297

    
298
    return shapes;
299
    }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302

    
303
  private JSONArray generateStickers(TwistyObject object) throws JSONException
304
    {
305
    JSONArray stickers = new JSONArray();
306

    
307
    int numStickers = object.getNumStickerTypes();
308

    
309
    for(int i=0; i<numStickers; i++)
310
      {
311
      JSONObject stickerObj = new JSONObject();
312
      JSONArray  vertexArray= new JSONArray();
313

    
314
      ObjectSticker sticker = object.retSticker(i);
315

    
316
      float[] coords     = sticker.getCoords();
317
      float[] curvatures = sticker.getCurvature();
318
      float[] radii      = sticker.getRadii();
319
      float   stroke     = sticker.getStroke();
320

    
321
      stickerObj.put("stroke", stroke);
322
      int numVertices = radii.length;
323

    
324
      for(int j=0; j<numVertices; j++)
325
        {
326
        JSONObject vertex = new JSONObject();
327
        vertex.put("x", coords[2*j  ]);
328
        vertex.put("y", coords[2*j+1]);
329
        vertex.put("angle", curvatures==null ? 0 : curvatures[j]);
330
        vertex.put("radius",radii[j]);
331
        vertexArray.put(vertex);
332
        }
333
      stickerObj.put("vertices", vertexArray);
334
      stickers.put(stickerObj);
335
      }
336

    
337
    return stickers;
338
    }
339

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341

    
342
  private JSONObject generateMesh(TwistyObject object) throws JSONException
343
    {
344
    JSONObject mesh = new JSONObject();
345

    
346
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
347
    JSONArray cubits   = generateCubits(object);
348
    JSONArray stickers = generateStickers(object);
349

    
350
    mesh.put("shapes"  , shapes);
351
    mesh.put("cubits"  , cubits);
352
    mesh.put("stickers", stickers);
353

    
354
    return mesh;
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
360
    {
361
    JSONObject metadata = new JSONObject();
362

    
363
    metadata.put("longname"   , object.getObjectName() );
364
    metadata.put("inventor"   , object.getInventor());
365
    metadata.put("year"       , object.getYearOfInvention());
366
    metadata.put("complexity" , object.getComplexity());
367
    metadata.put("size"       , object.getSize() );
368
    metadata.put("scrambles"  , numScramble );
369
    metadata.put("shortname"  , object.getShortName() );
370
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
371
    metadata.put("num_faces"  , object.getNumFaces() );
372

    
373
    ObjectSignature signature = object.getSignature();
374

    
375
    metadata.put("signature1" , signature.getLong1() );
376
    metadata.put("signature2" , signature.getLong2() );
377
    metadata.put("signature3" , signature.getLong3() );
378

    
379
    return metadata;
380
    }
381

    
382
///////////////////////////////////////////////////////////////////////////////////////////////////
383

    
384
  private JSONArray generateQuats(TwistyObject object) throws JSONException
385
    {
386
    JSONArray quatsArray = new JSONArray();
387
    Static4D[] quats = object.getQuats();
388

    
389
    for(Static4D quat : quats)
390
      {
391
      JSONObject q = new JSONObject();
392
      q.put("x",quat.get0());
393
      q.put("y",quat.get1());
394
      q.put("z",quat.get2());
395
      q.put("w",quat.get3());
396
      quatsArray.put(q);
397
      }
398

    
399
    return quatsArray;
400
    }
401

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403

    
404
  private JSONArray generateAxis(TwistyObject object) throws JSONException
405
    {
406
    JSONArray axis = new JSONArray();
407

    
408
    Static3D[] rotAxis = object.getRotationAxis();
409
    int numAxis = rotAxis.length;
410
    int[][] basicAngle = object.getBasicAngles();
411
    int[] numLayers = object.getNumLayers();
412
    float[][] cuts = object.getCuts(numLayers);
413
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
414

    
415
    for( int i=0; i<numAxis; i++ )
416
      {
417
      JSONObject axObject = new JSONObject();
418
      Static3D ax = rotAxis[i];
419

    
420
      axObject.put("x", ax.get0() );
421
      axObject.put("y", ax.get1() );
422
      axObject.put("z", ax.get2() );
423

    
424
      JSONArray angleArray = new JSONArray();
425
      for(float angle : basicAngle[i]) angleArray.put(angle);
426
      axObject.put("basicAngles", angleArray);
427
      JSONArray cutsArray = new JSONArray();
428
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
429
      axObject.put("cuts", cutsArray);
430
      JSONArray rotaArray = new JSONArray();
431
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
432
      axObject.put("rotatable", rotaArray );
433

    
434
      axis.put(axObject);
435
      }
436

    
437
    return axis;
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
443
    {
444
    JSONObject scrambling = new JSONObject();
445

    
446
    ScrambleState[] states = object.getScrambleStates();
447
    int scrambleType = object.getScrambleType();
448
    scrambling.put("scrambleType",scrambleType );
449

    
450
    if( states!=null )
451
      {
452
      JSONArray scrambleStates = new JSONArray();
453

    
454
      for(ScrambleState state : states)
455
        {
456
        JSONArray axisArray = new JSONArray();
457
        int numAxis = state.getNumAxis();
458

    
459
        for(int ax=0; ax<numAxis; ax++)
460
          {
461
          JSONArray axArray = new JSONArray();
462
          int[] axData = state.getAx(ax);
463

    
464
          if( axData!=null )
465
            for(int data : axData) axArray.put(data);
466

    
467
          axisArray.put(axArray);
468
          }
469

    
470
        scrambleStates.put(axisArray);
471
        }
472

    
473
      scrambling.put("scrambleStates", scrambleStates);
474
      }
475

    
476
    return scrambling;
477
    }
478

    
479
///////////////////////////////////////////////////////////////////////////////////////////////////
480

    
481
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
482
    {
483
    JSONObject touchControl = new JSONObject();
484

    
485
    touchControl.put("movementType" , object.getTouchControlType() );
486
    touchControl.put("movementSplit", object.getTouchControlSplit() );
487

    
488
    int[][][] enabled = object.getEnabled();
489

    
490
    if( enabled!=null )
491
      {
492
      JSONArray enabledArray = new JSONArray();
493

    
494
      for(int[][] faceEnabled : enabled)
495
        {
496
        JSONArray faceArray = new JSONArray();
497

    
498
        for(int[] sectionEnabled : faceEnabled)
499
          {
500
          JSONArray sectionArray = new JSONArray();
501
          for(int ax : sectionEnabled) sectionArray.put(ax);
502
          faceArray.put(sectionArray);
503
          }
504
        enabledArray.put(faceArray);
505
        }
506

    
507
      touchControl.put("enabledAxis", enabledArray);
508
      }
509

    
510
    int[] numLayers = object.getNumLayers();
511
    float[] dist3D = object.getDist3D(numLayers);
512

    
513
    if( dist3D!=null )
514
      {
515
      JSONArray distArray = new JSONArray();
516
      for( float dist: dist3D ) distArray.put(dist);
517
      touchControl.put("dist3D", distArray);
518
      }
519

    
520
    return touchControl;
521
    }
522

    
523
///////////////////////////////////////////////////////////////////////////////////////////////////
524

    
525
  private JSONArray generateColors(TwistyObject object)
526
    {
527
    JSONArray jsonColors = new JSONArray();
528
    int numFaceColors = object.getNumFaceColors();
529
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
530

    
531
    jsonColors.put(object.getInternalColor());
532

    
533
    return jsonColors;
534
    }
535

    
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537

    
538
  private JSONObject generateSolved(TwistyObject object) throws JSONException
539
    {
540
    JSONObject solved = new JSONObject();
541
    int[][] solvedGroups = object.getSolvedQuats();
542

    
543
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
544

    
545
    if( solvedGroups!=null )
546
      {
547
      JSONArray groupArray = new JSONArray();
548

    
549
      for( int[] group : solvedGroups )
550
        {
551
        JSONArray groupElements = new JSONArray();
552
        for( int element : group ) groupElements.put(element);
553
        groupArray.put(groupElements);
554
        }
555

    
556
      solved.put("groups", groupArray );
557
      }
558

    
559
    return solved;
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563

    
564
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
565
    {
566
    JSONObject json = new JSONObject();
567

    
568
    JSONObject metadata    = generateMetadata(object,numScramble);
569
    JSONObject mesh        = generateMesh(object);
570
    JSONArray  axis        = generateAxis(object);
571
    JSONArray  quats       = generateQuats(object);
572
    JSONObject scrambling  = generateScrambling(object);
573
    JSONObject touchControl= generateTouchControl(object);
574
    JSONArray  colors      = generateColors(object);
575
    JSONObject solved      = generateSolved(object);
576

    
577
    json.put("major"       , VERSION_OBJECT_MAJOR);
578
    json.put("minor"       , VERSION_OBJECT_MINOR);
579
    json.put("metadata"    , metadata);
580
    json.put("mesh"        , mesh);
581
    json.put("axis"        , axis);
582
    json.put("quats"       , quats);
583
    json.put("scrambling"  , scrambling);
584
    json.put("touchcontrol", touchControl);
585
    json.put("colors"      , colors);
586
    json.put("solved"      , solved);
587

    
588
    return json.toString();
589
    }
590

    
591
///////////////////////////////////////////////////////////////////////////////////////////////////
592

    
593
  public String createExtrasString(TwistyObject object) throws JSONException
594
    {
595
    String[][] tuts = object.getTutorials();
596

    
597
    if( tuts!=null )
598
      {
599
      JSONObject json = new JSONObject();
600
      JSONArray  tutorials = new JSONArray();
601

    
602
      for(String[] tut : tuts)
603
        {
604
        String language = tut[0];
605
        String link     = tut[1];
606
        String title    = tut[2];
607
        String author   = tut[3];
608

    
609
        JSONObject oneTut = new JSONObject();
610

    
611
        oneTut.put("language", language);
612
        oneTut.put("link"    , link    );
613
        oneTut.put("title"   , title   );
614
        oneTut.put("author"  , author  );
615

    
616
        tutorials.put(oneTut);
617
        }
618

    
619
      json.put("major"     , VERSION_EXTRAS_MAJOR);
620
      json.put("minor"     , VERSION_EXTRAS_MINOR);
621
      json.put("object"    , object.getShortName() );
622
      json.put("tutorials" , tutorials);
623

    
624
      return json.toString();
625
      }
626

    
627
    return null;
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

    
632
  public void write(String filename, String contents) throws IOException
633
    {
634
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
635
    BufferedWriter bw = new BufferedWriter(osw);
636
    bw.write(contents);
637
    bw.flush();
638
    }
639

    
640
///////////////////////////////////////////////////////////////////////////////////////////////////
641

    
642
  public static JsonWriter getInstance()
643
    {
644
    if( mThis==null ) mThis = new JsonWriter();
645
    return mThis;
646
    }
647
}
(2-2/2)