Example #1
0
 public static extern void Report(
         ReportType type,
         string reportContext,
         string fileName,
         int lineNo,
         DDS.ErrorCode reportCode,
         string description);
Example #2
0
 public static bool RequestedDeadlineMissedValid(DDS.IDataReader reader, int totalCount
     , int totalCountChange)
 {
     bool result = false;
     DDS.RequestedDeadlineMissedStatus holder = new DDS.RequestedDeadlineMissedStatus();
     DDS.ReturnCode rc = reader.GetRequestedDeadlineMissedStatus(ref holder);
     if (rc == DDS.ReturnCode.Ok)
     {
         DDS.RequestedDeadlineMissedStatus status = holder;
         if (status.TotalCount == totalCount)
         {
             if (status.TotalCountChange == totalCountChange)
             {
                 result = true;
             }
             else
             {
                 System.Console.Error.WriteLine("requested_deadline_missed.TotalCountChange != '"
                      + totalCountChange + "', but '" + status.TotalCountChange + "'.");
             }
         }
         else
         {
             System.Console.Error.WriteLine("requested_deadline_missed.TotalCount != '" + totalCount
                  + "', but '" + status.TotalCount + "'.");
         }
     }
     else
     {
         System.Console.Error.WriteLine("get_requested_deadline_missed_status returned " +
              rc);
     }
     return result;
 }
    private static DDS.TypeCode create_type_code(DDS.TypeCodeFactory tcf)
    {
        DDS.UnionMemberSeq members = new DDS.UnionMemberSeq();

        /* First, we create the typeCode for a union */
        /* Default-member index refers to which member of the union
         * will be the default one. In this example index = 1 refers
         * to the the member 'aLong'. Take into account that index
         * starts in 0 */
        try {
            DDS.TypeCode unionTC = tcf.create_union_tc("Foo",
                DDS.ExtensibilityKind.MUTABLE_EXTENSIBILITY,
                DDS.TypeCode.TC_LONG,
                1, /* default-member index */
                members); /* For now, it does not have any member */

            /* Case 1 will be a short named aShort */
            unionTC.add_member("aShort", DDS.DynamicData.MEMBER_ID_UNSPECIFIED,
                    DDS.TypeCode.TC_SHORT, DDS.TypeCode.NONKEY_MEMBER);

            /* Case 2, the default, will be a long named aLong */
            unionTC.add_member("aLong", 2, DDS.TypeCode.TC_LONG,
                    DDS.TypeCode.NONKEY_MEMBER);

            /* Case 3 will be a double named aDouble */
            unionTC.add_member("aDouble", 3, DDS.TypeCode.TC_DOUBLE,
                    DDS.TypeCode.NONKEY_MEMBER);

            return unionTC;
        } catch (Exception e) {
            Console.WriteLine("register_type error {0}", e);
            return null;
        }
    }
    static void shutdown(
        DDS.DomainParticipant participant)
    {
        /* Delete all entities */

        if (participant != null) {
            participant.delete_contained_entities();
            DDS.DomainParticipantFactory.get_instance().delete_participant(
                ref participant);
        }

        /* RTI Connext provides finalize_instance() method on
           domain participant factory for users who want to release memory
           used by the participant factory. Uncomment the following block of
           code for clean destruction of the singleton. */
        /*
        try {
            DDS.DomainParticipantFactory.finalize_instance();
        }
        catch(DDS.Exception e) {
            Console.WriteLine("finalize_instance error {0}", e);
            throw e;
        }
        */
    }
    static bool checkParticipant(DDS.DomainParticipant participant)
    {
        DDS.DomainParticipantQos participantQos = new DDS.DomainParticipantQos();
        participant.get_qos(participantQos);

        DDS.PropertySeq properties = participantQos.property_qos.value;

        for (int i = 0; i < properties.length; i++)
        {
            if (String.Compare(properties.get_at(i).name,
                "dds.transport.UDPv4.builtin.send_socket_buffer_size") == 0)
            {
                if (String.Compare(properties.get_at(i).value, NEW_SOCKET_BUFFER_SIZE_STRING)
                     != 0)
                {
                    Console.WriteLine("Error, send_socket_buffer_size...not modified");
                    return false;
                }
            }
            if (String.Compare(properties.get_at(i).name,
                "dds.transport.UDPv4.builtin.recv_socket_buffer_size") == 0)
            {
                string value = properties.get_at(i).value;
                if (String.Compare(properties.get_at(i).value, NEW_SOCKET_BUFFER_SIZE_STRING)
                     != 0)
                {
                    Console.WriteLine("Error, recv_socket_buffer_size...not modified");
                    return false;
                }
            }
        }
        return true;
    }
Example #6
0
 public static bool StatussesValid(DDS.IDataReader reader, int rdmTotalCount, int rdmTotalCountChange
     , int riqsTotalCount, int riqsTotalCountChange, int srTotalCount, int srTotalCountChange
     , int lcActiveCount, int lcActiveCountChange, int lcInactiveCount, int lcInactiveCountChange
     , int smTotalCount, int smTotalCountChange, int slTotalCount, int slTotalCountChange
     )
 {
     bool result = false;
     if (RequestedDeadlineMissedValid(reader, rdmTotalCount, rdmTotalCountChange))
     {
         if (RequestedIncompatibleQosValid(reader, riqsTotalCount, riqsTotalCountChange))
         {
             if (SampleRejectedValid(reader, srTotalCount, srTotalCountChange))
             {
                 if (LivelinessChangedValid(reader, lcActiveCount, lcActiveCountChange, lcInactiveCount
                     , lcInactiveCountChange))
                 {
                     if (SubscriptionMatchValid(reader, smTotalCount, smTotalCountChange))
                     {
                         if (SampleLostValid(reader, slTotalCount, slTotalCountChange))
                         {
                             result = true;
                         }
                     }
                 }
             }
         }
     }
     return result;
 }
 public virtual void OnLivelinessChanged(DDS.IDataReader reader, DDS.LivelinessChangedStatus
      status)
 {
     
     onLivelinessChangedCalled = true;
     lcStatus = status;
 }
    public override void on_data_available( DDS.DataReader reader )
    {
        DDS.PublicationBuiltinTopicDataDataReader builtin_reader =
                (DDS.PublicationBuiltinTopicDataDataReader)reader;

        try {
            builtin_reader.take(
                data_seq,
                info_seq,
                DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                DDS.SampleStateKind.ANY_SAMPLE_STATE,
                DDS.ViewStateKind.ANY_VIEW_STATE,
                DDS.InstanceStateKind.ANY_INSTANCE_STATE);
        } catch (DDS.Retcode_NoData) {
            return;
        } catch (DDS.Exception e) {
            Console.WriteLine("take error {0}", e);
            return;
        }

        System.Int32 data_length = data_seq.length;
        for (int i = 0; i < data_length; ++i) {

            if (!info_seq.get_at(i).valid_data) {
                continue;
            }
            Console.WriteLine("-----");
            Console.WriteLine("Found topic \"{0}\"",
                data_seq.get_at(i).topic_name);
            Console.WriteLine("participant: {0:x8}{1:x8}{2:x8}",
                data_seq.get_at(i).participant_key.value1,
                data_seq.get_at(i).participant_key.value2,
                data_seq.get_at(i).participant_key.value3);
            Console.WriteLine("datawriter: {0:x8}{1:x8}{2:x8}",
                data_seq.get_at(i).key.value1,
                data_seq.get_at(i).key.value2,
                data_seq.get_at(i).key.value3);
            Console.WriteLine("type:");

            if (data_seq.get_at(i).type_code == null) {
                Console.WriteLine("No type code received, perhaps increase " +
                    "type_code_max_serialized_length?");
                continue;
            }
            /* Using the type_code propagated we print the data type
             * with print_IDL(). */
            try {
                data_seq.get_at(i).type_code.print_IDL(2);
            } catch (DDS.Exception) {
                Console.WriteLine("error printing IDL");
            }
        }

        try {
            builtin_reader.return_loan(data_seq, info_seq);
        } catch (DDS.Exception e) {
            Console.WriteLine("return loan error {0}", e);
        }
    }
Example #9
0
 public static void Report(
         ReportType type,
         string reportContext,
         string fileName,
         DDS.ErrorCode reportCode,
         string description)
 {
     StackFrame callStack = new StackFrame(1, true);
     Report( type,
             reportContext,
             fileName,
             callStack.GetFileLineNumber(),
             reportCode,
             description);
 }
    /* Start changes for Ordered_Presentation*/
    /* No listener is needed; we poll readers in this function */
    private static void poll_data(DDS.DataReader[] reader, int numreaders)
    {
        DDS.SampleInfoSeq info_seq = new DDS.SampleInfoSeq();
        orderedSeq data_seq = new orderedSeq();

        for (int r = 0; r < numreaders; ++r) {
            try {
                ((orderedDataReader)(reader[r])).take(
                    data_seq,
                    info_seq,
                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            } catch (DDS.Retcode_NoData) {
                // Not an error
                return;
            } catch (DDS.Exception e) {
                // Is an error
                Console.WriteLine("take error {0}", e);
                return;
            }

            System.Int32 data_length = data_seq.length;
            for (int i = 0; i < data_length; ++i) {
                if (!info_seq.get_at(i).valid_data) {
                    continue;
                }
                // Make things a bit easier to read.
                int ident = r;
                while (ident-- != 0) {
                    Console.Write("\t");
                }
                Console.WriteLine("Reader {0}: Instance{1}->value = {2}", r,
                    data_seq.get_at(i).id, data_seq.get_at(i).value);
            }

            try {
                ((orderedDataReader)(reader[r])).return_loan(data_seq,
                        info_seq);
            } catch (DDS.Exception e) {
                Console.WriteLine("return loan error {0}", e);
            }

            info_seq.ensure_length(0, 0);
            data_seq.ensure_length(0, 0);
        }
    }
Example #11
0
 public static bool StatussesValid(DDS.IDataWriter writer, int odmTotalCount, int odmTotalCountChange
     , int oiqsTotalCount, int oiqsTotalCountChange, int llTotalCount, int llTotalCountChange
     , int pmTotalCount, int pmTotalCountChange)
 {
     bool result = false;
     if (OfferedDeadlineMissedValid(writer, odmTotalCount, odmTotalCountChange))
     {
         if (OfferedIncompatibleQosValid(writer, oiqsTotalCount, oiqsTotalCountChange))
         {
             if (LivelinessLostValid(writer, llTotalCount, llTotalCountChange))
             {
                 if (PublicationMatchValid(writer, pmTotalCount, pmTotalCountChange))
                 {
                     result = true;
                 }
             }
         }
     }
     return result;
 }
Example #12
0
 internal static DDS.ReturnCode CopyIn(
         DDS.OfferedIncompatibleQosStatus from, 
         IntPtr to, 
         int offset)
 {
     DDS.ReturnCode result = DDS.ReturnCode.Ok;
     if (from != null) {
         Write(to, offset_total_count, from.TotalCount);
         Write(to, offset_total_count_change, from.TotalCountChange);
         Write(to, offset_last_policy_id, (int) from.LastPolicyId);
         result = QosPolicyCountSequenceMarshaler.CopyIn(from.Policies, to, offset_policies);
     } else {
         result = DDS.ReturnCode.BadParameter;
         DDS.OpenSplice.OS.Report(
                 DDS.OpenSplice.ReportType.OS_ERROR,
                 "DDS.OpenSplice.CustomMarshalers.OfferedIncompatibleQosStatusMarshaler.CopyIn",
                 "DDS/OpenSplice/CustomMarshalers/StatusMarshalers.cs",
                 DDS.ErrorCode.InvalidValue,
                 "OfferedIncompatibleQosStatus attribute may not be a null pointer.");
     }
     return result; 
 }
Example #13
0
        public static int LoadTexture(string path, string name = null)
        {
            // Don't bother loading this texture again if we've already loaded it
            name = (string.IsNullOrEmpty(name)) ?
                   Path.GetFileNameWithoutExtension(path) : name;

            if (Textures.ContainsKey(name))
            {
                return(Textures[name]);
            }

            // Figure out what type of texture to use
            Texture tex;

            switch (Types.CurrentDataType)
            {
            case Types.DataTypes.Forces:
            case Types.DataTypes.LW:
            case Types.DataTypes.Gens:
            case Types.DataTypes.SU:
            case Types.DataTypes.S06:
                tex = new DDS();
                break;

            // TODO: Add Storybook Support
            case Types.DataTypes.Storybook:
                throw new NotImplementedException(
                          "Could not load, Storybook textures are not yet supported!");

            // TODO: Add Colors Support
            case Types.DataTypes.Colors:
                throw new NotImplementedException(
                          "Could not load, Colors textures are not yet supported!");

            // TODO: Add Heroes/Shadow Support
            case Types.DataTypes.Shadow:
            case Types.DataTypes.Heroes:
                throw new NotImplementedException(
                          "Could not load, Heroes/Shadow textures are not yet supported!");

            // TODO: Add SA2 Support
            case Types.DataTypes.SA2:
                throw new NotImplementedException(
                          "Could not load, SA2 textures are not yet supported!");

            default:
                throw new Exception(
                          "Could not load, game type has not been set!");
            }

            // Load Texture
            try
            {
                int texID = -1;
                tex.Load(path);
                Program.MainUIInvoke(() =>
                {
                    texID = AddTexture(name, tex);
                });

                return(texID);
            }
            catch (Exception ex)
            {
                LuaTerminal.LogError($"ERROR: {ex.Message}");
                return(-1);
            }
        }
Example #14
0
        public void Export(Stream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);

            byte[] buffer = null;
            switch (m_TextureFormat)
            {
            case TextureFormat.DXT1:
            case TextureFormat.DXT5:
                byte[] dds_header = DDS.CreateHeader(m_Width, m_Height, 32, m_MipMap ? 2 : 0,
                                                     m_TextureFormat == TextureFormat.DXT1
                                        ? (byte)'D' | ((byte)'X' << 8) | ((byte)'T' << 16) | ((byte)'1' << 24)
                                        : (byte)'D' | ((byte)'X' << 8) | ((byte)'T' << 16) | ((byte)'5' << 24));
                writer.Write(dds_header);
                buffer = image_data;
                break;

            case TextureFormat.RGB24:
                byte[] tga_header = new byte[0x12]
                {
                    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    (byte)m_Width, (byte)(m_Width >> 8), (byte)m_Height, (byte)(m_Height >> 8), 24, 0
                };
                writer.Write(tga_header);
                buffer = new byte[image_data.Length];
                for (int i = 0, j = 2; j < m_CompleteImageSize; i += 3, j += 3)
                {
                    byte b = image_data[j];
                    buffer[j]     = image_data[i];
                    buffer[i]     = b;
                    buffer[i + 1] = image_data[i + 1];
                }
                break;

            case TextureFormat.ARGB32:
                tga_header = new byte[0x12]
                {
                    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    (byte)m_Width, (byte)(m_Width >> 8), (byte)m_Height, (byte)(m_Height >> 8), 32, 0
                };
                writer.Write(tga_header);
                buffer = new byte[image_data.Length];
                for (int i = 0, j = 3, k = 1, l = 2; j < m_CompleteImageSize; i += 4, j += 4, k += 4, l += 4)
                {
                    byte b = image_data[j];
                    buffer[j] = image_data[i];
                    buffer[i] = b;
                    b         = image_data[l];
                    buffer[l] = image_data[k];
                    buffer[k] = b;
                }
                break;

            case TextureFormat.Alpha8:
                tga_header = new byte[0x12]
                {
                    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    (byte)m_Width, (byte)(m_Width >> 8), (byte)m_Height, (byte)(m_Height >> 8), 8, 0
                };
                writer.Write(tga_header);
                buffer = (byte[])image_data.Clone();
                break;

            default:
                throw new Exception("Unhandled Texture2D format: " + m_TextureFormat);
            }
            writer.Write(buffer);
        }
Example #15
0
        public DvdWritableInfoViewModel(MediaType mediaType, byte[] dds, byte[] cartridgeStatus, byte[] spareArea,
                                        byte[] lastBorderOutRmd, byte[] preRecordedInfo, byte[] mediaIdentifier,
                                        byte[] physicalInformation, byte[] mediumStatus, byte[] hdLastRmd,
                                        byte[] layerCapacity, byte[] middleZoneStart, byte[] jumpIntervalSize,
                                        byte[] manualLayerJumpStartLba, byte[] remapAnchorPoint, byte[] adip,
                                        byte[] dcb, Window view)
        {
            _view = view;
            SaveDvdRamDdsCommand             = ReactiveCommand.Create(ExecuteSaveDvdRamDdsCommand);
            SaveDvdRamCartridgeStatusCommand = ReactiveCommand.Create(ExecuteSaveDvdRamCartridgeStatusCommand);

            SaveDvdRamSpareAreaInformationCommand =
                ReactiveCommand.Create(ExecuteSaveDvdRamSpareAreaInformationCommand);

            SaveLastBorderOutRmdCommand        = ReactiveCommand.Create(ExecuteSaveLastBorderOutRmdCommand);
            SaveDvdPreRecordedInfoCommand      = ReactiveCommand.Create(ExecuteSaveDvdPreRecordedInfoCommand);
            SaveDvdrMediaIdentifierCommand     = ReactiveCommand.Create(ExecuteSaveDvdrMediaIdentifierCommand);
            SaveDvdrPhysicalInformationCommand = ReactiveCommand.Create(ExecuteSaveDvdrPhysicalInformationCommand);
            SaveHddvdrMediumStatusCommand      = ReactiveCommand.Create(ExecuteSaveHddvdrMediumStatusCommand);
            SaveHddvdrLastRmdCommand           = ReactiveCommand.Create(ExecuteSaveHddvdrLastRmdCommand);
            SaveDvdrLayerCapacityCommand       = ReactiveCommand.Create(ExecuteSaveDvdrLayerCapacityCommand);
            SaveDvdrDlMiddleZoneStartCommand   = ReactiveCommand.Create(ExecuteSaveDvdrDlMiddleZoneStartCommand);
            SaveDvdrDlJumpIntervalSizeCommand  = ReactiveCommand.Create(ExecuteSaveDvdrDlJumpIntervalSizeCommand);

            SaveDvdrDlManualLayerJumpStartLbaCommand =
                ReactiveCommand.Create(ExecuteSaveDvdrDlManualLayerJumpStartLbaCommand);

            SaveDvdrDlRemapAnchorPointCommand = ReactiveCommand.Create(ExecuteSaveDvdrDlRemapAnchorPointCommand);
            SaveDvdPlusAdipCommand            = ReactiveCommand.Create(ExecuteSaveDvdPlusAdipCommand);
            SaveDvdPlusDcbCommand             = ReactiveCommand.Create(ExecuteSaveDvdPlusDcbCommand);

            _dvdRamDds                     = dds;
            _dvdRamCartridgeStatus         = cartridgeStatus;
            _dvdRamSpareArea               = spareArea;
            _dvdLastBorderOutRmd           = lastBorderOutRmd;
            _dvdPreRecordedInfo            = preRecordedInfo;
            _dvdrMediaIdentifier           = mediaIdentifier;
            _dvdrPhysicalInformation       = physicalInformation;
            _hddvdrMediumStatus            = mediumStatus;
            _hddvdrLastRmd                 = hdLastRmd;
            _dvdrLayerCapacity             = layerCapacity;
            _dvdrDlMiddleZoneStart         = middleZoneStart;
            _dvdrDlJumpIntervalSize        = jumpIntervalSize;
            _dvdrDlManualLayerJumpStartLba = manualLayerJumpStartLba;
            _dvdrDlRemapAnchorPoint        = remapAnchorPoint;
            _dvdPlusAdip                   = adip;
            _dvdPlusDcb                    = dcb;

            /* TODO: Pass back
             * switch(mediaType)
             * {
             *  case MediaType.DVDR:
             *      Text = "DVD-R";
             *
             *      break;
             *  case MediaType.DVDRW:
             *      Text = "DVD-RW";
             *
             *      break;
             *  case MediaType.DVDPR:
             *      Text = "DVD+R";
             *
             *      break;
             *  case MediaType.DVDPRW:
             *      Text = "DVD+RW";
             *
             *      break;
             *  case MediaType.DVDPRWDL:
             *      Text = "DVD+RW DL";
             *
             *      break;
             *  case MediaType.DVDRDL:
             *      Text = "DVD-R DL";
             *
             *      break;
             *  case MediaType.DVDPRDL:
             *      Text = "DVD+R DL";
             *
             *      break;
             *  case MediaType.DVDRAM:
             *      Text = "DVD-RAM";
             *
             *      break;
             *  case MediaType.DVDRWDL:
             *      Text = "DVD-RW DL";
             *
             *      break;
             *  case MediaType.HDDVDRAM:
             *      Text = "HD DVD-RAM";
             *
             *      break;
             *  case MediaType.HDDVDR:
             *      Text = "HD DVD-R";
             *
             *      break;
             *  case MediaType.HDDVDRW:
             *      Text = "HD DVD-RW";
             *
             *      break;
             *  case MediaType.HDDVDRDL:
             *      Text = "HD DVD-R DL";
             *
             *      break;
             *  case MediaType.HDDVDRWDL:
             *      Text = "HD DVD-RW DL";
             *
             *      break;
             * }
             */

            if (dds != null)
            {
                DvdRamDdsText = DDS.Prettify(dds);
            }

            if (cartridgeStatus != null)
            {
                DvdRamCartridgeStatusText = Cartridge.Prettify(cartridgeStatus);
            }

            if (spareArea != null)
            {
                DvdRamSpareAreaInformationText = Spare.Prettify(spareArea);
            }

            SaveDvdRamDdsVisible                     = dds != null;
            SaveDvdRamCartridgeStatusVisible         = cartridgeStatus != null;
            SaveDvdRamSpareAreaInformationVisible    = spareArea != null;
            SaveLastBorderOutRmdVisible              = lastBorderOutRmd != null;
            SaveDvdPreRecordedInfoVisible            = preRecordedInfo != null;
            SaveDvdrMediaIdentifierVisible           = mediaIdentifier != null;
            SaveDvdrPhysicalInformationVisible       = physicalInformation != null;
            SaveHddvdrMediumStatusVisible            = mediumStatus != null;
            SaveHddvdrLastRmdVisible                 = hdLastRmd != null;
            SaveDvdrLayerCapacityVisible             = layerCapacity != null;
            SaveDvdrDlMiddleZoneStartVisible         = middleZoneStart != null;
            SaveDvdrDlJumpIntervalSizeVisible        = jumpIntervalSize != null;
            SaveDvdrDlManualLayerJumpStartLbaVisible = manualLayerJumpStartLba != null;
            SaveDvdrDlRemapAnchorPointVisible        = remapAnchorPoint != null;
            SaveDvdPlusAdipVisible                   = adip != null;
            SaveDvdPlusDcbVisible                    = dcb != null;
        }
 public override void on_requested_incompatible_qos(
     DDS.DataReader reader,
     DDS.RequestedIncompatibleQosStatus status)
 {
 }
        public override void on_data_available(DDS.DataReader reader)
        {
            keysDataReader keys_reader =
                (keysDataReader)reader;

            try {
                keys_reader.take(
                    data_seq,
                    info_seq,
                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            }
            catch(DDS.Retcode_NoData) {
                return;
            }
            catch(DDS.Exception e) {
                Console.WriteLine("take error {0}", e);
                return;
            }

            System.Int32 data_length = data_seq.length;
            for (int i = 0; i < data_length; ++i)
            {
                /* Start changes for Keyed_Data */
                /* We first check if the sample includes valid data */
                if (info_seq.get_at(i).valid_data)
                {
                    if (info_seq.get_at(i).view_state ==
                        DDS.ViewStateKind.NEW_VIEW_STATE)
                    {
                        Console.WriteLine("Found new instance; code = {0}",
                            data_seq.get_at(i).code);
                    }

                    Console.WriteLine("Instance {0}: x: {1}, y: {2}",
                        data_seq.get_at(i).code, data_seq.get_at(i).x,
                        data_seq.get_at(i).y);
                }
                else
                {
                    /* Since there is not valid data, it may include metadata */
                    keys dummy = new keys();
                    try
                    {
                        DDS.InstanceHandle_t temp =
                            info_seq.get_at(i).instance_handle;
                        keys_reader.get_key_value(dummy, ref temp);
                    }
                    catch (DDS.Exception e)
                    {
                        Console.WriteLine("get_key_value error {0}", e);
                    }

                    /* Here we print a message if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
                    if (info_seq.get_at(i).instance_state ==
                        DDS.InstanceStateKind.NOT_ALIVE_NO_WRITERS_INSTANCE_STATE)
                    {
                        Console.WriteLine("Instance {0} has no writers",
                            dummy.code);
                    }
                    else if (info_seq.get_at(i).instance_state ==
                        DDS.InstanceStateKind.NOT_ALIVE_DISPOSED_INSTANCE_STATE)
                    {
                        Console.WriteLine("Instance {0} disposed",
                            dummy.code);
                    }
                }
                /* End changes for Keyed_Data */
            }

            try {
                keys_reader.return_loan(data_seq, info_seq);
            }
            catch(DDS.Exception e) {
                Console.WriteLine("return loan error {0}", e);
            }
        }
        /**** Start changes for Advanced_Keys ****/
        public override void on_data_available(DDS.DataReader reader)
        {
            keysDataReader keys_reader =
                (keysDataReader)reader;

            //// Start changes for Advanced_Keys

            while (true)
            {
                /* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
                a sequence containing samples from only the next (in a well-determined
                but unspecified order) un-taken instance.
                */

                try
                {
                    keys_reader.take_next_instance(
                        data_seq,
                        info_seq,
                        DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                        ref DDS.InstanceHandle_t.HANDLE_NIL,
                        DDS.SampleStateKind.ANY_SAMPLE_STATE,
                        DDS.ViewStateKind.ANY_VIEW_STATE,
                        DDS.InstanceStateKind.ANY_INSTANCE_STATE);
                }
                catch (DDS.Retcode_NoData)
                {
                    break;
                }
                catch (DDS.Exception e)
                {
                    Console.WriteLine("take error {0}", e);
                    return;
                }

                System.Int32 data_length = data_seq.length;
                /* We process all the obtained samples for a particular instance */
                for (int i = 0; i < data_length; ++i)
                {
                    /* We first check if the sample includes valid data */
                    if (info_seq.get_at(i).valid_data)
                    {
                        if (info_seq.get_at(i).view_state == DDS.ViewStateKind.NEW_VIEW_STATE)
                        {
                            new_instance_found(keys_reader, info_seq.get_at(i), data_seq.get_at(i));
                        }

                        /* We check if the obtained samples are associated to one
                        of the instances of interest.
                        Since take_next_instance gives sequences of the same instance,
                        we only need to test this for the first sample obtained.
                        */
                        if (i == 0 && !key_is_relevant(data_seq.get_at(i)))
                        {
                            break;
                        }

                        handle_data(keys_reader, info_seq.get_at(i), data_seq.get_at(i));
                    }
                    else
                    {
                        /* Since there is not valid data, it may include metadata */
                        keys dummy = null; ;

                        dummy = keysTypeSupport.create_data();
                        if (dummy == null)
                        {
                            throw new ApplicationException(
                            "keysTypeSupport.create_data error");
                        }

                        DDS.InstanceHandle_t handle = info_seq.get_at(i).instance_handle;

                        try
                        {
                            keys_reader.get_key_value(dummy, ref handle);
                        }
                        catch (DDS.Exception e)
                        {
                            Console.WriteLine(" get_key_value error {0}", e);
                        }

                        /* Here we print a message and change the instance state
                        if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
                        if (info_seq.get_at(i).instance_state == DDS.InstanceStateKind.NOT_ALIVE_NO_WRITERS_INSTANCE_STATE)
                        {
                            instance_lost_writers(keys_reader, info_seq.get_at(i), dummy);
                        }
                        else if (info_seq.get_at(i).instance_state == DDS.InstanceStateKind.NOT_ALIVE_DISPOSED_INSTANCE_STATE)
                        {
                            instance_disposed(keys_reader, info_seq.get_at(i), dummy);
                        }
                    }
                }

                try
                {
                    keys_reader.return_loan(data_seq, info_seq);
                }
                catch (DDS.Exception e)
                {
                    Console.WriteLine("return loan error {0}", e);
                }
            }
        }
Example #19
0
        private SurfaceFormat LoadDDSFormat(uint fourCC, DDS dds = null, bool IsSRGB = false)
        {
            bool IsDX10 = false;

            switch (fourCC)
            {
            case DDS.FOURCC_DXT1:
                if (IsSRGB)
                {
                    return(SurfaceFormat.BC1_SRGB);
                }
                else
                {
                    return(SurfaceFormat.BC1_UNORM);
                }

            case DDS.FOURCC_DXT3:
                if (IsSRGB)
                {
                    return(SurfaceFormat.BC2_SRGB);
                }
                else
                {
                    return(SurfaceFormat.BC2_UNORM);
                }

            case DDS.FOURCC_DXT5:
                if (IsSRGB)
                {
                    return(SurfaceFormat.BC3_SRGB);
                }
                else
                {
                    return(SurfaceFormat.BC3_UNORM);
                }

            case DDS.FOURCC_BC4U:
                return(SurfaceFormat.BC4_UNORM);

            case DDS.FOURCC_BC4S:
                return(SurfaceFormat.BC4_SNORM);

            case DDS.FOURCC_ATI1:
                return(SurfaceFormat.BC4_UNORM);

            case DDS.FOURCC_ATI2:
                return(SurfaceFormat.BC5_UNORM);

            case DDS.FOURCC_BC5U:
                return(SurfaceFormat.BC5_UNORM);

            case DDS.FOURCC_BC5S:
                return(SurfaceFormat.BC5_SNORM);

            case DDS.FOURCC_DX10:
                IsDX10 = true;
                break;

            default:
                return(SurfaceFormat.R8_G8_B8_A8_SRGB);
            }
            Console.WriteLine(IsDX10);
            if (IsDX10)
            {
                Console.WriteLine(dds.DX10header.DXGI_Format);

                switch (dds.DX10header.DXGI_Format)
                {
                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_UNORM:
                    return(SurfaceFormat.BC4_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_SNORM:
                    return(SurfaceFormat.BC4_SNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_TYPELESS:
                    return(SurfaceFormat.BC4_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_UNORM:
                    return(SurfaceFormat.BC5_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_SNORM:
                    return(SurfaceFormat.BC5_SNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_TYPELESS:
                    return(SurfaceFormat.BC5_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC6H_SF16:
                    return(SurfaceFormat.BC6_FLOAT);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC6H_UF16:
                    return(SurfaceFormat.BC6_UFLOAT);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM:
                    return(SurfaceFormat.BC7_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM_SRGB:
                    return(SurfaceFormat.BC7_SRGB);

                default:
                    throw new Exception($"Format {dds.DX10header.DXGI_Format} not supported!");
                }
            }
            throw new Exception($"This shouldn't happen :(");
        }
Example #20
0
        public BlurayInfoViewModel(byte[] blurayDiscInformation, byte[] blurayBurstCuttingArea, byte[] blurayDds,
                                   byte[] blurayCartridgeStatus, byte[] bluraySpareAreaInformation,
                                   byte[] blurayPowResources, byte[] blurayTrackResources, byte[] blurayRawDfl,
                                   byte[] blurayPac, Window view)
        {
            _view             = view;
            _discInformation  = blurayDiscInformation;
            _burstCuttingArea = blurayBurstCuttingArea;
            _dds                              = blurayDds;
            _cartridgeStatus                  = blurayCartridgeStatus;
            _spareAreaInformation             = bluraySpareAreaInformation;
            _powResources                     = blurayPowResources;
            _trackResources                   = blurayTrackResources;
            _rawDfl                           = blurayRawDfl;
            _pac                              = blurayPac;
            SaveBlurayDiscInformationCommand  = ReactiveCommand.Create(ExecuteSaveBlurayDiscInformationCommand);
            SaveBlurayBurstCuttingAreaCommand = ReactiveCommand.Create(ExecuteSaveBlurayBurstCuttingAreaCommand);
            SaveBlurayDdsCommand              = ReactiveCommand.Create(ExecuteSaveBlurayDdsCommand);
            SaveBlurayCartridgeStatusCommand  = ReactiveCommand.Create(ExecuteSaveBlurayCartridgeStatusCommand);

            SaveBluraySpareAreaInformationCommand =
                ReactiveCommand.Create(ExecuteSaveBluraySpareAreaInformationCommand);

            SaveBlurayPowResourcesCommand   = ReactiveCommand.Create(ExecuteSaveBlurayPowResourcesCommand);
            SaveBlurayTrackResourcesCommand = ReactiveCommand.Create(ExecuteSaveBlurayTrackResourcesCommand);
            SaveBlurayRawDflCommand         = ReactiveCommand.Create(ExecuteSaveBlurayRawDflCommand);
            SaveBlurayPacCommand            = ReactiveCommand.Create(ExecuteSaveBlurayPacCommand);

            if (blurayDiscInformation != null)
            {
                SaveBlurayDiscInformationVisible = true;
                BlurayDiscInformationText        = DI.Prettify(blurayDiscInformation);
            }

            if (blurayBurstCuttingArea != null)
            {
                SaveBlurayBurstCuttingAreaVisible = true;
                BlurayBurstCuttingAreaText        = BCA.Prettify(blurayBurstCuttingArea);
            }

            if (blurayDds != null)
            {
                SaveBlurayDdsVisible = true;
                BlurayDdsText        = DDS.Prettify(blurayDds);
            }

            if (blurayCartridgeStatus != null)
            {
                SaveBlurayCartridgeStatusVisible = true;
                BlurayCartridgeStatusText        = Cartridge.Prettify(blurayCartridgeStatus);
            }

            if (bluraySpareAreaInformation != null)
            {
                SaveBluraySpareAreaInformationVisible = true;
                BluraySpareAreaInformationText        = Spare.Prettify(bluraySpareAreaInformation);
            }

            if (blurayPowResources != null)
            {
                SaveBlurayPowResourcesVisible = true;
                BlurayPowResourcesText        = DiscInformation.Prettify(blurayPowResources);
            }

            if (blurayTrackResources != null)
            {
                SaveBlurayTrackResourcesVisible = true;
                BlurayTrackResourcesText        = DiscInformation.Prettify(blurayTrackResources);
            }

            SaveBlurayRawDflVisible = blurayRawDfl != null;
            SaveBlurayPacVisible    = blurayPac != null;
        }
Example #21
0
        public void addBiggerImage(string imagePathToAdd, string archiveDir)
        {
            ImageSize biggerImageSizeOnList = imgList.Max(image => image.imgSize);
            // check if replacing image is supported
            ImageFile imgFile;
            string    fileFormat = Path.GetExtension(imagePathToAdd);

            switch (fileFormat)
            {
            case ".dds": imgFile = new DDS(imagePathToAdd, null); break;

            case ".tga": imgFile = new TGA(imagePathToAdd, null); break;

            default: throw new FileFormatException(fileFormat + " image extension not supported");
            }

            // check if image to add is valid
            if (biggerImageSizeOnList.width * 2 != imgFile.imgSize.width || biggerImageSizeOnList.height * 2 != imgFile.imgSize.height)
            {
                throw new FormatException("image size " + imgFile.imgSize + " isn't valid, must be " + new ImageSize(biggerImageSizeOnList.width * 2, biggerImageSizeOnList.height * 2));
            }

            // this check avoids insertion inside textures that have only 1 image stored inside pcc
            if (!imgList.Exists(img => img.storageType != storage.empty && img.storageType != storage.pccSto))
            {
                throw new Exception("Unable to add image, texture must have a reference to an external archive");
            }

            // !!! warning, this method breaks consistency between imgList and imageData[] !!!
            ImageInfo newImgInfo = new ImageInfo();

            newImgInfo.storageType = imgList.Find(img => img.storageType != storage.empty && img.storageType != storage.pccSto).storageType;
            newImgInfo.imgSize     = imgFile.imgSize;
            newImgInfo.uncSize     = imgFile.resize().Length;
            newImgInfo.cprSize     = 0x00; // not yet filled
            newImgInfo.offset      = 0x00; // not yet filled
            imgList.Insert(0, newImgInfo); // insert new image on top of the list
            //now I let believe the program that I'm doing an image replace, saving lot of code ;)
            replaceImage(newImgInfo.imgSize.ToString(), imagePathToAdd, archiveDir);

            //updating num of images
            numMipMaps++;

            // update MipTailBaseIdx
            //PropertyReader.Property MipTail = properties["MipTailBaseIdx"];
            int propVal = properties["MipTailBaseIdx"].Value.IntValue;

            propVal++;
            properties["MipTailBaseIdx"].Value.IntValue = propVal;
            //MessageBox.Show("raw size: " + properties["MipTailBaseIdx"].raw.Length + "\nproperty offset: " + properties["MipTailBaseIdx"].offsetval);
            using (MemoryStream rawStream = new MemoryStream(properties["MipTailBaseIdx"].raw))
            {
                rawStream.Seek(rawStream.Length - 4, SeekOrigin.Begin);
                rawStream.WriteValueS32(propVal);
                properties["MipTailBaseIdx"].raw = rawStream.ToArray();
            }
            //properties["MipTailBaseIdx"] = MipTail;

            // update Sizes
            //PropertyReader.Property Size = properties["SizeX"];
            propVal = (int)newImgInfo.imgSize.width;
            properties["SizeX"].Value.IntValue = propVal;
            using (MemoryStream rawStream = new MemoryStream(properties["SizeX"].raw))
            {
                rawStream.Seek(rawStream.Length - 4, SeekOrigin.Begin);
                rawStream.WriteValueS32(propVal);
                properties["SizeX"].raw = rawStream.ToArray();
            }
            //properties["SizeX"] = Size;
            //Size = properties["SizeY"];
            properties["SizeY"].Value.IntValue = (int)newImgInfo.imgSize.height;
            using (MemoryStream rawStream = new MemoryStream(properties["SizeY"].raw))
            {
                rawStream.Seek(rawStream.Length - 4, SeekOrigin.Begin);
                rawStream.WriteValueS32(propVal);
                properties["SizeY"].raw = rawStream.ToArray();
            }
            //properties["SizeY"] = Size;
            properties["OriginalSizeX"].Value.IntValue = propVal;
            using (MemoryStream rawStream = new MemoryStream(properties["OriginalSizeX"].raw))
            {
                rawStream.Seek(rawStream.Length - 4, SeekOrigin.Begin);
                rawStream.WriteValueS32(propVal);
                properties["OriginalSizeX"].raw = rawStream.ToArray();
            }
            properties["OriginalSizeY"].Value.IntValue = propVal;
            using (MemoryStream rawStream = new MemoryStream(properties["OriginalSizeY"].raw))
            {
                rawStream.Seek(rawStream.Length - 4, SeekOrigin.Begin);
                rawStream.WriteValueS32(propVal);
                properties["OriginalSizeY"].raw = rawStream.ToArray();
            }
        }
Example #22
0
        public void replaceImage(string strImgSize, string fileToReplace, string archiveDir)
        {
            ImageSize imgSize = ImageSize.stringToSize(strImgSize);

            if (!imgList.Exists(img => img.imgSize == imgSize))
            {
                throw new FileNotFoundException("Image with resolution " + imgSize + " isn't found");
            }

            int       imageIdx = imgList.FindIndex(img => img.imgSize == imgSize);
            ImageInfo imgInfo  = imgList[imageIdx];

            if (!File.Exists(fileToReplace))
            {
                throw new FileNotFoundException("invalid file to replace: " + fileToReplace);
            }

            // check if replacing image is supported
            ImageFile imgFile;
            string    fileFormat = Path.GetExtension(fileToReplace);

            switch (fileFormat)
            {
            case ".dds": imgFile = new DDS(fileToReplace, null); break;

            case ".tga": imgFile = new TGA(fileToReplace, null); break;

            default: throw new FileFormatException(fileFormat + " image extension not supported");
            }

            // check if images have same format type
            if (texFormat != imgFile.format)
            {
                DialogResult selection = MessageBox.Show("Warning, replacing image has format " + imgFile.subtype() + " while original has " + texFormat + ", would you like to replace it anyway?", "Warning, different image format found", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (selection == DialogResult.Yes)
                {
                    imgFile.format = texFormat;
                }
                else
                {
                    return;
                }
                //throw new FormatException("Different image format, original is " + texFormat + ", new is " + imgFile.subtype());
            }

            byte[] imgBuffer;

            // if the image is empty then recover the archive compression from the image list
            if (imgInfo.storageType == storage.empty)
            {
                imgInfo.storageType = imgList.Find(img => img.storageType != storage.empty && img.storageType != storage.pccSto).storageType;
                imgInfo.uncSize     = imgFile.resize().Length;
                imgInfo.cprSize     = imgFile.resize().Length;
            }

            switch (imgInfo.storageType)
            {
            case storage.arcCpr:
            case storage.arcUnc:
                string archivePath = archiveDir + "\\" + arcName + ".tfc";
                if (!File.Exists(archivePath))
                {
                    throw new FileNotFoundException("Texture archive not found in " + archivePath);
                }

                if (getFileFormat() == ".tga")
                {
                    imgBuffer = imgFile.resize();     // shrink image to essential data
                }
                else
                {
                    imgBuffer = imgFile.imgData;
                }

                if (imgBuffer.Length != imgInfo.uncSize)
                {
                    throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);
                }

                using (FileStream archiveStream = new FileStream(archivePath, FileMode.Append, FileAccess.Write))
                {
                    int newOffset = (int)archiveStream.Position;

                    if (imgInfo.storageType == storage.arcCpr)
                    {
                        imgBuffer = ZBlock.Compress(imgBuffer);

                        /*byte[] compressed = ZBlock.Compress(imgBuffer);
                         * archiveStream.Write(compressed, 0, compressed.Length);*/
                        imgInfo.cprSize = imgBuffer.Length;
                    }
                    //else
                    archiveStream.Write(imgBuffer, 0, imgBuffer.Length);

                    imgInfo.offset = newOffset;
                }
                break;

            case storage.pccSto:
                imgBuffer = imgFile.imgData;     // copy image data as-is
                if (imgBuffer.Length != imgInfo.uncSize)
                {
                    throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);
                }

                using (MemoryStream dataStream = new MemoryStream(imageData))
                {
                    dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                    dataStream.Write(imgBuffer, 0, imgBuffer.Length);
                }

                break;
            }

            imgList[imageIdx] = imgInfo;
        }
Example #23
0
        /// <summary>
        /// Convertit un fichier DDS en fichier 2DB (EVO_37). Génère un nouvel en-tête.
        /// </summary>
        /// <param name="sourceDDSFile">fichier DDS à convertir</param>
        /// <param name="target2DBFile">nouveau fichier 2DB à créer</param>
        /// <param name="newTextureName">if not null, allows to override texture name</param>
        /// <param name="mipmapCount">if not -1, forces mipmap count</param>
        public static void DDSTo2DB(string sourceDDSFile, string target2DBFile, string newTextureName, int mipmapCount)
        {
            if (sourceDDSFile != null && target2DBFile != null)
            {
                DDS ddsFile = (DDS)TduFile.GetFile(sourceDDSFile);
                DDS.TextureHeader ddsHeader = (DDS.TextureHeader)ddsFile.Header;

                // Construction d'un fichier 2DB flambant neuf
                FileInfo           fi         = new FileInfo(target2DBFile);
                _2DB               new2DBFile = (_2DB)TduFile.GetFile(target2DBFile);
                _2DB.TextureHeader newHeader  = new _2DB.TextureHeader();
                string             picName;

                // Override texture name ?
                if (newTextureName != null)
                {
                    picName = Tools.NormalizeName(newTextureName);
                }
                else
                {
                    picName = Tools.NormalizeName(fi.Name.ToUpper());
                }

                // Valeurs connues
                newHeader.bID1    = String2.ToByteArray(_2DB.ID1_STRING);
                newHeader.bID2    = String2.ToByteArray(_2DB.ID2_STRING);
                newHeader.dwTwo   = 2;
                newHeader.dwZero1 = newHeader.dwZero2 = newHeader.dwZero3 = 0;
                newHeader.one     = 1;
                newHeader.height  = (short)ddsHeader.ddsd.dwHeight;
                newHeader.width   = (short)ddsHeader.ddsd.dwWidth;
                newHeader.strName = String2.ToByteArray(picName);

                // BUG_58 : mipmap count in 2DB takes main texture into account (so always >= 1)
                uint ddsMipmapCount = ddsHeader.ddsd.dwMipMapCount;

                // Mipmap count enforcement
                if (mipmapCount == KEEP_ORIGINAL_MIPMAP_COUNT)
                {
                    newHeader.bMipMapCount = newHeader.bMipMapCountBis = (byte)(ddsMipmapCount + 1);
                }
                else
                {
                    newHeader.bMipMapCount = newHeader.bMipMapCountBis = (byte)mipmapCount;
                }

                // Format & type (linked ??)
                byte format;
                uint type;

                switch (ddsHeader.ddsd.ddpfPixelFormat.dwFourCC)
                {
                case DDS.FORMAT_FOURCC_DXT1:
                    format = _2DB.FORMAT_ID_B1;
                    type   = _2DB.TYPE_DXT1;
                    break;

                case DDS.FORMAT_FOURCC_DXT5:
                    format = _2DB.FORMAT_ID_B5;
                    type   = _2DB.TYPE_DXT5;
                    break;

                case DDS.FORMAT_FOURCC_UNKNOWN:
                    format = _2DB.FORMAT_ID_BARGB8;
                    type   = _2DB.TYPE_ARGB8;
                    break;

                default:
                    // Log warning
                    Log.Warning("Unsupported texture format: '" + ddsHeader.ddsd.ddpfPixelFormat.dwFourCC +
                                "'. Treated as DXT5.");
                    // DXT5
                    format = _2DB.FORMAT_ID_B5;
                    type   = _2DB.TYPE_DXT5;
                    break;
                }
                newHeader.bFormat = format;
                newHeader.dwType  = type;

                // TODO A découvrir... et initialiser plus tard
                newHeader.dwFlags = 512;
                newHeader.dwUnk6  = 0;
                newHeader.dwUnk7  = 0;
                newHeader.bUnk2   = 0;
                newHeader.unk3    = 0;
                newHeader.dwUnk4  = 0;

                // Derniers calculs : taille du fichier
                uint _2dbSize = (uint)(_2DB.HEADER_SIZE + ddsFile.ImageData.Length + _2DB.FINALIZATION_STRING.Length);

                newHeader.dwSize  = _2dbSize;
                newHeader.dwSize2 = newHeader.dwSize2Bis = _2dbSize - 32;

                // Ecriture des sections
                try
                {
                    using (BinaryWriter writer = new BinaryWriter(new FileStream(target2DBFile, FileMode.Create, FileAccess.Write)))
                    {
                        // 1. En-tête
                        new2DBFile.Header = newHeader;
                        writer.Write(new2DBFile.HeaderData);

                        // 2. Données d'image
                        writer.Write(ddsFile.ImageData);

                        // Finalisation
                        writer.Write(_2DB.FINALIZATION_STRING);
                    }
                }
                catch (IOException ioe)
                {
                    Exception2.PrintStackTrace(ioe);
                    throw;
                }
            }
        }
Example #24
0
        public static void DoMakeObjFile(string outputDir, string inputFile, string gradient, string emissive)
        {
            byte[] gradientColors = gradient.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray();

            SColor[] gradientObj = new SColor[] {
                new SColor {
                    R = gradientColors[0], B = gradientColors[1], G = gradientColors[2]
                },
                new SColor {
                    R = gradientColors[3], B = gradientColors[4], G = gradientColors[5]
                },
                new SColor {
                    R = gradientColors[6], B = gradientColors[7], G = gradientColors[8]
                },
            };

            byte[] emissiveColors = emissive.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray();

            SColor emissiveObj = new SColor {
                R = emissiveColors[0], B = emissiveColors[1], G = emissiveColors[2]
            };

            string inputOrg = inputFile;

            bool isJson    = inputFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase);
            bool isMsgpack = inputFile.EndsWith(".msgpack", StringComparison.OrdinalIgnoreCase);

            if (!File.Exists(inputFile) || (!isMsgpack && !isJson))
            {
                throw new Exception("Input file must be .msgpack or .json");
            }

            if (!Directory.Exists(outputDir))
            {
                throw new Exception("Output directory does not exist!");
            }

            if (isMsgpack)
            {
                Parser.DoParse(outputDir, inputFile);
                inputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.json");
            }

            string materialName     = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(inputFile));
            string materialFile     = $"{materialName}.mtl";
            string materialFilePath = Path.Combine(outputDir, materialFile);

            JObject root = JObject.Parse(File.ReadAllText(inputFile));

            Dictionary <string, Dictionary <string, string> > materialLookup = new Dictionary <string, Dictionary <string, string> >();

            foreach (var curNode in root["nodes"].Value <JObject>())
            {
                if (!curNode.Value.Value <JObject>().ContainsKey("geometryinstances"))
                {
                    continue;
                }

                foreach (var curGeom in curNode.Value["geometryinstances"].Value <JObject>())
                {
                    string geometry = curGeom.Value["geometry"].Value <string>();
                    string surface  = curGeom.Value["surface"].Value <string>();
                    string material = curGeom.Value["material"].Value <string>();

                    if (!materialLookup.TryGetValue(geometry, out Dictionary <string, string> curGeomLookup))
                    {
                        curGeomLookup = new Dictionary <string, string>();
                        materialLookup.Add(geometry, curGeomLookup);
                    }

                    curGeomLookup[surface] = material;
                }
            }

            bool failMat = false;

            string outputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.obj");

            using (StreamWriter sw = new StreamWriter(outputFile))
            {
                sw.WriteLine($"mtllib {materialFile}");

                int vOffset  = 0;
                int vtOffset = 0;
                int vnOffset = 0;

                foreach (var curGeom in root["geometries"].Value <JObject>())
                {
                    // TODO: handle TANGENT and BINORMAL. Anymore?

                    //if (curGeom.Value["inputs"].Count() != 3)
                    //{
                    //    throw new Exception("Invalid source input count...");
                    //}

                    double[][] vertLocs = ReadShit <double>(curGeom.Value, "POSITION", out int vertOffset);
                    foreach (double[] curVert in vertLocs)
                    {
                        sw.WriteLine($"v {curVert[0]} {curVert[1]} {curVert[2]}");
                    }

                    double[][] texCoords = ReadShit <double>(curGeom.Value, "TEXCOORD0", out int texOffset);
                    foreach (double[] curTex in texCoords)
                    {
                        sw.WriteLine($"vt {curTex[0]} {1-curTex[1]}");
                    }

                    double[][] normals = ReadShit <double>(curGeom.Value, "NORMAL", out int normOffset);
                    foreach (double[] curNorm in normals)
                    {
                        sw.WriteLine($"vn {curNorm[0]} {curNorm[1]} {curNorm[2]}");
                    }

                    foreach (var curSurf in curGeom.Value["surfaces"].Value <JObject>())
                    {
                        sw.WriteLine($"g {curSurf.Key}");

                        try
                        {
                            sw.WriteLine($"usemtl {materialLookup[curGeom.Key][curSurf.Key]}");
                        }
                        catch
                        {
                            failMat = true;
                            sw.WriteLine($"usemtl failMat");
                            Console.WriteLine("material not found...");
                        }

                        var blarg         = curSurf.Value["triangles"].Select(cur => cur.Value <int>());
                        int numPrimitives = curSurf.Value["numPrimitives"].Value <int>();

                        if ((blarg.Count() % numPrimitives) != 0)
                        {
                            throw new Exception("Invalid stride");
                        }

                        int stride = blarg.Count() / numPrimitives;

                        if ((stride % 3) != 0)
                        {
                            throw new Exception("Invalid stride");
                        }

                        int pointLength = stride / 3;

                        int[][] triangles = FuckinReadIt(blarg, stride);

                        foreach (int[] curTri in triangles)
                        {
                            if (pointLength >= 1)
                            {
                                if ((curTri[pointLength * 0 + 0] >= vertLocs.Length) ||
                                    (curTri[pointLength * 1 + 0] >= vertLocs.Length) ||
                                    (curTri[pointLength * 2 + 0] >= vertLocs.Length))
                                {
                                    Console.WriteLine("vert index out of range");
                                    continue;
                                }
                            }

                            if (pointLength >= 2)
                            {
                                if ((curTri[pointLength * 0 + 1] >= texCoords.Length) ||
                                    (curTri[pointLength * 1 + 1] >= texCoords.Length) ||
                                    (curTri[pointLength * 2 + 1] >= texCoords.Length))
                                {
                                    Console.WriteLine("tex index out of range");
                                    continue;
                                }
                            }

                            if (pointLength >= 3)
                            {
                                if ((curTri[pointLength * 0 + 2] >= normals.Length) ||
                                    (curTri[pointLength * 1 + 2] >= normals.Length) ||
                                    (curTri[pointLength * 2 + 2] >= normals.Length))
                                {
                                    Console.WriteLine("norm index out of range");
                                    continue;
                                }
                            }

                            sw.Write("f");

                            for (int i = 0; i < 3; ++i)
                            {
                                sw.Write(" ");

                                if (pointLength >= 1)
                                {
                                    sw.Write($"{curTri[pointLength * i + 0] + 1 + vOffset}");
                                }

                                if (pointLength >= 2)
                                {
                                    sw.Write($"/{curTri[pointLength * i + 1] + 1 + vtOffset}");
                                }

                                if (pointLength >= 3)
                                {
                                    sw.Write($"/{curTri[pointLength * i + 2] + 1 + vnOffset}");
                                }
                            }

                            sw.WriteLine();
                        }
                    }

                    vOffset  += vertLocs.Length;
                    vtOffset += texCoords.Length;
                    vnOffset += normals.Length;
                }

                sw.Flush();
                sw.Close();
                sw.Dispose();
            }

            string rootDir = inputOrg;

            while (Path.GetFileName(rootDir) != "assets")
            {
                rootDir = Path.GetDirectoryName(rootDir);
            }

            using (StreamWriter sw = new StreamWriter(materialFilePath))
            {
                foreach (var curMat in root["materials"].Value <JObject>())
                {
                    sw.WriteLine($"newmtl {curMat.Key}");

                    var material = curMat.Value.Value <JObject>();

                    int usedTextures = 0;

                    if (material["parameters"].Value <JObject>().ContainsKey("diffuse") ||
                        material["parameters"].Value <JObject>().ContainsKey("gradient_mask"))
                    {
                        string     diffuse;
                        FastBitmap diffuseTexture;

                        if (material["parameters"].Value <JObject>().ContainsKey("diffuse"))
                        {
                            ++usedTextures;
                            diffuse = material["parameters"]["diffuse"].Value <string>().Replace('/', '\\');

                            try
                            {
                                diffuseTexture = DDS.LoadImage(Path.Combine(rootDir, diffuse)).FastLock();
                            }
                            catch
                            {
                                diffuseTexture = null;
                                Console.WriteLine("Error loading texture");
                            }
                        }
                        else
                        {
                            diffuse        = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\');
                            diffuseTexture = null;
                        }

                        if (material["parameters"].Value <JObject>().ContainsKey("gradient_mask"))
                        {
                            ++usedTextures;
                            string gradient_mask = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\');

                            FastBitmap gradient_maskTexture = null;
                            bool       fail = false;

                            try
                            {
                                gradient_maskTexture = DDS.LoadImage(Path.Combine(rootDir, gradient_mask)).FastLock();
                            }
                            catch
                            {
                                fail = true;
                                Console.WriteLine("Error loading texture");
                            }

                            if (!fail)
                            {
                                if (diffuseTexture == null)
                                {
                                    diffuseTexture = new Bitmap(gradient_maskTexture.Width, gradient_maskTexture.Height, PixelFormat.Format32bppArgb).FastLock();
                                }

                                ApplyGradientToDiffuse(diffuseTexture, gradient_maskTexture, gradientObj);

                                gradient_maskTexture.Unlock();
                                gradient_maskTexture.Bitmap.Dispose();
                                gradient_maskTexture.Dispose();
                            }
                        }

                        if (diffuseTexture == null)
                        {
                            diffuseTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock();
                            SetFlatColor(diffuseTexture, new SColor {
                                R = 255, G = 0, B = 255
                            });
                        }

                        diffuseTexture.Unlock();

                        string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(diffuse)}.png");
                        sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}");

                        try
                        {
                            diffuseTexture.Bitmap.Save(saveFilePath, ImageFormat.Png);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}");
                        }

                        diffuseTexture.Bitmap.Dispose();
                        diffuseTexture.Dispose();
                    }

                    if (material["parameters"].Value <JObject>().ContainsKey("normal"))
                    {
                        ++usedTextures;
                        string normal = material["parameters"]["normal"].Value <string>().Replace('/', '\\');

                        FastBitmap normalTexture = null;
                        bool       fail          = false;

                        try
                        {
                            normalTexture = DDS.LoadImage(Path.Combine(rootDir, normal)).FastLock();
                        }
                        catch
                        {
                            fail = true;
                            Console.WriteLine("Error loading texture");
                        }

                        if (!fail)
                        {
                            normalTexture.Unlock();

                            string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(normal)}.png");
                            sw.WriteLine($"map_Bump {Path.GetFileName(saveFilePath)}");

                            try
                            {
                                normalTexture.Bitmap.Save(saveFilePath, ImageFormat.Png);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}");
                            }

                            normalTexture.Bitmap.Dispose();
                            normalTexture.Dispose();
                        }
                    }

                    if (material["parameters"].Value <JObject>().ContainsKey("specular_emissive"))
                    {
                        ++usedTextures;
                        string specular_emissive = material["parameters"]["specular_emissive"].Value <string>().Replace('/', '\\');

                        FastBitmap specular_emissiveTexture = null;

                        bool fail = false;
                        try
                        {
                            specular_emissiveTexture = DDS.LoadImage(Path.Combine(rootDir, specular_emissive)).FastLock();
                        }
                        catch
                        {
                            fail = true;
                            Console.WriteLine("Error loading texture");
                        }

                        if (!fail)
                        {
                            ApplyEmissiveColor(specular_emissiveTexture, emissiveObj);

                            specular_emissiveTexture.Unlock();

                            string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(specular_emissive)}.png");
                            sw.WriteLine($"map_Ke {Path.GetFileName(saveFilePath)}");

                            try
                            {
                                specular_emissiveTexture.Bitmap.Save(saveFilePath, ImageFormat.Png);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}");
                            }

                            specular_emissiveTexture.Bitmap.Dispose();
                            specular_emissiveTexture.Dispose();
                        }
                    }

                    if (material["parameters"].Value <JObject>().Count != usedTextures)
                    {
                        Console.WriteLine($"Warning, unused texture(s) on {curMat.Key}...");
                    }
                }

                if (failMat)
                {
                    FastBitmap failTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock();
                    SetFlatColor(failTexture, new SColor {
                        R = 255, G = 0, B = 255
                    });

                    sw.WriteLine($"newmtl failMat");

                    failTexture.Unlock();

                    string saveFilePath = Path.Combine(outputDir, $"failMat.png");
                    sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}");

                    try
                    {
                        failTexture.Bitmap.Save(saveFilePath, ImageFormat.Png);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}");
                    }

                    failTexture.Bitmap.Dispose();
                    failTexture.Dispose();
                }

                sw.Flush();
                sw.Close();
                sw.Dispose();
            }

            Console.WriteLine("Done Done!!!");
        }
        public Texture2D Fetch()
        {
            if (CachedTexture != null)
            {
                return(CachedTexture);
            }

            var textureBytes = FetchBytes();

            if (textureBytes == null)
            {
                return(null);
            }

            DDS header = new DDS(textureBytes);
            int height = header.dwHeight;
            int width  = header.dwWidth;

            int mipmapCount = header.dwMipMapCount;
            var br          = new BinaryReaderEx(false, textureBytes);

            br.Skip((int)header.dataOffset);

            SurfaceFormat surfaceFormat;

            if (header.ddspf.dwFourCC == "DX10")
            {
                // See if there are DX9 textures
                int fmt = (int)header.header10.dxgiFormat;
                if (fmt == 70 || fmt == 71 || fmt == 72)
                {
                    surfaceFormat = SurfaceFormat.Dxt1;
                }
                else if (fmt == 73 || fmt == 74 || fmt == 75)
                {
                    surfaceFormat = SurfaceFormat.Dxt3;
                }
                else if (fmt == 76 || fmt == 77 || fmt == 78)
                {
                    surfaceFormat = SurfaceFormat.Dxt5;
                }
                else if (fmt == 79 || fmt == 80 || fmt == 81)
                {
                    surfaceFormat = SurfaceFormat.ATI1;
                }
                else if (fmt == 82 || fmt == 83 || fmt == 84)
                {
                    surfaceFormat = SurfaceFormat.ATI2;
                }
                else if (fmt == 97 || fmt == 98 || fmt == 99)
                {
                    surfaceFormat = SurfaceFormat.BC7;
                }
                else
                {
                    // No DX10 texture support in monogame yet
                    IsDX10        = true;
                    CachedTexture = Main.DEFAULT_TEXTURE_MISSING;
                    header        = null;
                    TPFReference  = null;
                    return(CachedTexture);
                }
            }
            else
            {
                surfaceFormat = GetSurfaceFormatFromString(header.ddspf.dwFourCC);
            }
            // Adjust width and height because from has some DXTC textures that have dimensions not a multiple of 4 :shrug:
            Texture2D tex = new Texture2D(GFX.Device, GetNextMultipleOf4(width), GetNextMultipleOf4(height), true, surfaceFormat);

            for (int i = 0; i < mipmapCount; i++)
            {
                try
                {
                    int numTexels = GetNextMultipleOf4(width >> i) * GetNextMultipleOf4(height >> i);
                    if (surfaceFormat == SurfaceFormat.Dxt1 || surfaceFormat == SurfaceFormat.Dxt1SRgb)
                    {
                        numTexels /= 2;
                    }
                    byte[] thisMipMap = br.ReadBytes(numTexels);
                    tex.SetData(i, 0, null, thisMipMap, 0, numTexels);
                    thisMipMap = null;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"Error loading {TexName}: {ex.Message}");
                }
            }

            CachedTexture = tex;
            header        = null;
            TPFReference  = null;
            return(CachedTexture);
        }
 /* Called to handle relevant data samples */
 public void handle_data(keysDataReader keys_reader,
                         DDS.SampleInfo info,
                         keys msg)
 {
     Console.WriteLine("code: {0}, x: {1}, y: {2}",
                        msg.code, msg.x, msg.y);
 }
 public void instance_lost_writers(keysDataReader keys_reader,
                                   DDS.SampleInfo info,
                                   keys msg)
 {
     Console.WriteLine("Instance has no writers; code = {0}", msg.code);
     states[msg.code] = Instance_State.no_writers;
 }
        private GTX.GX2SurfaceFormat LoadDDSFormat(uint fourCC, DDS dds = null, bool IsSRGB = false)
        {
            bool IsDX10 = false;

            switch (fourCC)
            {
            case DDS.FOURCC_DXT1:
                if (IsSRGB)
                {
                    return(GTX.GX2SurfaceFormat.T_BC1_SRGB);
                }
                else
                {
                    return(GTX.GX2SurfaceFormat.T_BC1_UNORM);
                }

            case DDS.FOURCC_DXT3:
                if (IsSRGB)
                {
                    return(GTX.GX2SurfaceFormat.T_BC2_SRGB);
                }
                else
                {
                    return(GTX.GX2SurfaceFormat.T_BC2_UNORM);
                }

            case DDS.FOURCC_DXT5:
                if (IsSRGB)
                {
                    return(GTX.GX2SurfaceFormat.T_BC3_SRGB);
                }
                else
                {
                    return(GTX.GX2SurfaceFormat.T_BC3_UNORM);
                }

            case DDS.FOURCC_BC4U:
                return(GTX.GX2SurfaceFormat.T_BC4_UNORM);

            case DDS.FOURCC_ATI1:
                return(GTX.GX2SurfaceFormat.T_BC4_UNORM);

            case DDS.FOURCC_ATI2:
                return(GTX.GX2SurfaceFormat.T_BC5_UNORM);

            case DDS.FOURCC_BC5U:
                return(GTX.GX2SurfaceFormat.T_BC5_UNORM);

            case DDS.FOURCC_BC5S:
                return(GTX.GX2SurfaceFormat.T_BC5_SNORM);

            case DDS.FOURCC_DX10:
                IsDX10 = true;
                break;

            default:
                return(GTX.GX2SurfaceFormat.TCS_R8_G8_B8_A8_UNORM);
            }
            if (IsDX10)
            {
                switch (dds.DX10header.DXGI_Format)
                {
                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_UNORM:
                    return(GTX.GX2SurfaceFormat.T_BC4_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_SNORM:
                    return(GTX.GX2SurfaceFormat.T_BC4_SNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC4_TYPELESS:
                    return(GTX.GX2SurfaceFormat.T_BC4_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_UNORM:
                    return(GTX.GX2SurfaceFormat.T_BC5_UNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_SNORM:
                    return(GTX.GX2SurfaceFormat.T_BC5_SNORM);

                case DDS.DXGI_FORMAT.DXGI_FORMAT_BC5_TYPELESS:
                    return(GTX.GX2SurfaceFormat.T_BC5_UNORM);

                default:
                    throw new Exception($"Format {dds.DX10header.DXGI_Format} not supported!");
                }
            }
            throw new Exception($"This shouldn't happen :(");
        }
        public override void on_data_available( DDS.DataReader reader )
        {
            sequencesDataReader sequences_reader =
                (sequencesDataReader)reader;

            try {
                sequences_reader.take(
                    data_seq,
                    info_seq,
                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            } catch (DDS.Retcode_NoData) {
                return;
            } catch (DDS.Exception e) {
                Console.WriteLine("take error {0}", e);
                return;
            }

            System.Int32 data_length = data_seq.length;
            for (int i = 0; i < data_length; ++i) {
                if (info_seq.get_at(i).valid_data) {
                    sequencesTypeSupport.print_data(data_seq.get_at(i));
                }
            }

            try {
                sequences_reader.return_loan(data_seq, info_seq);
            } catch (DDS.Exception e) {
                Console.WriteLine("return loan error {0}", e);
            }
        }
Example #30
0
        public byte[] extractImage(ImageInfo imgInfo, bool NoOutput, string archiveDir = null, string fileName = null)
        {
            ImageFile imgFile;

            if (fileName == null)
            {
                fileName = texName + "_" + imgInfo.imgSize + getFileFormat();
            }

            byte[] imgBuffer;

            switch (imgInfo.storageType)
            {
            case storage.pccSto:
                imgBuffer = new byte[imgInfo.uncSize];
                Buffer.BlockCopy(imageData, imgInfo.offset, imgBuffer, 0, imgInfo.uncSize);
                break;

            case storage.arcCpr:
            case storage.arcUnc:
                string archivePath = archiveDir + "\\" + arcName + ".tfc";
                if (!File.Exists(archivePath))
                {
                    throw new FileNotFoundException("Texture archive not found in " + archivePath);
                }

                using (FileStream archiveStream = File.OpenRead(archivePath))
                {
                    archiveStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                    if (imgInfo.storageType == storage.arcCpr)
                    {
                        imgBuffer = ZBlock.Decompress(archiveStream, imgInfo.cprSize);
                    }
                    else
                    {
                        imgBuffer = new byte[imgInfo.uncSize];
                        archiveStream.Read(imgBuffer, 0, imgBuffer.Length);
                    }
                }
                break;

            default:
                throw new FormatException("Unsupported texture storage type");
            }

            if (getFileFormat() == ".dds")
            {
                imgFile = new DDS(fileName, imgInfo.imgSize, texFormat, imgBuffer);
            }
            else
            {
                imgFile = new TGA(fileName, imgInfo.imgSize, texFormat, imgBuffer);
            }

            byte[] saveImg = imgFile.ToArray();

            if (!NoOutput)
            {
                using (FileStream outputImg = new FileStream(imgFile.fileName, FileMode.Create, FileAccess.Write))
                    outputImg.Write(saveImg, 0, saveImg.Length);
            }
            return(saveImg);
        }
 public override void on_liveliness_changed(
     DDS.DataReader reader,
     ref DDS.LivelinessChangedStatus status)
 {
 }
Example #32
0
        private void handle(WADEntry entry, string namePath)
        {
            if (namePath.ToLower().EndsWith(".dds"))
            {
                if (mode == 0)
                {
                    mode = 1;
                    _viewPort.Visibility              = Visibility.Collapsed;
                    _previewImage.Visibility          = Visibility.Visible;
                    _previewTextureComboBox.IsEnabled = false;
                    _previewMeshesComboBox.IsEnabled  = false;
                }

                _previewTypeLabel.Content = "Type: DirectDraw Surface";
                _previewNameLabel.Content = "Name: " + namePath.Split('/').Last();

                var stream = new MemoryStream();
                var image  = DDS.LoadImage(entry.GetContent(true));
                image.Save(stream, ImageFormat.Png);


                var imageSource = new BitmapImage();
                imageSource.CacheOption = BitmapCacheOption.OnLoad;
                imageSource.BeginInit();
                imageSource.StreamSource = stream;
                imageSource.EndInit();
                imageSource.Freeze();
                _previewImage.Dispatcher.BeginInvoke(new Action(() =>
                {
                    _previewImage.Source = imageSource;
                    _previewImage.Width  = image.Width;
                    _previewImage.Height = image.Height;
                }));
                return;
            }

            if (mode == 1)
            {
                mode = 0;
                _previewImage.Visibility = Visibility.Collapsed;
                _viewPort.Visibility     = Visibility.Visible;
            }

            clearUp();
            _previewTextureComboBox.IsEnabled = true;
            _previewMeshesComboBox.IsEnabled  = true;

            if (!_previewExpander.IsExpanded)
            {
                _previewExpander.IsExpanded = true;
            }


            if (namePath.ToLower().EndsWith(".scb"))
            {
                _previewMeshesComboBox.IsEnabled = false;
                var model = applyMesh(new SCBFile(new MemoryStream(entry.GetContent(true))));
                _previewTypeLabel.Content = "Type: Static Object Binary";
                _previewNameLabel.Content = "Name: " + namePath.Split('/').Last();

                if (PreSelect != null)
                {
                    foreach (var wadEntry in window.Wad.Entries)
                    {
                        if (wadEntry.XXHash == PreSelect.Item2)
                        {
                            applyMaterial(wadEntry, PreSelect.Item1, model);
                            break;
                        }
                    }

                    PreSelect = null;
                }
                else
                {
                    applyMaterial(model);
                }

                return;
            }

            if (namePath.ToLower().EndsWith(".sco"))
            {
                _previewMeshesComboBox.IsEnabled = false;
                var model = applyMesh(new SCOFile(new MemoryStream(entry.GetContent(true))));
                _previewTypeLabel.Content = "Type: Static Object Mesh";
                _previewNameLabel.Content = "Name: " + namePath.Split('/').Last();

                if (PreSelect != null)
                {
                    foreach (var wadEntry in window.Wad.Entries)
                    {
                        if (wadEntry.XXHash == PreSelect.Item2)
                        {
                            applyMaterial(wadEntry, PreSelect.Item1, model);
                            break;
                        }
                    }

                    PreSelect = null;
                }
                else
                {
                    applyMaterial(model);
                }

                return;
            }

            var result = generateInfoHolder(namePath);

            if (result == null)
            {
                return;
            }

            var skn = new SKNFile(new MemoryStream(result.sknPath.GetContent(true)));

            foreach (var subMesh in skn.Submeshes)
            {
                var model = applyMesh(subMesh);
                _previewNameLabel.Content = "Name: " + namePath.Split('/').Last();

                _previewTypeLabel.Content = "Type: Simple Skin Mesh";
                if (PreSelect != null)
                {
                    foreach (var wadEntry in window.Wad.Entries)
                    {
                        if (wadEntry.XXHash == PreSelect.Item2)
                        {
                            applyMaterial(wadEntry, PreSelect.Item1, model);
                            break;
                        }
                    }
                }
                else
                {
                    if (result.textures.Count > 0)
                    {
                        applyMaterial(result.textures.First().Value, result.textures.First().Key, model);
                    }
                    else
                    {
                        applyMaterial(model);
                    }
                }
            }

            PreSelect = null;
        }
 public override void on_sample_rejected(
     DDS.DataReader reader,
     ref DDS.SampleRejectedStatus status)
 {
 }
Example #34
0
        public override void CreateFromStream(Stream stream)
        {
            var index_count = stream.ReadInt();

            Album.Length = stream.ReadInt();
            var count = stream.ReadInt();
            var table = new List <Color>(Colors.ReadPalette(stream, count));

            Album.Tables = new List <List <Color> > {
                table
            };
            var list = new List <DDS>();

            for (var i = 0; i < index_count; i++)
            {
                var dds = new DDS {
                    Version    = (DDS_Version)stream.ReadInt(),
                    Type       = (ColorBits)stream.ReadInt(),
                    Index      = stream.ReadInt(),
                    Length     = stream.ReadInt(),
                    FullLength = stream.ReadInt(),
                    Width      = stream.ReadInt(),
                    Height     = stream.ReadInt()
                };
                list.Add(dds);
            }
            var dic      = new Dictionary <Sprite, int>();
            var ver2List = new List <Sprite>();

            for (var i = 0; i < Album.Count; i++)
            {
                var entity = new Sprite(Album);
                entity.Index = Album.List.Count;
                entity.Type  = (ColorBits)stream.ReadInt();
                Album.List.Add(entity);
                if (entity.Type == ColorBits.LINK)
                {
                    dic.Add(entity, stream.ReadInt());
                    continue;
                }
                entity.Compress      = (Compress)stream.ReadInt();
                entity.Width         = stream.ReadInt();
                entity.Height        = stream.ReadInt();
                entity.Length        = stream.ReadInt();             //保留,固定为0
                entity.X             = stream.ReadInt();
                entity.Y             = stream.ReadInt();
                entity.Canvas_Width  = stream.ReadInt();
                entity.Canvas_Height = stream.ReadInt();
                if (entity.Type < ColorBits.LINK && entity.Length != 0)
                {
                    ver2List.Add(entity);
                    continue;
                }
                var j         = stream.ReadInt();
                var k         = stream.ReadInt();
                var dds       = list[k];
                var leftup    = new Point(stream.ReadInt(), stream.ReadInt());
                var rightdown = new Point(stream.ReadInt(), stream.ReadInt());
                var top       = stream.ReadInt();
                var info      = new DDS_Info()
                {
                    Unknown   = j,
                    DDS       = dds,
                    LeftUp    = leftup,
                    RightDown = rightdown,
                    Top       = top
                };
                Map.Add(entity.Index, info);
            }

            foreach (var entity in dic.Keys)
            {
                entity.Target = Album.List[dic[entity]];
            }
            foreach (var dds in list)
            {
                var data = new byte[dds.Length];
                stream.Read(data);
                dds.Data = data;
            }
            foreach (var entity in ver2List)
            {
                var data = new byte[entity.Length];
                stream.Read(data);
                entity.Data = data;
            }
        }
Example #35
0
        public void loadDDSInfo(string filename, ParsedBitmap pb)
        {
            FileStream   fs = new FileStream(filename, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);

            dds.ReadStruct(ref br);

            // Determine Format Type
            ParsedBitmap.BitmapType bitmapType = ParsedBitmap.BitmapType.BITM_TYPE_2D;
            if (((int)DDS.DDSEnum.DDSCAPS2_VOLUME & dds.ddsd.ddsCaps.caps2) > 0)
            {
                bitmapType = ParsedBitmap.BitmapType.BITM_TYPE_3D;
            }
            else if (((int)DDS.DDSEnum.DDSCAPS2_CUBEMAP & dds.ddsd.ddsCaps.caps2) > 0)
            {
                bitmapType = ParsedBitmap.BitmapType.BITM_TYPE_CUBEMAP;
            }


            // Used to display external (file) bitmap to be injected
            int tempsize = dds.ddsd.width * dds.ddsd.height;

            switch (dds.ddsd.ddfPixelFormat.FourCC)
            {
            case "DXT1":
                tempsize /= 2;
                break;

            case "DXT2":
            case "DXT3":
            case "DXT4":
            case "DXT5":

                // tempsize /= 1;
                break;

            // for non-compressed
            default:
                tempsize *= dds.ddsd.ddfPixelFormat.RGBBitCount >> 3;
                break;
            }

            int widthPad = 0;

            if (dds.ddsd.width % 16 != 0)
            {
                widthPad = 16 - dds.ddsd.width % 16;
            }

            int byteStep = dds.ddsd.ddfPixelFormat.RGBBitCount / 8;

            /*
             * int totalSize = tempsize + (dds.ddsd.height * widthPad * byteStep);
             * if (bitmapType == ParsedBitmap.BitmapType.BITM_TYPE_CUBEMAP)
             *  totalSize *= 6;
             * byte[] guh = new byte[totalSize];
             */
            byte[] guh = new byte[br.BaseStream.Length - br.BaseStream.Position]; // + (widthPad * dds.ddsd.height * byteStep)];
            br.BaseStream.Read(guh, 0, guh.Length);

            // Determine DDS Format
            ParsedBitmap.BitmapFormat bmf = DDS.getBitmapFormat(dds);

            // G8B8 same as A8Y8 (found as A8Y8), but adjusted to 128 as center
            if (bmf == ParsedBitmap.BitmapFormat.BITM_FORMAT_A8Y8 &&
                pb.Properties[0].formatname == ParsedBitmap.BitmapFormat.BITM_FORMAT_G8B8)
            {
                for (int ii = 0; ii < guh.Length; ii++)
                {
                    guh[ii] += 128;
                }

                bmf = ParsedBitmap.BitmapFormat.BITM_FORMAT_G8B8;
            }

            pbSourceDDS.Image = ParsedBitmap.DecodeBitm(
                guh,
                dds.ddsd.height,
                dds.ddsd.width,
                dds.ddsd.depth,
                dds.ddsd.ddfPixelFormat.RGBBitCount,
                bitmapType,
                bmf,
                false,
                null,
                -1,
                -1);

            br.Close();
            fs.Close();

            #region Fill the source info box with the DDS information
            this.lbSourceDDS.Items.Add("Aspect : " + dds.ddsd.width + "x" + dds.ddsd.height);
            this.lbSourceDDS.Items.Add("w/ Pad : " + (dds.ddsd.width + widthPad) + "x" + dds.ddsd.height);
            int    bpp    = 32;
            string format = string.Empty;
            switch (dds.ddsd.ddfPixelFormat.FourCC)
            {
            case "DXT1":
                format = "DXT1";
                break;

            case "DXT2":
            case "DXT3":
                format = "DXT2AND3";
                break;

            case "DXT4":
            case "DXT5":
                format = "DXT4AND5";
                break;

            default:
                bpp = dds.ddsd.ddfPixelFormat.RGBBitCount;
                int aCount = 0;
                int rCount = 0;
                int gCount = 0;
                int bCount = 0;

                for (int i = 0; i < bpp; i++)
                {
                    // # of alpha bits
                    if ((dds.ddsd.ddfPixelFormat.RGBAlphaBitMask & (1 << i)) != 0)
                    {
                        aCount++;
                    }

                    // # of red bits
                    if ((dds.ddsd.ddfPixelFormat.RBitMask & (1 << i)) != 0)
                    {
                        rCount++;
                    }

                    // # of green bits
                    if ((dds.ddsd.ddfPixelFormat.GBitMask & (1 << i)) != 0)
                    {
                        gCount++;
                    }

                    // # of blue bits
                    if ((dds.ddsd.ddfPixelFormat.BBitMask & (1 << i)) != 0)
                    {
                        bCount++;
                    }
                }

                if ((aCount > 0) && ((dds.ddsd.ddfPixelFormat.Flags & 0x03) > 0))
                {
                    format += "A" + aCount;
                }
                else if (bpp - (rCount + gCount + bCount) > 0)
                {
                    format += "X" + (bpp - (rCount + gCount + bCount));
                }

                if (rCount > 0)
                {
                    format += "R" + rCount;
                }

                if (gCount > 0)
                {
                    format += "G" + gCount;
                }

                if (bCount > 0)
                {
                    format += "B" + bCount;
                }

                break;
            }
            lbSourceDDS.Items.Add("BPP    : " + bpp);
            lbSourceDDS.Items.Add("Type   : " + bitmapType.ToString().Substring(10));
            lbSourceDDS.Items.Add("Format : " + format); // remove "BITMAP_FORMAT_"
            lbSourceDDS.Items.Add("# Mips : " + Math.Max(dds.ddsd.MipMapCount - 1, 0));
            #endregion
        }
Example #36
0
        public Texture FromBitMap(byte[] data, TextureImporterSettings settings)
        {
            Texture tex = new Texture();

            tex.Height = (uint)settings.TexHeight;
            tex.Width  = (uint)settings.TexWidth;
            var formats = TextureData.GetSurfaceFormat(settings.Format, settings.FormatType);

            tex.Format     = formats.Item1;
            tex.FormatType = formats.Item2;

            tex.Name        = settings.TexName;
            tex.Path        = "";
            tex.TextureData = new List <List <byte[]> >();

            if (settings.MipCount == 0)
            {
                settings.MipCount = 1;
            }

            STChannelType[] channels = STGenericTexture.SetChannelsByFormat(settings.Format);
            tex.ChannelRed      = (ChannelType)channels[0];
            tex.ChannelGreen    = (ChannelType)channels[1];
            tex.ChannelBlue     = (ChannelType)channels[2];
            tex.ChannelAlpha    = (ChannelType)channels[3];
            tex.sparseBinding   = settings.sparseBinding;
            tex.sparseResidency = settings.sparseResidency;
            tex.AccessFlags     = settings.AccessFlags;
            tex.ArrayLength     = settings.arrayLength;
            tex.MipCount        = settings.MipCount;
            tex.Depth           = settings.Depth;
            tex.Dim             = settings.Dim;
            tex.Flags           = settings.Flags;
            tex.TileMode        = settings.TileMode;
            tex.textureLayout   = settings.TextureLayout;
            tex.textureLayout2  = settings.TextureLayout2;
            tex.Swizzle         = settings.Swizzle;
            tex.SurfaceDim      = settings.SurfaceDim;
            tex.SampleCount     = settings.SampleCount;
            tex.Regs            = settings.Regs;
            tex.Pitch           = settings.Pitch;

            tex.MipOffsets = new long[tex.MipCount];

            List <byte[]> arrayFaces = new List <byte[]>();

            if (tex.ArrayLength > 1)
            {
                arrayFaces = DDS.GetArrayFaces(data, tex.ArrayLength);
            }
            else
            {
                arrayFaces.Add(data);
            }

            for (int i = 0; i < tex.ArrayLength; i++)
            {
                List <byte[]> mipmaps = SwizzleSurfaceMipMaps(tex, arrayFaces[i], tex.TileMode);
                tex.TextureData.Add(mipmaps);
                byte[] test = Combine(mipmaps);
                tex.TextureData[i][0] = test;
            }
            return(tex);
        }
        internal void LoadData(MediaType mediaType, byte[] dds, byte[] cartridgeStatus,
                               byte[]    spareArea,
                               byte[]    lastBorderOutRmd, byte[] preRecordedInfo, byte[] mediaIdentifier,
                               byte[]    physicalInformation, byte[] mediumStatus, byte[] hdLastRmd,
                               byte[]    layerCapacity,
                               byte[]    middleZoneStart, byte[] jumpIntervalSize, byte[] manualLayerJumpStartLba,
                               byte[]    remapAnchorPoint, byte[] adip, byte[] dcb)
        {
            dvdRamDds                     = dds;
            dvdRamCartridgeStatus         = cartridgeStatus;
            dvdRamSpareArea               = spareArea;
            dvdLastBorderOutRmd           = lastBorderOutRmd;
            dvdPreRecordedInfo            = preRecordedInfo;
            dvdrMediaIdentifier           = mediaIdentifier;
            dvdrPhysicalInformation       = physicalInformation;
            hddvdrMediumStatus            = mediumStatus;
            hddvdrLastRmd                 = hdLastRmd;
            dvdrLayerCapacity             = layerCapacity;
            dvdrDlMiddleZoneStart         = middleZoneStart;
            dvdrDlJumpIntervalSize        = jumpIntervalSize;
            dvdrDlManualLayerJumpStartLba = manualLayerJumpStartLba;
            dvdrDlRemapAnchorPoint        = remapAnchorPoint;
            dvdPlusAdip                   = adip;
            dvdPlusDcb                    = dcb;
            switch (mediaType)
            {
            case MediaType.DVDR:
                Text = "DVD-R";
                break;

            case MediaType.DVDRW:
                Text = "DVD-RW";
                break;

            case MediaType.DVDPR:
                Text = "DVD+R";
                break;

            case MediaType.DVDPRW:
                Text = "DVD+RW";
                break;

            case MediaType.DVDPRWDL:
                Text = "DVD+RW DL";
                break;

            case MediaType.DVDRDL:
                Text = "DVD-R DL";
                break;

            case MediaType.DVDPRDL:
                Text = "DVD+R DL";
                break;

            case MediaType.DVDRAM:
                Text = "DVD-RAM";
                break;

            case MediaType.DVDRWDL:
                Text = "DVD-RW DL";
                break;

            case MediaType.HDDVDRAM:
                Text = "HD DVD-RAM";
                break;

            case MediaType.HDDVDR:
                Text = "HD DVD-R";
                break;

            case MediaType.HDDVDRW:
                Text = "HD DVD-RW";
                break;

            case MediaType.HDDVDRDL:
                Text = "HD DVD-R DL";
                break;

            case MediaType.HDDVDRWDL:
                Text = "HD DVD-RW DL";
                break;
            }

            if (dds != null)
            {
                grpDvdRamDds.Visible     = true;
                btnSaveDvdRamDds.Visible = true;
                txtDvdRamDds.Text        = DDS.Prettify(dds);
            }

            if (cartridgeStatus != null)
            {
                grpDvdRamCartridgeStatus.Visible     = true;
                btnSaveDvdRamCartridgeStatus.Visible = true;
                txtDvdRamCartridgeStatus.Text        = Cartridge.Prettify(cartridgeStatus);
            }

            if (spareArea != null)
            {
                grpDvdRamSpareAreaInformation.Visible     = true;
                btnSaveDvdRamSpareAreaInformation.Visible = true;
                txtDvdRamSpareAreaInformation.Text        = Spare.Prettify(spareArea);
            }

            btnSaveDvdRamDds.Visible                     = dds != null;
            btnSaveDvdRamCartridgeStatus.Visible         = cartridgeStatus != null;
            btnSaveDvdRamSpareAreaInformation.Visible    = spareArea != null;
            btnSaveLastBorderOutRmd.Visible              = lastBorderOutRmd != null;
            btnSaveDvdPreRecordedInfo.Visible            = preRecordedInfo != null;
            btnSaveDvdrMediaIdentifier.Visible           = mediaIdentifier != null;
            btnSaveDvdrPhysicalInformation.Visible       = physicalInformation != null;
            btnSaveHddvdrMediumStatus.Visible            = mediumStatus != null;
            btnSaveHddvdrLastRmd.Visible                 = hdLastRmd != null;
            btnSaveDvdrLayerCapacity.Visible             = layerCapacity != null;
            btnSaveDvdrDlMiddleZoneStart.Visible         = middleZoneStart != null;
            btnSaveDvdrDlJumpIntervalSize.Visible        = jumpIntervalSize != null;
            btnSaveDvdrDlManualLayerJumpStartLba.Visible = manualLayerJumpStartLba != null;
            btnSaveDvdrDlRemapAnchorPoint.Visible        = remapAnchorPoint != null;
            btnSaveDvdPlusAdip.Visible                   = adip != null;
            btnSaveDvdPlusDcb.Visible                    = dcb != null;

            Visible = grpDvdRamDds.Visible || grpDvdRamCartridgeStatus.Visible ||
                      grpDvdRamSpareAreaInformation.Visible || btnSaveDvdRamDds.Visible ||
                      btnSaveDvdRamCartridgeStatus.Visible || btnSaveDvdRamSpareAreaInformation.Visible ||
                      btnSaveLastBorderOutRmd.Visible || btnSaveDvdPreRecordedInfo.Visible ||
                      btnSaveDvdrMediaIdentifier.Visible || btnSaveDvdrPhysicalInformation.Visible ||
                      btnSaveHddvdrMediumStatus.Visible || btnSaveHddvdrLastRmd.Visible ||
                      btnSaveDvdrLayerCapacity.Visible || btnSaveDvdrDlMiddleZoneStart.Visible ||
                      btnSaveDvdrDlJumpIntervalSize.Visible || btnSaveDvdrDlManualLayerJumpStartLba.Visible ||
                      btnSaveDvdrDlRemapAnchorPoint.Visible || btnSaveDvdPlusAdip.Visible ||
                      btnSaveDvdPlusDcb.Visible;
        }
Example #38
0
        }   //FINE AD9954_WriteRSCW()

        ////////////////////////////////////////////////////////////
        // INIZIO SCRITTURA BYTES NELLA RAM
        public void AD9954_StartRamWrite()
        {
            byte[] _StartWriteRAM = { 0x0B };
            DDS.Write(_StartWriteRAM);
        }   //FINE AD9954_StartRamWrite()
Example #39
0
        public override void CreateFromStream(Stream stream)
        {
            int index_count = stream.ReadInt();

            Album.Length = stream.ReadInt();
            int count = stream.ReadInt();
            var table = new List <Color>(stream.ReadColorChart(count));

            Album.Tables = new List <List <Color> >();
            Album.Tables.Add(table);
            var list = new List <DDS>();

            for (int i = 0; i < index_count; i++)
            {
                var dds = new DDS();
                dds.Version  = (DDS_Version)stream.ReadInt();
                dds.unknow   = stream.ReadInt();
                dds.Index    = stream.ReadInt();
                dds.Size     = stream.ReadInt();
                dds.DDS_Size = stream.ReadInt();
                dds.Width    = stream.ReadInt();
                dds.Height   = stream.ReadInt();
                list.Add(dds);
            }
            var indexes  = new int[Album.Count];
            var dic      = new Dictionary <ImageEntity, int>();
            var ver2List = new List <ImageEntity>();

            for (var i = 0; i < Album.Count; i++)
            {
                var entity = new ImageEntity(Album);
                entity.Type     = (ColorBits)stream.ReadInt();
                entity.Compress = (Compress)stream.ReadInt();
                if (entity.Type > ColorBits.LINK)  //ver5 a型
                {
                    entity.Width  = stream.ReadInt();
                    entity.Height = stream.ReadInt();
                    stream.Seek(4);                      //保留,固定为0
                    entity.X             = stream.ReadInt();
                    entity.Y             = stream.ReadInt();
                    entity.Canvas_Width  = stream.ReadInt();
                    entity.Canvas_Height = stream.ReadInt();
                    stream.Seek(4);
                    var index     = stream.ReadInt();
                    var dds       = list[index];
                    var leftup    = new Point(stream.ReadInt(), stream.ReadInt());
                    var rightdown = new Point(stream.ReadInt(), stream.ReadInt());
                    stream.Seek(4);
                    Map.Add(entity, new DDS_Info(dds, leftup, rightdown));
                }
                else if (entity.Type == ColorBits.LINK)
                {
                    dic.Add(entity, stream.ReadInt());
                }
                else
                {
                    entity.Width         = stream.ReadInt();
                    entity.Height        = stream.ReadInt();
                    entity.Length        = stream.ReadInt();
                    entity.X             = stream.ReadInt();
                    entity.Y             = stream.ReadInt();
                    entity.Canvas_Width  = stream.ReadInt();
                    entity.Canvas_Height = stream.ReadInt();
                    if (entity.Length == 0)
                    {
                        var unknow7   = stream.ReadInt();
                        var unknow5   = stream.ReadInt();
                        var leftup    = new Point(stream.ReadInt(), stream.ReadInt());
                        var rightdown = new Point(stream.ReadInt(), stream.ReadInt());
                        var unknow6   = stream.ReadInt();
                        Map.Add(entity, new DDS_Info(list[0], leftup, rightdown));
                    }
                    else
                    {
                        ver2List.Add(entity);
                    }
                }
                entity.Index = Album.List.Count;
                Album.List.Add(entity);
            }
            foreach (var entity in dic.Keys)
            {
                entity.Target = Album.List[dic[entity]];
            }
            foreach (var dds in list)
            {
                var data = new byte[dds.Size];
                stream.Read(data);
                dds.Data = data;
            }
            foreach (var entity in ver2List)
            {
                var data = new byte[entity.Length];
                stream.Read(data);
                entity.Data = data;
            }
        }
Example #40
0
        }   //FINE AD9954_StartRamWrite()

        ////////////////////////////////////////////////////////////
        // INIZIO LETTURA BYTES DALLA RAM
        public void AD9954_StartRamRead()
        {
            byte[] _StartRamRead = { 0x8B };
            DDS.Write(_StartRamRead);
        }   //FINE AD9954_StartRamRead()
        public override void on_data_on_readers(
                DDS.Subscriber sub)
        {
            /* IMPORTANT for GROUP access scope: Invoking begin_access() */
            sub.begin_access();

            /* Obtain DataReaders. We obtain a sequence of DataReaders that specifies
            the order in which each sample should be read */
            try {
                sub.get_datareaders(my_datareaders,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            } catch (DDS.Exception e) {
                Console.WriteLine("get_datareaders error {0}", e);
                my_datareaders.ensure_length(0, 0);
                sub.end_access();
                return;
            }

            /* Read the samples received, following the DataReaders sequence */
            try {
                for (int i = 0; i < my_datareaders.length; ++i) {
                    try {
                        ordered_group_reader = (ordered_groupDataReader)
                            my_datareaders.get_at(i);
                    } catch (DDS.Exception e) {
                        Console.WriteLine("my_datareaders.get_at error {0}", e);
                        sub.end_access();
                        return;
                    }

                    /* IMPORTANT. Use take_next_sample(). We need to take only
                     * one sample each time, as we want to follow the sequence
                     * of DataReaders. This way the samples will be returned in
                     * the order in which they were modified
                     */
                    ordered_group_reader.take_next_sample(data, info);

                    if (info.valid_data) {
                        ordered_groupTypeSupport.print_data(data);
                    }

                    my_datareaders.ensure_length(0, 0);

                    /* IMPORTANT for GROUP access scope: Invoking end_access() */
                    sub.end_access();
                }
            } catch (DDS.Retcode_NoData noData) {
                //No data to process
            }
        }
Example #42
0
        }   //FINE AD9954_StartRamRead()

        ////////////////////////////////////////////////////////////
        // SCRITTURA DI UN BYTE NELLA RAM
        public void AD9954_WriteRamByte(byte b)
        {
            byte[] _b = { b };
            DDS.Write(_b);
        }   //FINE AD9954_WriteRamByte()
 public void instance_disposed(keysDataReader keys_reader,
                               DDS.SampleInfo info,
                               keys msg)
 {
     Console.WriteLine("Instance disposed; code = {0}", msg.code);
     states[msg.code] = Instance_State.disposed;
 }
Example #44
0
        }   //FINE AD9954_ReadRam()

        ////////////////////////////////////////////////////////////
        // SCRITTURA DI UNA WORD NELLA RAM
        public void AD9954_WriteRamWord(UInt16 Word)
        {
            byte[] _Word = { (byte)(Word >> 8), (byte)(Word) };
            DDS.Write(_Word);
        }   //FINE AD9954_WriteRamWord()
        /* These are not called by DDS.   on_data_available() calls
        the appropriate function when it gets updates about
        an instances' status
        */
        public void new_instance_found(keysDataReader keys_reader,
                                       DDS.SampleInfo info,
                                       keys msg)
        {
            /* There are really three cases here:
               1.) truly new instance
               2.) instance lost all writers, but now we're getting data again
               3.) instance was disposed, but a new one has been created

               We distinguish these cases by examining generation counts, BUT
               note that if the instance resources have been reclaimed, the
               generation counts may be reset to 0.

               Instances are eligible for resource cleanup if there are no
               active writers and all samples have been taken.  To reliably
               determine which case a 'new' instance falls into, the application
               must store state information on a per-instance basis.

               Note that this example assumes that state changes only occur via
               explicit register_instance(), unregister_instance() and dispose()
               calls from the datawriter.  In reality, these changes could also
               occur due to lost liveliness or missed deadlines, so those
               listeners would also need to update the instance state.
             */

            switch (states[msg.code])
            {
                case Instance_State.inactive:
                    Console.WriteLine("New instance found; code = {0}", msg.code);
                    break;
                case Instance_State.active:
                    /* An active instance should never be interpreted as new */
                    Console.WriteLine("Error, 'new' already-active instance found; code = {0}", msg.code);
                    break;
                case Instance_State.no_writers:
                    Console.WriteLine("Found writer for instance; code = {0}", msg.code);
                    break;
                case Instance_State.disposed:
                    Console.WriteLine("Found reborn instance; code = {0}", msg.code);
                    break;
            }
            states[msg.code] = Instance_State.active;
        }
Example #46
0
        }   //FINE AD9954_WriteRamWord()

        ////////////////////////////////////////////////////////////
        // SCRITTURA DI UN LONG NELLA RAM
        public void AD9954_WriteRamLong(ulong l)
        {
            byte[] _l = { (byte)(l >> 24), (byte)(l >> 16), (byte)(l >> 8), (byte)(l) };
            DDS.Write(_l);
        }
 public ReturnCode GetDiscoveredTopicData(
     ref DDS.TopicBuiltinTopicData[] topic_data,
     long topic_handle)
 {
     throw new System.NotImplementedException();
     //return realParticipant.get_discovered_topic_data(
     //        topic_data, topic_handle);
 }
Example #48
0
 public static AnalyzedTexture OpenFile(string input)
 {
     try
     {
         using (var file = File.OpenRead(input))
         {
             if (DDS.StreamIsDDS(file))
             {
                 return(new AnalyzedTexture()
                 {
                     Type = TexLoadType.DDS,
                     Texture = (Texture2D)DDS.FromStream(file)
                 });
             }
         }
         Generic.LoadResult lr;
         using (var file = File.OpenRead(input))
         {
             lr = Generic.BytesFromStream(file);
         }
         if (lr.Width != lr.Height)
         {
             return new AnalyzedTexture()
                    {
                        Type = TexLoadType.ErrorNonSquare
                    }
         }
         ;
         if (!MathHelper.IsPowerOfTwo(lr.Width) ||
             !MathHelper.IsPowerOfTwo(lr.Height))
         {
             return new AnalyzedTexture()
                    {
                        Type = TexLoadType.ErrorNonPowerOfTwo
                    }
         }
         ;
         bool opaque = true;
         //Swap channels + check alpha
         for (int i = 0; i < lr.Data.Length; i += 4)
         {
             var R = lr.Data[i];
             var B = lr.Data[i + 2];
             var A = lr.Data[i + 3];
             lr.Data[i + 2] = R;
             lr.Data[i]     = B;
             if (A != 255)
             {
                 opaque = false;
             }
         }
         var tex = new Texture2D(lr.Width, lr.Height);
         tex.SetData(lr.Data);
         return(new AnalyzedTexture()
         {
             Type = opaque ? TexLoadType.Opaque : TexLoadType.Alpha,
             Texture = tex
         });
     }
     catch (Exception e)
     {
         return(new AnalyzedTexture()
         {
             Type = TexLoadType.ErrorLoad
         });
     }
 }
        public override void on_data_available(DDS.DataReader reader)
        {
            /* We need to create a DynamicDataReader to receive the DynamicData
             */
            DDS.DynamicDataReader DynamicData_reader =
                (DDS.DynamicDataReader)reader;

            try {
                DynamicData_reader.take(
                    data_seq,
                    info_seq,
                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            }
            catch(DDS.Retcode_NoData) {
                return;
            }
            catch(DDS.Exception e) {
                Console.WriteLine("take error {0}", e);
                return;
            }

            System.Int32 data_length = data_seq.length;
            for (int i = 0; i < data_length; ++i) {
                if (info_seq.get_at(i).valid_data) {
                    data_seq.get_at(i).print(1);
                }
            }

            try {
                DynamicData_reader.return_loan(data_seq, info_seq);
            }
            catch(DDS.Exception e) {
                Console.WriteLine("return loan error {0}", e);
            }
        }
Example #50
0
        /// <summary>
        /// 校正下标
        /// </summary>
        /// <returns></returns>
        public override byte[] AdjustIndex()
        {
            var ms = new MemoryStream();

            foreach (var entity in Album.List)
            {
                ms.WriteInt((int)entity.Type);
                ms.WriteInt((int)entity.Compress);
                if (entity.Type > ColorBits.LINK)
                {
                    ms.WriteInt(entity.Size.Width);
                    ms.WriteInt(entity.Size.Height);
                    ms.WriteInt(0x00);
                    ms.WriteInt(entity.Location.X);
                    ms.WriteInt(entity.Location.Y);
                    ms.WriteInt(entity.Canvas_Size.Width);
                    ms.WriteInt(entity.Canvas_Size.Height);
                    ms.WriteInt(0x00);
                    var info      = Map[entity];
                    var dds_index = List.IndexOf(info.DDS);
                    ms.WriteInt(dds_index);
                    ms.WriteInt(info.LeftUp.X);
                    ms.WriteInt(info.LeftUp.Y);
                    ms.WriteInt(info.RightDown.X);
                    ms.WriteInt(info.RightDown.Y);
                    ms.WriteInt(0x00);
                }
                else if (entity.Type == ColorBits.LINK)
                {
                    ms.WriteInt(Album.List.IndexOf(entity.Target));
                }
                else
                {
                    ms.WriteInt(entity.Width);
                    ms.WriteInt(entity.Height);
                    ms.WriteInt(entity.Length);
                    ms.WriteInt(entity.X);
                    ms.WriteInt(entity.Y);
                    ms.WriteInt(entity.Canvas_Width);
                    ms.WriteInt(entity.Canvas_Height);
                }
            }
            ms.Close();
            var Index_Data = ms.ToArray();

            Album.Info_Length = Index_Data.Length;
            Album.Length      = 44;
            ms = new MemoryStream();
            foreach (var entity in Album.List)
            {
                var index = Map[entity];
                var dds   = index.DDS;
                if (entity.IsOpen)
                {
                    dds = DDS.CreateFromBitmap(entity.Picture, entity.Compress);
                }
                if (!Map.ContainsValue(index))
                {
                    dds.Index     = Map.Count;
                    Map[entity]   = index;
                    Album.Length += dds.Size;
                }
            }
            ms.WriteInt(Map.Count);
            Album.Length += 28 * Map.Count + 64 * Album.List.Count;
            ms.WriteInt(Album.Length);
            var table = Album.CurrentTable.ToArray();

            ms.WriteInt(table.Length);
            ms.WriteColorChart(table);
            var list = new List <DDS>();

            foreach (var index in Map.Values)
            {
                var dds = index.DDS;
                if (list.Contains(dds))
                {
                    continue;
                }
                ms.WriteInt((int)dds.Version);
                ms.WriteInt(dds.unknow);
                ms.WriteInt(dds.Index);
                ms.WriteInt(dds.Size);
                ms.WriteInt(dds.DDS_Size);
                ms.WriteInt(dds.Width);
                ms.WriteInt(dds.Height);
                list.Add(dds);
            }
            ms.Write(Index_Data);
            ms.Close();
            Index_Data = ms.ToArray();
            return(Index_Data);
        }
        public override void on_data_available(DDS.DataReader reader)
        {
            tbfDataReader tbf_reader =
                (tbfDataReader)reader;

            try {
                tbf_reader.take(
                    data_seq,
                    info_seq,
                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                    DDS.ViewStateKind.ANY_VIEW_STATE,
                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);
            }
            catch(DDS.Retcode_NoData) {
                return;
            }
            catch(DDS.Exception e) {
                Console.WriteLine("take error {0}", e);
                return;
            }

            System.Int32 data_length = data_seq.length;
            for (int i = 0; i < data_length; ++i) {
                if (info_seq.get_at(i).valid_data) {
                    /* Here we get source timestamp of the sample using the
                     * sample info.
                     *
                     * info_seq[i].source_timestamp returns DDS_Time_t
                     * ({seconds,nanoseconds}). We convert nanoseconds to
                     * seconds to get the decimal part of the timestamp.
                     */
                    System.Double source_timestamp =
                        info_seq.get_at(i).source_timestamp.sec +
                        (info_seq.get_at(i).source_timestamp.nanosec /
                         Constant.NANOSECOND);

                    Console.WriteLine(source_timestamp.ToString("0.00000") +
                        "\t" + data_seq.get_at(i).code + "\t\t" +
                        data_seq.get_at(i).x);
                }
            }

            try {
                tbf_reader.return_loan(data_seq, info_seq);
            }
            catch(DDS.Exception e) {
                Console.WriteLine("return loan error {0}", e);
            }
        }
Example #52
0
        /// <summary>
        /// Trys to find the fitting file type for the given file with the file signature.
        /// </summary>
        public static Type GetFileTypeFromSignature(Stream stream)
        {
            byte[] buffer = new byte[8];
            stream.Read(buffer, 0, buffer.Length);

            //Archives
            if (AFS.IsValid(buffer))
            {
                return(typeof(AFS));
            }
            if (GZ.IsValid(buffer))
            {
                return(typeof(GZ));
            }
            if (IDX.IsValid(buffer))
            {
                return(typeof(IDX));
            }
            if (IPAC.IsValid(buffer))
            {
                return(typeof(IPAC));
            }
            if (PKF.IsValid(buffer))
            {
                return(typeof(PKF));
            }
            if (PKS.IsValid(buffer))
            {
                return(typeof(PKS));
            }
            //if (SPR.IsValid(buffer)) return typeof(SPR); //same as TEXN skip and base identification on extension
            if (TAD.IsValid(buffer))
            {
                return(typeof(TAD));
            }

            //Textures/Images
            if (TEXN.IsValid(buffer))
            {
                return(typeof(TEXN));
            }
            if (PVRT.IsValid(buffer))
            {
                return(typeof(PVRT));
            }
            if (DDS.IsValid(buffer))
            {
                return(typeof(DDS));
            }

            //Models
            if (MT5.IsValid(buffer))
            {
                return(typeof(MT5));
            }
            if (MT7.IsValid(buffer))
            {
                return(typeof(MT7));
            }

            //Subtitles
            if (SUB.IsValid(buffer))
            {
                return(typeof(SUB));
            }

            return(null);
        }
 public override void on_requested_deadline_missed(
     DDS.DataReader reader,
     ref DDS.RequestedDeadlineMissedStatus status)
 {
 }
Example #54
0
        public static string GetExtensionFromBuffer(byte[] buffer)
        {
            //Archives
            if (AFS.IsValid(buffer))
            {
                return("AFS");
            }
            if (GZ.IsValid(buffer))
            {
                return("GZ");
            }
            if (IDX.IsValid(buffer))
            {
                return("IDX");
            }
            if (IPAC.IsValid(buffer))
            {
                return("IPAC");
            }
            if (PKF.IsValid(buffer))
            {
                return("PKF");
            }
            if (PKS.IsValid(buffer))
            {
                return("PKS");
            }
            //if (SPR.IsValid(buffer)) return typeof(SPR); //same as TEXN skip and base identification on extension
            if (TAD.IsValid(buffer))
            {
                return("TAD");
            }

            //Textures/Images
            if (TEXN.IsValid(buffer))
            {
                return("TEXN");
            }
            if (PVRT.IsValid(buffer))
            {
                return("PVRT");
            }
            if (DDS.IsValid(buffer))
            {
                return("DDS");
            }

            //Models
            if (MT5.IsValid(buffer))
            {
                return("MT5");
            }
            if (MT7.IsValid(buffer))
            {
                return("MT7");
            }

            //Subtitles
            if (SUB.IsValid(buffer))
            {
                return("SUB");
            }

            return("UNKNOWN");
        }
 public override void on_sample_lost(
     DDS.DataReader reader,
     ref DDS.SampleLostStatus status)
 {
 }
Example #56
0
            public unsafe void FillWithTPF(GraphicsDevice d, CommandList cl, TPF.TPFPlatform platform, TPF.Texture tex, string name)
            {
                DDS dds;
                var bytes = tex.Bytes;

                if (platform != TPF.TPFPlatform.PC)
                {
                    bytes = tex.Headerize();
                    dds   = new DDS(bytes);
                }
                else
                {
                    dds = new DDS(tex.Bytes);
                }

                uint        width  = (uint)dds.dwWidth;
                uint        height = (uint)dds.dwHeight;
                PixelFormat format;

                if (dds.header10 != null)
                {
                    format = GetPixelFormatFromDXGI(dds.header10.dxgiFormat);
                }
                else
                {
                    if (dds.ddspf.dwFlags == (DDS.DDPF.RGB | DDS.DDPF.ALPHAPIXELS) &&
                        dds.ddspf.dwRGBBitCount == 32)
                    {
                        format = PixelFormat.R8_G8_B8_A8_UNorm_SRgb;
                    }
                    else if (dds.ddspf.dwFlags == (DDS.DDPF.RGB) && dds.ddspf.dwRGBBitCount == 24)
                    {
                        format = PixelFormat.R8_G8_B8_A8_UNorm_SRgb;
                        // 24-bit formats are annoying for now
                        return;
                    }
                    else
                    {
                        format = GetPixelFormatFromFourCC(dds.ddspf.dwFourCC);
                    }
                }

                if (!Utils.IsPowerTwo(width) || !Utils.IsPowerTwo(height))
                {
                    return;
                }
                width  = IsCompressedFormat(format) ? (uint)((width + 3) & ~0x3) : width;
                height = IsCompressedFormat(format) ? (uint)((height + 3) & ~0x3) : height;

                bool isCubemap = false;

                if ((dds.dwCaps2 & DDS.DDSCAPS2.CUBEMAP) > 0)
                {
                    isCubemap = true;
                }

                var usage = (isCubemap) ? TextureUsage.Cubemap : 0;

                uint arrayCount = isCubemap ? 6u : 1;

                TextureDescription desc = new TextureDescription();

                desc.Width       = width;
                desc.Height      = height;
                desc.MipLevels   = (uint)dds.dwMipMapCount;
                desc.SampleCount = TextureSampleCount.Count1;
                desc.ArrayLayers = arrayCount;
                desc.Depth       = 1;
                desc.Type        = TextureType.Texture2D;
                desc.Usage       = TextureUsage.Staging;
                desc.Format      = format;

                _staging = d.ResourceFactory.CreateTexture(desc);

                int paddedWidth  = 0;
                int paddedHeight = 0;
                int paddedSize   = 0;
                int copyOffset   = dds.DataOffset;

                for (int slice = 0; slice < arrayCount; slice++)
                {
                    for (uint level = 0; level < dds.dwMipMapCount; level++)
                    {
                        MappedResource map     = d.Map(_staging, MapMode.Write, (uint)slice * (uint)dds.dwMipMapCount + level);
                        var            mipInfo = GetMipInfo(format, (int)dds.dwWidth, (int)dds.dwHeight, (int)level, false);
                        //paddedSize = mipInfo.ByteCount;
                        paddedSize = mipInfo;
                        fixed(void *data = &bytes[copyOffset])
                        {
                            Unsafe.CopyBlock(map.Data.ToPointer(), data, (uint)paddedSize);
                        }

                        copyOffset += paddedSize;
                    }
                }

                desc.Usage       = TextureUsage.Sampled | usage;
                desc.ArrayLayers = 1;
                _texture         = d.ResourceFactory.CreateTexture(desc);
                _texture.Name    = name;
                cl.CopyTexture(_staging, _texture);
                Resident = true;
                _pool.DescriptorTableDirty = true;
            }
 public override void on_subscription_matched(
     DDS.DataReader reader,
     ref DDS.SubscriptionMatchedStatus status)
 {
 }
        internal void LoadData(byte[] blurayDiscInformation, byte[] blurayBurstCuttingArea, byte[] blurayDds,
                               byte[] blurayCartridgeStatus, byte[] bluraySpareAreaInformation,
                               byte[] blurayPowResources, byte[] blurayTrackResources, byte[] blurayRawDfl,
                               byte[] blurayPac)
        {
            DiscInformation  = blurayDiscInformation;
            BurstCuttingArea = blurayBurstCuttingArea;
            Dds                  = blurayDds;
            CartridgeStatus      = blurayCartridgeStatus;
            SpareAreaInformation = bluraySpareAreaInformation;
            PowResources         = blurayPowResources;
            TrackResources       = blurayTrackResources;
            RawDfl               = blurayRawDfl;
            Pac                  = blurayPac;

            if (blurayDiscInformation != null)
            {
                grpBlurayDiscInformation.Visible     = true;
                btnSaveBlurayDiscInformation.Visible = true;
                txtBlurayDiscInformation.Text        = DI.Prettify(blurayDiscInformation);
            }

            if (blurayBurstCuttingArea != null)
            {
                grpBlurayBurstCuttingArea.Visible     = true;
                btnSaveBlurayBurstCuttingArea.Visible = true;
                txtBlurayBurstCuttingArea.Text        = BCA.Prettify(blurayBurstCuttingArea);
            }

            if (blurayDds != null)
            {
                grpBlurayDds.Visible     = true;
                btnSaveBlurayDds.Visible = true;
                txtBlurayDds.Text        = DDS.Prettify(blurayDds);
            }

            if (blurayCartridgeStatus != null)
            {
                grpBlurayCartridgeStatus.Visible     = true;
                btnSaveBlurayCartridgeStatus.Visible = true;
                txtBlurayCartridgeStatus.Text        = Cartridge.Prettify(blurayCartridgeStatus);
            }

            if (bluraySpareAreaInformation != null)
            {
                grpBluraySpareAreaInformation.Visible     = true;
                btnSaveBluraySpareAreaInformation.Visible = true;
                txtBluraySpareAreaInformation.Text        = Spare.Prettify(bluraySpareAreaInformation);
            }

            if (blurayPowResources != null)
            {
                grpBlurayPowResources.Visible     = true;
                btnSaveBlurayPowResources.Visible = true;
                txtBlurayPowResources.Text        = Decoders.SCSI.MMC.DiscInformation.Prettify(blurayPowResources);
            }

            if (blurayTrackResources != null)
            {
                grpBlurayTrackResources.Visible     = true;
                btnSaveBlurayTrackResources.Visible = true;
                txtBlurayTrackResources.Text        = Decoders.SCSI.MMC.DiscInformation.Prettify(blurayTrackResources);
            }

            btnSaveBlurayRawDfl.Visible = blurayRawDfl != null;
            btnSaveBlurayPac.Visible    = blurayPac != null;

            Visible = grpBlurayDiscInformation.Visible || grpBlurayBurstCuttingArea.Visible ||
                      grpBlurayDds.Visible ||
                      grpBlurayCartridgeStatus.Visible || grpBluraySpareAreaInformation.Visible ||
                      grpBlurayPowResources.Visible || grpBlurayTrackResources.Visible ||
                      btnSaveBlurayRawDfl.Visible ||
                      btnSaveBlurayPac.Visible;
        }
Example #59
0
 private void Cleanup(DDS.DomainParticipantFactory f, DDS.IDomainParticipant p)
 {
     if (p != null)
     {
         p.DeleteContainedEntities();
     }
     if (f != null)
     {
         f.DeleteParticipant(p);
     }
 }
Example #60
0
        public Texture FetchNew()
        {
            if (CachedTexture != null)
            {
                return(CachedTexture);
            }

            var texInfo = FetchTexInfo();

            if (texInfo == null)
            {
                return(null);
            }

            int  height      = texInfo.Texture?.Header?.Height ?? 0;
            int  width       = texInfo.Texture?.Header?.Width ?? 0;
            int  dxgiFormat  = texInfo.Texture?.Header?.DXGIFormat ?? 0;
            int  mipmapCount = texInfo.Texture?.Mipmaps ?? 0;
            uint fourCC      = FourCCDX10;
            int  arraySize   = texInfo.Texture?.Header?.TextureCount ?? 1;

            if (arraySize < 1)
            {
                arraySize = 1;
            }

            DDS ppDdsHeader_ForDebug = null;

            bool hasFullCubeDDSCaps2 = false;

            int dataStartOffset = 0;

            var br = new BinaryReaderEx(false, texInfo.DDSBytes);

            bool hasHeader = br.ReadASCII(4) == "DDS ";

            int blockSize = !hasHeader?GetBlockSize(texInfo.Texture.Format) : -1;

            if (hasHeader)
            {
                DDS header = new DDS(texInfo.DDSBytes);
                height      = header.dwHeight;
                width       = header.dwWidth;
                mipmapCount = header.dwMipMapCount;
                fourCC      = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(header.ddspf.dwFourCC), 0);

                if ((header.dwCaps2 & FullCubeDDSCaps2) == FullCubeDDSCaps2)
                {
                    hasFullCubeDDSCaps2 = true;
                }

                if (header.header10 != null)
                {
                    arraySize  = (int)header.header10.arraySize;
                    dxgiFormat = (int)header.header10.dxgiFormat;
                }

                dataStartOffset = header.DataOffset;

                ppDdsHeader_ForDebug = header;
            }
            else
            {
                if (texInfo.Platform == TPF.TPFPlatform.PS4)
                {
                    switch (texInfo.Texture.Format)
                    {
                    case 0:
                    case 1:
                    case 25:
                    case 103:
                    case 108:
                    case 109:
                        fourCC = FourCCDX10;     //DX10
                        break;

                    case 5:
                    case 100:
                    case 102:
                    case 106:
                    case 107:
                    case 110:
                        fourCC = FourCCDX10;     //DX10
                        break;

                    case 22:
                        fourCC = 0x71;
                        break;

                    case 105:
                        fourCC = 0;
                        break;
                    }
                }
                else if (texInfo.Platform == TPF.TPFPlatform.PS3)
                {
                    switch (texInfo.Texture.Format)
                    {
                    case 0:
                    case 1:
                        fourCC = 0x31545844;
                        break;

                    case 5:
                        fourCC = 0x35545844;
                        break;

                    case 9:
                    case 10:
                        fourCC = 0;
                        break;
                    }
                }

                if (mipmapCount == 0)
                {
                    // something Hork came up with :fatcat:
                    mipmapCount = (int)(1 + Math.Floor(Math.Log(Math.Max(width, height), 2)));
                }

                dataStartOffset = 0;
            }

            SurfaceFormat surfaceFormat;

            if (fourCC == FourCCDX10)
            {
                // See if there are DX9 textures
                int fmt = dxgiFormat;
                if (fmt == 70 || fmt == 71 || fmt == 72)
                {
                    surfaceFormat = SurfaceFormat.Dxt1;
                }
                else if (fmt == 73 || fmt == 74 || fmt == 75)
                {
                    surfaceFormat = SurfaceFormat.Dxt3;
                }
                else if (fmt == 76 || fmt == 77 || fmt == 78)
                {
                    surfaceFormat = SurfaceFormat.Dxt5;
                }
                else if (fmt == 79 || fmt == 80 || fmt == 81)
                {
                    surfaceFormat = SurfaceFormat.ATI1;
                }
                else if (fmt == 82 || fmt == 83 || fmt == 84)
                {
                    surfaceFormat = SurfaceFormat.ATI2;
                }
                else if (fmt == 95)
                {
                    surfaceFormat = SurfaceFormat.BC6HUF16;
                }
                else if (fmt == 96)
                {
                    surfaceFormat = SurfaceFormat.BC6HSF16;
                }
                else if (fmt == 94)
                {
                    surfaceFormat = SurfaceFormat.BC6HTypeless;
                }
                else if (fmt == 97 || fmt == 98 || fmt == 99)
                {
                    surfaceFormat = SurfaceFormat.BC7;
                }
                else
                {
                    // No DX10 texture support in monogame yet
                    Console.WriteLine($"Unable to load {TexName} because it uses DX10+ exclusive texture type.");
                    CachedTexture = Main.DEFAULT_TEXTURE_MISSING_CUBE;
                    TPFReference  = null;
                    return((TextureCube)CachedTexture);
                }
            }
            else
            {
                surfaceFormat = GetSurfaceFormatFromString(System.Text.Encoding.ASCII.GetString(BitConverter.GetBytes(fourCC)));
            }

            bool mipmaps = mipmapCount > 0;

            // apply memes
            if (texInfo.Platform == TPF.TPFPlatform.PC || texInfo.Platform == TPF.TPFPlatform.PS3)
            {
                width   = IsCompressedFormat(surfaceFormat) ? ((width + 3) & ~0x3) : width;
                height  = IsCompressedFormat(surfaceFormat) ? ((height + 3) & ~0x3) : height;
                mipmaps = true;
            }
            else if (texInfo.Platform == TPF.TPFPlatform.PS4)
            {
                width  = (int)(Math.Ceiling(width / 4f) * 4f);
                height = (int)(Math.Ceiling(height / 4f) * 4f);
            }
            //else if (texInfo.Platform == TPF.TPFPlatform.PS3)
            //{
            //    throw new NotImplementedException();
            //}
            else
            {
                throw new NotImplementedException();
            }

            Texture tex = null;

            int paddedWidth  = 0;
            int paddedHeight = 0;
            int paddedSize   = 0;
            int copyOffset   = dataStartOffset;

            bool isCubeMap = (texInfo.Texture?.Type == TPF.TexType.Cubemap) || arraySize >= 6 || hasFullCubeDDSCaps2;

            if (isCubeMap)
            {
                tex = new TextureCube(GFX.Device, width, true, surfaceFormat);
            }
            else
            {
                tex = new Texture2D(GFX.Device, width, height,
                                    mipmapCount > 1,
                                    surfaceFormat,
                                    arraySize);
            }

            if (texInfo.Platform == TPF.TPFPlatform.PC || texInfo.Platform == TPF.TPFPlatform.PS3)
            {
                for (int i = 0; i < arraySize; i++)
                {
                    for (int j = 0; j < mipmapCount; j++)
                    {
                        var mipInfo = GetMipInfo(surfaceFormat, width, height, j, isCubeMap);

                        paddedSize = mipInfo.ByteCount;

                        //if (surfaceFormat == SurfaceFormat.Dxt1 || surfaceFormat == SurfaceFormat.Dxt1SRgb)
                        //    paddedSize /= 2;

                        //if (GameDataManager.GameType == GameDataManager.GameTypes.DS1R && surfaceFormat == SurfaceFormat.Dxt1)
                        //    paddedSize /= 2;

                        if (isCubeMap)
                        {
                            ((TextureCube)tex).SetData((CubeMapFace)i, j, null, br.GetBytes(copyOffset, paddedSize), 0, paddedSize);
                        }
                        else
                        {
                            try
                            {
                                ((Texture2D)tex).SetData(j, i, null, br.GetBytes(copyOffset, paddedSize), 0, paddedSize);
                            }
                            catch (ArgumentException)
                            {
                                try
                                {
                                    ((Texture2D)tex).SetData(j, i, null, br.GetBytes(copyOffset, paddedSize / 2), 0, paddedSize);
                                }
                                catch
                                {
                                }
                            }
                        }

                        copyOffset += paddedSize;
                    }
                }
            }
            else if (texInfo.Platform == TPF.TPFPlatform.PS4)
            {
                if (isCubeMap)
                {
                    throw new NotImplementedException();
                    //for (int i = 0; i < arraySize; i++)
                    //{
                    //    int currentWidth = width;
                    //    int currentHeight = height;

                    //    void SetPaddedSize_PS4(int w, int h)
                    //    {
                    //        if (isCubeMap)
                    //        {
                    //            if (texInfo.Texture.Format == 22)
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 8f) * 8f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 8f) * 8f);
                    //                paddedSize = paddedWidth * paddedHeight * blockSize;
                    //            }
                    //            else
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 32f) * 32f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 32f) * 32f);
                    //                paddedSize = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                    //            }
                    //        }
                    //        else
                    //        {
                    //            if (texInfo.Texture.Format == 105)
                    //            {
                    //                paddedWidth = w;
                    //                paddedHeight = h;
                    //                paddedSize = paddedWidth * paddedHeight * blockSize;
                    //            }
                    //            else
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 32f) * 32f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 32f) * 32f);
                    //                paddedSize = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                    //            }
                    //        }
                    //    }

                    //    SetPaddedSize_PS4(currentWidth, currentHeight);

                    //    copyOffset = dataStartOffset + paddedSize * i;

                    //    for (int j = 0; j < mipmapCount; j++)
                    //    {
                    //        if (j > 0)
                    //        {
                    //            SetPaddedSize_PS4(currentWidth, currentHeight);

                    //            copyOffset += paddedSize * i;
                    //        }

                    //        var deswizzler = new DDSDeswizzler(texInfo.Texture.Format, br.GetBytes(copyOffset, paddedSize), blockSize);

                    //        byte[] deswizzledMipMap = null;

                    //        deswizzler.CreateOutput();
                    //        deswizzler.DDSWidth = paddedWidth;
                    //        deswizzler.DeswizzleDDSBytesPS4(currentWidth, currentHeight);
                    //        deswizzledMipMap = deswizzler.OutputBytes;

                    //        var finalBytes = (deswizzledMipMap ?? deswizzler.InputBytes);

                    //        using (var tempMemStream = new System.IO.MemoryStream(finalBytes.Length))
                    //        {
                    //            var tempWriter = new BinaryWriter(tempMemStream);

                    //            if (texInfo.Texture.Format == 22)
                    //            {
                    //                for (int h = 0; h < currentHeight; h++)
                    //                {
                    //                    tempWriter.Write(finalBytes, h * paddedWidth * blockSize, currentWidth * blockSize);
                    //                }
                    //            }
                    //            else
                    //            {
                    //                for (int h = 0; h < (int)Math.Ceiling(currentHeight / 4f); h++)
                    //                {
                    //                    tempWriter.Write(finalBytes, (int)(h * Math.Ceiling(paddedWidth / 4f) * blockSize), (int)(Math.Ceiling(currentWidth / 4f) * blockSize));
                    //                }
                    //            }

                    //            if (isCubeMap)
                    //            {
                    //                ((TextureCube)tex).SetData((CubeMapFace)j, i, null, tempMemStream.ToArray(), 0, finalBytes.Length);
                    //            }
                    //            else
                    //            {
                    //                ((Texture2D)tex).SetData(j, i, null, tempMemStream.ToArray(), 0, finalBytes.Length);
                    //            }


                    //        }

                    //        copyOffset += (arraySize - i) * paddedSize + paddedSize * 2;

                    //        if (currentWidth > 1)
                    //            currentWidth /= 2;

                    //        if (currentHeight > 1)
                    //            currentHeight /= 2;
                    //    }
                    //}
                }
                else
                {
                    int currentWidth  = width;
                    int currentHeight = height;

                    for (int j = 0; j < mipmapCount; j++)
                    {
                        if (texInfo.Texture.Format == 105)
                        {
                            paddedWidth  = currentWidth;
                            paddedHeight = currentHeight;
                            paddedSize   = paddedWidth * paddedHeight * blockSize;
                        }
                        else
                        {
                            paddedWidth  = (int)(Math.Ceiling(currentWidth / 32f) * 32f);
                            paddedHeight = (int)(Math.Ceiling(currentHeight / 32f) * 32f);
                            paddedSize   = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                        }

                        var deswizzler = new DDSDeswizzler(texInfo.Texture.Format, br.GetBytes(copyOffset, paddedSize), blockSize);

                        byte[] deswizzledMipMap = null;

                        deswizzler.CreateOutput();
                        deswizzler.DDSWidth = paddedWidth;
                        deswizzler.DeswizzleDDSBytesPS4(currentWidth, currentHeight);
                        deswizzledMipMap = deswizzler.OutputBytes;

                        var finalBytes = (deswizzledMipMap ?? deswizzler.InputBytes);

                        using (var tempMemStream = new System.IO.MemoryStream())
                        {
                            var tempWriter = new BinaryWriter(tempMemStream);


                            if (texInfo.Texture.Format == 105)
                            {
                                tempWriter.Write(finalBytes);
                            }
                            else
                            {
                                for (int h = 0; h < (int)Math.Ceiling(currentHeight / 4f); h++)
                                {
                                    tempWriter.Write(finalBytes, (int)(h * Math.Ceiling(paddedWidth / 4f) * blockSize), (int)(Math.Ceiling(currentWidth / 4f) * blockSize));
                                }
                            }

                            ((Texture2D)tex).SetData(j, 0, null, tempMemStream.ToArray(), 0, (int)tempMemStream.Length);
                        }

                        copyOffset += paddedSize;

                        if (currentWidth > 1)
                        {
                            currentWidth /= 2;
                        }

                        if (currentHeight > 1)
                        {
                            currentHeight /= 2;
                        }
                    }
                }
            }

            CachedTexture?.Dispose();

            CachedTexture = tex;

            return(CachedTexture);
        }